repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
TechExhibeo/kernel_lenovo_a7000 | arch/arm/mach-s3c64xx/mach-smartq7.c | 2280 | 3911 | /*
* linux/arch/arm/mach-s3c64xx/mach-smartq7.c
*
* Copyright (C) 2010 Maurus Cuelenaere
*
* 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/fb.h>
#include <linux/gpio.h>
#include <linux/gpio_keys.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/leds.h>
#include <linux/platform_device.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <video/samsung_fimd.h>
#include <mach/map.h>
#include <mach/regs-gpio.h>
#include <plat/cpu.h>
#include <plat/devs.h>
#include <plat/fb.h>
#include <plat/gpio-cfg.h>
#include <plat/samsung-time.h>
#include "common.h"
#include "mach-smartq.h"
static struct gpio_led smartq7_leds[] = {
{
.name = "smartq7:red",
.active_low = 1,
.gpio = S3C64XX_GPN(8),
},
{
.name = "smartq7:green",
.active_low = 1,
.gpio = S3C64XX_GPN(9),
},
};
static struct gpio_led_platform_data smartq7_led_data = {
.num_leds = ARRAY_SIZE(smartq7_leds),
.leds = smartq7_leds,
};
static struct platform_device smartq7_leds_device = {
.name = "leds-gpio",
.id = -1,
.dev.platform_data = &smartq7_led_data,
};
/* Labels according to the SmartQ manual */
static struct gpio_keys_button smartq7_buttons[] = {
{
.gpio = S3C64XX_GPL(14),
.code = KEY_POWER,
.desc = "Power",
.active_low = 1,
.debounce_interval = 5,
.type = EV_KEY,
},
{
.gpio = S3C64XX_GPN(2),
.code = KEY_FN,
.desc = "Function",
.active_low = 1,
.debounce_interval = 5,
.type = EV_KEY,
},
{
.gpio = S3C64XX_GPN(3),
.code = KEY_KPMINUS,
.desc = "Minus",
.active_low = 1,
.debounce_interval = 5,
.type = EV_KEY,
},
{
.gpio = S3C64XX_GPN(4),
.code = KEY_KPPLUS,
.desc = "Plus",
.active_low = 1,
.debounce_interval = 5,
.type = EV_KEY,
},
{
.gpio = S3C64XX_GPN(12),
.code = KEY_ENTER,
.desc = "Enter",
.active_low = 1,
.debounce_interval = 5,
.type = EV_KEY,
},
{
.gpio = S3C64XX_GPN(15),
.code = KEY_ESC,
.desc = "Cancel",
.active_low = 1,
.debounce_interval = 5,
.type = EV_KEY,
},
};
static struct gpio_keys_platform_data smartq7_buttons_data = {
.buttons = smartq7_buttons,
.nbuttons = ARRAY_SIZE(smartq7_buttons),
};
static struct platform_device smartq7_buttons_device = {
.name = "gpio-keys",
.id = 0,
.num_resources = 0,
.dev = {
.platform_data = &smartq7_buttons_data,
}
};
static struct s3c_fb_pd_win smartq7_fb_win0 = {
.max_bpp = 32,
.default_bpp = 16,
.xres = 800,
.yres = 480,
};
static struct fb_videomode smartq7_lcd_timing = {
.left_margin = 3,
.right_margin = 5,
.upper_margin = 1,
.lower_margin = 20,
.hsync_len = 10,
.vsync_len = 3,
.xres = 800,
.yres = 480,
.refresh = 80,
};
static struct s3c_fb_platdata smartq7_lcd_pdata __initdata = {
.setup_gpio = s3c64xx_fb_gpio_setup_24bpp,
.vtiming = &smartq7_lcd_timing,
.win[0] = &smartq7_fb_win0,
.vidcon0 = VIDCON0_VIDOUT_RGB | VIDCON0_PNRMODE_RGB,
.vidcon1 = VIDCON1_INV_HSYNC | VIDCON1_INV_VSYNC |
VIDCON1_INV_VCLK,
};
static struct platform_device *smartq7_devices[] __initdata = {
&smartq7_leds_device,
&smartq7_buttons_device,
};
static void __init smartq7_machine_init(void)
{
s3c_fb_set_platdata(&smartq7_lcd_pdata);
smartq_machine_init();
platform_add_devices(smartq7_devices, ARRAY_SIZE(smartq7_devices));
}
MACHINE_START(SMARTQ7, "SmartQ 7")
/* Maintainer: Maurus Cuelenaere <mcuelenaere AT gmail DOT com> */
.atag_offset = 0x100,
.init_irq = s3c6410_init_irq,
.map_io = smartq_map_io,
.init_machine = smartq7_machine_init,
.init_late = s3c64xx_init_late,
.init_time = samsung_timer_init,
.restart = s3c64xx_restart,
MACHINE_END
| gpl-2.0 |
EmericanX/android_kernel_motorola_msm8960-common | drivers/staging/westbridge/astoria/api/src/cyasmtp.c | 2536 | 29266 | /* Cypress West Bridge API header file (cyasmtp.h)
## ===========================
## Copyright (C) 2010 Cypress Semiconductor
##
## This program is free software; you can redistribute 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 "../../include/linux/westbridge/cyashal.h"
#include "../../include/linux/westbridge/cyasmtp.h"
#include "../../include/linux/westbridge/cyaserr.h"
#include "../../include/linux/westbridge/cyasdma.h"
#include "../../include/linux/westbridge/cyaslowlevel.h"
static void
cy_as_mtp_func_callback(cy_as_device *dev_p,
uint8_t context,
cy_as_ll_request_response *rqt,
cy_as_ll_request_response *resp,
cy_as_return_status_t stat);
static cy_as_return_status_t
is_mtp_active(cy_as_device *dev_p)
{
if (!cy_as_device_is_configured(dev_p))
return CY_AS_ERROR_NOT_CONFIGURED;
if (!cy_as_device_is_firmware_loaded(dev_p))
return CY_AS_ERROR_NO_FIRMWARE;
if (dev_p->mtp_count == 0)
return CY_AS_ERROR_NOT_RUNNING;
if (cy_as_device_is_in_suspend_mode(dev_p))
return CY_AS_ERROR_IN_SUSPEND;
return CY_AS_ERROR_SUCCESS;
}
static void
my_mtp_request_callback(cy_as_device *dev_p,
uint8_t context,
cy_as_ll_request_response *req_p,
cy_as_ll_request_response *resp_p,
cy_as_return_status_t ret)
{
uint16_t val, ev, status;
uint16_t mtp_datalen = 0;
uint32_t bytecount_l, bytecount_h;
cy_as_mtp_send_object_complete_data send_obj_data;
cy_as_mtp_get_object_complete_data get_obj_data;
cy_as_dma_end_point *ep_p;
uint8_t code = cy_as_ll_request_response__get_code(req_p);
(void)resp_p;
(void)context;
(void)ret;
switch (code) {
case CY_RQT_MTP_EVENT:
val = cy_as_ll_request_response__get_word(req_p, 0);
/* MSB indicates status of read/write */
status = (val >> 8) & 0xFF;
/* event type */
ev = val & 0xFF;
switch (ev) {
case 0: /* SendObject Complete */
{
bytecount_l =
cy_as_ll_request_response__get_word
(req_p, 1);
bytecount_h =
cy_as_ll_request_response__get_word
(req_p, 2);
send_obj_data.byte_count =
(bytecount_h << 16) | bytecount_l;
send_obj_data.status = status;
/* use the byte count again */
bytecount_l =
cy_as_ll_request_response__get_word
(req_p, 3);
bytecount_h =
cy_as_ll_request_response__get_word
(req_p, 4);
send_obj_data.transaction_id =
(bytecount_h << 16) | bytecount_l;
dev_p->mtp_turbo_active = cy_false;
if (dev_p->mtp_event_cb)
dev_p->mtp_event_cb(
(cy_as_device_handle) dev_p,
cy_as_mtp_send_object_complete,
&send_obj_data);
}
break;
case 1: /* GetObject Complete */
{
bytecount_l =
cy_as_ll_request_response__get_word
(req_p, 1);
bytecount_h =
cy_as_ll_request_response__get_word
(req_p, 2);
get_obj_data.byte_count =
(bytecount_h << 16) | bytecount_l;
get_obj_data.status = status;
dev_p->mtp_turbo_active = cy_false;
if (dev_p->mtp_event_cb)
dev_p->mtp_event_cb(
(cy_as_device_handle) dev_p,
cy_as_mtp_get_object_complete,
&get_obj_data);
}
break;
case 2: /* BlockTable Needed */
{
if (dev_p->mtp_event_cb)
dev_p->mtp_event_cb(
(cy_as_device_handle) dev_p,
cy_as_mtp_block_table_needed, 0);
}
break;
default:
cy_as_hal_print_message("invalid event type\n");
cy_as_ll_send_data_response(dev_p,
CY_RQT_TUR_RQT_CONTEXT,
CY_RESP_MTP_INVALID_EVENT,
sizeof(ev), &ev);
break;
}
break;
case CY_RQT_TURBO_CMD_FROM_HOST:
{
mtp_datalen =
cy_as_ll_request_response__get_word(req_p, 1);
/* Get the endpoint pointer based on
* the endpoint number */
ep_p = CY_AS_NUM_EP(dev_p, CY_AS_MTP_READ_ENDPOINT);
/* The event should arrive only after the DMA operation
* has been queued. */
cy_as_hal_assert(ep_p->queue_p != 0);
/* Put the len in ep data information in
* dmaqueue and kick start the queue */
cy_as_hal_assert(ep_p->queue_p->size >= mtp_datalen);
if (mtp_datalen == 0) {
cy_as_dma_completed_callback(dev_p->tag,
CY_AS_MTP_READ_ENDPOINT, 0,
CY_AS_ERROR_SUCCESS);
} else {
ep_p->maxhwdata = mtp_datalen;
/*
* make sure that the DMA status for this
* EP is not running, so that the call to
* cy_as_dma_kick_start gets this transfer
* going. note: in MTP mode, we never leave
* a DMA transfer of greater than one packet
* running. so, it is okay to override the
* status here and start the next packet
* transfer.
*/
cy_as_dma_end_point_set_stopped(ep_p);
/* Kick start the queue if it is not running */
cy_as_dma_kick_start(dev_p,
CY_AS_MTP_READ_ENDPOINT);
}
}
break;
case CY_RQT_TURBO_START_WRITE_DMA:
{
/*
* now that the firmware is ready to receive the
* next packet of data, start the corresponding
* DMA transfer. first, ensure that a DMA
* operation is still pending in the queue for the
* write endpoint.
*/
cy_as_ll_send_status_response(dev_p,
CY_RQT_TUR_RQT_CONTEXT,
CY_AS_ERROR_SUCCESS, 0);
ep_p = CY_AS_NUM_EP(dev_p, CY_AS_MTP_WRITE_ENDPOINT);
cy_as_hal_assert(ep_p->queue_p != 0);
cy_as_dma_end_point_set_stopped(ep_p);
cy_as_dma_kick_start(dev_p, CY_AS_MTP_WRITE_ENDPOINT);
}
break;
default:
cy_as_hal_print_message("invalid request received "
"on TUR context\n");
val = req_p->box0;
cy_as_ll_send_data_response(dev_p, CY_RQT_TUR_RQT_CONTEXT,
CY_RESP_INVALID_REQUEST, sizeof(val), &val);
break;
}
}
static cy_as_return_status_t
my_handle_response_no_data(cy_as_device *dev_p,
cy_as_ll_request_response *req_p,
cy_as_ll_request_response *reply_p)
{
cy_as_return_status_t ret = CY_AS_ERROR_SUCCESS;
if (cy_as_ll_request_response__get_code(reply_p) !=
CY_RESP_SUCCESS_FAILURE) {
ret = CY_AS_ERROR_INVALID_RESPONSE;
goto destroy;
}
ret = cy_as_ll_request_response__get_word(reply_p, 0);
destroy:
cy_as_ll_destroy_request(dev_p, req_p);
cy_as_ll_destroy_response(dev_p, reply_p);
return ret;
}
static cy_as_return_status_t
my_handle_response_mtp_start(cy_as_device *dev_p,
cy_as_ll_request_response *req_p,
cy_as_ll_request_response *reply_p,
cy_as_return_status_t ret)
{
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
if (cy_as_ll_request_response__get_code(reply_p) !=
CY_RESP_SUCCESS_FAILURE) {
ret = CY_AS_ERROR_INVALID_RESPONSE;
goto destroy;
}
ret = cy_as_ll_request_response__get_word(reply_p, 0);
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
dev_p->mtp_count++;
cy_as_dma_enable_end_point(dev_p, CY_AS_MTP_READ_ENDPOINT,
cy_true, cy_as_direction_out);
dev_p->usb_config[CY_AS_MTP_READ_ENDPOINT].enabled = cy_true;
dev_p->usb_config[CY_AS_MTP_READ_ENDPOINT].dir = cy_as_usb_out;
dev_p->usb_config[CY_AS_MTP_READ_ENDPOINT].type = cy_as_usb_bulk;
cy_as_dma_enable_end_point(dev_p, CY_AS_MTP_WRITE_ENDPOINT,
cy_true, cy_as_direction_in);
dev_p->usb_config[CY_AS_MTP_WRITE_ENDPOINT].enabled = cy_true;
dev_p->usb_config[CY_AS_MTP_WRITE_ENDPOINT].dir = cy_as_usb_in;
dev_p->usb_config[CY_AS_MTP_WRITE_ENDPOINT].type = cy_as_usb_bulk;
/* Packet size is 512 bytes */
cy_as_dma_set_max_dma_size(dev_p, 0x02, 0x0200);
/* Packet size is 64 bytes until a switch to high speed happens.*/
cy_as_dma_set_max_dma_size(dev_p, 0x06, 0x40);
destroy:
cy_as_ll_destroy_request(dev_p, req_p);
cy_as_ll_destroy_response(dev_p, reply_p);
if (ret != CY_AS_ERROR_SUCCESS)
cy_as_ll_register_request_callback(dev_p,
CY_RQT_TUR_RQT_CONTEXT, 0);
cy_as_device_clear_m_s_s_pending(dev_p);
return ret;
}
cy_as_return_status_t
cy_as_mtp_start(cy_as_device_handle handle,
cy_as_mtp_event_callback event_c_b,
cy_as_function_callback cb,
uint32_t client
)
{
cy_as_ll_request_response *req_p, *reply_p;
cy_as_return_status_t ret = CY_AS_ERROR_SUCCESS;
cy_as_device *dev_p;
dev_p = (cy_as_device *)handle;
if (!dev_p || (dev_p->sig != CY_AS_DEVICE_HANDLE_SIGNATURE))
return CY_AS_ERROR_INVALID_HANDLE;
if (!cy_as_device_is_configured(dev_p))
return CY_AS_ERROR_NOT_CONFIGURED;
if (!cy_as_device_is_firmware_loaded(dev_p))
return CY_AS_ERROR_NO_FIRMWARE;
if (cy_as_device_is_in_suspend_mode(dev_p))
return CY_AS_ERROR_IN_SUSPEND;
if (cy_as_device_is_in_callback(dev_p))
return CY_AS_ERROR_INVALID_IN_CALLBACK;
if (cy_as_device_is_m_s_s_pending(dev_p))
return CY_AS_ERROR_STARTSTOP_PENDING;
if (dev_p->storage_count == 0)
return CY_AS_ERROR_NOT_RUNNING;
if (dev_p->usb_count == 0)
return CY_AS_ERROR_NOT_RUNNING;
if (dev_p->is_mtp_firmware == 0)
return CY_AS_ERROR_NOT_SUPPORTED;
cy_as_device_set_m_s_s_pending(dev_p);
if (dev_p->mtp_count == 0) {
dev_p->mtp_event_cb = event_c_b;
/*
* we register here because the start request may cause
* events to occur before the response to the start request.
*/
cy_as_ll_register_request_callback(dev_p,
CY_RQT_TUR_RQT_CONTEXT, my_mtp_request_callback);
/* Create the request to send to the West Bridge device */
req_p = cy_as_ll_create_request(dev_p,
CY_RQT_START_MTP, CY_RQT_TUR_RQT_CONTEXT, 0);
if (req_p == 0) {
cy_as_device_clear_m_s_s_pending(dev_p);
return CY_AS_ERROR_OUT_OF_MEMORY;
}
/* Reserve space for the reply, the reply data will
* not exceed one word */
reply_p = cy_as_ll_create_response(dev_p, 1);
if (reply_p == 0) {
cy_as_ll_destroy_request(dev_p, req_p);
cy_as_device_clear_m_s_s_pending(dev_p);
return CY_AS_ERROR_OUT_OF_MEMORY;
}
if (cb == 0) {
ret = cy_as_ll_send_request_wait_reply(dev_p,
req_p, reply_p);
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
return my_handle_response_mtp_start(dev_p, req_p,
reply_p, ret);
} else {
ret = cy_as_misc_send_request(dev_p, cb, client,
CY_FUNCT_CB_MTP_START, 0, dev_p->func_cbs_mtp,
CY_AS_REQUEST_RESPONSE_EX, req_p, reply_p,
cy_as_mtp_func_callback);
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
return ret;
}
destroy:
cy_as_ll_destroy_request(dev_p, req_p);
cy_as_ll_destroy_response(dev_p, reply_p);
} else {
dev_p->mtp_count++;
if (cb)
cb(handle, ret, client, CY_FUNCT_CB_MTP_START, 0);
}
cy_as_device_clear_m_s_s_pending(dev_p);
return ret;
}
EXPORT_SYMBOL(cy_as_mtp_start);
static cy_as_return_status_t
my_handle_response_mtp_stop(cy_as_device *dev_p,
cy_as_ll_request_response *req_p,
cy_as_ll_request_response *reply_p,
cy_as_return_status_t ret)
{
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
if (cy_as_ll_request_response__get_code(reply_p) !=
CY_RESP_SUCCESS_FAILURE) {
ret = CY_AS_ERROR_INVALID_RESPONSE;
goto destroy;
}
ret = cy_as_ll_request_response__get_word(reply_p, 0);
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
/*
* we successfully shutdown the stack, so decrement
* to make the count zero.
*/
dev_p->mtp_count--;
destroy:
cy_as_ll_destroy_request(dev_p, req_p);
cy_as_ll_destroy_response(dev_p, reply_p);
if (ret != CY_AS_ERROR_SUCCESS)
cy_as_ll_register_request_callback(dev_p,
CY_RQT_TUR_RQT_CONTEXT, 0);
cy_as_device_clear_m_s_s_pending(dev_p);
return ret;
}
cy_as_return_status_t
cy_as_mtp_stop(cy_as_device_handle handle,
cy_as_function_callback cb,
uint32_t client
)
{
cy_as_ll_request_response *req_p = 0, *reply_p = 0;
cy_as_return_status_t ret = CY_AS_ERROR_SUCCESS;
cy_as_device *dev_p;
cy_as_log_debug_message(6, "cy_as_mtp_stop called");
dev_p = (cy_as_device *)handle;
if (!dev_p || (dev_p->sig != CY_AS_DEVICE_HANDLE_SIGNATURE))
return CY_AS_ERROR_INVALID_HANDLE;
ret = is_mtp_active(dev_p);
if (ret != CY_AS_ERROR_SUCCESS)
return ret;
if (cy_as_device_is_in_callback(dev_p))
return CY_AS_ERROR_INVALID_IN_CALLBACK;
if (cy_as_device_is_m_s_s_pending(dev_p))
return CY_AS_ERROR_STARTSTOP_PENDING;
cy_as_device_set_m_s_s_pending(dev_p);
if (dev_p->mtp_count == 1) {
/* Create the request to send to the West
* Bridge device */
req_p = cy_as_ll_create_request(dev_p, CY_RQT_STOP_MTP,
CY_RQT_TUR_RQT_CONTEXT, 0);
if (req_p == 0) {
ret = CY_AS_ERROR_OUT_OF_MEMORY;
goto destroy;
}
/* Reserve space for the reply, the reply data will
* not exceed one word */
reply_p = cy_as_ll_create_response(dev_p, 1);
if (reply_p == 0) {
ret = CY_AS_ERROR_OUT_OF_MEMORY;
goto destroy;
}
if (cb == 0) {
ret = cy_as_ll_send_request_wait_reply(dev_p,
req_p, reply_p);
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
return my_handle_response_mtp_stop(dev_p, req_p,
reply_p, ret);
} else {
ret = cy_as_misc_send_request(dev_p, cb, client,
CY_FUNCT_CB_MTP_STOP, 0, dev_p->func_cbs_mtp,
CY_AS_REQUEST_RESPONSE_EX, req_p, reply_p,
cy_as_mtp_func_callback);
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
return ret;
}
destroy:
cy_as_ll_destroy_request(dev_p, req_p);
cy_as_ll_destroy_response(dev_p, reply_p);
} else if (dev_p->mtp_count > 1) {
dev_p->mtp_count--;
if (cb)
cb(handle, ret, client, CY_FUNCT_CB_MTP_STOP, 0);
}
cy_as_device_clear_m_s_s_pending(dev_p);
return ret;
}
static void
mtp_write_callback(
cy_as_device *dev_p,
uint8_t context,
cy_as_ll_request_response *rqt,
cy_as_ll_request_response *resp,
cy_as_return_status_t ret)
{
cy_as_hal_assert(context == CY_RQT_TUR_RQT_CONTEXT);
if (ret == CY_AS_ERROR_SUCCESS) {
if (cy_as_ll_request_response__get_code(resp) !=
CY_RESP_SUCCESS_FAILURE)
ret = CY_AS_ERROR_INVALID_RESPONSE;
else
ret = cy_as_ll_request_response__get_word(resp, 0);
}
if (ret != CY_AS_ERROR_SUCCESS) {
/* Firmware failed the request. Cancel the DMA transfer. */
cy_as_dma_cancel(dev_p, 0x04, CY_AS_ERROR_CANCELED);
cy_as_device_clear_storage_async_pending(dev_p);
}
cy_as_ll_destroy_response(dev_p, resp);
cy_as_ll_destroy_request(dev_p, rqt);
}
static void
async_write_request_callback(cy_as_device *dev_p,
cy_as_end_point_number_t ep, void *buf_p, uint32_t size,
cy_as_return_status_t err)
{
cy_as_device_handle h;
cy_as_function_callback cb;
(void)size;
(void)buf_p;
(void)ep;
cy_as_log_debug_message(6, "async_write_request_callback called");
h = (cy_as_device_handle)dev_p;
cb = dev_p->mtp_cb;
dev_p->mtp_cb = 0;
cy_as_device_clear_storage_async_pending(dev_p);
if (cb)
cb(h, err, dev_p->mtp_client, dev_p->mtp_op, 0);
}
static void
sync_mtp_callback(cy_as_device *dev_p, cy_as_end_point_number_t ep,
void *buf_p, uint32_t size, cy_as_return_status_t err)
{
(void)ep;
(void)buf_p;
(void)size;
dev_p->mtp_error = err;
}
static cy_as_return_status_t
cy_as_mtp_operation(cy_as_device *dev_p,
cy_as_mtp_block_table *blk_table,
uint32_t num_bytes,
uint32_t transaction_id,
cy_as_function_callback cb,
uint32_t client,
uint8_t rqttype
)
{
cy_as_ll_request_response *req_p = 0, *reply_p = 0;
cy_as_return_status_t ret = CY_AS_ERROR_SUCCESS;
uint32_t mask = 0;
cy_as_funct_c_b_type mtp_cb_op = 0;
uint16_t size = 2;
if (dev_p->mtp_count == 0)
return CY_AS_ERROR_NOT_RUNNING;
if (rqttype == CY_RQT_INIT_SEND_OBJECT) {
mtp_cb_op = CY_FUNCT_CB_MTP_INIT_SEND_OBJECT;
dev_p->mtp_turbo_active = cy_true;
} else if (rqttype == CY_RQT_INIT_GET_OBJECT) {
mtp_cb_op = CY_FUNCT_CB_MTP_INIT_GET_OBJECT;
dev_p->mtp_turbo_active = cy_true;
} else
mtp_cb_op = CY_FUNCT_CB_MTP_SEND_BLOCK_TABLE;
ret = is_mtp_active(dev_p);
if (ret != CY_AS_ERROR_SUCCESS)
return ret;
if (CY_RQT_INIT_GET_OBJECT == rqttype)
size = 4;
/* Create the request to send to the West
* Bridge device */
req_p = cy_as_ll_create_request(dev_p, rqttype,
CY_RQT_TUR_RQT_CONTEXT, size);
if (req_p == 0) {
ret = CY_AS_ERROR_OUT_OF_MEMORY;
goto destroy;
}
/* Reserve space for the reply, the reply data will
* not exceed one word */
reply_p = cy_as_ll_create_response(dev_p, 1);
if (reply_p == 0) {
ret = CY_AS_ERROR_OUT_OF_MEMORY;
goto destroy;
}
cy_as_ll_request_response__set_word(req_p, 0,
(uint16_t)(num_bytes & 0xFFFF));
cy_as_ll_request_response__set_word(req_p, 1,
(uint16_t)((num_bytes >> 16) & 0xFFFF));
/* If it is GET_OBJECT, send transaction id as well*/
if (CY_RQT_INIT_GET_OBJECT == rqttype) {
cy_as_ll_request_response__set_word(req_p, 2,
(uint16_t)(transaction_id & 0xFFFF));
cy_as_ll_request_response__set_word(req_p, 3,
(uint16_t)((transaction_id >> 16) & 0xFFFF));
}
if (cb == 0) {
/* Queue the DMA request for block table write */
ret = cy_as_dma_queue_request(dev_p, 4, blk_table,
sizeof(cy_as_mtp_block_table), cy_false,
cy_false, sync_mtp_callback);
ret = cy_as_ll_send_request_wait_reply(dev_p,
req_p, reply_p);
if (ret != CY_AS_ERROR_SUCCESS) {
cy_as_dma_cancel(dev_p, 4, CY_AS_ERROR_CANCELED);
cy_as_device_clear_storage_async_pending(dev_p);
goto destroy;
}
ret = cy_as_dma_drain_queue(dev_p, 4, cy_true);
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
ret = dev_p->mtp_error;
goto destroy;
} else {
#if 0
ret = cy_as_misc_send_request(dev_p, cb, client,
CY_FUNCT_CB_MTP_INIT_SEND_OBJECT,
0, dev_p->func_cbs_mtp, CY_AS_REQUEST_RESPONSE_EX,
req_p, reply_p, cy_as_mtp_func_callback);
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
#endif
/* Protection from interrupt driven code */
/* since we are using storage EP4 check if any
* storage activity is pending */
mask = cy_as_hal_disable_interrupts();
if ((cy_as_device_is_storage_async_pending(dev_p)) ||
(dev_p->storage_wait)) {
cy_as_hal_enable_interrupts(mask);
return CY_AS_ERROR_ASYNC_PENDING;
}
cy_as_device_set_storage_async_pending(dev_p);
cy_as_hal_enable_interrupts(mask);
dev_p->mtp_cb = cb;
dev_p->mtp_client = client;
dev_p->mtp_op = mtp_cb_op;
ret = cy_as_ll_send_request(dev_p, req_p, reply_p,
cy_false, mtp_write_callback);
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
ret = cy_as_dma_queue_request(dev_p, 4, blk_table,
sizeof(cy_as_mtp_block_table), cy_false, cy_false,
async_write_request_callback);
if (ret != CY_AS_ERROR_SUCCESS)
return ret;
/* Kick start the queue if it is not running */
cy_as_dma_kick_start(dev_p, 4);
return CY_AS_ERROR_SUCCESS;
}
destroy:
cy_as_ll_destroy_request(dev_p, req_p);
cy_as_ll_destroy_response(dev_p, reply_p);
return ret;
}
cy_as_return_status_t
cy_as_mtp_init_send_object(cy_as_device_handle handle,
cy_as_mtp_block_table *blk_table,
uint32_t num_bytes,
cy_as_function_callback cb,
uint32_t client
)
{
cy_as_device *dev_p;
dev_p = (cy_as_device *)handle;
if (!dev_p || (dev_p->sig != CY_AS_DEVICE_HANDLE_SIGNATURE))
return CY_AS_ERROR_INVALID_HANDLE;
return cy_as_mtp_operation(dev_p, blk_table, num_bytes, 0, cb,
client, CY_RQT_INIT_SEND_OBJECT);
}
EXPORT_SYMBOL(cy_as_mtp_init_send_object);
cy_as_return_status_t
cy_as_mtp_init_get_object(cy_as_device_handle handle,
cy_as_mtp_block_table *blk_table,
uint32_t num_bytes,
uint32_t transaction_id,
cy_as_function_callback cb,
uint32_t client
)
{
cy_as_device *dev_p;
dev_p = (cy_as_device *)handle;
if (!dev_p || (dev_p->sig != CY_AS_DEVICE_HANDLE_SIGNATURE))
return CY_AS_ERROR_INVALID_HANDLE;
return cy_as_mtp_operation(dev_p, blk_table, num_bytes,
transaction_id, cb, client, CY_RQT_INIT_GET_OBJECT);
}
EXPORT_SYMBOL(cy_as_mtp_init_get_object);
static cy_as_return_status_t
my_handle_response_cancel_send_object(cy_as_device *dev_p,
cy_as_ll_request_response *req_p,
cy_as_ll_request_response *reply_p,
cy_as_return_status_t ret)
{
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
if (cy_as_ll_request_response__get_code(reply_p) !=
CY_RESP_SUCCESS_FAILURE) {
ret = CY_AS_ERROR_INVALID_RESPONSE;
goto destroy;
}
ret = cy_as_ll_request_response__get_word(reply_p, 0);
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
destroy:
cy_as_ll_destroy_request(dev_p, req_p);
cy_as_ll_destroy_response(dev_p, reply_p);
return ret;
}
cy_as_return_status_t
cy_as_mtp_cancel_send_object(cy_as_device_handle handle,
cy_as_function_callback cb,
uint32_t client
)
{
cy_as_ll_request_response *req_p = 0, *reply_p = 0;
cy_as_return_status_t ret = CY_AS_ERROR_SUCCESS;
cy_as_device *dev_p;
dev_p = (cy_as_device *)handle;
if (!dev_p || (dev_p->sig != CY_AS_DEVICE_HANDLE_SIGNATURE))
return CY_AS_ERROR_INVALID_HANDLE;
if (dev_p->mtp_count == 0)
return CY_AS_ERROR_NOT_RUNNING;
/* Create the request to send to the West Bridge device */
req_p = cy_as_ll_create_request(dev_p,
CY_RQT_CANCEL_SEND_OBJECT, CY_RQT_TUR_RQT_CONTEXT, 0);
if (req_p == 0) {
ret = CY_AS_ERROR_OUT_OF_MEMORY;
goto destroy;
}
/* Reserve space for the reply, the reply data will
* not exceed one word */
reply_p = cy_as_ll_create_response(dev_p, 1);
if (reply_p == 0) {
ret = CY_AS_ERROR_OUT_OF_MEMORY;
goto destroy;
}
if (cb == 0) {
ret = cy_as_ll_send_request_wait_reply(dev_p,
req_p, reply_p);
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
return my_handle_response_cancel_send_object(dev_p,
req_p, reply_p, ret);
} else {
ret = cy_as_misc_send_request(dev_p, cb, client,
CY_FUNCT_CB_MTP_CANCEL_SEND_OBJECT, 0,
dev_p->func_cbs_mtp, CY_AS_REQUEST_RESPONSE_EX,
req_p, reply_p, cy_as_mtp_func_callback);
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
return ret;
}
destroy:
cy_as_ll_destroy_request(dev_p, req_p);
cy_as_ll_destroy_response(dev_p, reply_p);
return ret;
}
EXPORT_SYMBOL(cy_as_mtp_cancel_send_object);
static cy_as_return_status_t
my_handle_response_cancel_get_object(cy_as_device *dev_p,
cy_as_ll_request_response *req_p,
cy_as_ll_request_response *reply_p,
cy_as_return_status_t ret)
{
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
if (cy_as_ll_request_response__get_code(reply_p) !=
CY_RESP_SUCCESS_FAILURE) {
ret = CY_AS_ERROR_INVALID_RESPONSE;
goto destroy;
}
ret = cy_as_ll_request_response__get_word(reply_p, 0);
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
destroy:
cy_as_ll_destroy_request(dev_p, req_p);
cy_as_ll_destroy_response(dev_p, reply_p);
return ret;
}
cy_as_return_status_t
cy_as_mtp_cancel_get_object(cy_as_device_handle handle,
cy_as_function_callback cb,
uint32_t client
)
{
cy_as_ll_request_response *req_p = 0, *reply_p = 0;
cy_as_return_status_t ret = CY_AS_ERROR_SUCCESS;
cy_as_device *dev_p;
dev_p = (cy_as_device *)handle;
if (!dev_p || (dev_p->sig != CY_AS_DEVICE_HANDLE_SIGNATURE))
return CY_AS_ERROR_INVALID_HANDLE;
if (dev_p->mtp_count == 0)
return CY_AS_ERROR_NOT_RUNNING;
/* Create the request to send to the West Bridge device */
req_p = cy_as_ll_create_request(dev_p, CY_RQT_CANCEL_GET_OBJECT,
CY_RQT_TUR_RQT_CONTEXT, 0);
if (req_p == 0) {
ret = CY_AS_ERROR_OUT_OF_MEMORY;
goto destroy;
}
/* Reserve space for the reply, the reply data will
* not exceed one word */
reply_p = cy_as_ll_create_response(dev_p, 1);
if (reply_p == 0) {
ret = CY_AS_ERROR_OUT_OF_MEMORY;
goto destroy;
}
if (cb == 0) {
ret = cy_as_ll_send_request_wait_reply(dev_p,
req_p, reply_p);
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
return my_handle_response_cancel_get_object(dev_p,
req_p, reply_p, ret);
} else {
ret = cy_as_misc_send_request(dev_p, cb, client,
CY_FUNCT_CB_MTP_CANCEL_GET_OBJECT, 0,
dev_p->func_cbs_mtp, CY_AS_REQUEST_RESPONSE_EX,
req_p, reply_p, cy_as_mtp_func_callback);
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
return ret;
}
destroy:
cy_as_ll_destroy_request(dev_p, req_p);
cy_as_ll_destroy_response(dev_p, reply_p);
return ret;
}
EXPORT_SYMBOL(cy_as_mtp_cancel_get_object);
cy_as_return_status_t
cy_as_mtp_send_block_table(cy_as_device_handle handle,
cy_as_mtp_block_table *blk_table,
cy_as_function_callback cb,
uint32_t client)
{
cy_as_device *dev_p;
dev_p = (cy_as_device *)handle;
if (!dev_p || (dev_p->sig != CY_AS_DEVICE_HANDLE_SIGNATURE))
return CY_AS_ERROR_INVALID_HANDLE;
return cy_as_mtp_operation(dev_p, blk_table, 0, 0, cb,
client, CY_RQT_SEND_BLOCK_TABLE);
}
static void
cy_as_mtp_func_callback(cy_as_device *dev_p,
uint8_t context,
cy_as_ll_request_response *rqt,
cy_as_ll_request_response *resp,
cy_as_return_status_t stat)
{
cy_as_func_c_b_node* node = (cy_as_func_c_b_node *)
dev_p->func_cbs_mtp->head_p;
cy_as_return_status_t ret = CY_AS_ERROR_SUCCESS;
uint8_t code;
cy_bool delay_callback = cy_false;
cy_as_hal_assert(dev_p->func_cbs_mtp->count != 0);
cy_as_hal_assert(dev_p->func_cbs_mtp->type == CYAS_FUNC_CB);
(void)context;
/* The Handlers are responsible for Deleting the
* rqt and resp when they are finished
*/
code = cy_as_ll_request_response__get_code(rqt);
switch (code) {
case CY_RQT_START_MTP:
ret = my_handle_response_mtp_start(dev_p, rqt,
resp, stat);
break;
case CY_RQT_STOP_MTP:
ret = my_handle_response_mtp_stop(dev_p, rqt,
resp, stat);
break;
#if 0
case CY_RQT_INIT_SEND_OBJECT:
ret = my_handle_response_init_send_object(dev_p,
rqt, resp, stat, cy_true);
delay_callback = cy_true;
break;
#endif
case CY_RQT_CANCEL_SEND_OBJECT:
ret = my_handle_response_cancel_send_object(dev_p,
rqt, resp, stat);
break;
#if 0
case CY_RQT_INIT_GET_OBJECT:
ret = my_handle_response_init_get_object(dev_p,
rqt, resp, stat, cy_true);
delay_callback = cy_true;
break;
#endif
case CY_RQT_CANCEL_GET_OBJECT:
ret = my_handle_response_cancel_get_object(dev_p,
rqt, resp, stat);
break;
#if 0
case CY_RQT_SEND_BLOCK_TABLE:
ret = my_handle_response_send_block_table(dev_p, rqt,
resp, stat, cy_true);
delay_callback = cy_true;
break;
#endif
case CY_RQT_ENABLE_USB_PATH:
ret = my_handle_response_no_data(dev_p, rqt, resp);
if (ret == CY_AS_ERROR_SUCCESS)
dev_p->is_storage_only_mode = cy_false;
break;
default:
ret = CY_AS_ERROR_INVALID_RESPONSE;
cy_as_hal_assert(cy_false);
break;
}
/*
* if the low level layer returns a direct error, use the
* corresponding error code. if not, use the error code
* based on the response from firmware.
*/
if (stat == CY_AS_ERROR_SUCCESS)
stat = ret;
if (!delay_callback) {
node->cb_p((cy_as_device_handle)dev_p, stat, node->client_data,
node->data_type, node->data);
cy_as_remove_c_b_node(dev_p->func_cbs_mtp);
}
}
cy_as_return_status_t
cy_as_mtp_storage_only_start(cy_as_device_handle handle)
{
cy_as_device *dev_p = (cy_as_device *)handle;
if (!dev_p || (dev_p->sig != CY_AS_DEVICE_HANDLE_SIGNATURE))
return CY_AS_ERROR_INVALID_HANDLE;
if (!cy_as_device_is_configured(dev_p))
return CY_AS_ERROR_NOT_CONFIGURED;
if (!cy_as_device_is_firmware_loaded(dev_p))
return CY_AS_ERROR_NO_FIRMWARE;
if (dev_p->storage_count == 0)
return CY_AS_ERROR_NOT_RUNNING;
dev_p->is_storage_only_mode = cy_true;
return CY_AS_ERROR_SUCCESS;
}
EXPORT_SYMBOL(cy_as_mtp_storage_only_start);
cy_as_return_status_t
cy_as_mtp_storage_only_stop(cy_as_device_handle handle,
cy_as_function_callback cb,
uint32_t client)
{
cy_as_device *dev_p = (cy_as_device *)handle;
cy_as_ll_request_response *req_p, *reply_p;
cy_as_return_status_t ret = CY_AS_ERROR_SUCCESS;
if (!dev_p || (dev_p->sig != CY_AS_DEVICE_HANDLE_SIGNATURE))
return CY_AS_ERROR_INVALID_HANDLE;
if (!cy_as_device_is_configured(dev_p))
return CY_AS_ERROR_NOT_CONFIGURED;
if (!cy_as_device_is_firmware_loaded(dev_p))
return CY_AS_ERROR_NO_FIRMWARE;
if (dev_p->storage_count == 0)
return CY_AS_ERROR_NOT_RUNNING;
if (dev_p->is_storage_only_mode == cy_false)
return CY_AS_ERROR_SUCCESS;
if (cy_as_device_is_in_callback(dev_p))
return CY_AS_ERROR_INVALID_IN_CALLBACK;
req_p = cy_as_ll_create_request(dev_p,
CY_RQT_ENABLE_USB_PATH, CY_RQT_TUR_RQT_CONTEXT, 1);
if (req_p == 0)
return CY_AS_ERROR_OUT_OF_MEMORY;
reply_p = cy_as_ll_create_response(dev_p, 1);
if (reply_p == 0) {
cy_as_ll_destroy_request(dev_p, req_p);
return CY_AS_ERROR_OUT_OF_MEMORY;
}
if (cb == 0) {
ret = cy_as_ll_send_request_wait_reply(dev_p,
req_p, reply_p);
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
ret = my_handle_response_no_data(dev_p, req_p,
reply_p);
if (ret == CY_AS_ERROR_SUCCESS)
dev_p->is_storage_only_mode = cy_false;
return ret;
} else {
ret = cy_as_misc_send_request(dev_p, cb, client,
CY_FUNCT_CB_MTP_STOP_STORAGE_ONLY, 0,
dev_p->func_cbs_mtp, CY_AS_REQUEST_RESPONSE_EX,
req_p, reply_p, cy_as_mtp_func_callback);
if (ret != CY_AS_ERROR_SUCCESS)
goto destroy;
return ret;
}
destroy:
cy_as_ll_destroy_request(dev_p, req_p);
cy_as_ll_destroy_response(dev_p, reply_p);
return ret;
}
EXPORT_SYMBOL(cy_as_mtp_storage_only_stop);
| gpl-2.0 |
corphish/zapdos_mint | drivers/media/video/ov9640.c | 2536 | 20346 | /*
* OmniVision OV96xx Camera Driver
*
* Copyright (C) 2009 Marek Vasut <marek.vasut@gmail.com>
*
* Based on ov772x camera driver:
*
* Copyright (C) 2008 Renesas Solutions Corp.
* Kuninori Morimoto <morimoto.kuninori@renesas.com>
*
* Based on ov7670 and soc_camera_platform driver,
*
* Copyright 2006-7 Jonathan Corbet <corbet@lwn.net>
* Copyright (C) 2008 Magnus Damm
* Copyright (C) 2008, Guennadi Liakhovetski <kernel@pengutronix.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/videodev2.h>
#include <media/v4l2-chip-ident.h>
#include <media/v4l2-common.h>
#include <media/soc_camera.h>
#include "ov9640.h"
#define to_ov9640_sensor(sd) container_of(sd, struct ov9640_priv, subdev)
/* default register setup */
static const struct ov9640_reg ov9640_regs_dflt[] = {
{ OV9640_COM5, OV9640_COM5_SYSCLK | OV9640_COM5_LONGEXP },
{ OV9640_COM6, OV9640_COM6_OPT_BLC | OV9640_COM6_ADBLC_BIAS |
OV9640_COM6_FMT_RST | OV9640_COM6_ADBLC_OPTEN },
{ OV9640_PSHFT, OV9640_PSHFT_VAL(0x01) },
{ OV9640_ACOM, OV9640_ACOM_2X_ANALOG | OV9640_ACOM_RSVD },
{ OV9640_TSLB, OV9640_TSLB_YUYV_UYVY },
{ OV9640_COM16, OV9640_COM16_RB_AVG },
/* Gamma curve P */
{ 0x6c, 0x40 }, { 0x6d, 0x30 }, { 0x6e, 0x4b }, { 0x6f, 0x60 },
{ 0x70, 0x70 }, { 0x71, 0x70 }, { 0x72, 0x70 }, { 0x73, 0x70 },
{ 0x74, 0x60 }, { 0x75, 0x60 }, { 0x76, 0x50 }, { 0x77, 0x48 },
{ 0x78, 0x3a }, { 0x79, 0x2e }, { 0x7a, 0x28 }, { 0x7b, 0x22 },
/* Gamma curve T */
{ 0x7c, 0x04 }, { 0x7d, 0x07 }, { 0x7e, 0x10 }, { 0x7f, 0x28 },
{ 0x80, 0x36 }, { 0x81, 0x44 }, { 0x82, 0x52 }, { 0x83, 0x60 },
{ 0x84, 0x6c }, { 0x85, 0x78 }, { 0x86, 0x8c }, { 0x87, 0x9e },
{ 0x88, 0xbb }, { 0x89, 0xd2 }, { 0x8a, 0xe6 },
};
/* Configurations
* NOTE: for YUV, alter the following registers:
* COM12 |= OV9640_COM12_YUV_AVG
*
* for RGB, alter the following registers:
* COM7 |= OV9640_COM7_RGB
* COM13 |= OV9640_COM13_RGB_AVG
* COM15 |= proper RGB color encoding mode
*/
static const struct ov9640_reg ov9640_regs_qqcif[] = {
{ OV9640_CLKRC, OV9640_CLKRC_DPLL_EN | OV9640_CLKRC_DIV(0x0f) },
{ OV9640_COM1, OV9640_COM1_QQFMT | OV9640_COM1_HREF_2SKIP },
{ OV9640_COM4, OV9640_COM4_QQ_VP | OV9640_COM4_RSVD },
{ OV9640_COM7, OV9640_COM7_QCIF },
{ OV9640_COM12, OV9640_COM12_RSVD },
{ OV9640_COM13, OV9640_COM13_GAMMA_RAW | OV9640_COM13_MATRIX_EN },
{ OV9640_COM15, OV9640_COM15_OR_10F0 },
};
static const struct ov9640_reg ov9640_regs_qqvga[] = {
{ OV9640_CLKRC, OV9640_CLKRC_DPLL_EN | OV9640_CLKRC_DIV(0x07) },
{ OV9640_COM1, OV9640_COM1_QQFMT | OV9640_COM1_HREF_2SKIP },
{ OV9640_COM4, OV9640_COM4_QQ_VP | OV9640_COM4_RSVD },
{ OV9640_COM7, OV9640_COM7_QVGA },
{ OV9640_COM12, OV9640_COM12_RSVD },
{ OV9640_COM13, OV9640_COM13_GAMMA_RAW | OV9640_COM13_MATRIX_EN },
{ OV9640_COM15, OV9640_COM15_OR_10F0 },
};
static const struct ov9640_reg ov9640_regs_qcif[] = {
{ OV9640_CLKRC, OV9640_CLKRC_DPLL_EN | OV9640_CLKRC_DIV(0x07) },
{ OV9640_COM4, OV9640_COM4_QQ_VP | OV9640_COM4_RSVD },
{ OV9640_COM7, OV9640_COM7_QCIF },
{ OV9640_COM12, OV9640_COM12_RSVD },
{ OV9640_COM13, OV9640_COM13_GAMMA_RAW | OV9640_COM13_MATRIX_EN },
{ OV9640_COM15, OV9640_COM15_OR_10F0 },
};
static const struct ov9640_reg ov9640_regs_qvga[] = {
{ OV9640_CLKRC, OV9640_CLKRC_DPLL_EN | OV9640_CLKRC_DIV(0x03) },
{ OV9640_COM4, OV9640_COM4_QQ_VP | OV9640_COM4_RSVD },
{ OV9640_COM7, OV9640_COM7_QVGA },
{ OV9640_COM12, OV9640_COM12_RSVD },
{ OV9640_COM13, OV9640_COM13_GAMMA_RAW | OV9640_COM13_MATRIX_EN },
{ OV9640_COM15, OV9640_COM15_OR_10F0 },
};
static const struct ov9640_reg ov9640_regs_cif[] = {
{ OV9640_CLKRC, OV9640_CLKRC_DPLL_EN | OV9640_CLKRC_DIV(0x03) },
{ OV9640_COM3, OV9640_COM3_VP },
{ OV9640_COM7, OV9640_COM7_CIF },
{ OV9640_COM12, OV9640_COM12_RSVD },
{ OV9640_COM13, OV9640_COM13_GAMMA_RAW | OV9640_COM13_MATRIX_EN },
{ OV9640_COM15, OV9640_COM15_OR_10F0 },
};
static const struct ov9640_reg ov9640_regs_vga[] = {
{ OV9640_CLKRC, OV9640_CLKRC_DPLL_EN | OV9640_CLKRC_DIV(0x01) },
{ OV9640_COM3, OV9640_COM3_VP },
{ OV9640_COM7, OV9640_COM7_VGA },
{ OV9640_COM12, OV9640_COM12_RSVD },
{ OV9640_COM13, OV9640_COM13_GAMMA_RAW | OV9640_COM13_MATRIX_EN },
{ OV9640_COM15, OV9640_COM15_OR_10F0 },
};
static const struct ov9640_reg ov9640_regs_sxga[] = {
{ OV9640_CLKRC, OV9640_CLKRC_DPLL_EN | OV9640_CLKRC_DIV(0x01) },
{ OV9640_COM3, OV9640_COM3_VP },
{ OV9640_COM7, 0 },
{ OV9640_COM12, OV9640_COM12_RSVD },
{ OV9640_COM13, OV9640_COM13_GAMMA_RAW | OV9640_COM13_MATRIX_EN },
{ OV9640_COM15, OV9640_COM15_OR_10F0 },
};
static const struct ov9640_reg ov9640_regs_yuv[] = {
{ OV9640_MTX1, 0x58 },
{ OV9640_MTX2, 0x48 },
{ OV9640_MTX3, 0x10 },
{ OV9640_MTX4, 0x28 },
{ OV9640_MTX5, 0x48 },
{ OV9640_MTX6, 0x70 },
{ OV9640_MTX7, 0x40 },
{ OV9640_MTX8, 0x40 },
{ OV9640_MTX9, 0x40 },
{ OV9640_MTXS, 0x0f },
};
static const struct ov9640_reg ov9640_regs_rgb[] = {
{ OV9640_MTX1, 0x71 },
{ OV9640_MTX2, 0x3e },
{ OV9640_MTX3, 0x0c },
{ OV9640_MTX4, 0x33 },
{ OV9640_MTX5, 0x72 },
{ OV9640_MTX6, 0x00 },
{ OV9640_MTX7, 0x2b },
{ OV9640_MTX8, 0x66 },
{ OV9640_MTX9, 0xd2 },
{ OV9640_MTXS, 0x65 },
};
static enum v4l2_mbus_pixelcode ov9640_codes[] = {
V4L2_MBUS_FMT_UYVY8_2X8,
V4L2_MBUS_FMT_RGB555_2X8_PADHI_LE,
V4L2_MBUS_FMT_RGB565_2X8_LE,
};
static const struct v4l2_queryctrl ov9640_controls[] = {
{
.id = V4L2_CID_VFLIP,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Flip Vertically",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 0,
},
{
.id = V4L2_CID_HFLIP,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Flip Horizontally",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 0,
},
};
/* read a register */
static int ov9640_reg_read(struct i2c_client *client, u8 reg, u8 *val)
{
int ret;
u8 data = reg;
struct i2c_msg msg = {
.addr = client->addr,
.flags = 0,
.len = 1,
.buf = &data,
};
ret = i2c_transfer(client->adapter, &msg, 1);
if (ret < 0)
goto err;
msg.flags = I2C_M_RD;
ret = i2c_transfer(client->adapter, &msg, 1);
if (ret < 0)
goto err;
*val = data;
return 0;
err:
dev_err(&client->dev, "Failed reading register 0x%02x!\n", reg);
return ret;
}
/* write a register */
static int ov9640_reg_write(struct i2c_client *client, u8 reg, u8 val)
{
int ret;
u8 _val;
unsigned char data[2] = { reg, val };
struct i2c_msg msg = {
.addr = client->addr,
.flags = 0,
.len = 2,
.buf = data,
};
ret = i2c_transfer(client->adapter, &msg, 1);
if (ret < 0) {
dev_err(&client->dev, "Failed writing register 0x%02x!\n", reg);
return ret;
}
/* we have to read the register back ... no idea why, maybe HW bug */
ret = ov9640_reg_read(client, reg, &_val);
if (ret)
dev_err(&client->dev,
"Failed reading back register 0x%02x!\n", reg);
return 0;
}
/* Read a register, alter its bits, write it back */
static int ov9640_reg_rmw(struct i2c_client *client, u8 reg, u8 set, u8 unset)
{
u8 val;
int ret;
ret = ov9640_reg_read(client, reg, &val);
if (ret) {
dev_err(&client->dev,
"[Read]-Modify-Write of register %02x failed!\n", reg);
return val;
}
val |= set;
val &= ~unset;
ret = ov9640_reg_write(client, reg, val);
if (ret)
dev_err(&client->dev,
"Read-Modify-[Write] of register %02x failed!\n", reg);
return ret;
}
/* Soft reset the camera. This has nothing to do with the RESET pin! */
static int ov9640_reset(struct i2c_client *client)
{
int ret;
ret = ov9640_reg_write(client, OV9640_COM7, OV9640_COM7_SCCB_RESET);
if (ret)
dev_err(&client->dev,
"An error occurred while entering soft reset!\n");
return ret;
}
/* Start/Stop streaming from the device */
static int ov9640_s_stream(struct v4l2_subdev *sd, int enable)
{
return 0;
}
/* Alter bus settings on camera side */
static int ov9640_set_bus_param(struct soc_camera_device *icd,
unsigned long flags)
{
return 0;
}
/* Request bus settings on camera side */
static unsigned long ov9640_query_bus_param(struct soc_camera_device *icd)
{
struct soc_camera_link *icl = to_soc_camera_link(icd);
/*
* REVISIT: the camera probably can do 10 bit transfers, but I don't
* have those pins connected on my hardware.
*/
unsigned long flags = SOCAM_PCLK_SAMPLE_RISING | SOCAM_MASTER |
SOCAM_VSYNC_ACTIVE_HIGH | SOCAM_HSYNC_ACTIVE_HIGH |
SOCAM_DATA_ACTIVE_HIGH | SOCAM_DATAWIDTH_8;
return soc_camera_apply_sensor_flags(icl, flags);
}
/* Get status of additional camera capabilities */
static int ov9640_g_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl)
{
struct ov9640_priv *priv = to_ov9640_sensor(sd);
switch (ctrl->id) {
case V4L2_CID_VFLIP:
ctrl->value = priv->flag_vflip;
break;
case V4L2_CID_HFLIP:
ctrl->value = priv->flag_hflip;
break;
}
return 0;
}
/* Set status of additional camera capabilities */
static int ov9640_s_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct ov9640_priv *priv = to_ov9640_sensor(sd);
int ret = 0;
switch (ctrl->id) {
case V4L2_CID_VFLIP:
priv->flag_vflip = ctrl->value;
if (ctrl->value)
ret = ov9640_reg_rmw(client, OV9640_MVFP,
OV9640_MVFP_V, 0);
else
ret = ov9640_reg_rmw(client, OV9640_MVFP,
0, OV9640_MVFP_V);
break;
case V4L2_CID_HFLIP:
priv->flag_hflip = ctrl->value;
if (ctrl->value)
ret = ov9640_reg_rmw(client, OV9640_MVFP,
OV9640_MVFP_H, 0);
else
ret = ov9640_reg_rmw(client, OV9640_MVFP,
0, OV9640_MVFP_H);
break;
}
return ret;
}
/* Get chip identification */
static int ov9640_g_chip_ident(struct v4l2_subdev *sd,
struct v4l2_dbg_chip_ident *id)
{
struct ov9640_priv *priv = to_ov9640_sensor(sd);
id->ident = priv->model;
id->revision = priv->revision;
return 0;
}
#ifdef CONFIG_VIDEO_ADV_DEBUG
static int ov9640_get_register(struct v4l2_subdev *sd,
struct v4l2_dbg_register *reg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
int ret;
u8 val;
if (reg->reg & ~0xff)
return -EINVAL;
reg->size = 1;
ret = ov9640_reg_read(client, reg->reg, &val);
if (ret)
return ret;
reg->val = (__u64)val;
return 0;
}
static int ov9640_set_register(struct v4l2_subdev *sd,
struct v4l2_dbg_register *reg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
if (reg->reg & ~0xff || reg->val & ~0xff)
return -EINVAL;
return ov9640_reg_write(client, reg->reg, reg->val);
}
#endif
/* select nearest higher resolution for capture */
static void ov9640_res_roundup(u32 *width, u32 *height)
{
int i;
enum { QQCIF, QQVGA, QCIF, QVGA, CIF, VGA, SXGA };
int res_x[] = { 88, 160, 176, 320, 352, 640, 1280 };
int res_y[] = { 72, 120, 144, 240, 288, 480, 960 };
for (i = 0; i < ARRAY_SIZE(res_x); i++) {
if (res_x[i] >= *width && res_y[i] >= *height) {
*width = res_x[i];
*height = res_y[i];
return;
}
}
*width = res_x[SXGA];
*height = res_y[SXGA];
}
/* Prepare necessary register changes depending on color encoding */
static void ov9640_alter_regs(enum v4l2_mbus_pixelcode code,
struct ov9640_reg_alt *alt)
{
switch (code) {
default:
case V4L2_MBUS_FMT_UYVY8_2X8:
alt->com12 = OV9640_COM12_YUV_AVG;
alt->com13 = OV9640_COM13_Y_DELAY_EN |
OV9640_COM13_YUV_DLY(0x01);
break;
case V4L2_MBUS_FMT_RGB555_2X8_PADHI_LE:
alt->com7 = OV9640_COM7_RGB;
alt->com13 = OV9640_COM13_RGB_AVG;
alt->com15 = OV9640_COM15_RGB_555;
break;
case V4L2_MBUS_FMT_RGB565_2X8_LE:
alt->com7 = OV9640_COM7_RGB;
alt->com13 = OV9640_COM13_RGB_AVG;
alt->com15 = OV9640_COM15_RGB_565;
break;
};
}
/* Setup registers according to resolution and color encoding */
static int ov9640_write_regs(struct i2c_client *client, u32 width,
enum v4l2_mbus_pixelcode code, struct ov9640_reg_alt *alts)
{
const struct ov9640_reg *ov9640_regs, *matrix_regs;
int ov9640_regs_len, matrix_regs_len;
int i, ret;
u8 val;
/* select register configuration for given resolution */
switch (width) {
case W_QQCIF:
ov9640_regs = ov9640_regs_qqcif;
ov9640_regs_len = ARRAY_SIZE(ov9640_regs_qqcif);
break;
case W_QQVGA:
ov9640_regs = ov9640_regs_qqvga;
ov9640_regs_len = ARRAY_SIZE(ov9640_regs_qqvga);
break;
case W_QCIF:
ov9640_regs = ov9640_regs_qcif;
ov9640_regs_len = ARRAY_SIZE(ov9640_regs_qcif);
break;
case W_QVGA:
ov9640_regs = ov9640_regs_qvga;
ov9640_regs_len = ARRAY_SIZE(ov9640_regs_qvga);
break;
case W_CIF:
ov9640_regs = ov9640_regs_cif;
ov9640_regs_len = ARRAY_SIZE(ov9640_regs_cif);
break;
case W_VGA:
ov9640_regs = ov9640_regs_vga;
ov9640_regs_len = ARRAY_SIZE(ov9640_regs_vga);
break;
case W_SXGA:
ov9640_regs = ov9640_regs_sxga;
ov9640_regs_len = ARRAY_SIZE(ov9640_regs_sxga);
break;
default:
dev_err(&client->dev, "Failed to select resolution!\n");
return -EINVAL;
}
/* select color matrix configuration for given color encoding */
if (code == V4L2_MBUS_FMT_UYVY8_2X8) {
matrix_regs = ov9640_regs_yuv;
matrix_regs_len = ARRAY_SIZE(ov9640_regs_yuv);
} else {
matrix_regs = ov9640_regs_rgb;
matrix_regs_len = ARRAY_SIZE(ov9640_regs_rgb);
}
/* write register settings into the module */
for (i = 0; i < ov9640_regs_len; i++) {
val = ov9640_regs[i].val;
switch (ov9640_regs[i].reg) {
case OV9640_COM7:
val |= alts->com7;
break;
case OV9640_COM12:
val |= alts->com12;
break;
case OV9640_COM13:
val |= alts->com13;
break;
case OV9640_COM15:
val |= alts->com15;
break;
}
ret = ov9640_reg_write(client, ov9640_regs[i].reg, val);
if (ret)
return ret;
}
/* write color matrix configuration into the module */
for (i = 0; i < matrix_regs_len; i++) {
ret = ov9640_reg_write(client, matrix_regs[i].reg,
matrix_regs[i].val);
if (ret)
return ret;
}
return 0;
}
/* program default register values */
static int ov9640_prog_dflt(struct i2c_client *client)
{
int i, ret;
for (i = 0; i < ARRAY_SIZE(ov9640_regs_dflt); i++) {
ret = ov9640_reg_write(client, ov9640_regs_dflt[i].reg,
ov9640_regs_dflt[i].val);
if (ret)
return ret;
}
/* wait for the changes to actually happen, 140ms are not enough yet */
mdelay(150);
return 0;
}
/* set the format we will capture in */
static int ov9640_s_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct ov9640_reg_alt alts = {0};
enum v4l2_colorspace cspace;
enum v4l2_mbus_pixelcode code = mf->code;
int ret;
ov9640_res_roundup(&mf->width, &mf->height);
ov9640_alter_regs(mf->code, &alts);
ov9640_reset(client);
ret = ov9640_prog_dflt(client);
if (ret)
return ret;
switch (code) {
case V4L2_MBUS_FMT_RGB555_2X8_PADHI_LE:
case V4L2_MBUS_FMT_RGB565_2X8_LE:
cspace = V4L2_COLORSPACE_SRGB;
break;
default:
code = V4L2_MBUS_FMT_UYVY8_2X8;
case V4L2_MBUS_FMT_UYVY8_2X8:
cspace = V4L2_COLORSPACE_JPEG;
}
ret = ov9640_write_regs(client, mf->width, code, &alts);
if (!ret) {
mf->code = code;
mf->colorspace = cspace;
}
return ret;
}
static int ov9640_try_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
ov9640_res_roundup(&mf->width, &mf->height);
mf->field = V4L2_FIELD_NONE;
switch (mf->code) {
case V4L2_MBUS_FMT_RGB555_2X8_PADHI_LE:
case V4L2_MBUS_FMT_RGB565_2X8_LE:
mf->colorspace = V4L2_COLORSPACE_SRGB;
break;
default:
mf->code = V4L2_MBUS_FMT_UYVY8_2X8;
case V4L2_MBUS_FMT_UYVY8_2X8:
mf->colorspace = V4L2_COLORSPACE_JPEG;
}
return 0;
}
static int ov9640_enum_fmt(struct v4l2_subdev *sd, unsigned int index,
enum v4l2_mbus_pixelcode *code)
{
if (index >= ARRAY_SIZE(ov9640_codes))
return -EINVAL;
*code = ov9640_codes[index];
return 0;
}
static int ov9640_g_crop(struct v4l2_subdev *sd, struct v4l2_crop *a)
{
a->c.left = 0;
a->c.top = 0;
a->c.width = W_SXGA;
a->c.height = H_SXGA;
a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
return 0;
}
static int ov9640_cropcap(struct v4l2_subdev *sd, struct v4l2_cropcap *a)
{
a->bounds.left = 0;
a->bounds.top = 0;
a->bounds.width = W_SXGA;
a->bounds.height = H_SXGA;
a->defrect = a->bounds;
a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
a->pixelaspect.numerator = 1;
a->pixelaspect.denominator = 1;
return 0;
}
static int ov9640_video_probe(struct soc_camera_device *icd,
struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
struct ov9640_priv *priv = to_ov9640_sensor(sd);
u8 pid, ver, midh, midl;
const char *devname;
int ret = 0;
/*
* We must have a parent by now. And it cannot be a wrong one.
* So this entire test is completely redundant.
*/
if (!icd->dev.parent ||
to_soc_camera_host(icd->dev.parent)->nr != icd->iface) {
dev_err(&client->dev, "Parent missing or invalid!\n");
ret = -ENODEV;
goto err;
}
/*
* check and show product ID and manufacturer ID
*/
ret = ov9640_reg_read(client, OV9640_PID, &pid);
if (ret)
goto err;
ret = ov9640_reg_read(client, OV9640_VER, &ver);
if (ret)
goto err;
ret = ov9640_reg_read(client, OV9640_MIDH, &midh);
if (ret)
goto err;
ret = ov9640_reg_read(client, OV9640_MIDL, &midl);
if (ret)
goto err;
switch (VERSION(pid, ver)) {
case OV9640_V2:
devname = "ov9640";
priv->model = V4L2_IDENT_OV9640;
priv->revision = 2;
case OV9640_V3:
devname = "ov9640";
priv->model = V4L2_IDENT_OV9640;
priv->revision = 3;
break;
default:
dev_err(&client->dev, "Product ID error %x:%x\n", pid, ver);
ret = -ENODEV;
goto err;
}
dev_info(&client->dev, "%s Product ID %0x:%0x Manufacturer ID %x:%x\n",
devname, pid, ver, midh, midl);
err:
return ret;
}
static struct soc_camera_ops ov9640_ops = {
.set_bus_param = ov9640_set_bus_param,
.query_bus_param = ov9640_query_bus_param,
.controls = ov9640_controls,
.num_controls = ARRAY_SIZE(ov9640_controls),
};
static struct v4l2_subdev_core_ops ov9640_core_ops = {
.g_ctrl = ov9640_g_ctrl,
.s_ctrl = ov9640_s_ctrl,
.g_chip_ident = ov9640_g_chip_ident,
#ifdef CONFIG_VIDEO_ADV_DEBUG
.g_register = ov9640_get_register,
.s_register = ov9640_set_register,
#endif
};
static struct v4l2_subdev_video_ops ov9640_video_ops = {
.s_stream = ov9640_s_stream,
.s_mbus_fmt = ov9640_s_fmt,
.try_mbus_fmt = ov9640_try_fmt,
.enum_mbus_fmt = ov9640_enum_fmt,
.cropcap = ov9640_cropcap,
.g_crop = ov9640_g_crop,
};
static struct v4l2_subdev_ops ov9640_subdev_ops = {
.core = &ov9640_core_ops,
.video = &ov9640_video_ops,
};
/*
* i2c_driver function
*/
static int ov9640_probe(struct i2c_client *client,
const struct i2c_device_id *did)
{
struct ov9640_priv *priv;
struct soc_camera_device *icd = client->dev.platform_data;
struct soc_camera_link *icl;
int ret;
if (!icd) {
dev_err(&client->dev, "Missing soc-camera data!\n");
return -EINVAL;
}
icl = to_soc_camera_link(icd);
if (!icl) {
dev_err(&client->dev, "Missing platform_data for driver\n");
return -EINVAL;
}
priv = kzalloc(sizeof(struct ov9640_priv), GFP_KERNEL);
if (!priv) {
dev_err(&client->dev,
"Failed to allocate memory for private data!\n");
return -ENOMEM;
}
v4l2_i2c_subdev_init(&priv->subdev, client, &ov9640_subdev_ops);
icd->ops = &ov9640_ops;
ret = ov9640_video_probe(icd, client);
if (ret) {
icd->ops = NULL;
kfree(priv);
}
return ret;
}
static int ov9640_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
struct ov9640_priv *priv = to_ov9640_sensor(sd);
kfree(priv);
return 0;
}
static const struct i2c_device_id ov9640_id[] = {
{ "ov9640", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, ov9640_id);
static struct i2c_driver ov9640_i2c_driver = {
.driver = {
.name = "ov9640",
},
.probe = ov9640_probe,
.remove = ov9640_remove,
.id_table = ov9640_id,
};
static int __init ov9640_module_init(void)
{
return i2c_add_driver(&ov9640_i2c_driver);
}
static void __exit ov9640_module_exit(void)
{
i2c_del_driver(&ov9640_i2c_driver);
}
module_init(ov9640_module_init);
module_exit(ov9640_module_exit);
MODULE_DESCRIPTION("SoC Camera driver for OmniVision OV96xx");
MODULE_AUTHOR("Marek Vasut <marek.vasut@gmail.com>");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
vic3t3chn0/android_kernel_sony_msm8974_togari_5.0.2 | drivers/staging/ste_rmi4/synaptics_i2c_rmi4_staging.c | 2792 | 35803 | /**
*
* Synaptics Register Mapped Interface (RMI4) I2C Physical Layer Driver.
* Copyright (c) 2007-2010, Synaptics Incorporated
*
* Author: Js HA <js.ha@stericsson.com> for ST-Ericsson
* Author: Naveen Kumar G <naveen.gaddipati@stericsson.com> for ST-Ericsson
* Copyright 2010 (c) ST-Ericsson AB
*/
/*
* This file is licensed under the GPL2 license.
*
*#############################################################################
* GPL
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
*#############################################################################
*/
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/regulator/consumer.h>
#include <linux/module.h>
#include "synaptics_i2c_rmi4_staging.h"
/* TODO: for multiple device support will need a per-device mutex */
#define DRIVER_NAME "synaptics_rmi4_i2c"
#define MAX_ERROR_REPORT 6
#define MAX_TOUCH_MAJOR 15
#define MAX_RETRY_COUNT 5
#define STD_QUERY_LEN 21
#define PAGE_LEN 2
#define DATA_BUF_LEN 32
#define BUF_LEN 37
#define QUERY_LEN 9
#define DATA_LEN 12
#define HAS_TAP 0x01
#define HAS_PALMDETECT 0x01
#define HAS_ROTATE 0x02
#define HAS_TAPANDHOLD 0x02
#define HAS_DOUBLETAP 0x04
#define HAS_EARLYTAP 0x08
#define HAS_RELEASE 0x08
#define HAS_FLICK 0x10
#define HAS_PRESS 0x20
#define HAS_PINCH 0x40
#define MASK_16BIT 0xFFFF
#define MASK_8BIT 0xFF
#define MASK_7BIT 0x7F
#define MASK_5BIT 0x1F
#define MASK_4BIT 0x0F
#define MASK_3BIT 0x07
#define MASK_2BIT 0x03
#define TOUCHPAD_CTRL_INTR 0x8
#define PDT_START_SCAN_LOCATION (0x00E9)
#define PDT_END_SCAN_LOCATION (0x000A)
#define PDT_ENTRY_SIZE (0x0006)
#define RMI4_NUMBER_OF_MAX_FINGERS (8)
#define SYNAPTICS_RMI4_TOUCHPAD_FUNC_NUM (0x11)
#define SYNAPTICS_RMI4_DEVICE_CONTROL_FUNC_NUM (0x01)
/**
* struct synaptics_rmi4_fn_desc - contains the function descriptor information
* @query_base_addr: base address for query
* @cmd_base_addr: base address for command
* @ctrl_base_addr: base address for control
* @data_base_addr: base address for data
* @intr_src_count: count for the interrupt source
* @fn_number: function number
*
* This structure is used to gives the function descriptor information
* of the particular functionality.
*/
struct synaptics_rmi4_fn_desc {
unsigned char query_base_addr;
unsigned char cmd_base_addr;
unsigned char ctrl_base_addr;
unsigned char data_base_addr;
unsigned char intr_src_count;
unsigned char fn_number;
};
/**
* struct synaptics_rmi4_fn - contains the function information
* @fn_number: function number
* @num_of_data_sources: number of data sources
* @num_of_data_points: number of fingers touched
* @size_of_data_register_block: data register block size
* @index_to_intr_reg: index for interrupt register
* @intr_mask: interrupt mask value
* @fn_desc: variable for function descriptor structure
* @link: linked list for function descriptors
*
* This structure gives information about the number of data sources and
* the number of data registers associated with the function.
*/
struct synaptics_rmi4_fn {
unsigned char fn_number;
unsigned char num_of_data_sources;
unsigned char num_of_data_points;
unsigned char size_of_data_register_block;
unsigned char index_to_intr_reg;
unsigned char intr_mask;
struct synaptics_rmi4_fn_desc fn_desc;
struct list_head link;
};
/**
* struct synaptics_rmi4_device_info - contains the rmi4 device information
* @version_major: protocol major version number
* @version_minor: protocol minor version number
* @manufacturer_id: manufacturer identification byte
* @product_props: product properties information
* @product_info: product info array
* @date_code: device manufacture date
* @tester_id: tester id array
* @serial_number: serial number for that device
* @product_id_string: product id for the device
* @support_fn_list: linked list for device information
*
* This structure gives information about the number of data sources and
* the number of data registers associated with the function.
*/
struct synaptics_rmi4_device_info {
unsigned int version_major;
unsigned int version_minor;
unsigned char manufacturer_id;
unsigned char product_props;
unsigned char product_info[2];
unsigned char date_code[3];
unsigned short tester_id;
unsigned short serial_number;
unsigned char product_id_string[11];
struct list_head support_fn_list;
};
/**
* struct synaptics_rmi4_data - contains the rmi4 device data
* @rmi4_mod_info: structure variable for rmi4 device info
* @input_dev: pointer for input device
* @i2c_client: pointer for i2c client
* @board: constant pointer for touch platform data
* @fn_list_mutex: mutex for function list
* @rmi4_page_mutex: mutex for rmi4 page
* @current_page: variable for integer
* @number_of_interrupt_register: interrupt registers count
* @fn01_ctrl_base_addr: control base address for fn01
* @fn01_query_base_addr: query base address for fn01
* @fn01_data_base_addr: data base address for fn01
* @sensor_max_x: sensor maximum x value
* @sensor_max_y: sensor maximum y value
* @regulator: pointer to the regulator structure
* @wait: wait queue structure variable
* @touch_stopped: flag to stop the thread function
*
* This structure gives the device data information.
*/
struct synaptics_rmi4_data {
struct synaptics_rmi4_device_info rmi4_mod_info;
struct input_dev *input_dev;
struct i2c_client *i2c_client;
const struct synaptics_rmi4_platform_data *board;
struct mutex fn_list_mutex;
struct mutex rmi4_page_mutex;
int current_page;
unsigned int number_of_interrupt_register;
unsigned short fn01_ctrl_base_addr;
unsigned short fn01_query_base_addr;
unsigned short fn01_data_base_addr;
int sensor_max_x;
int sensor_max_y;
struct regulator *regulator;
wait_queue_head_t wait;
bool touch_stopped;
};
/**
* synaptics_rmi4_set_page() - sets the page
* @pdata: pointer to synaptics_rmi4_data structure
* @address: set the address of the page
*
* This function is used to set the page and returns integer.
*/
static int synaptics_rmi4_set_page(struct synaptics_rmi4_data *pdata,
unsigned int address)
{
unsigned char txbuf[PAGE_LEN];
int retval;
unsigned int page;
struct i2c_client *i2c = pdata->i2c_client;
page = ((address >> 8) & MASK_8BIT);
if (page != pdata->current_page) {
txbuf[0] = MASK_8BIT;
txbuf[1] = page;
retval = i2c_master_send(i2c, txbuf, PAGE_LEN);
if (retval != PAGE_LEN)
dev_err(&i2c->dev, "%s:failed:%d\n", __func__, retval);
else
pdata->current_page = page;
} else
retval = PAGE_LEN;
return retval;
}
/**
* synaptics_rmi4_i2c_block_read() - read the block of data
* @pdata: pointer to synaptics_rmi4_data structure
* @address: read the block of data from this offset
* @valp: pointer to a buffer containing the data to be read
* @size: number of bytes to read
*
* This function is to read the block of data and returns integer.
*/
static int synaptics_rmi4_i2c_block_read(struct synaptics_rmi4_data *pdata,
unsigned short address,
unsigned char *valp, int size)
{
int retval = 0;
int retry_count = 0;
int index;
struct i2c_client *i2c = pdata->i2c_client;
mutex_lock(&(pdata->rmi4_page_mutex));
retval = synaptics_rmi4_set_page(pdata, address);
if (retval != PAGE_LEN)
goto exit;
index = address & MASK_8BIT;
retry:
retval = i2c_smbus_read_i2c_block_data(i2c, index, size, valp);
if (retval != size) {
if (++retry_count == MAX_RETRY_COUNT)
dev_err(&i2c->dev,
"%s:address 0x%04x size %d failed:%d\n",
__func__, address, size, retval);
else {
synaptics_rmi4_set_page(pdata, address);
goto retry;
}
}
exit:
mutex_unlock(&(pdata->rmi4_page_mutex));
return retval;
}
/**
* synaptics_rmi4_i2c_byte_write() - write the single byte data
* @pdata: pointer to synaptics_rmi4_data structure
* @address: write the block of data from this offset
* @data: data to be write
*
* This function is to write the single byte data and returns integer.
*/
static int synaptics_rmi4_i2c_byte_write(struct synaptics_rmi4_data *pdata,
unsigned short address,
unsigned char data)
{
unsigned char txbuf[2];
int retval = 0;
struct i2c_client *i2c = pdata->i2c_client;
/* Can't have anyone else changing the page behind our backs */
mutex_lock(&(pdata->rmi4_page_mutex));
retval = synaptics_rmi4_set_page(pdata, address);
if (retval != PAGE_LEN)
goto exit;
txbuf[0] = address & MASK_8BIT;
txbuf[1] = data;
retval = i2c_master_send(pdata->i2c_client, txbuf, 2);
/* Add in retry on writes only in certain error return values */
if (retval != 2) {
dev_err(&i2c->dev, "%s:failed:%d\n", __func__, retval);
retval = -EIO;
} else
retval = 1;
exit:
mutex_unlock(&(pdata->rmi4_page_mutex));
return retval;
}
/**
* synpatics_rmi4_touchpad_report() - reports for the rmi4 touchpad device
* @pdata: pointer to synaptics_rmi4_data structure
* @rfi: pointer to synaptics_rmi4_fn structure
*
* This function calls to reports for the rmi4 touchpad device
*/
static int synpatics_rmi4_touchpad_report(struct synaptics_rmi4_data *pdata,
struct synaptics_rmi4_fn *rfi)
{
/* number of touch points - fingers down in this case */
int touch_count = 0;
int finger;
int fingers_supported;
int finger_registers;
int reg;
int finger_shift;
int finger_status;
int retval;
unsigned short data_base_addr;
unsigned short data_offset;
unsigned char data_reg_blk_size;
unsigned char values[2];
unsigned char data[DATA_LEN];
int x[RMI4_NUMBER_OF_MAX_FINGERS];
int y[RMI4_NUMBER_OF_MAX_FINGERS];
int wx[RMI4_NUMBER_OF_MAX_FINGERS];
int wy[RMI4_NUMBER_OF_MAX_FINGERS];
struct i2c_client *client = pdata->i2c_client;
/* get 2D sensor finger data */
/*
* First get the finger status field - the size of the finger status
* field is determined by the number of finger supporte - 2 bits per
* finger, so the number of registers to read is:
* registerCount = ceil(numberOfFingers/4).
* Read the required number of registers and check each 2 bit field to
* determine if a finger is down:
* 00 = finger not present,
* 01 = finger present and data accurate,
* 10 = finger present but data may not be accurate,
* 11 = reserved for product use.
*/
fingers_supported = rfi->num_of_data_points;
finger_registers = (fingers_supported + 3)/4;
data_base_addr = rfi->fn_desc.data_base_addr;
retval = synaptics_rmi4_i2c_block_read(pdata, data_base_addr, values,
finger_registers);
if (retval != finger_registers) {
dev_err(&client->dev, "%s:read status registers failed\n",
__func__);
return 0;
}
/*
* For each finger present, read the proper number of registers
* to get absolute data.
*/
data_reg_blk_size = rfi->size_of_data_register_block;
for (finger = 0; finger < fingers_supported; finger++) {
/* determine which data byte the finger status is in */
reg = finger/4;
/* bit shift to get finger's status */
finger_shift = (finger % 4) * 2;
finger_status = (values[reg] >> finger_shift) & 3;
/*
* if finger status indicates a finger is present then
* read the finger data and report it
*/
if (finger_status == 1 || finger_status == 2) {
/* Read the finger data */
data_offset = data_base_addr +
((finger * data_reg_blk_size) +
finger_registers);
retval = synaptics_rmi4_i2c_block_read(pdata,
data_offset, data,
data_reg_blk_size);
if (retval != data_reg_blk_size) {
printk(KERN_ERR "%s:read data failed\n",
__func__);
return 0;
} else {
x[touch_count] =
(data[0] << 4) | (data[2] & MASK_4BIT);
y[touch_count] =
(data[1] << 4) |
((data[2] >> 4) & MASK_4BIT);
wy[touch_count] =
(data[3] >> 4) & MASK_4BIT;
wx[touch_count] =
(data[3] & MASK_4BIT);
if (pdata->board->x_flip)
x[touch_count] =
pdata->sensor_max_x -
x[touch_count];
if (pdata->board->y_flip)
y[touch_count] =
pdata->sensor_max_y -
y[touch_count];
}
/* number of active touch points */
touch_count++;
}
}
/* report to input subsystem */
if (touch_count) {
for (finger = 0; finger < touch_count; finger++) {
input_report_abs(pdata->input_dev, ABS_MT_TOUCH_MAJOR,
max(wx[finger] , wy[finger]));
input_report_abs(pdata->input_dev, ABS_MT_POSITION_X,
x[finger]);
input_report_abs(pdata->input_dev, ABS_MT_POSITION_Y,
y[finger]);
input_mt_sync(pdata->input_dev);
}
} else
input_mt_sync(pdata->input_dev);
/* sync after groups of events */
input_sync(pdata->input_dev);
/* return the number of touch points */
return touch_count;
}
/**
* synaptics_rmi4_report_device() - reports the rmi4 device
* @pdata: pointer to synaptics_rmi4_data structure
* @rfi: pointer to synaptics_rmi4_fn
*
* This function is used to call the report function of the rmi4 device.
*/
static int synaptics_rmi4_report_device(struct synaptics_rmi4_data *pdata,
struct synaptics_rmi4_fn *rfi)
{
int touch = 0;
struct i2c_client *client = pdata->i2c_client;
static int num_error_reports;
if (rfi->fn_number != SYNAPTICS_RMI4_TOUCHPAD_FUNC_NUM) {
num_error_reports++;
if (num_error_reports < MAX_ERROR_REPORT)
dev_err(&client->dev, "%s:report not supported\n",
__func__);
} else
touch = synpatics_rmi4_touchpad_report(pdata, rfi);
return touch;
}
/**
* synaptics_rmi4_sensor_report() - reports to input subsystem
* @pdata: pointer to synaptics_rmi4_data structure
*
* This function is used to reads in all data sources and reports
* them to the input subsystem.
*/
static int synaptics_rmi4_sensor_report(struct synaptics_rmi4_data *pdata)
{
unsigned char intr_status[4];
/* number of touch points - fingers or buttons */
int touch = 0;
unsigned int retval;
struct synaptics_rmi4_fn *rfi;
struct synaptics_rmi4_device_info *rmi;
struct i2c_client *client = pdata->i2c_client;
/*
* Get the interrupt status from the function $01
* control register+1 to find which source(s) were interrupting
* so we can read the data from the source(s) (2D sensor, buttons..)
*/
retval = synaptics_rmi4_i2c_block_read(pdata,
pdata->fn01_data_base_addr + 1,
intr_status,
pdata->number_of_interrupt_register);
if (retval != pdata->number_of_interrupt_register) {
dev_err(&client->dev,
"could not read interrupt status registers\n");
return 0;
}
/*
* check each function that has data sources and if the interrupt for
* that triggered then call that RMI4 functions report() function to
* gather data and report it to the input subsystem
*/
rmi = &(pdata->rmi4_mod_info);
list_for_each_entry(rfi, &rmi->support_fn_list, link) {
if (rfi->num_of_data_sources) {
if (intr_status[rfi->index_to_intr_reg] &
rfi->intr_mask)
touch = synaptics_rmi4_report_device(pdata,
rfi);
}
}
/* return the number of touch points */
return touch;
}
/**
* synaptics_rmi4_irq() - thread function for rmi4 attention line
* @irq: irq value
* @data: void pointer
*
* This function is interrupt thread function. It just notifies the
* application layer that attention is required.
*/
static irqreturn_t synaptics_rmi4_irq(int irq, void *data)
{
struct synaptics_rmi4_data *pdata = data;
int touch_count;
do {
touch_count = synaptics_rmi4_sensor_report(pdata);
if (touch_count)
wait_event_timeout(pdata->wait, pdata->touch_stopped,
msecs_to_jiffies(1));
else
break;
} while (!pdata->touch_stopped);
return IRQ_HANDLED;
}
/**
* synpatics_rmi4_touchpad_detect() - detects the rmi4 touchpad device
* @pdata: pointer to synaptics_rmi4_data structure
* @rfi: pointer to synaptics_rmi4_fn structure
* @fd: pointer to synaptics_rmi4_fn_desc structure
* @interruptcount: count the number of interrupts
*
* This function calls to detects the rmi4 touchpad device
*/
static int synpatics_rmi4_touchpad_detect(struct synaptics_rmi4_data *pdata,
struct synaptics_rmi4_fn *rfi,
struct synaptics_rmi4_fn_desc *fd,
unsigned int interruptcount)
{
unsigned char queries[QUERY_LEN];
unsigned short intr_offset;
unsigned char abs_data_size;
unsigned char abs_data_blk_size;
unsigned char egr_0, egr_1;
unsigned int all_data_blk_size;
int has_pinch, has_flick, has_tap;
int has_tapandhold, has_doubletap;
int has_earlytap, has_press;
int has_palmdetect, has_rotate;
int has_rel;
int i;
int retval;
struct i2c_client *client = pdata->i2c_client;
rfi->fn_desc.query_base_addr = fd->query_base_addr;
rfi->fn_desc.data_base_addr = fd->data_base_addr;
rfi->fn_desc.intr_src_count = fd->intr_src_count;
rfi->fn_desc.fn_number = fd->fn_number;
rfi->fn_number = fd->fn_number;
rfi->num_of_data_sources = fd->intr_src_count;
rfi->fn_desc.ctrl_base_addr = fd->ctrl_base_addr;
rfi->fn_desc.cmd_base_addr = fd->cmd_base_addr;
/*
* need to get number of fingers supported, data size, etc.
* to be used when getting data since the number of registers to
* read depends on the number of fingers supported and data size.
*/
retval = synaptics_rmi4_i2c_block_read(pdata, fd->query_base_addr,
queries,
sizeof(queries));
if (retval != sizeof(queries)) {
dev_err(&client->dev, "%s:read function query registers\n",
__func__);
return retval;
}
/*
* 2D data sources have only 3 bits for the number of fingers
* supported - so the encoding is a bit weird.
*/
if ((queries[1] & MASK_3BIT) <= 4)
/* add 1 since zero based */
rfi->num_of_data_points = (queries[1] & MASK_3BIT) + 1;
else {
/*
* a value of 5 is up to 10 fingers - 6 and 7 are reserved
* (shouldn't get these i int retval;n a normal 2D source).
*/
if ((queries[1] & MASK_3BIT) == 5)
rfi->num_of_data_points = 10;
}
/* Need to get interrupt info for handling interrupts */
rfi->index_to_intr_reg = (interruptcount + 7)/8;
if (rfi->index_to_intr_reg != 0)
rfi->index_to_intr_reg -= 1;
/*
* loop through interrupts for each source in fn $11
* and or in a bit to the interrupt mask for each.
*/
intr_offset = interruptcount % 8;
rfi->intr_mask = 0;
for (i = intr_offset;
i < ((fd->intr_src_count & MASK_3BIT) + intr_offset); i++)
rfi->intr_mask |= 1 << i;
/* Size of just the absolute data for one finger */
abs_data_size = queries[5] & MASK_2BIT;
/* One each for X and Y, one for LSB for X & Y, one for W, one for Z */
abs_data_blk_size = 3 + (2 * (abs_data_size == 0 ? 1 : 0));
rfi->size_of_data_register_block = abs_data_blk_size;
/*
* need to determine the size of data to read - this depends on
* conditions such as whether Relative data is reported and if Gesture
* data is reported.
*/
egr_0 = queries[7];
egr_1 = queries[8];
/*
* Get info about what EGR data is supported, whether it has
* Relative data supported, etc.
*/
has_pinch = egr_0 & HAS_PINCH;
has_flick = egr_0 & HAS_FLICK;
has_tap = egr_0 & HAS_TAP;
has_earlytap = egr_0 & HAS_EARLYTAP;
has_press = egr_0 & HAS_PRESS;
has_rotate = egr_1 & HAS_ROTATE;
has_rel = queries[1] & HAS_RELEASE;
has_tapandhold = egr_0 & HAS_TAPANDHOLD;
has_doubletap = egr_0 & HAS_DOUBLETAP;
has_palmdetect = egr_1 & HAS_PALMDETECT;
/*
* Size of all data including finger status, absolute data for each
* finger, relative data and EGR data
*/
all_data_blk_size =
/* finger status, four fingers per register */
((rfi->num_of_data_points + 3) / 4) +
/* absolute data, per finger times number of fingers */
(abs_data_blk_size * rfi->num_of_data_points) +
/*
* two relative registers (if relative is being reported)
*/
2 * has_rel +
/*
* F11_2D_data8 is only present if the egr_0
* register is non-zero.
*/
!!(egr_0) +
/*
* F11_2D_data9 is only present if either egr_0 or
* egr_1 registers are non-zero.
*/
(egr_0 || egr_1) +
/*
* F11_2D_data10 is only present if EGR_PINCH or EGR_FLICK of
* egr_0 reports as 1.
*/
!!(has_pinch | has_flick) +
/*
* F11_2D_data11 and F11_2D_data12 are only present if
* EGR_FLICK of egr_0 reports as 1.
*/
2 * !!(has_flick);
return retval;
}
/**
* synpatics_rmi4_touchpad_config() - confiures the rmi4 touchpad device
* @pdata: pointer to synaptics_rmi4_data structure
* @rfi: pointer to synaptics_rmi4_fn structure
*
* This function calls to confiures the rmi4 touchpad device
*/
int synpatics_rmi4_touchpad_config(struct synaptics_rmi4_data *pdata,
struct synaptics_rmi4_fn *rfi)
{
/*
* For the data source - print info and do any
* source specific configuration.
*/
unsigned char data[BUF_LEN];
int retval = 0;
struct i2c_client *client = pdata->i2c_client;
/* Get and print some info about the data source... */
/* To Query 2D devices we need to read from the address obtained
* from the function descriptor stored in the RMI function info.
*/
retval = synaptics_rmi4_i2c_block_read(pdata,
rfi->fn_desc.query_base_addr,
data, QUERY_LEN);
if (retval != QUERY_LEN)
dev_err(&client->dev, "%s:read query registers failed\n",
__func__);
else {
retval = synaptics_rmi4_i2c_block_read(pdata,
rfi->fn_desc.ctrl_base_addr,
data, DATA_BUF_LEN);
if (retval != DATA_BUF_LEN) {
dev_err(&client->dev,
"%s:read control registers failed\n",
__func__);
return retval;
}
/* Store these for use later*/
pdata->sensor_max_x = ((data[6] & MASK_8BIT) << 0) |
((data[7] & MASK_4BIT) << 8);
pdata->sensor_max_y = ((data[8] & MASK_5BIT) << 0) |
((data[9] & MASK_4BIT) << 8);
}
return retval;
}
/**
* synaptics_rmi4_i2c_query_device() - query the rmi4 device
* @pdata: pointer to synaptics_rmi4_data structure
*
* This function is used to query the rmi4 device.
*/
static int synaptics_rmi4_i2c_query_device(struct synaptics_rmi4_data *pdata)
{
int i;
int retval;
unsigned char std_queries[STD_QUERY_LEN];
unsigned char intr_count = 0;
int data_sources = 0;
unsigned int ctrl_offset;
struct synaptics_rmi4_fn *rfi;
struct synaptics_rmi4_fn_desc rmi_fd;
struct synaptics_rmi4_device_info *rmi;
struct i2c_client *client = pdata->i2c_client;
/*
* init the physical drivers RMI module
* info list of functions
*/
INIT_LIST_HEAD(&pdata->rmi4_mod_info.support_fn_list);
/*
* Read the Page Descriptor Table to determine what functions
* are present
*/
for (i = PDT_START_SCAN_LOCATION; i > PDT_END_SCAN_LOCATION;
i -= PDT_ENTRY_SIZE) {
retval = synaptics_rmi4_i2c_block_read(pdata, i,
(unsigned char *)&rmi_fd,
sizeof(rmi_fd));
if (retval != sizeof(rmi_fd)) {
/* failed to read next PDT entry */
dev_err(&client->dev, "%s: read error\n", __func__);
return -EIO;
}
rfi = NULL;
if (rmi_fd.fn_number) {
switch (rmi_fd.fn_number & MASK_8BIT) {
case SYNAPTICS_RMI4_DEVICE_CONTROL_FUNC_NUM:
pdata->fn01_query_base_addr =
rmi_fd.query_base_addr;
pdata->fn01_ctrl_base_addr =
rmi_fd.ctrl_base_addr;
pdata->fn01_data_base_addr =
rmi_fd.data_base_addr;
break;
case SYNAPTICS_RMI4_TOUCHPAD_FUNC_NUM:
if (rmi_fd.intr_src_count) {
rfi = kmalloc(sizeof(*rfi),
GFP_KERNEL);
if (!rfi) {
dev_err(&client->dev,
"%s:kmalloc failed\n",
__func__);
return -ENOMEM;
}
retval = synpatics_rmi4_touchpad_detect
(pdata, rfi,
&rmi_fd,
intr_count);
if (retval < 0) {
kfree(rfi);
return retval;
}
}
break;
}
/* interrupt count for next iteration */
intr_count += (rmi_fd.intr_src_count & MASK_3BIT);
/*
* We only want to add functions to the list
* that have data associated with them.
*/
if (rfi && rmi_fd.intr_src_count) {
/* link this function info to the RMI module */
mutex_lock(&(pdata->fn_list_mutex));
list_add_tail(&rfi->link,
&pdata->rmi4_mod_info.support_fn_list);
mutex_unlock(&(pdata->fn_list_mutex));
}
} else {
/*
* A zero in the function number
* signals the end of the PDT
*/
dev_dbg(&client->dev,
"%s:end of PDT\n", __func__);
break;
}
}
/*
* calculate the interrupt register count - used in the
* ISR to read the correct number of interrupt registers
*/
pdata->number_of_interrupt_register = (intr_count + 7) / 8;
/*
* Function $01 will be used to query the product properties,
* and product ID so we had to read the PDT above first to get
* the Fn $01 query address and prior to filling in the product
* info. NOTE: Even an unflashed device will still have FN $01.
*/
/* Load up the standard queries and get the RMI4 module info */
retval = synaptics_rmi4_i2c_block_read(pdata,
pdata->fn01_query_base_addr,
std_queries,
sizeof(std_queries));
if (retval != sizeof(std_queries)) {
dev_err(&client->dev, "%s:Failed reading queries\n",
__func__);
return -EIO;
}
/* Currently supported RMI version is 4.0 */
pdata->rmi4_mod_info.version_major = 4;
pdata->rmi4_mod_info.version_minor = 0;
/*
* get manufacturer id, product_props, product info,
* date code, tester id, serial num and product id (name)
*/
pdata->rmi4_mod_info.manufacturer_id = std_queries[0];
pdata->rmi4_mod_info.product_props = std_queries[1];
pdata->rmi4_mod_info.product_info[0] = std_queries[2];
pdata->rmi4_mod_info.product_info[1] = std_queries[3];
/* year - 2001-2032 */
pdata->rmi4_mod_info.date_code[0] = std_queries[4] & MASK_5BIT;
/* month - 1-12 */
pdata->rmi4_mod_info.date_code[1] = std_queries[5] & MASK_4BIT;
/* day - 1-31 */
pdata->rmi4_mod_info.date_code[2] = std_queries[6] & MASK_5BIT;
pdata->rmi4_mod_info.tester_id = ((std_queries[7] & MASK_7BIT) << 8) |
(std_queries[8] & MASK_7BIT);
pdata->rmi4_mod_info.serial_number =
((std_queries[9] & MASK_7BIT) << 8) |
(std_queries[10] & MASK_7BIT);
memcpy(pdata->rmi4_mod_info.product_id_string, &std_queries[11], 10);
/* Check if this is a Synaptics device - report if not. */
if (pdata->rmi4_mod_info.manufacturer_id != 1)
dev_err(&client->dev, "%s: non-Synaptics mfg id:%d\n",
__func__, pdata->rmi4_mod_info.manufacturer_id);
list_for_each_entry(rfi, &pdata->rmi4_mod_info.support_fn_list, link)
data_sources += rfi->num_of_data_sources;
if (data_sources) {
rmi = &(pdata->rmi4_mod_info);
list_for_each_entry(rfi, &rmi->support_fn_list, link) {
if (rfi->num_of_data_sources) {
if (rfi->fn_number ==
SYNAPTICS_RMI4_TOUCHPAD_FUNC_NUM) {
retval = synpatics_rmi4_touchpad_config
(pdata, rfi);
if (retval < 0)
return retval;
} else
dev_err(&client->dev,
"%s:fn_number not supported\n",
__func__);
/*
* Turn on interrupts for this
* function's data sources.
*/
ctrl_offset = pdata->fn01_ctrl_base_addr + 1 +
rfi->index_to_intr_reg;
retval = synaptics_rmi4_i2c_byte_write(pdata,
ctrl_offset,
rfi->intr_mask);
if (retval < 0)
return retval;
}
}
}
return 0;
}
/**
* synaptics_rmi4_probe() - Initialze the i2c-client touchscreen driver
* @i2c: i2c client structure pointer
* @id:i2c device id pointer
*
* This function will allocate and initialize the instance
* data and request the irq and set the instance data as the clients
* platform data then register the physical driver which will do a scan of
* the rmi4 Physical Device Table and enumerate any rmi4 functions that
* have data sources associated with them.
*/
static int __devinit synaptics_rmi4_probe
(struct i2c_client *client, const struct i2c_device_id *dev_id)
{
int retval;
unsigned char intr_status[4];
struct synaptics_rmi4_data *rmi4_data;
const struct synaptics_rmi4_platform_data *platformdata =
client->dev.platform_data;
if (!i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_BYTE_DATA)) {
dev_err(&client->dev, "i2c smbus byte data not supported\n");
return -EIO;
}
if (!platformdata) {
dev_err(&client->dev, "%s: no platform data\n", __func__);
return -EINVAL;
}
/* Allocate and initialize the instance data for this client */
rmi4_data = kzalloc(sizeof(struct synaptics_rmi4_data) * 2,
GFP_KERNEL);
if (!rmi4_data) {
dev_err(&client->dev, "%s: no memory allocated\n", __func__);
return -ENOMEM;
}
rmi4_data->input_dev = input_allocate_device();
if (rmi4_data->input_dev == NULL) {
dev_err(&client->dev, "%s:input device alloc failed\n",
__func__);
retval = -ENOMEM;
goto err_input;
}
rmi4_data->regulator = regulator_get(&client->dev, "vdd");
if (IS_ERR(rmi4_data->regulator)) {
dev_err(&client->dev, "%s:get regulator failed\n",
__func__);
retval = PTR_ERR(rmi4_data->regulator);
goto err_get_regulator;
}
retval = regulator_enable(rmi4_data->regulator);
if (retval < 0) {
dev_err(&client->dev, "%s:regulator enable failed\n",
__func__);
goto err_regulator_enable;
}
init_waitqueue_head(&rmi4_data->wait);
/*
* Copy i2c_client pointer into RTID's i2c_client pointer for
* later use in rmi4_read, rmi4_write, etc.
*/
rmi4_data->i2c_client = client;
/* So we set the page correctly the first time */
rmi4_data->current_page = MASK_16BIT;
rmi4_data->board = platformdata;
rmi4_data->touch_stopped = false;
/* init the mutexes for maintain the lists */
mutex_init(&(rmi4_data->fn_list_mutex));
mutex_init(&(rmi4_data->rmi4_page_mutex));
/*
* Register physical driver - this will call the detect function that
* will then scan the device and determine the supported
* rmi4 functions.
*/
retval = synaptics_rmi4_i2c_query_device(rmi4_data);
if (retval) {
dev_err(&client->dev, "%s: rmi4 query device failed\n",
__func__);
goto err_query_dev;
}
/* Store the instance data in the i2c_client */
i2c_set_clientdata(client, rmi4_data);
/*initialize the input device parameters */
rmi4_data->input_dev->name = DRIVER_NAME;
rmi4_data->input_dev->phys = "Synaptics_Clearpad";
rmi4_data->input_dev->id.bustype = BUS_I2C;
rmi4_data->input_dev->dev.parent = &client->dev;
input_set_drvdata(rmi4_data->input_dev, rmi4_data);
/* Initialize the function handlers for rmi4 */
set_bit(EV_SYN, rmi4_data->input_dev->evbit);
set_bit(EV_KEY, rmi4_data->input_dev->evbit);
set_bit(EV_ABS, rmi4_data->input_dev->evbit);
input_set_abs_params(rmi4_data->input_dev, ABS_MT_POSITION_X, 0,
rmi4_data->sensor_max_x, 0, 0);
input_set_abs_params(rmi4_data->input_dev, ABS_MT_POSITION_Y, 0,
rmi4_data->sensor_max_y, 0, 0);
input_set_abs_params(rmi4_data->input_dev, ABS_MT_TOUCH_MAJOR, 0,
MAX_TOUCH_MAJOR, 0, 0);
/* Clear interrupts */
synaptics_rmi4_i2c_block_read(rmi4_data,
rmi4_data->fn01_data_base_addr + 1, intr_status,
rmi4_data->number_of_interrupt_register);
retval = request_threaded_irq(platformdata->irq_number, NULL,
synaptics_rmi4_irq,
platformdata->irq_type,
DRIVER_NAME, rmi4_data);
if (retval) {
dev_err(&client->dev, "%s:Unable to get attn irq %d\n",
__func__, platformdata->irq_number);
goto err_query_dev;
}
retval = input_register_device(rmi4_data->input_dev);
if (retval) {
dev_err(&client->dev, "%s:input register failed\n", __func__);
goto err_free_irq;
}
return retval;
err_free_irq:
free_irq(platformdata->irq_number, rmi4_data);
err_query_dev:
regulator_disable(rmi4_data->regulator);
err_regulator_enable:
regulator_put(rmi4_data->regulator);
err_get_regulator:
input_free_device(rmi4_data->input_dev);
rmi4_data->input_dev = NULL;
err_input:
kfree(rmi4_data);
return retval;
}
/**
* synaptics_rmi4_remove() - Removes the i2c-client touchscreen driver
* @client: i2c client structure pointer
*
* This function uses to remove the i2c-client
* touchscreen driver and returns integer.
*/
static int __devexit synaptics_rmi4_remove(struct i2c_client *client)
{
struct synaptics_rmi4_data *rmi4_data = i2c_get_clientdata(client);
const struct synaptics_rmi4_platform_data *pdata = rmi4_data->board;
rmi4_data->touch_stopped = true;
wake_up(&rmi4_data->wait);
free_irq(pdata->irq_number, rmi4_data);
input_unregister_device(rmi4_data->input_dev);
regulator_disable(rmi4_data->regulator);
regulator_put(rmi4_data->regulator);
kfree(rmi4_data);
return 0;
}
#ifdef CONFIG_PM
/**
* synaptics_rmi4_suspend() - suspend the touch screen controller
* @dev: pointer to device structure
*
* This function is used to suspend the
* touch panel controller and returns integer
*/
static int synaptics_rmi4_suspend(struct device *dev)
{
/* Touch sleep mode */
int retval;
unsigned char intr_status;
struct synaptics_rmi4_data *rmi4_data = dev_get_drvdata(dev);
const struct synaptics_rmi4_platform_data *pdata = rmi4_data->board;
rmi4_data->touch_stopped = true;
disable_irq(pdata->irq_number);
retval = synaptics_rmi4_i2c_block_read(rmi4_data,
rmi4_data->fn01_data_base_addr + 1,
&intr_status,
rmi4_data->number_of_interrupt_register);
if (retval < 0)
return retval;
retval = synaptics_rmi4_i2c_byte_write(rmi4_data,
rmi4_data->fn01_ctrl_base_addr + 1,
(intr_status & ~TOUCHPAD_CTRL_INTR));
if (retval < 0)
return retval;
regulator_disable(rmi4_data->regulator);
return 0;
}
/**
* synaptics_rmi4_resume() - resume the touch screen controller
* @dev: pointer to device structure
*
* This function is used to resume the touch panel
* controller and returns integer.
*/
static int synaptics_rmi4_resume(struct device *dev)
{
int retval;
unsigned char intr_status;
struct synaptics_rmi4_data *rmi4_data = dev_get_drvdata(dev);
const struct synaptics_rmi4_platform_data *pdata = rmi4_data->board;
regulator_enable(rmi4_data->regulator);
enable_irq(pdata->irq_number);
rmi4_data->touch_stopped = false;
retval = synaptics_rmi4_i2c_block_read(rmi4_data,
rmi4_data->fn01_data_base_addr + 1,
&intr_status,
rmi4_data->number_of_interrupt_register);
if (retval < 0)
return retval;
retval = synaptics_rmi4_i2c_byte_write(rmi4_data,
rmi4_data->fn01_ctrl_base_addr + 1,
(intr_status | TOUCHPAD_CTRL_INTR));
if (retval < 0)
return retval;
return 0;
}
static const struct dev_pm_ops synaptics_rmi4_dev_pm_ops = {
.suspend = synaptics_rmi4_suspend,
.resume = synaptics_rmi4_resume,
};
#endif
static const struct i2c_device_id synaptics_rmi4_id_table[] = {
{ DRIVER_NAME, 0 },
{ },
};
MODULE_DEVICE_TABLE(i2c, synaptics_rmi4_id_table);
static struct i2c_driver synaptics_rmi4_driver = {
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &synaptics_rmi4_dev_pm_ops,
#endif
},
.probe = synaptics_rmi4_probe,
.remove = __devexit_p(synaptics_rmi4_remove),
.id_table = synaptics_rmi4_id_table,
};
/**
* synaptics_rmi4_init() - Initialize the touchscreen driver
*
* This function uses to initializes the synaptics
* touchscreen driver and returns integer.
*/
static int __init synaptics_rmi4_init(void)
{
return i2c_add_driver(&synaptics_rmi4_driver);
}
/**
* synaptics_rmi4_exit() - De-initialize the touchscreen driver
*
* This function uses to de-initialize the synaptics
* touchscreen driver and returns none.
*/
static void __exit synaptics_rmi4_exit(void)
{
i2c_del_driver(&synaptics_rmi4_driver);
}
module_init(synaptics_rmi4_init);
module_exit(synaptics_rmi4_exit);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("naveen.gaddipati@stericsson.com, js.ha@stericsson.com");
MODULE_DESCRIPTION("synaptics rmi4 i2c touch Driver");
MODULE_ALIAS("i2c:synaptics_rmi4_ts");
| gpl-2.0 |
rmbq/bubba_kernel_3.0 | drivers/media/rc/keymaps/rc-tivo.c | 2792 | 2873 | /* rc-tivo.c - Keytable for TiVo remotes
*
* Copyright (c) 2011 by Jarod Wilson <jarod@redhat.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 <media/rc-map.h>
/*
* Initial mapping is for the TiVo remote included in the Nero LiquidTV bundle,
* which also ships with a TiVo-branded IR transceiver, supported by the mceusb
* driver. Note that the remote uses an NEC-ish protocol, but instead of having
* a command/not_command pair, it has a vendor ID of 0xa10c, but some keys, the
* NEC extended checksums do pass, so the table presently has the intended
* values and the checksum-passed versions for those keys.
*/
static struct rc_map_table tivo[] = {
{ 0xa10c900f, KEY_MEDIA }, /* TiVo Button */
{ 0xa10c0807, KEY_POWER2 }, /* TV Power */
{ 0xa10c8807, KEY_TV }, /* Live TV/Swap */
{ 0xa10c2c03, KEY_VIDEO_NEXT }, /* TV Input */
{ 0xa10cc807, KEY_INFO },
{ 0xa10cfa05, KEY_CYCLEWINDOWS }, /* Window */
{ 0x0085305f, KEY_CYCLEWINDOWS },
{ 0xa10c6c03, KEY_EPG }, /* Guide */
{ 0xa10c2807, KEY_UP },
{ 0xa10c6807, KEY_DOWN },
{ 0xa10ce807, KEY_LEFT },
{ 0xa10ca807, KEY_RIGHT },
{ 0xa10c1807, KEY_SCROLLDOWN }, /* Red Thumbs Down */
{ 0xa10c9807, KEY_SELECT },
{ 0xa10c5807, KEY_SCROLLUP }, /* Green Thumbs Up */
{ 0xa10c3807, KEY_VOLUMEUP },
{ 0xa10cb807, KEY_VOLUMEDOWN },
{ 0xa10cd807, KEY_MUTE },
{ 0xa10c040b, KEY_RECORD },
{ 0xa10c7807, KEY_CHANNELUP },
{ 0xa10cf807, KEY_CHANNELDOWN },
{ 0x0085301f, KEY_CHANNELDOWN },
{ 0xa10c840b, KEY_PLAY },
{ 0xa10cc40b, KEY_PAUSE },
{ 0xa10ca40b, KEY_SLOW },
{ 0xa10c440b, KEY_REWIND },
{ 0xa10c240b, KEY_FASTFORWARD },
{ 0xa10c640b, KEY_PREVIOUS },
{ 0xa10ce40b, KEY_NEXT }, /* ->| */
{ 0xa10c220d, KEY_ZOOM }, /* Aspect */
{ 0xa10c120d, KEY_STOP },
{ 0xa10c520d, KEY_DVD }, /* DVD Menu */
{ 0xa10c140b, KEY_NUMERIC_1 },
{ 0xa10c940b, KEY_NUMERIC_2 },
{ 0xa10c540b, KEY_NUMERIC_3 },
{ 0xa10cd40b, KEY_NUMERIC_4 },
{ 0xa10c340b, KEY_NUMERIC_5 },
{ 0xa10cb40b, KEY_NUMERIC_6 },
{ 0xa10c740b, KEY_NUMERIC_7 },
{ 0xa10cf40b, KEY_NUMERIC_8 },
{ 0x0085302f, KEY_NUMERIC_8 },
{ 0xa10c0c03, KEY_NUMERIC_9 },
{ 0xa10c8c03, KEY_NUMERIC_0 },
{ 0xa10ccc03, KEY_ENTER },
{ 0xa10c4c03, KEY_CLEAR },
};
static struct rc_map_list tivo_map = {
.map = {
.scan = tivo,
.size = ARRAY_SIZE(tivo),
.rc_type = RC_TYPE_NEC,
.name = RC_MAP_TIVO,
}
};
static int __init init_rc_map_tivo(void)
{
return rc_map_register(&tivo_map);
}
static void __exit exit_rc_map_tivo(void)
{
rc_map_unregister(&tivo_map);
}
module_init(init_rc_map_tivo)
module_exit(exit_rc_map_tivo)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jarod Wilson <jarod@redhat.com>");
| gpl-2.0 |
PatrikKT/android_kernel_huawei_y536a1 | kernel/async.c | 2792 | 9257 | /*
* async.c: Asynchronous function calls for boot performance
*
* (C) Copyright 2009 Intel Corporation
* Author: Arjan van de Ven <arjan@linux.intel.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; version 2
* of the License.
*/
/*
Goals and Theory of Operation
The primary goal of this feature is to reduce the kernel boot time,
by doing various independent hardware delays and discovery operations
decoupled and not strictly serialized.
More specifically, the asynchronous function call concept allows
certain operations (primarily during system boot) to happen
asynchronously, out of order, while these operations still
have their externally visible parts happen sequentially and in-order.
(not unlike how out-of-order CPUs retire their instructions in order)
Key to the asynchronous function call implementation is the concept of
a "sequence cookie" (which, although it has an abstracted type, can be
thought of as a monotonically incrementing number).
The async core will assign each scheduled event such a sequence cookie and
pass this to the called functions.
The asynchronously called function should before doing a globally visible
operation, such as registering device numbers, call the
async_synchronize_cookie() function and pass in its own cookie. The
async_synchronize_cookie() function will make sure that all asynchronous
operations that were scheduled prior to the operation corresponding with the
cookie have completed.
Subsystem/driver initialization code that scheduled asynchronous probe
functions, but which shares global resources with other drivers/subsystems
that do not use the asynchronous call feature, need to do a full
synchronization with the async_synchronize_full() function, before returning
from their init function. This is to maintain strict ordering between the
asynchronous and synchronous parts of the kernel.
*/
#include <linux/async.h>
#include <linux/atomic.h>
#include <linux/ktime.h>
#include <linux/export.h>
#include <linux/wait.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
static async_cookie_t next_cookie = 1;
#define MAX_WORK 32768
static LIST_HEAD(async_pending);
static LIST_HEAD(async_running);
static DEFINE_SPINLOCK(async_lock);
struct async_entry {
struct list_head list;
struct work_struct work;
async_cookie_t cookie;
async_func_ptr *func;
void *data;
struct list_head *running;
};
static DECLARE_WAIT_QUEUE_HEAD(async_done);
static atomic_t entry_count;
/*
* MUST be called with the lock held!
*/
static async_cookie_t __lowest_in_progress(struct list_head *running)
{
struct async_entry *entry;
if (!list_empty(running)) {
entry = list_first_entry(running,
struct async_entry, list);
return entry->cookie;
}
list_for_each_entry(entry, &async_pending, list)
if (entry->running == running)
return entry->cookie;
return next_cookie; /* "infinity" value */
}
static async_cookie_t lowest_in_progress(struct list_head *running)
{
unsigned long flags;
async_cookie_t ret;
spin_lock_irqsave(&async_lock, flags);
ret = __lowest_in_progress(running);
spin_unlock_irqrestore(&async_lock, flags);
return ret;
}
/*
* pick the first pending entry and run it
*/
static void async_run_entry_fn(struct work_struct *work)
{
struct async_entry *entry =
container_of(work, struct async_entry, work);
unsigned long flags;
ktime_t uninitialized_var(calltime), delta, rettime;
/* 1) move self to the running queue */
spin_lock_irqsave(&async_lock, flags);
list_move_tail(&entry->list, entry->running);
spin_unlock_irqrestore(&async_lock, flags);
/* 2) run (and print duration) */
if (initcall_debug && system_state == SYSTEM_BOOTING) {
printk(KERN_DEBUG "calling %lli_%pF @ %i\n",
(long long)entry->cookie,
entry->func, task_pid_nr(current));
calltime = ktime_get();
}
entry->func(entry->data, entry->cookie);
if (initcall_debug && system_state == SYSTEM_BOOTING) {
rettime = ktime_get();
delta = ktime_sub(rettime, calltime);
printk(KERN_DEBUG "initcall %lli_%pF returned 0 after %lld usecs\n",
(long long)entry->cookie,
entry->func,
(long long)ktime_to_ns(delta) >> 10);
}
/* 3) remove self from the running queue */
spin_lock_irqsave(&async_lock, flags);
list_del(&entry->list);
/* 4) free the entry */
kfree(entry);
atomic_dec(&entry_count);
spin_unlock_irqrestore(&async_lock, flags);
/* 5) wake up any waiters */
wake_up(&async_done);
}
static async_cookie_t __async_schedule(async_func_ptr *ptr, void *data, struct list_head *running)
{
struct async_entry *entry;
unsigned long flags;
async_cookie_t newcookie;
/* allow irq-off callers */
entry = kzalloc(sizeof(struct async_entry), GFP_ATOMIC);
/*
* If we're out of memory or if there's too much work
* pending already, we execute synchronously.
*/
if (!entry || atomic_read(&entry_count) > MAX_WORK) {
kfree(entry);
spin_lock_irqsave(&async_lock, flags);
newcookie = next_cookie++;
spin_unlock_irqrestore(&async_lock, flags);
/* low on memory.. run synchronously */
ptr(data, newcookie);
return newcookie;
}
INIT_WORK(&entry->work, async_run_entry_fn);
entry->func = ptr;
entry->data = data;
entry->running = running;
spin_lock_irqsave(&async_lock, flags);
newcookie = entry->cookie = next_cookie++;
list_add_tail(&entry->list, &async_pending);
atomic_inc(&entry_count);
spin_unlock_irqrestore(&async_lock, flags);
/* schedule for execution */
queue_work(system_unbound_wq, &entry->work);
return newcookie;
}
/**
* async_schedule - schedule a function for asynchronous execution
* @ptr: function to execute asynchronously
* @data: data pointer to pass to the function
*
* Returns an async_cookie_t that may be used for checkpointing later.
* Note: This function may be called from atomic or non-atomic contexts.
*/
async_cookie_t async_schedule(async_func_ptr *ptr, void *data)
{
return __async_schedule(ptr, data, &async_running);
}
EXPORT_SYMBOL_GPL(async_schedule);
/**
* async_schedule_domain - schedule a function for asynchronous execution within a certain domain
* @ptr: function to execute asynchronously
* @data: data pointer to pass to the function
* @running: running list for the domain
*
* Returns an async_cookie_t that may be used for checkpointing later.
* @running may be used in the async_synchronize_*_domain() functions
* to wait within a certain synchronization domain rather than globally.
* A synchronization domain is specified via the running queue @running to use.
* Note: This function may be called from atomic or non-atomic contexts.
*/
async_cookie_t async_schedule_domain(async_func_ptr *ptr, void *data,
struct list_head *running)
{
return __async_schedule(ptr, data, running);
}
EXPORT_SYMBOL_GPL(async_schedule_domain);
/**
* async_synchronize_full - synchronize all asynchronous function calls
*
* This function waits until all asynchronous function calls have been done.
*/
void async_synchronize_full(void)
{
do {
async_synchronize_cookie(next_cookie);
} while (!list_empty(&async_running) || !list_empty(&async_pending));
}
EXPORT_SYMBOL_GPL(async_synchronize_full);
/**
* async_synchronize_full_domain - synchronize all asynchronous function within a certain domain
* @list: running list to synchronize on
*
* This function waits until all asynchronous function calls for the
* synchronization domain specified by the running list @list have been done.
*/
void async_synchronize_full_domain(struct list_head *list)
{
async_synchronize_cookie_domain(next_cookie, list);
}
EXPORT_SYMBOL_GPL(async_synchronize_full_domain);
/**
* async_synchronize_cookie_domain - synchronize asynchronous function calls within a certain domain with cookie checkpointing
* @cookie: async_cookie_t to use as checkpoint
* @running: running list to synchronize on
*
* This function waits until all asynchronous function calls for the
* synchronization domain specified by the running list @list submitted
* prior to @cookie have been done.
*/
void async_synchronize_cookie_domain(async_cookie_t cookie,
struct list_head *running)
{
ktime_t uninitialized_var(starttime), delta, endtime;
if (initcall_debug && system_state == SYSTEM_BOOTING) {
printk(KERN_DEBUG "async_waiting @ %i\n", task_pid_nr(current));
starttime = ktime_get();
}
wait_event(async_done, lowest_in_progress(running) >= cookie);
if (initcall_debug && system_state == SYSTEM_BOOTING) {
endtime = ktime_get();
delta = ktime_sub(endtime, starttime);
printk(KERN_DEBUG "async_continuing @ %i after %lli usec\n",
task_pid_nr(current),
(long long)ktime_to_ns(delta) >> 10);
}
}
EXPORT_SYMBOL_GPL(async_synchronize_cookie_domain);
/**
* async_synchronize_cookie - synchronize asynchronous function calls with cookie checkpointing
* @cookie: async_cookie_t to use as checkpoint
*
* This function waits until all asynchronous function calls prior to @cookie
* have been done.
*/
void async_synchronize_cookie(async_cookie_t cookie)
{
async_synchronize_cookie_domain(cookie, &async_running);
}
EXPORT_SYMBOL_GPL(async_synchronize_cookie);
| gpl-2.0 |
Alex-V2/Alex-V_SE_OneX | drivers/spi/spi-coldfire-qspi.c | 2792 | 16559 | /*
* Freescale/Motorola Coldfire Queued SPI driver
*
* Copyright 2010 Steven King <sfking@fdwdc.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., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/errno.h>
#include <linux/platform_device.h>
#include <linux/sched.h>
#include <linux/workqueue.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/spi/spi.h>
#include <asm/coldfire.h>
#include <asm/mcfsim.h>
#include <asm/mcfqspi.h>
#define DRIVER_NAME "mcfqspi"
#define MCFQSPI_BUSCLK (MCF_BUSCLK / 2)
#define MCFQSPI_QMR 0x00
#define MCFQSPI_QMR_MSTR 0x8000
#define MCFQSPI_QMR_CPOL 0x0200
#define MCFQSPI_QMR_CPHA 0x0100
#define MCFQSPI_QDLYR 0x04
#define MCFQSPI_QDLYR_SPE 0x8000
#define MCFQSPI_QWR 0x08
#define MCFQSPI_QWR_HALT 0x8000
#define MCFQSPI_QWR_WREN 0x4000
#define MCFQSPI_QWR_CSIV 0x1000
#define MCFQSPI_QIR 0x0C
#define MCFQSPI_QIR_WCEFB 0x8000
#define MCFQSPI_QIR_ABRTB 0x4000
#define MCFQSPI_QIR_ABRTL 0x1000
#define MCFQSPI_QIR_WCEFE 0x0800
#define MCFQSPI_QIR_ABRTE 0x0400
#define MCFQSPI_QIR_SPIFE 0x0100
#define MCFQSPI_QIR_WCEF 0x0008
#define MCFQSPI_QIR_ABRT 0x0004
#define MCFQSPI_QIR_SPIF 0x0001
#define MCFQSPI_QAR 0x010
#define MCFQSPI_QAR_TXBUF 0x00
#define MCFQSPI_QAR_RXBUF 0x10
#define MCFQSPI_QAR_CMDBUF 0x20
#define MCFQSPI_QDR 0x014
#define MCFQSPI_QCR 0x014
#define MCFQSPI_QCR_CONT 0x8000
#define MCFQSPI_QCR_BITSE 0x4000
#define MCFQSPI_QCR_DT 0x2000
struct mcfqspi {
void __iomem *iobase;
int irq;
struct clk *clk;
struct mcfqspi_cs_control *cs_control;
wait_queue_head_t waitq;
struct work_struct work;
struct workqueue_struct *workq;
spinlock_t lock;
struct list_head msgq;
};
static void mcfqspi_wr_qmr(struct mcfqspi *mcfqspi, u16 val)
{
writew(val, mcfqspi->iobase + MCFQSPI_QMR);
}
static void mcfqspi_wr_qdlyr(struct mcfqspi *mcfqspi, u16 val)
{
writew(val, mcfqspi->iobase + MCFQSPI_QDLYR);
}
static u16 mcfqspi_rd_qdlyr(struct mcfqspi *mcfqspi)
{
return readw(mcfqspi->iobase + MCFQSPI_QDLYR);
}
static void mcfqspi_wr_qwr(struct mcfqspi *mcfqspi, u16 val)
{
writew(val, mcfqspi->iobase + MCFQSPI_QWR);
}
static void mcfqspi_wr_qir(struct mcfqspi *mcfqspi, u16 val)
{
writew(val, mcfqspi->iobase + MCFQSPI_QIR);
}
static void mcfqspi_wr_qar(struct mcfqspi *mcfqspi, u16 val)
{
writew(val, mcfqspi->iobase + MCFQSPI_QAR);
}
static void mcfqspi_wr_qdr(struct mcfqspi *mcfqspi, u16 val)
{
writew(val, mcfqspi->iobase + MCFQSPI_QDR);
}
static u16 mcfqspi_rd_qdr(struct mcfqspi *mcfqspi)
{
return readw(mcfqspi->iobase + MCFQSPI_QDR);
}
static void mcfqspi_cs_select(struct mcfqspi *mcfqspi, u8 chip_select,
bool cs_high)
{
mcfqspi->cs_control->select(mcfqspi->cs_control, chip_select, cs_high);
}
static void mcfqspi_cs_deselect(struct mcfqspi *mcfqspi, u8 chip_select,
bool cs_high)
{
mcfqspi->cs_control->deselect(mcfqspi->cs_control, chip_select, cs_high);
}
static int mcfqspi_cs_setup(struct mcfqspi *mcfqspi)
{
return (mcfqspi->cs_control && mcfqspi->cs_control->setup) ?
mcfqspi->cs_control->setup(mcfqspi->cs_control) : 0;
}
static void mcfqspi_cs_teardown(struct mcfqspi *mcfqspi)
{
if (mcfqspi->cs_control && mcfqspi->cs_control->teardown)
mcfqspi->cs_control->teardown(mcfqspi->cs_control);
}
static u8 mcfqspi_qmr_baud(u32 speed_hz)
{
return clamp((MCFQSPI_BUSCLK + speed_hz - 1) / speed_hz, 2u, 255u);
}
static bool mcfqspi_qdlyr_spe(struct mcfqspi *mcfqspi)
{
return mcfqspi_rd_qdlyr(mcfqspi) & MCFQSPI_QDLYR_SPE;
}
static irqreturn_t mcfqspi_irq_handler(int this_irq, void *dev_id)
{
struct mcfqspi *mcfqspi = dev_id;
/* clear interrupt */
mcfqspi_wr_qir(mcfqspi, MCFQSPI_QIR_SPIFE | MCFQSPI_QIR_SPIF);
wake_up(&mcfqspi->waitq);
return IRQ_HANDLED;
}
static void mcfqspi_transfer_msg8(struct mcfqspi *mcfqspi, unsigned count,
const u8 *txbuf, u8 *rxbuf)
{
unsigned i, n, offset = 0;
n = min(count, 16u);
mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_CMDBUF);
for (i = 0; i < n; ++i)
mcfqspi_wr_qdr(mcfqspi, MCFQSPI_QCR_BITSE);
mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_TXBUF);
if (txbuf)
for (i = 0; i < n; ++i)
mcfqspi_wr_qdr(mcfqspi, *txbuf++);
else
for (i = 0; i < count; ++i)
mcfqspi_wr_qdr(mcfqspi, 0);
count -= n;
if (count) {
u16 qwr = 0xf08;
mcfqspi_wr_qwr(mcfqspi, 0x700);
mcfqspi_wr_qdlyr(mcfqspi, MCFQSPI_QDLYR_SPE);
do {
wait_event(mcfqspi->waitq, !mcfqspi_qdlyr_spe(mcfqspi));
mcfqspi_wr_qwr(mcfqspi, qwr);
mcfqspi_wr_qdlyr(mcfqspi, MCFQSPI_QDLYR_SPE);
if (rxbuf) {
mcfqspi_wr_qar(mcfqspi,
MCFQSPI_QAR_RXBUF + offset);
for (i = 0; i < 8; ++i)
*rxbuf++ = mcfqspi_rd_qdr(mcfqspi);
}
n = min(count, 8u);
if (txbuf) {
mcfqspi_wr_qar(mcfqspi,
MCFQSPI_QAR_TXBUF + offset);
for (i = 0; i < n; ++i)
mcfqspi_wr_qdr(mcfqspi, *txbuf++);
}
qwr = (offset ? 0x808 : 0) + ((n - 1) << 8);
offset ^= 8;
count -= n;
} while (count);
wait_event(mcfqspi->waitq, !mcfqspi_qdlyr_spe(mcfqspi));
mcfqspi_wr_qwr(mcfqspi, qwr);
mcfqspi_wr_qdlyr(mcfqspi, MCFQSPI_QDLYR_SPE);
if (rxbuf) {
mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_RXBUF + offset);
for (i = 0; i < 8; ++i)
*rxbuf++ = mcfqspi_rd_qdr(mcfqspi);
offset ^= 8;
}
} else {
mcfqspi_wr_qwr(mcfqspi, (n - 1) << 8);
mcfqspi_wr_qdlyr(mcfqspi, MCFQSPI_QDLYR_SPE);
}
wait_event(mcfqspi->waitq, !mcfqspi_qdlyr_spe(mcfqspi));
if (rxbuf) {
mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_RXBUF + offset);
for (i = 0; i < n; ++i)
*rxbuf++ = mcfqspi_rd_qdr(mcfqspi);
}
}
static void mcfqspi_transfer_msg16(struct mcfqspi *mcfqspi, unsigned count,
const u16 *txbuf, u16 *rxbuf)
{
unsigned i, n, offset = 0;
n = min(count, 16u);
mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_CMDBUF);
for (i = 0; i < n; ++i)
mcfqspi_wr_qdr(mcfqspi, MCFQSPI_QCR_BITSE);
mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_TXBUF);
if (txbuf)
for (i = 0; i < n; ++i)
mcfqspi_wr_qdr(mcfqspi, *txbuf++);
else
for (i = 0; i < count; ++i)
mcfqspi_wr_qdr(mcfqspi, 0);
count -= n;
if (count) {
u16 qwr = 0xf08;
mcfqspi_wr_qwr(mcfqspi, 0x700);
mcfqspi_wr_qdlyr(mcfqspi, MCFQSPI_QDLYR_SPE);
do {
wait_event(mcfqspi->waitq, !mcfqspi_qdlyr_spe(mcfqspi));
mcfqspi_wr_qwr(mcfqspi, qwr);
mcfqspi_wr_qdlyr(mcfqspi, MCFQSPI_QDLYR_SPE);
if (rxbuf) {
mcfqspi_wr_qar(mcfqspi,
MCFQSPI_QAR_RXBUF + offset);
for (i = 0; i < 8; ++i)
*rxbuf++ = mcfqspi_rd_qdr(mcfqspi);
}
n = min(count, 8u);
if (txbuf) {
mcfqspi_wr_qar(mcfqspi,
MCFQSPI_QAR_TXBUF + offset);
for (i = 0; i < n; ++i)
mcfqspi_wr_qdr(mcfqspi, *txbuf++);
}
qwr = (offset ? 0x808 : 0x000) + ((n - 1) << 8);
offset ^= 8;
count -= n;
} while (count);
wait_event(mcfqspi->waitq, !mcfqspi_qdlyr_spe(mcfqspi));
mcfqspi_wr_qwr(mcfqspi, qwr);
mcfqspi_wr_qdlyr(mcfqspi, MCFQSPI_QDLYR_SPE);
if (rxbuf) {
mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_RXBUF + offset);
for (i = 0; i < 8; ++i)
*rxbuf++ = mcfqspi_rd_qdr(mcfqspi);
offset ^= 8;
}
} else {
mcfqspi_wr_qwr(mcfqspi, (n - 1) << 8);
mcfqspi_wr_qdlyr(mcfqspi, MCFQSPI_QDLYR_SPE);
}
wait_event(mcfqspi->waitq, !mcfqspi_qdlyr_spe(mcfqspi));
if (rxbuf) {
mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_RXBUF + offset);
for (i = 0; i < n; ++i)
*rxbuf++ = mcfqspi_rd_qdr(mcfqspi);
}
}
static void mcfqspi_work(struct work_struct *work)
{
struct mcfqspi *mcfqspi = container_of(work, struct mcfqspi, work);
unsigned long flags;
spin_lock_irqsave(&mcfqspi->lock, flags);
while (!list_empty(&mcfqspi->msgq)) {
struct spi_message *msg;
struct spi_device *spi;
struct spi_transfer *xfer;
int status = 0;
msg = container_of(mcfqspi->msgq.next, struct spi_message,
queue);
list_del_init(&msg->queue);
spin_unlock_irqrestore(&mcfqspi->lock, flags);
spi = msg->spi;
list_for_each_entry(xfer, &msg->transfers, transfer_list) {
bool cs_high = spi->mode & SPI_CS_HIGH;
u16 qmr = MCFQSPI_QMR_MSTR;
if (xfer->bits_per_word)
qmr |= xfer->bits_per_word << 10;
else
qmr |= spi->bits_per_word << 10;
if (spi->mode & SPI_CPHA)
qmr |= MCFQSPI_QMR_CPHA;
if (spi->mode & SPI_CPOL)
qmr |= MCFQSPI_QMR_CPOL;
if (xfer->speed_hz)
qmr |= mcfqspi_qmr_baud(xfer->speed_hz);
else
qmr |= mcfqspi_qmr_baud(spi->max_speed_hz);
mcfqspi_wr_qmr(mcfqspi, qmr);
mcfqspi_cs_select(mcfqspi, spi->chip_select, cs_high);
mcfqspi_wr_qir(mcfqspi, MCFQSPI_QIR_SPIFE);
if ((xfer->bits_per_word ? xfer->bits_per_word :
spi->bits_per_word) == 8)
mcfqspi_transfer_msg8(mcfqspi, xfer->len,
xfer->tx_buf,
xfer->rx_buf);
else
mcfqspi_transfer_msg16(mcfqspi, xfer->len / 2,
xfer->tx_buf,
xfer->rx_buf);
mcfqspi_wr_qir(mcfqspi, 0);
if (xfer->delay_usecs)
udelay(xfer->delay_usecs);
if (xfer->cs_change) {
if (!list_is_last(&xfer->transfer_list,
&msg->transfers))
mcfqspi_cs_deselect(mcfqspi,
spi->chip_select,
cs_high);
} else {
if (list_is_last(&xfer->transfer_list,
&msg->transfers))
mcfqspi_cs_deselect(mcfqspi,
spi->chip_select,
cs_high);
}
msg->actual_length += xfer->len;
}
msg->status = status;
msg->complete(msg->context);
spin_lock_irqsave(&mcfqspi->lock, flags);
}
spin_unlock_irqrestore(&mcfqspi->lock, flags);
}
static int mcfqspi_transfer(struct spi_device *spi, struct spi_message *msg)
{
struct mcfqspi *mcfqspi;
struct spi_transfer *xfer;
unsigned long flags;
mcfqspi = spi_master_get_devdata(spi->master);
list_for_each_entry(xfer, &msg->transfers, transfer_list) {
if (xfer->bits_per_word && ((xfer->bits_per_word < 8)
|| (xfer->bits_per_word > 16))) {
dev_dbg(&spi->dev,
"%d bits per word is not supported\n",
xfer->bits_per_word);
goto fail;
}
if (xfer->speed_hz) {
u32 real_speed = MCFQSPI_BUSCLK /
mcfqspi_qmr_baud(xfer->speed_hz);
if (real_speed != xfer->speed_hz)
dev_dbg(&spi->dev,
"using speed %d instead of %d\n",
real_speed, xfer->speed_hz);
}
}
msg->status = -EINPROGRESS;
msg->actual_length = 0;
spin_lock_irqsave(&mcfqspi->lock, flags);
list_add_tail(&msg->queue, &mcfqspi->msgq);
queue_work(mcfqspi->workq, &mcfqspi->work);
spin_unlock_irqrestore(&mcfqspi->lock, flags);
return 0;
fail:
msg->status = -EINVAL;
return -EINVAL;
}
static int mcfqspi_setup(struct spi_device *spi)
{
if ((spi->bits_per_word < 8) || (spi->bits_per_word > 16)) {
dev_dbg(&spi->dev, "%d bits per word is not supported\n",
spi->bits_per_word);
return -EINVAL;
}
if (spi->chip_select >= spi->master->num_chipselect) {
dev_dbg(&spi->dev, "%d chip select is out of range\n",
spi->chip_select);
return -EINVAL;
}
mcfqspi_cs_deselect(spi_master_get_devdata(spi->master),
spi->chip_select, spi->mode & SPI_CS_HIGH);
dev_dbg(&spi->dev,
"bits per word %d, chip select %d, speed %d KHz\n",
spi->bits_per_word, spi->chip_select,
(MCFQSPI_BUSCLK / mcfqspi_qmr_baud(spi->max_speed_hz))
/ 1000);
return 0;
}
static int __devinit mcfqspi_probe(struct platform_device *pdev)
{
struct spi_master *master;
struct mcfqspi *mcfqspi;
struct resource *res;
struct mcfqspi_platform_data *pdata;
int status;
master = spi_alloc_master(&pdev->dev, sizeof(*mcfqspi));
if (master == NULL) {
dev_dbg(&pdev->dev, "spi_alloc_master failed\n");
return -ENOMEM;
}
mcfqspi = spi_master_get_devdata(master);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_dbg(&pdev->dev, "platform_get_resource failed\n");
status = -ENXIO;
goto fail0;
}
if (!request_mem_region(res->start, resource_size(res), pdev->name)) {
dev_dbg(&pdev->dev, "request_mem_region failed\n");
status = -EBUSY;
goto fail0;
}
mcfqspi->iobase = ioremap(res->start, resource_size(res));
if (!mcfqspi->iobase) {
dev_dbg(&pdev->dev, "ioremap failed\n");
status = -ENOMEM;
goto fail1;
}
mcfqspi->irq = platform_get_irq(pdev, 0);
if (mcfqspi->irq < 0) {
dev_dbg(&pdev->dev, "platform_get_irq failed\n");
status = -ENXIO;
goto fail2;
}
status = request_irq(mcfqspi->irq, mcfqspi_irq_handler, IRQF_DISABLED,
pdev->name, mcfqspi);
if (status) {
dev_dbg(&pdev->dev, "request_irq failed\n");
goto fail2;
}
mcfqspi->clk = clk_get(&pdev->dev, "qspi_clk");
if (IS_ERR(mcfqspi->clk)) {
dev_dbg(&pdev->dev, "clk_get failed\n");
status = PTR_ERR(mcfqspi->clk);
goto fail3;
}
clk_enable(mcfqspi->clk);
mcfqspi->workq = create_singlethread_workqueue(dev_name(master->dev.parent));
if (!mcfqspi->workq) {
dev_dbg(&pdev->dev, "create_workqueue failed\n");
status = -ENOMEM;
goto fail4;
}
INIT_WORK(&mcfqspi->work, mcfqspi_work);
spin_lock_init(&mcfqspi->lock);
INIT_LIST_HEAD(&mcfqspi->msgq);
init_waitqueue_head(&mcfqspi->waitq);
pdata = pdev->dev.platform_data;
if (!pdata) {
dev_dbg(&pdev->dev, "platform data is missing\n");
goto fail5;
}
master->bus_num = pdata->bus_num;
master->num_chipselect = pdata->num_chipselect;
mcfqspi->cs_control = pdata->cs_control;
status = mcfqspi_cs_setup(mcfqspi);
if (status) {
dev_dbg(&pdev->dev, "error initializing cs_control\n");
goto fail5;
}
master->mode_bits = SPI_CS_HIGH | SPI_CPOL | SPI_CPHA;
master->setup = mcfqspi_setup;
master->transfer = mcfqspi_transfer;
platform_set_drvdata(pdev, master);
status = spi_register_master(master);
if (status) {
dev_dbg(&pdev->dev, "spi_register_master failed\n");
goto fail6;
}
dev_info(&pdev->dev, "Coldfire QSPI bus driver\n");
return 0;
fail6:
mcfqspi_cs_teardown(mcfqspi);
fail5:
destroy_workqueue(mcfqspi->workq);
fail4:
clk_disable(mcfqspi->clk);
clk_put(mcfqspi->clk);
fail3:
free_irq(mcfqspi->irq, mcfqspi);
fail2:
iounmap(mcfqspi->iobase);
fail1:
release_mem_region(res->start, resource_size(res));
fail0:
spi_master_put(master);
dev_dbg(&pdev->dev, "Coldfire QSPI probe failed\n");
return status;
}
static int __devexit mcfqspi_remove(struct platform_device *pdev)
{
struct spi_master *master = platform_get_drvdata(pdev);
struct mcfqspi *mcfqspi = spi_master_get_devdata(master);
struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
/* disable the hardware (set the baud rate to 0) */
mcfqspi_wr_qmr(mcfqspi, MCFQSPI_QMR_MSTR);
platform_set_drvdata(pdev, NULL);
mcfqspi_cs_teardown(mcfqspi);
destroy_workqueue(mcfqspi->workq);
clk_disable(mcfqspi->clk);
clk_put(mcfqspi->clk);
free_irq(mcfqspi->irq, mcfqspi);
iounmap(mcfqspi->iobase);
release_mem_region(res->start, resource_size(res));
spi_unregister_master(master);
spi_master_put(master);
return 0;
}
#ifdef CONFIG_PM
static int mcfqspi_suspend(struct device *dev)
{
struct mcfqspi *mcfqspi = platform_get_drvdata(to_platform_device(dev));
clk_disable(mcfqspi->clk);
return 0;
}
static int mcfqspi_resume(struct device *dev)
{
struct mcfqspi *mcfqspi = platform_get_drvdata(to_platform_device(dev));
clk_enable(mcfqspi->clk);
return 0;
}
static struct dev_pm_ops mcfqspi_dev_pm_ops = {
.suspend = mcfqspi_suspend,
.resume = mcfqspi_resume,
};
#define MCFQSPI_DEV_PM_OPS (&mcfqspi_dev_pm_ops)
#else
#define MCFQSPI_DEV_PM_OPS NULL
#endif
static struct platform_driver mcfqspi_driver = {
.driver.name = DRIVER_NAME,
.driver.owner = THIS_MODULE,
.driver.pm = MCFQSPI_DEV_PM_OPS,
.remove = __devexit_p(mcfqspi_remove),
};
static int __init mcfqspi_init(void)
{
return platform_driver_probe(&mcfqspi_driver, mcfqspi_probe);
}
module_init(mcfqspi_init);
static void __exit mcfqspi_exit(void)
{
platform_driver_unregister(&mcfqspi_driver);
}
module_exit(mcfqspi_exit);
MODULE_AUTHOR("Steven King <sfking@fdwdc.com>");
MODULE_DESCRIPTION("Coldfire QSPI Controller Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" DRIVER_NAME);
| gpl-2.0 |
ztemt/NX512J_kernel | drivers/gpio/gpio-max7300.c | 3304 | 2011 | /*
* Copyright (C) 2009 Wolfram Sang, 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.
*
* Check max730x.c for further details.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/mutex.h>
#include <linux/i2c.h>
#include <linux/spi/max7301.h>
#include <linux/slab.h>
static int max7300_i2c_write(struct device *dev, unsigned int reg,
unsigned int val)
{
struct i2c_client *client = to_i2c_client(dev);
return i2c_smbus_write_byte_data(client, reg, val);
}
static int max7300_i2c_read(struct device *dev, unsigned int reg)
{
struct i2c_client *client = to_i2c_client(dev);
return i2c_smbus_read_byte_data(client, reg);
}
static int max7300_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct max7301 *ts;
int ret;
if (!i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_BYTE_DATA))
return -EIO;
ts = devm_kzalloc(&client->dev, sizeof(struct max7301), GFP_KERNEL);
if (!ts)
return -ENOMEM;
ts->read = max7300_i2c_read;
ts->write = max7300_i2c_write;
ts->dev = &client->dev;
ret = __max730x_probe(ts);
return ret;
}
static int max7300_remove(struct i2c_client *client)
{
return __max730x_remove(&client->dev);
}
static const struct i2c_device_id max7300_id[] = {
{ "max7300", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, max7300_id);
static struct i2c_driver max7300_driver = {
.driver = {
.name = "max7300",
.owner = THIS_MODULE,
},
.probe = max7300_probe,
.remove = max7300_remove,
.id_table = max7300_id,
};
static int __init max7300_init(void)
{
return i2c_add_driver(&max7300_driver);
}
subsys_initcall(max7300_init);
static void __exit max7300_exit(void)
{
i2c_del_driver(&max7300_driver);
}
module_exit(max7300_exit);
MODULE_AUTHOR("Wolfram Sang");
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("MAX7300 GPIO-Expander");
| gpl-2.0 |
Nibsalot/AK-Mako | net/netfilter/ipvs/ip_vs_xmit.c | 3816 | 34522 | /*
* ip_vs_xmit.c: various packet transmitters for IPVS
*
* Authors: Wensong Zhang <wensong@linuxvirtualserver.org>
* Julian Anastasov <ja@ssi.bg>
*
* This program is free software; you can redistribute 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.
*
* Changes:
*
* Description of forwarding methods:
* - all transmitters are called from LOCAL_IN (remote clients) and
* LOCAL_OUT (local clients) but for ICMP can be called from FORWARD
* - not all connections have destination server, for example,
* connections in backup server when fwmark is used
* - bypass connections use daddr from packet
* LOCAL_OUT rules:
* - skb->dev is NULL, skb->protocol is not set (both are set in POST_ROUTING)
* - skb->pkt_type is not set yet
* - the only place where we can see skb->sk != NULL
*/
#define KMSG_COMPONENT "IPVS"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/tcp.h> /* for tcphdr */
#include <net/ip.h>
#include <net/tcp.h> /* for csum_tcpudp_magic */
#include <net/udp.h>
#include <net/icmp.h> /* for icmp_send */
#include <net/route.h> /* for ip_route_output */
#include <net/ipv6.h>
#include <net/ip6_route.h>
#include <net/addrconf.h>
#include <linux/icmpv6.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <net/ip_vs.h>
enum {
IP_VS_RT_MODE_LOCAL = 1, /* Allow local dest */
IP_VS_RT_MODE_NON_LOCAL = 2, /* Allow non-local dest */
IP_VS_RT_MODE_RDR = 4, /* Allow redirect from remote daddr to
* local
*/
};
/*
* Destination cache to speed up outgoing route lookup
*/
static inline void
__ip_vs_dst_set(struct ip_vs_dest *dest, u32 rtos, struct dst_entry *dst,
u32 dst_cookie)
{
struct dst_entry *old_dst;
old_dst = dest->dst_cache;
dest->dst_cache = dst;
dest->dst_rtos = rtos;
dest->dst_cookie = dst_cookie;
dst_release(old_dst);
}
static inline struct dst_entry *
__ip_vs_dst_check(struct ip_vs_dest *dest, u32 rtos)
{
struct dst_entry *dst = dest->dst_cache;
if (!dst)
return NULL;
if ((dst->obsolete || rtos != dest->dst_rtos) &&
dst->ops->check(dst, dest->dst_cookie) == NULL) {
dest->dst_cache = NULL;
dst_release(dst);
return NULL;
}
dst_hold(dst);
return dst;
}
/* Get route to destination or remote server */
static struct rtable *
__ip_vs_get_out_rt(struct sk_buff *skb, struct ip_vs_dest *dest,
__be32 daddr, u32 rtos, int rt_mode, __be32 *ret_saddr)
{
struct net *net = dev_net(skb_dst(skb)->dev);
struct rtable *rt; /* Route to the other host */
struct rtable *ort; /* Original route */
int local;
if (dest) {
spin_lock(&dest->dst_lock);
if (!(rt = (struct rtable *)
__ip_vs_dst_check(dest, rtos))) {
struct flowi4 fl4;
memset(&fl4, 0, sizeof(fl4));
fl4.daddr = dest->addr.ip;
fl4.flowi4_tos = rtos;
rt = ip_route_output_key(net, &fl4);
if (IS_ERR(rt)) {
spin_unlock(&dest->dst_lock);
IP_VS_DBG_RL("ip_route_output error, dest: %pI4\n",
&dest->addr.ip);
return NULL;
}
__ip_vs_dst_set(dest, rtos, dst_clone(&rt->dst), 0);
dest->dst_saddr.ip = fl4.saddr;
IP_VS_DBG(10, "new dst %pI4, src %pI4, refcnt=%d, "
"rtos=%X\n",
&dest->addr.ip, &dest->dst_saddr.ip,
atomic_read(&rt->dst.__refcnt), rtos);
}
daddr = dest->addr.ip;
if (ret_saddr)
*ret_saddr = dest->dst_saddr.ip;
spin_unlock(&dest->dst_lock);
} else {
struct flowi4 fl4;
memset(&fl4, 0, sizeof(fl4));
fl4.daddr = daddr;
fl4.flowi4_tos = rtos;
rt = ip_route_output_key(net, &fl4);
if (IS_ERR(rt)) {
IP_VS_DBG_RL("ip_route_output error, dest: %pI4\n",
&daddr);
return NULL;
}
if (ret_saddr)
*ret_saddr = fl4.saddr;
}
local = rt->rt_flags & RTCF_LOCAL;
if (!((local ? IP_VS_RT_MODE_LOCAL : IP_VS_RT_MODE_NON_LOCAL) &
rt_mode)) {
IP_VS_DBG_RL("Stopping traffic to %s address, dest: %pI4\n",
(rt->rt_flags & RTCF_LOCAL) ?
"local":"non-local", &daddr);
ip_rt_put(rt);
return NULL;
}
if (local && !(rt_mode & IP_VS_RT_MODE_RDR) &&
!((ort = skb_rtable(skb)) && ort->rt_flags & RTCF_LOCAL)) {
IP_VS_DBG_RL("Redirect from non-local address %pI4 to local "
"requires NAT method, dest: %pI4\n",
&ip_hdr(skb)->daddr, &daddr);
ip_rt_put(rt);
return NULL;
}
if (unlikely(!local && ipv4_is_loopback(ip_hdr(skb)->saddr))) {
IP_VS_DBG_RL("Stopping traffic from loopback address %pI4 "
"to non-local address, dest: %pI4\n",
&ip_hdr(skb)->saddr, &daddr);
ip_rt_put(rt);
return NULL;
}
return rt;
}
/* Reroute packet to local IPv4 stack after DNAT */
static int
__ip_vs_reroute_locally(struct sk_buff *skb)
{
struct rtable *rt = skb_rtable(skb);
struct net_device *dev = rt->dst.dev;
struct net *net = dev_net(dev);
struct iphdr *iph = ip_hdr(skb);
if (rt_is_input_route(rt)) {
unsigned long orefdst = skb->_skb_refdst;
if (ip_route_input(skb, iph->daddr, iph->saddr,
iph->tos, skb->dev))
return 0;
refdst_drop(orefdst);
} else {
struct flowi4 fl4 = {
.daddr = iph->daddr,
.saddr = iph->saddr,
.flowi4_tos = RT_TOS(iph->tos),
.flowi4_mark = skb->mark,
};
rt = ip_route_output_key(net, &fl4);
if (IS_ERR(rt))
return 0;
if (!(rt->rt_flags & RTCF_LOCAL)) {
ip_rt_put(rt);
return 0;
}
/* Drop old route. */
skb_dst_drop(skb);
skb_dst_set(skb, &rt->dst);
}
return 1;
}
#ifdef CONFIG_IP_VS_IPV6
static inline int __ip_vs_is_local_route6(struct rt6_info *rt)
{
return rt->dst.dev && rt->dst.dev->flags & IFF_LOOPBACK;
}
static struct dst_entry *
__ip_vs_route_output_v6(struct net *net, struct in6_addr *daddr,
struct in6_addr *ret_saddr, int do_xfrm)
{
struct dst_entry *dst;
struct flowi6 fl6 = {
.daddr = *daddr,
};
dst = ip6_route_output(net, NULL, &fl6);
if (dst->error)
goto out_err;
if (!ret_saddr)
return dst;
if (ipv6_addr_any(&fl6.saddr) &&
ipv6_dev_get_saddr(net, ip6_dst_idev(dst)->dev,
&fl6.daddr, 0, &fl6.saddr) < 0)
goto out_err;
if (do_xfrm) {
dst = xfrm_lookup(net, dst, flowi6_to_flowi(&fl6), NULL, 0);
if (IS_ERR(dst)) {
dst = NULL;
goto out_err;
}
}
*ret_saddr = fl6.saddr;
return dst;
out_err:
dst_release(dst);
IP_VS_DBG_RL("ip6_route_output error, dest: %pI6\n", daddr);
return NULL;
}
/*
* Get route to destination or remote server
*/
static struct rt6_info *
__ip_vs_get_out_rt_v6(struct sk_buff *skb, struct ip_vs_dest *dest,
struct in6_addr *daddr, struct in6_addr *ret_saddr,
int do_xfrm, int rt_mode)
{
struct net *net = dev_net(skb_dst(skb)->dev);
struct rt6_info *rt; /* Route to the other host */
struct rt6_info *ort; /* Original route */
struct dst_entry *dst;
int local;
if (dest) {
spin_lock(&dest->dst_lock);
rt = (struct rt6_info *)__ip_vs_dst_check(dest, 0);
if (!rt) {
u32 cookie;
dst = __ip_vs_route_output_v6(net, &dest->addr.in6,
&dest->dst_saddr.in6,
do_xfrm);
if (!dst) {
spin_unlock(&dest->dst_lock);
return NULL;
}
rt = (struct rt6_info *) dst;
cookie = rt->rt6i_node ? rt->rt6i_node->fn_sernum : 0;
__ip_vs_dst_set(dest, 0, dst_clone(&rt->dst), cookie);
IP_VS_DBG(10, "new dst %pI6, src %pI6, refcnt=%d\n",
&dest->addr.in6, &dest->dst_saddr.in6,
atomic_read(&rt->dst.__refcnt));
}
if (ret_saddr)
*ret_saddr = dest->dst_saddr.in6;
spin_unlock(&dest->dst_lock);
} else {
dst = __ip_vs_route_output_v6(net, daddr, ret_saddr, do_xfrm);
if (!dst)
return NULL;
rt = (struct rt6_info *) dst;
}
local = __ip_vs_is_local_route6(rt);
if (!((local ? IP_VS_RT_MODE_LOCAL : IP_VS_RT_MODE_NON_LOCAL) &
rt_mode)) {
IP_VS_DBG_RL("Stopping traffic to %s address, dest: %pI6\n",
local ? "local":"non-local", daddr);
dst_release(&rt->dst);
return NULL;
}
if (local && !(rt_mode & IP_VS_RT_MODE_RDR) &&
!((ort = (struct rt6_info *) skb_dst(skb)) &&
__ip_vs_is_local_route6(ort))) {
IP_VS_DBG_RL("Redirect from non-local address %pI6 to local "
"requires NAT method, dest: %pI6\n",
&ipv6_hdr(skb)->daddr, daddr);
dst_release(&rt->dst);
return NULL;
}
if (unlikely(!local && (!skb->dev || skb->dev->flags & IFF_LOOPBACK) &&
ipv6_addr_type(&ipv6_hdr(skb)->saddr) &
IPV6_ADDR_LOOPBACK)) {
IP_VS_DBG_RL("Stopping traffic from loopback address %pI6 "
"to non-local address, dest: %pI6\n",
&ipv6_hdr(skb)->saddr, daddr);
dst_release(&rt->dst);
return NULL;
}
return rt;
}
#endif
/*
* Release dest->dst_cache before a dest is removed
*/
void
ip_vs_dst_reset(struct ip_vs_dest *dest)
{
struct dst_entry *old_dst;
old_dst = dest->dst_cache;
dest->dst_cache = NULL;
dst_release(old_dst);
}
#define IP_VS_XMIT_TUNNEL(skb, cp) \
({ \
int __ret = NF_ACCEPT; \
\
(skb)->ipvs_property = 1; \
if (unlikely((cp)->flags & IP_VS_CONN_F_NFCT)) \
__ret = ip_vs_confirm_conntrack(skb); \
if (__ret == NF_ACCEPT) { \
nf_reset(skb); \
skb_forward_csum(skb); \
} \
__ret; \
})
#define IP_VS_XMIT_NAT(pf, skb, cp, local) \
do { \
(skb)->ipvs_property = 1; \
if (likely(!((cp)->flags & IP_VS_CONN_F_NFCT))) \
ip_vs_notrack(skb); \
else \
ip_vs_update_conntrack(skb, cp, 1); \
if (local) \
return NF_ACCEPT; \
skb_forward_csum(skb); \
NF_HOOK(pf, NF_INET_LOCAL_OUT, (skb), NULL, \
skb_dst(skb)->dev, dst_output); \
} while (0)
#define IP_VS_XMIT(pf, skb, cp, local) \
do { \
(skb)->ipvs_property = 1; \
if (likely(!((cp)->flags & IP_VS_CONN_F_NFCT))) \
ip_vs_notrack(skb); \
if (local) \
return NF_ACCEPT; \
skb_forward_csum(skb); \
NF_HOOK(pf, NF_INET_LOCAL_OUT, (skb), NULL, \
skb_dst(skb)->dev, dst_output); \
} while (0)
/*
* NULL transmitter (do nothing except return NF_ACCEPT)
*/
int
ip_vs_null_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp)
{
/* we do not touch skb and do not need pskb ptr */
IP_VS_XMIT(NFPROTO_IPV4, skb, cp, 1);
}
/*
* Bypass transmitter
* Let packets bypass the destination when the destination is not
* available, it may be only used in transparent cache cluster.
*/
int
ip_vs_bypass_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp)
{
struct rtable *rt; /* Route to the other host */
struct iphdr *iph = ip_hdr(skb);
int mtu;
EnterFunction(10);
if (!(rt = __ip_vs_get_out_rt(skb, NULL, iph->daddr, RT_TOS(iph->tos),
IP_VS_RT_MODE_NON_LOCAL, NULL)))
goto tx_error_icmp;
/* MTU checking */
mtu = dst_mtu(&rt->dst);
if ((skb->len > mtu) && (iph->frag_off & htons(IP_DF)) &&
!skb_is_gso(skb)) {
ip_rt_put(rt);
icmp_send(skb, ICMP_DEST_UNREACH,ICMP_FRAG_NEEDED, htonl(mtu));
IP_VS_DBG_RL("%s(): frag needed\n", __func__);
goto tx_error;
}
/*
* Call ip_send_check because we are not sure it is called
* after ip_defrag. Is copy-on-write needed?
*/
if (unlikely((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL)) {
ip_rt_put(rt);
return NF_STOLEN;
}
ip_send_check(ip_hdr(skb));
/* drop old route */
skb_dst_drop(skb);
skb_dst_set(skb, &rt->dst);
/* Another hack: avoid icmp_send in ip_fragment */
skb->local_df = 1;
IP_VS_XMIT(NFPROTO_IPV4, skb, cp, 0);
LeaveFunction(10);
return NF_STOLEN;
tx_error_icmp:
dst_link_failure(skb);
tx_error:
kfree_skb(skb);
LeaveFunction(10);
return NF_STOLEN;
}
#ifdef CONFIG_IP_VS_IPV6
int
ip_vs_bypass_xmit_v6(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp)
{
struct rt6_info *rt; /* Route to the other host */
struct ipv6hdr *iph = ipv6_hdr(skb);
int mtu;
EnterFunction(10);
if (!(rt = __ip_vs_get_out_rt_v6(skb, NULL, &iph->daddr, NULL, 0,
IP_VS_RT_MODE_NON_LOCAL)))
goto tx_error_icmp;
/* MTU checking */
mtu = dst_mtu(&rt->dst);
if (skb->len > mtu && !skb_is_gso(skb)) {
if (!skb->dev) {
struct net *net = dev_net(skb_dst(skb)->dev);
skb->dev = net->loopback_dev;
}
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
dst_release(&rt->dst);
IP_VS_DBG_RL("%s(): frag needed\n", __func__);
goto tx_error;
}
/*
* Call ip_send_check because we are not sure it is called
* after ip_defrag. Is copy-on-write needed?
*/
skb = skb_share_check(skb, GFP_ATOMIC);
if (unlikely(skb == NULL)) {
dst_release(&rt->dst);
return NF_STOLEN;
}
/* drop old route */
skb_dst_drop(skb);
skb_dst_set(skb, &rt->dst);
/* Another hack: avoid icmp_send in ip_fragment */
skb->local_df = 1;
IP_VS_XMIT(NFPROTO_IPV6, skb, cp, 0);
LeaveFunction(10);
return NF_STOLEN;
tx_error_icmp:
dst_link_failure(skb);
tx_error:
kfree_skb(skb);
LeaveFunction(10);
return NF_STOLEN;
}
#endif
/*
* NAT transmitter (only for outside-to-inside nat forwarding)
* Not used for related ICMP
*/
int
ip_vs_nat_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp)
{
struct rtable *rt; /* Route to the other host */
int mtu;
struct iphdr *iph = ip_hdr(skb);
int local;
EnterFunction(10);
/* check if it is a connection of no-client-port */
if (unlikely(cp->flags & IP_VS_CONN_F_NO_CPORT)) {
__be16 _pt, *p;
p = skb_header_pointer(skb, iph->ihl*4, sizeof(_pt), &_pt);
if (p == NULL)
goto tx_error;
ip_vs_conn_fill_cport(cp, *p);
IP_VS_DBG(10, "filled cport=%d\n", ntohs(*p));
}
if (!(rt = __ip_vs_get_out_rt(skb, cp->dest, cp->daddr.ip,
RT_TOS(iph->tos),
IP_VS_RT_MODE_LOCAL |
IP_VS_RT_MODE_NON_LOCAL |
IP_VS_RT_MODE_RDR, NULL)))
goto tx_error_icmp;
local = rt->rt_flags & RTCF_LOCAL;
/*
* Avoid duplicate tuple in reply direction for NAT traffic
* to local address when connection is sync-ed
*/
#if IS_ENABLED(CONFIG_NF_CONNTRACK)
if (cp->flags & IP_VS_CONN_F_SYNC && local) {
enum ip_conntrack_info ctinfo;
struct nf_conn *ct = ct = nf_ct_get(skb, &ctinfo);
if (ct && !nf_ct_is_untracked(ct)) {
IP_VS_DBG_RL_PKT(10, AF_INET, pp, skb, 0,
"ip_vs_nat_xmit(): "
"stopping DNAT to local address");
goto tx_error_put;
}
}
#endif
/* From world but DNAT to loopback address? */
if (local && ipv4_is_loopback(cp->daddr.ip) &&
rt_is_input_route(skb_rtable(skb))) {
IP_VS_DBG_RL_PKT(1, AF_INET, pp, skb, 0, "ip_vs_nat_xmit(): "
"stopping DNAT to loopback address");
goto tx_error_put;
}
/* MTU checking */
mtu = dst_mtu(&rt->dst);
if ((skb->len > mtu) && (iph->frag_off & htons(IP_DF)) &&
!skb_is_gso(skb)) {
icmp_send(skb, ICMP_DEST_UNREACH,ICMP_FRAG_NEEDED, htonl(mtu));
IP_VS_DBG_RL_PKT(0, AF_INET, pp, skb, 0,
"ip_vs_nat_xmit(): frag needed for");
goto tx_error_put;
}
/* copy-on-write the packet before mangling it */
if (!skb_make_writable(skb, sizeof(struct iphdr)))
goto tx_error_put;
if (skb_cow(skb, rt->dst.dev->hard_header_len))
goto tx_error_put;
/* mangle the packet */
if (pp->dnat_handler && !pp->dnat_handler(skb, pp, cp))
goto tx_error_put;
ip_hdr(skb)->daddr = cp->daddr.ip;
ip_send_check(ip_hdr(skb));
if (!local) {
/* drop old route */
skb_dst_drop(skb);
skb_dst_set(skb, &rt->dst);
} else {
ip_rt_put(rt);
/*
* Some IPv4 replies get local address from routes,
* not from iph, so while we DNAT after routing
* we need this second input/output route.
*/
if (!__ip_vs_reroute_locally(skb))
goto tx_error;
}
IP_VS_DBG_PKT(10, AF_INET, pp, skb, 0, "After DNAT");
/* FIXME: when application helper enlarges the packet and the length
is larger than the MTU of outgoing device, there will be still
MTU problem. */
/* Another hack: avoid icmp_send in ip_fragment */
skb->local_df = 1;
IP_VS_XMIT_NAT(NFPROTO_IPV4, skb, cp, local);
LeaveFunction(10);
return NF_STOLEN;
tx_error_icmp:
dst_link_failure(skb);
tx_error:
kfree_skb(skb);
LeaveFunction(10);
return NF_STOLEN;
tx_error_put:
ip_rt_put(rt);
goto tx_error;
}
#ifdef CONFIG_IP_VS_IPV6
int
ip_vs_nat_xmit_v6(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp)
{
struct rt6_info *rt; /* Route to the other host */
int mtu;
int local;
EnterFunction(10);
/* check if it is a connection of no-client-port */
if (unlikely(cp->flags & IP_VS_CONN_F_NO_CPORT)) {
__be16 _pt, *p;
p = skb_header_pointer(skb, sizeof(struct ipv6hdr),
sizeof(_pt), &_pt);
if (p == NULL)
goto tx_error;
ip_vs_conn_fill_cport(cp, *p);
IP_VS_DBG(10, "filled cport=%d\n", ntohs(*p));
}
if (!(rt = __ip_vs_get_out_rt_v6(skb, cp->dest, &cp->daddr.in6, NULL,
0, (IP_VS_RT_MODE_LOCAL |
IP_VS_RT_MODE_NON_LOCAL |
IP_VS_RT_MODE_RDR))))
goto tx_error_icmp;
local = __ip_vs_is_local_route6(rt);
/*
* Avoid duplicate tuple in reply direction for NAT traffic
* to local address when connection is sync-ed
*/
#if IS_ENABLED(CONFIG_NF_CONNTRACK)
if (cp->flags & IP_VS_CONN_F_SYNC && local) {
enum ip_conntrack_info ctinfo;
struct nf_conn *ct = ct = nf_ct_get(skb, &ctinfo);
if (ct && !nf_ct_is_untracked(ct)) {
IP_VS_DBG_RL_PKT(10, AF_INET6, pp, skb, 0,
"ip_vs_nat_xmit_v6(): "
"stopping DNAT to local address");
goto tx_error_put;
}
}
#endif
/* From world but DNAT to loopback address? */
if (local && skb->dev && !(skb->dev->flags & IFF_LOOPBACK) &&
ipv6_addr_type(&rt->rt6i_dst.addr) & IPV6_ADDR_LOOPBACK) {
IP_VS_DBG_RL_PKT(1, AF_INET6, pp, skb, 0,
"ip_vs_nat_xmit_v6(): "
"stopping DNAT to loopback address");
goto tx_error_put;
}
/* MTU checking */
mtu = dst_mtu(&rt->dst);
if (skb->len > mtu && !skb_is_gso(skb)) {
if (!skb->dev) {
struct net *net = dev_net(skb_dst(skb)->dev);
skb->dev = net->loopback_dev;
}
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
IP_VS_DBG_RL_PKT(0, AF_INET6, pp, skb, 0,
"ip_vs_nat_xmit_v6(): frag needed for");
goto tx_error_put;
}
/* copy-on-write the packet before mangling it */
if (!skb_make_writable(skb, sizeof(struct ipv6hdr)))
goto tx_error_put;
if (skb_cow(skb, rt->dst.dev->hard_header_len))
goto tx_error_put;
/* mangle the packet */
if (pp->dnat_handler && !pp->dnat_handler(skb, pp, cp))
goto tx_error;
ipv6_hdr(skb)->daddr = cp->daddr.in6;
if (!local || !skb->dev) {
/* drop the old route when skb is not shared */
skb_dst_drop(skb);
skb_dst_set(skb, &rt->dst);
} else {
/* destined to loopback, do we need to change route? */
dst_release(&rt->dst);
}
IP_VS_DBG_PKT(10, AF_INET6, pp, skb, 0, "After DNAT");
/* FIXME: when application helper enlarges the packet and the length
is larger than the MTU of outgoing device, there will be still
MTU problem. */
/* Another hack: avoid icmp_send in ip_fragment */
skb->local_df = 1;
IP_VS_XMIT_NAT(NFPROTO_IPV6, skb, cp, local);
LeaveFunction(10);
return NF_STOLEN;
tx_error_icmp:
dst_link_failure(skb);
tx_error:
LeaveFunction(10);
kfree_skb(skb);
return NF_STOLEN;
tx_error_put:
dst_release(&rt->dst);
goto tx_error;
}
#endif
/*
* IP Tunneling transmitter
*
* This function encapsulates the packet in a new IP packet, its
* destination will be set to cp->daddr. Most code of this function
* is taken from ipip.c.
*
* It is used in VS/TUN cluster. The load balancer selects a real
* server from a cluster based on a scheduling algorithm,
* encapsulates the request packet and forwards it to the selected
* server. For example, all real servers are configured with
* "ifconfig tunl0 <Virtual IP Address> up". When the server receives
* the encapsulated packet, it will decapsulate the packet, processe
* the request and return the response packets directly to the client
* without passing the load balancer. This can greatly increase the
* scalability of virtual server.
*
* Used for ANY protocol
*/
int
ip_vs_tunnel_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp)
{
struct rtable *rt; /* Route to the other host */
__be32 saddr; /* Source for tunnel */
struct net_device *tdev; /* Device to other host */
struct iphdr *old_iph = ip_hdr(skb);
u8 tos = old_iph->tos;
__be16 df = old_iph->frag_off;
struct iphdr *iph; /* Our new IP header */
unsigned int max_headroom; /* The extra header space needed */
int mtu;
int ret;
EnterFunction(10);
if (!(rt = __ip_vs_get_out_rt(skb, cp->dest, cp->daddr.ip,
RT_TOS(tos), IP_VS_RT_MODE_LOCAL |
IP_VS_RT_MODE_NON_LOCAL,
&saddr)))
goto tx_error_icmp;
if (rt->rt_flags & RTCF_LOCAL) {
ip_rt_put(rt);
IP_VS_XMIT(NFPROTO_IPV4, skb, cp, 1);
}
tdev = rt->dst.dev;
mtu = dst_mtu(&rt->dst) - sizeof(struct iphdr);
if (mtu < 68) {
IP_VS_DBG_RL("%s(): mtu less than 68\n", __func__);
goto tx_error_put;
}
if (skb_dst(skb))
skb_dst(skb)->ops->update_pmtu(skb_dst(skb), mtu);
df |= (old_iph->frag_off & htons(IP_DF));
if ((old_iph->frag_off & htons(IP_DF) &&
mtu < ntohs(old_iph->tot_len) && !skb_is_gso(skb))) {
icmp_send(skb, ICMP_DEST_UNREACH,ICMP_FRAG_NEEDED, htonl(mtu));
IP_VS_DBG_RL("%s(): frag needed\n", __func__);
goto tx_error_put;
}
/*
* Okay, now see if we can stuff it in the buffer as-is.
*/
max_headroom = LL_RESERVED_SPACE(tdev) + sizeof(struct iphdr);
if (skb_headroom(skb) < max_headroom
|| skb_cloned(skb) || skb_shared(skb)) {
struct sk_buff *new_skb =
skb_realloc_headroom(skb, max_headroom);
if (!new_skb) {
ip_rt_put(rt);
kfree_skb(skb);
IP_VS_ERR_RL("%s(): no memory\n", __func__);
return NF_STOLEN;
}
kfree_skb(skb);
skb = new_skb;
old_iph = ip_hdr(skb);
}
skb->transport_header = skb->network_header;
/* fix old IP header checksum */
ip_send_check(old_iph);
skb_push(skb, sizeof(struct iphdr));
skb_reset_network_header(skb);
memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt));
/* drop old route */
skb_dst_drop(skb);
skb_dst_set(skb, &rt->dst);
/*
* Push down and install the IPIP header.
*/
iph = ip_hdr(skb);
iph->version = 4;
iph->ihl = sizeof(struct iphdr)>>2;
iph->frag_off = df;
iph->protocol = IPPROTO_IPIP;
iph->tos = tos;
iph->daddr = cp->daddr.ip;
iph->saddr = saddr;
iph->ttl = old_iph->ttl;
ip_select_ident(iph, &rt->dst, NULL);
/* Another hack: avoid icmp_send in ip_fragment */
skb->local_df = 1;
ret = IP_VS_XMIT_TUNNEL(skb, cp);
if (ret == NF_ACCEPT)
ip_local_out(skb);
else if (ret == NF_DROP)
kfree_skb(skb);
LeaveFunction(10);
return NF_STOLEN;
tx_error_icmp:
dst_link_failure(skb);
tx_error:
kfree_skb(skb);
LeaveFunction(10);
return NF_STOLEN;
tx_error_put:
ip_rt_put(rt);
goto tx_error;
}
#ifdef CONFIG_IP_VS_IPV6
int
ip_vs_tunnel_xmit_v6(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp)
{
struct rt6_info *rt; /* Route to the other host */
struct in6_addr saddr; /* Source for tunnel */
struct net_device *tdev; /* Device to other host */
struct ipv6hdr *old_iph = ipv6_hdr(skb);
struct ipv6hdr *iph; /* Our new IP header */
unsigned int max_headroom; /* The extra header space needed */
int mtu;
int ret;
EnterFunction(10);
if (!(rt = __ip_vs_get_out_rt_v6(skb, cp->dest, &cp->daddr.in6,
&saddr, 1, (IP_VS_RT_MODE_LOCAL |
IP_VS_RT_MODE_NON_LOCAL))))
goto tx_error_icmp;
if (__ip_vs_is_local_route6(rt)) {
dst_release(&rt->dst);
IP_VS_XMIT(NFPROTO_IPV6, skb, cp, 1);
}
tdev = rt->dst.dev;
mtu = dst_mtu(&rt->dst) - sizeof(struct ipv6hdr);
if (mtu < IPV6_MIN_MTU) {
IP_VS_DBG_RL("%s(): mtu less than %d\n", __func__,
IPV6_MIN_MTU);
goto tx_error_put;
}
if (skb_dst(skb))
skb_dst(skb)->ops->update_pmtu(skb_dst(skb), mtu);
if (mtu < ntohs(old_iph->payload_len) + sizeof(struct ipv6hdr) &&
!skb_is_gso(skb)) {
if (!skb->dev) {
struct net *net = dev_net(skb_dst(skb)->dev);
skb->dev = net->loopback_dev;
}
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
IP_VS_DBG_RL("%s(): frag needed\n", __func__);
goto tx_error_put;
}
/*
* Okay, now see if we can stuff it in the buffer as-is.
*/
max_headroom = LL_RESERVED_SPACE(tdev) + sizeof(struct ipv6hdr);
if (skb_headroom(skb) < max_headroom
|| skb_cloned(skb) || skb_shared(skb)) {
struct sk_buff *new_skb =
skb_realloc_headroom(skb, max_headroom);
if (!new_skb) {
dst_release(&rt->dst);
kfree_skb(skb);
IP_VS_ERR_RL("%s(): no memory\n", __func__);
return NF_STOLEN;
}
kfree_skb(skb);
skb = new_skb;
old_iph = ipv6_hdr(skb);
}
skb->transport_header = skb->network_header;
skb_push(skb, sizeof(struct ipv6hdr));
skb_reset_network_header(skb);
memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt));
/* drop old route */
skb_dst_drop(skb);
skb_dst_set(skb, &rt->dst);
/*
* Push down and install the IPIP header.
*/
iph = ipv6_hdr(skb);
iph->version = 6;
iph->nexthdr = IPPROTO_IPV6;
iph->payload_len = old_iph->payload_len;
be16_add_cpu(&iph->payload_len, sizeof(*old_iph));
iph->priority = old_iph->priority;
memset(&iph->flow_lbl, 0, sizeof(iph->flow_lbl));
iph->daddr = cp->daddr.in6;
iph->saddr = saddr;
iph->hop_limit = old_iph->hop_limit;
/* Another hack: avoid icmp_send in ip_fragment */
skb->local_df = 1;
ret = IP_VS_XMIT_TUNNEL(skb, cp);
if (ret == NF_ACCEPT)
ip6_local_out(skb);
else if (ret == NF_DROP)
kfree_skb(skb);
LeaveFunction(10);
return NF_STOLEN;
tx_error_icmp:
dst_link_failure(skb);
tx_error:
kfree_skb(skb);
LeaveFunction(10);
return NF_STOLEN;
tx_error_put:
dst_release(&rt->dst);
goto tx_error;
}
#endif
/*
* Direct Routing transmitter
* Used for ANY protocol
*/
int
ip_vs_dr_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp)
{
struct rtable *rt; /* Route to the other host */
struct iphdr *iph = ip_hdr(skb);
int mtu;
EnterFunction(10);
if (!(rt = __ip_vs_get_out_rt(skb, cp->dest, cp->daddr.ip,
RT_TOS(iph->tos),
IP_VS_RT_MODE_LOCAL |
IP_VS_RT_MODE_NON_LOCAL, NULL)))
goto tx_error_icmp;
if (rt->rt_flags & RTCF_LOCAL) {
ip_rt_put(rt);
IP_VS_XMIT(NFPROTO_IPV4, skb, cp, 1);
}
/* MTU checking */
mtu = dst_mtu(&rt->dst);
if ((iph->frag_off & htons(IP_DF)) && skb->len > mtu &&
!skb_is_gso(skb)) {
icmp_send(skb, ICMP_DEST_UNREACH,ICMP_FRAG_NEEDED, htonl(mtu));
ip_rt_put(rt);
IP_VS_DBG_RL("%s(): frag needed\n", __func__);
goto tx_error;
}
/*
* Call ip_send_check because we are not sure it is called
* after ip_defrag. Is copy-on-write needed?
*/
if (unlikely((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL)) {
ip_rt_put(rt);
return NF_STOLEN;
}
ip_send_check(ip_hdr(skb));
/* drop old route */
skb_dst_drop(skb);
skb_dst_set(skb, &rt->dst);
/* Another hack: avoid icmp_send in ip_fragment */
skb->local_df = 1;
IP_VS_XMIT(NFPROTO_IPV4, skb, cp, 0);
LeaveFunction(10);
return NF_STOLEN;
tx_error_icmp:
dst_link_failure(skb);
tx_error:
kfree_skb(skb);
LeaveFunction(10);
return NF_STOLEN;
}
#ifdef CONFIG_IP_VS_IPV6
int
ip_vs_dr_xmit_v6(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp)
{
struct rt6_info *rt; /* Route to the other host */
int mtu;
EnterFunction(10);
if (!(rt = __ip_vs_get_out_rt_v6(skb, cp->dest, &cp->daddr.in6, NULL,
0, (IP_VS_RT_MODE_LOCAL |
IP_VS_RT_MODE_NON_LOCAL))))
goto tx_error_icmp;
if (__ip_vs_is_local_route6(rt)) {
dst_release(&rt->dst);
IP_VS_XMIT(NFPROTO_IPV6, skb, cp, 1);
}
/* MTU checking */
mtu = dst_mtu(&rt->dst);
if (skb->len > mtu) {
if (!skb->dev) {
struct net *net = dev_net(skb_dst(skb)->dev);
skb->dev = net->loopback_dev;
}
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
dst_release(&rt->dst);
IP_VS_DBG_RL("%s(): frag needed\n", __func__);
goto tx_error;
}
/*
* Call ip_send_check because we are not sure it is called
* after ip_defrag. Is copy-on-write needed?
*/
skb = skb_share_check(skb, GFP_ATOMIC);
if (unlikely(skb == NULL)) {
dst_release(&rt->dst);
return NF_STOLEN;
}
/* drop old route */
skb_dst_drop(skb);
skb_dst_set(skb, &rt->dst);
/* Another hack: avoid icmp_send in ip_fragment */
skb->local_df = 1;
IP_VS_XMIT(NFPROTO_IPV6, skb, cp, 0);
LeaveFunction(10);
return NF_STOLEN;
tx_error_icmp:
dst_link_failure(skb);
tx_error:
kfree_skb(skb);
LeaveFunction(10);
return NF_STOLEN;
}
#endif
/*
* ICMP packet transmitter
* called by the ip_vs_in_icmp
*/
int
ip_vs_icmp_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp, int offset, unsigned int hooknum)
{
struct rtable *rt; /* Route to the other host */
int mtu;
int rc;
int local;
int rt_mode;
EnterFunction(10);
/* The ICMP packet for VS/TUN, VS/DR and LOCALNODE will be
forwarded directly here, because there is no need to
translate address/port back */
if (IP_VS_FWD_METHOD(cp) != IP_VS_CONN_F_MASQ) {
if (cp->packet_xmit)
rc = cp->packet_xmit(skb, cp, pp);
else
rc = NF_ACCEPT;
/* do not touch skb anymore */
atomic_inc(&cp->in_pkts);
goto out;
}
/*
* mangle and send the packet here (only for VS/NAT)
*/
/* LOCALNODE from FORWARD hook is not supported */
rt_mode = (hooknum != NF_INET_FORWARD) ?
IP_VS_RT_MODE_LOCAL | IP_VS_RT_MODE_NON_LOCAL |
IP_VS_RT_MODE_RDR : IP_VS_RT_MODE_NON_LOCAL;
if (!(rt = __ip_vs_get_out_rt(skb, cp->dest, cp->daddr.ip,
RT_TOS(ip_hdr(skb)->tos),
rt_mode, NULL)))
goto tx_error_icmp;
local = rt->rt_flags & RTCF_LOCAL;
/*
* Avoid duplicate tuple in reply direction for NAT traffic
* to local address when connection is sync-ed
*/
#if IS_ENABLED(CONFIG_NF_CONNTRACK)
if (cp->flags & IP_VS_CONN_F_SYNC && local) {
enum ip_conntrack_info ctinfo;
struct nf_conn *ct = ct = nf_ct_get(skb, &ctinfo);
if (ct && !nf_ct_is_untracked(ct)) {
IP_VS_DBG(10, "%s(): "
"stopping DNAT to local address %pI4\n",
__func__, &cp->daddr.ip);
goto tx_error_put;
}
}
#endif
/* From world but DNAT to loopback address? */
if (local && ipv4_is_loopback(cp->daddr.ip) &&
rt_is_input_route(skb_rtable(skb))) {
IP_VS_DBG(1, "%s(): "
"stopping DNAT to loopback %pI4\n",
__func__, &cp->daddr.ip);
goto tx_error_put;
}
/* MTU checking */
mtu = dst_mtu(&rt->dst);
if ((skb->len > mtu) && (ip_hdr(skb)->frag_off & htons(IP_DF)) &&
!skb_is_gso(skb)) {
icmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED, htonl(mtu));
IP_VS_DBG_RL("%s(): frag needed\n", __func__);
goto tx_error_put;
}
/* copy-on-write the packet before mangling it */
if (!skb_make_writable(skb, offset))
goto tx_error_put;
if (skb_cow(skb, rt->dst.dev->hard_header_len))
goto tx_error_put;
ip_vs_nat_icmp(skb, pp, cp, 0);
if (!local) {
/* drop the old route when skb is not shared */
skb_dst_drop(skb);
skb_dst_set(skb, &rt->dst);
} else {
ip_rt_put(rt);
/*
* Some IPv4 replies get local address from routes,
* not from iph, so while we DNAT after routing
* we need this second input/output route.
*/
if (!__ip_vs_reroute_locally(skb))
goto tx_error;
}
/* Another hack: avoid icmp_send in ip_fragment */
skb->local_df = 1;
IP_VS_XMIT_NAT(NFPROTO_IPV4, skb, cp, local);
rc = NF_STOLEN;
goto out;
tx_error_icmp:
dst_link_failure(skb);
tx_error:
dev_kfree_skb(skb);
rc = NF_STOLEN;
out:
LeaveFunction(10);
return rc;
tx_error_put:
ip_rt_put(rt);
goto tx_error;
}
#ifdef CONFIG_IP_VS_IPV6
int
ip_vs_icmp_xmit_v6(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp, int offset, unsigned int hooknum)
{
struct rt6_info *rt; /* Route to the other host */
int mtu;
int rc;
int local;
int rt_mode;
EnterFunction(10);
/* The ICMP packet for VS/TUN, VS/DR and LOCALNODE will be
forwarded directly here, because there is no need to
translate address/port back */
if (IP_VS_FWD_METHOD(cp) != IP_VS_CONN_F_MASQ) {
if (cp->packet_xmit)
rc = cp->packet_xmit(skb, cp, pp);
else
rc = NF_ACCEPT;
/* do not touch skb anymore */
atomic_inc(&cp->in_pkts);
goto out;
}
/*
* mangle and send the packet here (only for VS/NAT)
*/
/* LOCALNODE from FORWARD hook is not supported */
rt_mode = (hooknum != NF_INET_FORWARD) ?
IP_VS_RT_MODE_LOCAL | IP_VS_RT_MODE_NON_LOCAL |
IP_VS_RT_MODE_RDR : IP_VS_RT_MODE_NON_LOCAL;
if (!(rt = __ip_vs_get_out_rt_v6(skb, cp->dest, &cp->daddr.in6, NULL,
0, rt_mode)))
goto tx_error_icmp;
local = __ip_vs_is_local_route6(rt);
/*
* Avoid duplicate tuple in reply direction for NAT traffic
* to local address when connection is sync-ed
*/
#if IS_ENABLED(CONFIG_NF_CONNTRACK)
if (cp->flags & IP_VS_CONN_F_SYNC && local) {
enum ip_conntrack_info ctinfo;
struct nf_conn *ct = ct = nf_ct_get(skb, &ctinfo);
if (ct && !nf_ct_is_untracked(ct)) {
IP_VS_DBG(10, "%s(): "
"stopping DNAT to local address %pI6\n",
__func__, &cp->daddr.in6);
goto tx_error_put;
}
}
#endif
/* From world but DNAT to loopback address? */
if (local && skb->dev && !(skb->dev->flags & IFF_LOOPBACK) &&
ipv6_addr_type(&rt->rt6i_dst.addr) & IPV6_ADDR_LOOPBACK) {
IP_VS_DBG(1, "%s(): "
"stopping DNAT to loopback %pI6\n",
__func__, &cp->daddr.in6);
goto tx_error_put;
}
/* MTU checking */
mtu = dst_mtu(&rt->dst);
if (skb->len > mtu && !skb_is_gso(skb)) {
if (!skb->dev) {
struct net *net = dev_net(skb_dst(skb)->dev);
skb->dev = net->loopback_dev;
}
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
IP_VS_DBG_RL("%s(): frag needed\n", __func__);
goto tx_error_put;
}
/* copy-on-write the packet before mangling it */
if (!skb_make_writable(skb, offset))
goto tx_error_put;
if (skb_cow(skb, rt->dst.dev->hard_header_len))
goto tx_error_put;
ip_vs_nat_icmp_v6(skb, pp, cp, 0);
if (!local || !skb->dev) {
/* drop the old route when skb is not shared */
skb_dst_drop(skb);
skb_dst_set(skb, &rt->dst);
} else {
/* destined to loopback, do we need to change route? */
dst_release(&rt->dst);
}
/* Another hack: avoid icmp_send in ip_fragment */
skb->local_df = 1;
IP_VS_XMIT_NAT(NFPROTO_IPV6, skb, cp, local);
rc = NF_STOLEN;
goto out;
tx_error_icmp:
dst_link_failure(skb);
tx_error:
dev_kfree_skb(skb);
rc = NF_STOLEN;
out:
LeaveFunction(10);
return rc;
tx_error_put:
dst_release(&rt->dst);
goto tx_error;
}
#endif
| gpl-2.0 |
KiWiX-s2/kernel | drivers/scsi/scsi_lib_dma.c | 4584 | 1125 | /*
* SCSI library functions depending on DMA
*/
#include <linux/blkdev.h>
#include <linux/device.h>
#include <linux/kernel.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
/**
* scsi_dma_map - perform DMA mapping against command's sg lists
* @cmd: scsi command
*
* Returns the number of sg lists actually used, zero if the sg lists
* is NULL, or -ENOMEM if the mapping failed.
*/
int scsi_dma_map(struct scsi_cmnd *cmd)
{
int nseg = 0;
if (scsi_sg_count(cmd)) {
struct device *dev = cmd->device->host->dma_dev;
nseg = dma_map_sg(dev, scsi_sglist(cmd), scsi_sg_count(cmd),
cmd->sc_data_direction);
if (unlikely(!nseg))
return -ENOMEM;
}
return nseg;
}
EXPORT_SYMBOL(scsi_dma_map);
/**
* scsi_dma_unmap - unmap command's sg lists mapped by scsi_dma_map
* @cmd: scsi command
*/
void scsi_dma_unmap(struct scsi_cmnd *cmd)
{
if (scsi_sg_count(cmd)) {
struct device *dev = cmd->device->host->dma_dev;
dma_unmap_sg(dev, scsi_sglist(cmd), scsi_sg_count(cmd),
cmd->sc_data_direction);
}
}
EXPORT_SYMBOL(scsi_dma_unmap);
| gpl-2.0 |
turuchan/ISW11SC_ICS_Kernel | drivers/scsi/scsi_lib_dma.c | 4584 | 1125 | /*
* SCSI library functions depending on DMA
*/
#include <linux/blkdev.h>
#include <linux/device.h>
#include <linux/kernel.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
/**
* scsi_dma_map - perform DMA mapping against command's sg lists
* @cmd: scsi command
*
* Returns the number of sg lists actually used, zero if the sg lists
* is NULL, or -ENOMEM if the mapping failed.
*/
int scsi_dma_map(struct scsi_cmnd *cmd)
{
int nseg = 0;
if (scsi_sg_count(cmd)) {
struct device *dev = cmd->device->host->dma_dev;
nseg = dma_map_sg(dev, scsi_sglist(cmd), scsi_sg_count(cmd),
cmd->sc_data_direction);
if (unlikely(!nseg))
return -ENOMEM;
}
return nseg;
}
EXPORT_SYMBOL(scsi_dma_map);
/**
* scsi_dma_unmap - unmap command's sg lists mapped by scsi_dma_map
* @cmd: scsi command
*/
void scsi_dma_unmap(struct scsi_cmnd *cmd)
{
if (scsi_sg_count(cmd)) {
struct device *dev = cmd->device->host->dma_dev;
dma_unmap_sg(dev, scsi_sglist(cmd), scsi_sg_count(cmd),
cmd->sc_data_direction);
}
}
EXPORT_SYMBOL(scsi_dma_unmap);
| gpl-2.0 |
LeJay/android_kernel_samsung_jactiveltexx_stock | arch/arm/mach-msm/board-trout.c | 4584 | 2558 | /* linux/arch/arm/mach-msm/board-trout.c
*
* Copyright (C) 2009 Google, Inc.
* Author: Brian Swetland <swetland@google.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/clkdev.h>
#include <asm/system_info.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/setup.h>
#include <mach/board.h>
#include <mach/hardware.h>
#include <mach/msm_iomap.h>
#include "devices.h"
#include "board-trout.h"
extern int trout_init_mmc(unsigned int);
static struct platform_device *devices[] __initdata = {
&msm_device_uart3,
&msm_device_smd,
&msm_device_nand,
&msm_device_hsusb,
&msm_device_i2c,
};
extern struct sys_timer msm_timer;
static void __init trout_init_early(void)
{
arch_ioremap_caller = __msm_ioremap_caller;
}
static void __init trout_init_irq(void)
{
msm_init_irq();
}
static void __init trout_fixup(struct tag *tags, char **cmdline,
struct meminfo *mi)
{
mi->nr_banks = 1;
mi->bank[0].start = PHYS_OFFSET;
mi->bank[0].size = (101*1024*1024);
}
static void __init trout_init(void)
{
int rc;
platform_add_devices(devices, ARRAY_SIZE(devices));
#ifdef CONFIG_MMC
rc = trout_init_mmc(system_rev);
if (rc)
printk(KERN_CRIT "%s: MMC init failure (%d)\n", __func__, rc);
#endif
}
static struct map_desc trout_io_desc[] __initdata = {
{
.virtual = TROUT_CPLD_BASE,
.pfn = __phys_to_pfn(TROUT_CPLD_START),
.length = TROUT_CPLD_SIZE,
.type = MT_DEVICE_NONSHARED
}
};
static void __init trout_map_io(void)
{
msm_map_common_io();
iotable_init(trout_io_desc, ARRAY_SIZE(trout_io_desc));
#ifdef CONFIG_MSM_DEBUG_UART3
/* route UART3 to the "H2W" extended usb connector */
writeb(0x80, TROUT_CPLD_BASE + 0x00);
#endif
msm_clock_init(msm_clocks_7x01a, msm_num_clocks_7x01a);
}
MACHINE_START(TROUT, "HTC Dream")
.atag_offset = 0x100,
.fixup = trout_fixup,
.map_io = trout_map_io,
.init_early = trout_init_early,
.init_irq = trout_init_irq,
.init_machine = trout_init,
.timer = &msm_timer,
MACHINE_END
| gpl-2.0 |
deedwar/evolve | arch/ia64/sn/kernel/irq.c | 7144 | 12634 | /*
* Platform dependent support for SGI SN
*
* 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.
*
* Copyright (c) 2000-2008 Silicon Graphics, Inc. All Rights Reserved.
*/
#include <linux/irq.h>
#include <linux/spinlock.h>
#include <linux/init.h>
#include <linux/rculist.h>
#include <linux/slab.h>
#include <asm/sn/addrs.h>
#include <asm/sn/arch.h>
#include <asm/sn/intr.h>
#include <asm/sn/pcibr_provider.h>
#include <asm/sn/pcibus_provider_defs.h>
#include <asm/sn/pcidev.h>
#include <asm/sn/shub_mmr.h>
#include <asm/sn/sn_sal.h>
#include <asm/sn/sn_feature_sets.h>
static void register_intr_pda(struct sn_irq_info *sn_irq_info);
static void unregister_intr_pda(struct sn_irq_info *sn_irq_info);
extern int sn_ioif_inited;
struct list_head **sn_irq_lh;
static DEFINE_SPINLOCK(sn_irq_info_lock); /* non-IRQ lock */
u64 sn_intr_alloc(nasid_t local_nasid, int local_widget,
struct sn_irq_info *sn_irq_info,
int req_irq, nasid_t req_nasid,
int req_slice)
{
struct ia64_sal_retval ret_stuff;
ret_stuff.status = 0;
ret_stuff.v0 = 0;
SAL_CALL_NOLOCK(ret_stuff, (u64) SN_SAL_IOIF_INTERRUPT,
(u64) SAL_INTR_ALLOC, (u64) local_nasid,
(u64) local_widget, __pa(sn_irq_info), (u64) req_irq,
(u64) req_nasid, (u64) req_slice);
return ret_stuff.status;
}
void sn_intr_free(nasid_t local_nasid, int local_widget,
struct sn_irq_info *sn_irq_info)
{
struct ia64_sal_retval ret_stuff;
ret_stuff.status = 0;
ret_stuff.v0 = 0;
SAL_CALL_NOLOCK(ret_stuff, (u64) SN_SAL_IOIF_INTERRUPT,
(u64) SAL_INTR_FREE, (u64) local_nasid,
(u64) local_widget, (u64) sn_irq_info->irq_irq,
(u64) sn_irq_info->irq_cookie, 0, 0);
}
u64 sn_intr_redirect(nasid_t local_nasid, int local_widget,
struct sn_irq_info *sn_irq_info,
nasid_t req_nasid, int req_slice)
{
struct ia64_sal_retval ret_stuff;
ret_stuff.status = 0;
ret_stuff.v0 = 0;
SAL_CALL_NOLOCK(ret_stuff, (u64) SN_SAL_IOIF_INTERRUPT,
(u64) SAL_INTR_REDIRECT, (u64) local_nasid,
(u64) local_widget, __pa(sn_irq_info),
(u64) req_nasid, (u64) req_slice, 0);
return ret_stuff.status;
}
static unsigned int sn_startup_irq(struct irq_data *data)
{
return 0;
}
static void sn_shutdown_irq(struct irq_data *data)
{
}
extern void ia64_mca_register_cpev(int);
static void sn_disable_irq(struct irq_data *data)
{
if (data->irq == local_vector_to_irq(IA64_CPE_VECTOR))
ia64_mca_register_cpev(0);
}
static void sn_enable_irq(struct irq_data *data)
{
if (data->irq == local_vector_to_irq(IA64_CPE_VECTOR))
ia64_mca_register_cpev(data->irq);
}
static void sn_ack_irq(struct irq_data *data)
{
u64 event_occurred, mask;
unsigned int irq = data->irq & 0xff;
event_occurred = HUB_L((u64*)LOCAL_MMR_ADDR(SH_EVENT_OCCURRED));
mask = event_occurred & SH_ALL_INT_MASK;
HUB_S((u64*)LOCAL_MMR_ADDR(SH_EVENT_OCCURRED_ALIAS), mask);
__set_bit(irq, (volatile void *)pda->sn_in_service_ivecs);
irq_move_irq(data);
}
struct sn_irq_info *sn_retarget_vector(struct sn_irq_info *sn_irq_info,
nasid_t nasid, int slice)
{
int vector;
int cpuid;
#ifdef CONFIG_SMP
int cpuphys;
#endif
int64_t bridge;
int local_widget, status;
nasid_t local_nasid;
struct sn_irq_info *new_irq_info;
struct sn_pcibus_provider *pci_provider;
bridge = (u64) sn_irq_info->irq_bridge;
if (!bridge) {
return NULL; /* irq is not a device interrupt */
}
local_nasid = NASID_GET(bridge);
if (local_nasid & 1)
local_widget = TIO_SWIN_WIDGETNUM(bridge);
else
local_widget = SWIN_WIDGETNUM(bridge);
vector = sn_irq_info->irq_irq;
/* Make use of SAL_INTR_REDIRECT if PROM supports it */
status = sn_intr_redirect(local_nasid, local_widget, sn_irq_info, nasid, slice);
if (!status) {
new_irq_info = sn_irq_info;
goto finish_up;
}
/*
* PROM does not support SAL_INTR_REDIRECT, or it failed.
* Revert to old method.
*/
new_irq_info = kmemdup(sn_irq_info, sizeof(struct sn_irq_info),
GFP_ATOMIC);
if (new_irq_info == NULL)
return NULL;
/* Free the old PROM new_irq_info structure */
sn_intr_free(local_nasid, local_widget, new_irq_info);
unregister_intr_pda(new_irq_info);
/* allocate a new PROM new_irq_info struct */
status = sn_intr_alloc(local_nasid, local_widget,
new_irq_info, vector,
nasid, slice);
/* SAL call failed */
if (status) {
kfree(new_irq_info);
return NULL;
}
register_intr_pda(new_irq_info);
spin_lock(&sn_irq_info_lock);
list_replace_rcu(&sn_irq_info->list, &new_irq_info->list);
spin_unlock(&sn_irq_info_lock);
kfree_rcu(sn_irq_info, rcu);
finish_up:
/* Update kernels new_irq_info with new target info */
cpuid = nasid_slice_to_cpuid(new_irq_info->irq_nasid,
new_irq_info->irq_slice);
new_irq_info->irq_cpuid = cpuid;
pci_provider = sn_pci_provider[new_irq_info->irq_bridge_type];
/*
* If this represents a line interrupt, target it. If it's
* an msi (irq_int_bit < 0), it's already targeted.
*/
if (new_irq_info->irq_int_bit >= 0 &&
pci_provider && pci_provider->target_interrupt)
(pci_provider->target_interrupt)(new_irq_info);
#ifdef CONFIG_SMP
cpuphys = cpu_physical_id(cpuid);
set_irq_affinity_info((vector & 0xff), cpuphys, 0);
#endif
return new_irq_info;
}
static int sn_set_affinity_irq(struct irq_data *data,
const struct cpumask *mask, bool force)
{
struct sn_irq_info *sn_irq_info, *sn_irq_info_safe;
unsigned int irq = data->irq;
nasid_t nasid;
int slice;
nasid = cpuid_to_nasid(cpumask_first(mask));
slice = cpuid_to_slice(cpumask_first(mask));
list_for_each_entry_safe(sn_irq_info, sn_irq_info_safe,
sn_irq_lh[irq], list)
(void)sn_retarget_vector(sn_irq_info, nasid, slice);
return 0;
}
#ifdef CONFIG_SMP
void sn_set_err_irq_affinity(unsigned int irq)
{
/*
* On systems which support CPU disabling (SHub2), all error interrupts
* are targeted at the boot CPU.
*/
if (is_shub2() && sn_prom_feature_available(PRF_CPU_DISABLE_SUPPORT))
set_irq_affinity_info(irq, cpu_physical_id(0), 0);
}
#else
void sn_set_err_irq_affinity(unsigned int irq) { }
#endif
static void
sn_mask_irq(struct irq_data *data)
{
}
static void
sn_unmask_irq(struct irq_data *data)
{
}
struct irq_chip irq_type_sn = {
.name = "SN hub",
.irq_startup = sn_startup_irq,
.irq_shutdown = sn_shutdown_irq,
.irq_enable = sn_enable_irq,
.irq_disable = sn_disable_irq,
.irq_ack = sn_ack_irq,
.irq_mask = sn_mask_irq,
.irq_unmask = sn_unmask_irq,
.irq_set_affinity = sn_set_affinity_irq
};
ia64_vector sn_irq_to_vector(int irq)
{
if (irq >= IA64_NUM_VECTORS)
return 0;
return (ia64_vector)irq;
}
unsigned int sn_local_vector_to_irq(u8 vector)
{
return (CPU_VECTOR_TO_IRQ(smp_processor_id(), vector));
}
void sn_irq_init(void)
{
int i;
ia64_first_device_vector = IA64_SN2_FIRST_DEVICE_VECTOR;
ia64_last_device_vector = IA64_SN2_LAST_DEVICE_VECTOR;
for (i = 0; i < NR_IRQS; i++) {
if (irq_get_chip(i) == &no_irq_chip)
irq_set_chip(i, &irq_type_sn);
}
}
static void register_intr_pda(struct sn_irq_info *sn_irq_info)
{
int irq = sn_irq_info->irq_irq;
int cpu = sn_irq_info->irq_cpuid;
if (pdacpu(cpu)->sn_last_irq < irq) {
pdacpu(cpu)->sn_last_irq = irq;
}
if (pdacpu(cpu)->sn_first_irq == 0 || pdacpu(cpu)->sn_first_irq > irq)
pdacpu(cpu)->sn_first_irq = irq;
}
static void unregister_intr_pda(struct sn_irq_info *sn_irq_info)
{
int irq = sn_irq_info->irq_irq;
int cpu = sn_irq_info->irq_cpuid;
struct sn_irq_info *tmp_irq_info;
int i, foundmatch;
rcu_read_lock();
if (pdacpu(cpu)->sn_last_irq == irq) {
foundmatch = 0;
for (i = pdacpu(cpu)->sn_last_irq - 1;
i && !foundmatch; i--) {
list_for_each_entry_rcu(tmp_irq_info,
sn_irq_lh[i],
list) {
if (tmp_irq_info->irq_cpuid == cpu) {
foundmatch = 1;
break;
}
}
}
pdacpu(cpu)->sn_last_irq = i;
}
if (pdacpu(cpu)->sn_first_irq == irq) {
foundmatch = 0;
for (i = pdacpu(cpu)->sn_first_irq + 1;
i < NR_IRQS && !foundmatch; i++) {
list_for_each_entry_rcu(tmp_irq_info,
sn_irq_lh[i],
list) {
if (tmp_irq_info->irq_cpuid == cpu) {
foundmatch = 1;
break;
}
}
}
pdacpu(cpu)->sn_first_irq = ((i == NR_IRQS) ? 0 : i);
}
rcu_read_unlock();
}
void sn_irq_fixup(struct pci_dev *pci_dev, struct sn_irq_info *sn_irq_info)
{
nasid_t nasid = sn_irq_info->irq_nasid;
int slice = sn_irq_info->irq_slice;
int cpu = nasid_slice_to_cpuid(nasid, slice);
#ifdef CONFIG_SMP
int cpuphys;
#endif
pci_dev_get(pci_dev);
sn_irq_info->irq_cpuid = cpu;
sn_irq_info->irq_pciioinfo = SN_PCIDEV_INFO(pci_dev);
/* link it into the sn_irq[irq] list */
spin_lock(&sn_irq_info_lock);
list_add_rcu(&sn_irq_info->list, sn_irq_lh[sn_irq_info->irq_irq]);
reserve_irq_vector(sn_irq_info->irq_irq);
if (sn_irq_info->irq_int_bit != -1)
irq_set_handler(sn_irq_info->irq_irq, handle_level_irq);
spin_unlock(&sn_irq_info_lock);
register_intr_pda(sn_irq_info);
#ifdef CONFIG_SMP
cpuphys = cpu_physical_id(cpu);
set_irq_affinity_info(sn_irq_info->irq_irq, cpuphys, 0);
/*
* Affinity was set by the PROM, prevent it from
* being reset by the request_irq() path.
*/
irqd_mark_affinity_was_set(irq_get_irq_data(sn_irq_info->irq_irq));
#endif
}
void sn_irq_unfixup(struct pci_dev *pci_dev)
{
struct sn_irq_info *sn_irq_info;
/* Only cleanup IRQ stuff if this device has a host bus context */
if (!SN_PCIDEV_BUSSOFT(pci_dev))
return;
sn_irq_info = SN_PCIDEV_INFO(pci_dev)->pdi_sn_irq_info;
if (!sn_irq_info)
return;
if (!sn_irq_info->irq_irq) {
kfree(sn_irq_info);
return;
}
unregister_intr_pda(sn_irq_info);
spin_lock(&sn_irq_info_lock);
list_del_rcu(&sn_irq_info->list);
spin_unlock(&sn_irq_info_lock);
if (list_empty(sn_irq_lh[sn_irq_info->irq_irq]))
free_irq_vector(sn_irq_info->irq_irq);
kfree_rcu(sn_irq_info, rcu);
pci_dev_put(pci_dev);
}
static inline void
sn_call_force_intr_provider(struct sn_irq_info *sn_irq_info)
{
struct sn_pcibus_provider *pci_provider;
pci_provider = sn_pci_provider[sn_irq_info->irq_bridge_type];
/* Don't force an interrupt if the irq has been disabled */
if (!irqd_irq_disabled(irq_get_irq_data(sn_irq_info->irq_irq)) &&
pci_provider && pci_provider->force_interrupt)
(*pci_provider->force_interrupt)(sn_irq_info);
}
/*
* Check for lost interrupts. If the PIC int_status reg. says that
* an interrupt has been sent, but not handled, and the interrupt
* is not pending in either the cpu irr regs or in the soft irr regs,
* and the interrupt is not in service, then the interrupt may have
* been lost. Force an interrupt on that pin. It is possible that
* the interrupt is in flight, so we may generate a spurious interrupt,
* but we should never miss a real lost interrupt.
*/
static void sn_check_intr(int irq, struct sn_irq_info *sn_irq_info)
{
u64 regval;
struct pcidev_info *pcidev_info;
struct pcibus_info *pcibus_info;
/*
* Bridge types attached to TIO (anything but PIC) do not need this WAR
* since they do not target Shub II interrupt registers. If that
* ever changes, this check needs to accommodate.
*/
if (sn_irq_info->irq_bridge_type != PCIIO_ASIC_TYPE_PIC)
return;
pcidev_info = (struct pcidev_info *)sn_irq_info->irq_pciioinfo;
if (!pcidev_info)
return;
pcibus_info =
(struct pcibus_info *)pcidev_info->pdi_host_pcidev_info->
pdi_pcibus_info;
regval = pcireg_intr_status_get(pcibus_info);
if (!ia64_get_irr(irq_to_vector(irq))) {
if (!test_bit(irq, pda->sn_in_service_ivecs)) {
regval &= 0xff;
if (sn_irq_info->irq_int_bit & regval &
sn_irq_info->irq_last_intr) {
regval &= ~(sn_irq_info->irq_int_bit & regval);
sn_call_force_intr_provider(sn_irq_info);
}
}
}
sn_irq_info->irq_last_intr = regval;
}
void sn_lb_int_war_check(void)
{
struct sn_irq_info *sn_irq_info;
int i;
if (!sn_ioif_inited || pda->sn_first_irq == 0)
return;
rcu_read_lock();
for (i = pda->sn_first_irq; i <= pda->sn_last_irq; i++) {
list_for_each_entry_rcu(sn_irq_info, sn_irq_lh[i], list) {
sn_check_intr(i, sn_irq_info);
}
}
rcu_read_unlock();
}
void __init sn_irq_lh_init(void)
{
int i;
sn_irq_lh = kmalloc(sizeof(struct list_head *) * NR_IRQS, GFP_KERNEL);
if (!sn_irq_lh)
panic("SN PCI INIT: Failed to allocate memory for PCI init\n");
for (i = 0; i < NR_IRQS; i++) {
sn_irq_lh[i] = kmalloc(sizeof(struct list_head), GFP_KERNEL);
if (!sn_irq_lh[i])
panic("SN PCI INIT: Failed IRQ memory allocation\n");
INIT_LIST_HEAD(sn_irq_lh[i]);
}
}
| gpl-2.0 |
ARMP/ARM-Project | arch/score/mm/cache.c | 8680 | 7027 | /*
* arch/score/mm/cache.c
*
* Score Processor version.
*
* Copyright (C) 2009 Sunplus Core Technology Co., Ltd.
* Lennox Wu <lennox.wu@sunplusct.com>
* Chen Liqin <liqin.chen@sunplusct.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see the file COPYING, or write
* to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/init.h>
#include <linux/linkage.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <asm/mmu_context.h>
/*
Just flush entire Dcache!!
You must ensure the page doesn't include instructions, because
the function will not flush the Icache.
The addr must be cache aligned.
*/
static void flush_data_cache_page(unsigned long addr)
{
unsigned int i;
for (i = 0; i < (PAGE_SIZE / L1_CACHE_BYTES); i += L1_CACHE_BYTES) {
__asm__ __volatile__(
"cache 0x0e, [%0, 0]\n"
"cache 0x1a, [%0, 0]\n"
"nop\n"
: : "r" (addr));
addr += L1_CACHE_BYTES;
}
}
void flush_dcache_page(struct page *page)
{
struct address_space *mapping = page_mapping(page);
unsigned long addr;
if (PageHighMem(page))
return;
if (mapping && !mapping_mapped(mapping)) {
set_bit(PG_dcache_dirty, &(page)->flags);
return;
}
/*
* We could delay the flush for the !page_mapping case too. But that
* case is for exec env/arg pages and those are %99 certainly going to
* get faulted into the tlb (and thus flushed) anyways.
*/
addr = (unsigned long) page_address(page);
flush_data_cache_page(addr);
}
/* called by update_mmu_cache. */
void __update_cache(struct vm_area_struct *vma, unsigned long address,
pte_t pte)
{
struct page *page;
unsigned long pfn, addr;
int exec = (vma->vm_flags & VM_EXEC);
pfn = pte_pfn(pte);
if (unlikely(!pfn_valid(pfn)))
return;
page = pfn_to_page(pfn);
if (page_mapping(page) && test_bit(PG_dcache_dirty, &(page)->flags)) {
addr = (unsigned long) page_address(page);
if (exec)
flush_data_cache_page(addr);
clear_bit(PG_dcache_dirty, &(page)->flags);
}
}
static inline void setup_protection_map(void)
{
protection_map[0] = PAGE_NONE;
protection_map[1] = PAGE_READONLY;
protection_map[2] = PAGE_COPY;
protection_map[3] = PAGE_COPY;
protection_map[4] = PAGE_READONLY;
protection_map[5] = PAGE_READONLY;
protection_map[6] = PAGE_COPY;
protection_map[7] = PAGE_COPY;
protection_map[8] = PAGE_NONE;
protection_map[9] = PAGE_READONLY;
protection_map[10] = PAGE_SHARED;
protection_map[11] = PAGE_SHARED;
protection_map[12] = PAGE_READONLY;
protection_map[13] = PAGE_READONLY;
protection_map[14] = PAGE_SHARED;
protection_map[15] = PAGE_SHARED;
}
void __devinit cpu_cache_init(void)
{
setup_protection_map();
}
void flush_icache_all(void)
{
__asm__ __volatile__(
"la r8, flush_icache_all\n"
"cache 0x10, [r8, 0]\n"
"nop\nnop\nnop\nnop\nnop\nnop\n"
: : : "r8");
}
void flush_dcache_all(void)
{
__asm__ __volatile__(
"la r8, flush_dcache_all\n"
"cache 0x1f, [r8, 0]\n"
"nop\nnop\nnop\nnop\nnop\nnop\n"
"cache 0x1a, [r8, 0]\n"
"nop\nnop\nnop\nnop\nnop\nnop\n"
: : : "r8");
}
void flush_cache_all(void)
{
__asm__ __volatile__(
"la r8, flush_cache_all\n"
"cache 0x10, [r8, 0]\n"
"nop\nnop\nnop\nnop\nnop\nnop\n"
"cache 0x1f, [r8, 0]\n"
"nop\nnop\nnop\nnop\nnop\nnop\n"
"cache 0x1a, [r8, 0]\n"
"nop\nnop\nnop\nnop\nnop\nnop\n"
: : : "r8");
}
void flush_cache_mm(struct mm_struct *mm)
{
if (!(mm->context))
return;
flush_cache_all();
}
/*if we flush a range precisely , the processing may be very long.
We must check each page in the range whether present. If the page is present,
we can flush the range in the page. Be careful, the range may be cross two
page, a page is present and another is not present.
*/
/*
The interface is provided in hopes that the port can find
a suitably efficient method for removing multiple page
sized regions from the cache.
*/
void flush_cache_range(struct vm_area_struct *vma,
unsigned long start, unsigned long end)
{
struct mm_struct *mm = vma->vm_mm;
int exec = vma->vm_flags & VM_EXEC;
pgd_t *pgdp;
pud_t *pudp;
pmd_t *pmdp;
pte_t *ptep;
if (!(mm->context))
return;
pgdp = pgd_offset(mm, start);
pudp = pud_offset(pgdp, start);
pmdp = pmd_offset(pudp, start);
ptep = pte_offset(pmdp, start);
while (start <= end) {
unsigned long tmpend;
pgdp = pgd_offset(mm, start);
pudp = pud_offset(pgdp, start);
pmdp = pmd_offset(pudp, start);
ptep = pte_offset(pmdp, start);
if (!(pte_val(*ptep) & _PAGE_PRESENT)) {
start = (start + PAGE_SIZE) & ~(PAGE_SIZE - 1);
continue;
}
tmpend = (start | (PAGE_SIZE-1)) > end ?
end : (start | (PAGE_SIZE-1));
flush_dcache_range(start, tmpend);
if (exec)
flush_icache_range(start, tmpend);
start = (start + PAGE_SIZE) & ~(PAGE_SIZE - 1);
}
}
void flush_cache_page(struct vm_area_struct *vma,
unsigned long addr, unsigned long pfn)
{
int exec = vma->vm_flags & VM_EXEC;
unsigned long kaddr = 0xa0000000 | (pfn << PAGE_SHIFT);
flush_dcache_range(kaddr, kaddr + PAGE_SIZE);
if (exec)
flush_icache_range(kaddr, kaddr + PAGE_SIZE);
}
void flush_cache_sigtramp(unsigned long addr)
{
__asm__ __volatile__(
"cache 0x02, [%0, 0]\n"
"nop\nnop\nnop\nnop\nnop\n"
"cache 0x02, [%0, 0x4]\n"
"nop\nnop\nnop\nnop\nnop\n"
"cache 0x0d, [%0, 0]\n"
"nop\nnop\nnop\nnop\nnop\n"
"cache 0x0d, [%0, 0x4]\n"
"nop\nnop\nnop\nnop\nnop\n"
"cache 0x1a, [%0, 0]\n"
"nop\nnop\nnop\nnop\nnop\n"
: : "r" (addr));
}
/*
1. WB and invalid a cache line of Dcache
2. Drain Write Buffer
the range must be smaller than PAGE_SIZE
*/
void flush_dcache_range(unsigned long start, unsigned long end)
{
int size, i;
start = start & ~(L1_CACHE_BYTES - 1);
end = end & ~(L1_CACHE_BYTES - 1);
size = end - start;
/* flush dcache to ram, and invalidate dcache lines. */
for (i = 0; i < size; i += L1_CACHE_BYTES) {
__asm__ __volatile__(
"cache 0x0e, [%0, 0]\n"
"nop\nnop\nnop\nnop\nnop\n"
"cache 0x1a, [%0, 0]\n"
"nop\nnop\nnop\nnop\nnop\n"
: : "r" (start));
start += L1_CACHE_BYTES;
}
}
void flush_icache_range(unsigned long start, unsigned long end)
{
int size, i;
start = start & ~(L1_CACHE_BYTES - 1);
end = end & ~(L1_CACHE_BYTES - 1);
size = end - start;
/* invalidate icache lines. */
for (i = 0; i < size; i += L1_CACHE_BYTES) {
__asm__ __volatile__(
"cache 0x02, [%0, 0]\n"
"nop\nnop\nnop\nnop\nnop\n"
: : "r" (start));
start += L1_CACHE_BYTES;
}
}
| gpl-2.0 |
flar2/ElementalX-m7-2.0 | Documentation/laptops/dslm.c | 11496 | 3682 | /*
* dslm.c
* Simple Disk Sleep Monitor
* by Bartek Kania
* Licenced under the GPL
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <string.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <linux/hdreg.h>
#ifdef DEBUG
#define D(x) x
#else
#define D(x)
#endif
int endit = 0;
/* Check if the disk is in powersave-mode
* Most of the code is stolen from hdparm.
* 1 = active, 0 = standby/sleep, -1 = unknown */
static int check_powermode(int fd)
{
unsigned char args[4] = {WIN_CHECKPOWERMODE1,0,0,0};
int state;
if (ioctl(fd, HDIO_DRIVE_CMD, &args)
&& (args[0] = WIN_CHECKPOWERMODE2) /* try again with 0x98 */
&& ioctl(fd, HDIO_DRIVE_CMD, &args)) {
if (errno != EIO || args[0] != 0 || args[1] != 0) {
state = -1; /* "unknown"; */
} else
state = 0; /* "sleeping"; */
} else {
state = (args[2] == 255) ? 1 : 0;
}
D(printf(" drive state is: %d\n", state));
return state;
}
static char *state_name(int i)
{
if (i == -1) return "unknown";
if (i == 0) return "sleeping";
if (i == 1) return "active";
return "internal error";
}
static char *myctime(time_t time)
{
char *ts = ctime(&time);
ts[strlen(ts) - 1] = 0;
return ts;
}
static void measure(int fd)
{
time_t start_time;
int last_state;
time_t last_time;
int curr_state;
time_t curr_time = 0;
time_t time_diff;
time_t active_time = 0;
time_t sleep_time = 0;
time_t unknown_time = 0;
time_t total_time = 0;
int changes = 0;
float tmp;
printf("Starting measurements\n");
last_state = check_powermode(fd);
start_time = last_time = time(0);
printf(" System is in state %s\n\n", state_name(last_state));
while(!endit) {
sleep(1);
curr_state = check_powermode(fd);
if (curr_state != last_state || endit) {
changes++;
curr_time = time(0);
time_diff = curr_time - last_time;
if (last_state == 1) active_time += time_diff;
else if (last_state == 0) sleep_time += time_diff;
else unknown_time += time_diff;
last_state = curr_state;
last_time = curr_time;
printf("%s: State-change to %s\n", myctime(curr_time),
state_name(curr_state));
}
}
changes--; /* Compensate for SIGINT */
total_time = time(0) - start_time;
printf("\nTotal running time: %lus\n", curr_time - start_time);
printf(" State changed %d times\n", changes);
tmp = (float)sleep_time / (float)total_time * 100;
printf(" Time in sleep state: %lus (%.2f%%)\n", sleep_time, tmp);
tmp = (float)active_time / (float)total_time * 100;
printf(" Time in active state: %lus (%.2f%%)\n", active_time, tmp);
tmp = (float)unknown_time / (float)total_time * 100;
printf(" Time in unknown state: %lus (%.2f%%)\n", unknown_time, tmp);
}
static void ender(int s)
{
endit = 1;
}
static void usage(void)
{
puts("usage: dslm [-w <time>] <disk>");
exit(0);
}
int main(int argc, char **argv)
{
int fd;
char *disk = 0;
int settle_time = 60;
/* Parse the simple command-line */
if (argc == 2)
disk = argv[1];
else if (argc == 4) {
settle_time = atoi(argv[2]);
disk = argv[3];
} else
usage();
if (!(fd = open(disk, O_RDONLY|O_NONBLOCK))) {
printf("Can't open %s, because: %s\n", disk, strerror(errno));
exit(-1);
}
if (settle_time) {
printf("Waiting %d seconds for the system to settle down to "
"'normal'\n", settle_time);
sleep(settle_time);
} else
puts("Not waiting for system to settle down");
signal(SIGINT, ender);
measure(fd);
close(fd);
return 0;
}
| gpl-2.0 |
LiquidSmooth-Devices/android_kernel_asus_grouper | drivers/i2c/i2c-slave.c | 489 | 9049 | /*
* i2c-slave.c - a device driver for the iic-slave bus interface.
*
* Copyright (c) 2009-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/module.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/i2c-slave.h>
struct i2c_slave_priv {
struct i2c_adapter master_adap;
struct i2c_slave_adapter *slave_adap;
struct i2c_algorithm master_algo;
};
/**
* i2c_slave_send - Sends data to master. When master issues a read cycle, the
* data is sent by the slave.
* This function copies the client data into the slave tx buffer and return to
* client. This is not a blocking call. Data will be sent to master later once
* slave got the master-ready cycle transfer.
* if there is no sufficient space to write the client buffer, it will return
* error. it will not write partial data.
* @client: Handle to i2c-slave client.
* @buf: Data that will be written to the master
* @count: How many bytes to write.
*
* Returns negative errno, or else the number of bytes written.
*/
int i2c_slave_send(struct i2c_client *client, const char *buf, int count)
{
struct i2c_adapter *adap = client->adapter;
struct i2c_slave_priv *priv = adap->algo_data;
if (!(adap->algo->functionality(adap) & I2C_FUNC_I2C_SLAVE_SUPPORT))
BUG();
if (priv->slave_adap->slv_algo->slave_send)
return priv->slave_adap->slv_algo->slave_send(priv->slave_adap,
buf, count);
return -ENODEV;
}
EXPORT_SYMBOL(i2c_slave_send);
/**
* i2c_slave_get_tx_status - Get amount of data available in tx buffer. If there
* is still data in tx buffer then wait for given time to transfer complete
* for a give timeout.
* @client: Handle to i2c-slave client.
* @timeout_ms: Time to wait for transfer to complete.
*
* Returns negative errno, or else the number of bytes remaining in tx buffer.
*/
int i2c_slave_get_tx_status(struct i2c_client *client, int timeout_ms)
{
struct i2c_adapter *adap = client->adapter;
struct i2c_slave_priv *priv = adap->algo_data;
if (!(adap->algo->functionality(adap) & I2C_FUNC_I2C_SLAVE_SUPPORT))
BUG();
if (priv->slave_adap->slv_algo->slave_get_tx_status)
return priv->slave_adap->slv_algo->slave_get_tx_status(
priv->slave_adap, timeout_ms);
return -ENODEV;
}
EXPORT_SYMBOL(i2c_slave_get_tx_status);
/**
* i2c_slave_recv - Receive data from master. The data receive from master is
* stored on slave rx buffer. When this api will be called, the data will be
* copied from the slave rx buffer to client buffer. If requested amount (count)
* of data is not available then it will wait for either min_count to be receive
* or timeout whatever first.
*
* if timeout_ms = 0, then wait for min_count data to be read.
* if timoue_ms non zero then wait for the data till timeout happen.
* @client: Handle to i2c-slave client.
* @buf: Data that will be read from the master
* @count: How many bytes to read.
* @min_count: Block till read min_count of data.
* @timeout_ms: Time to wait for read to be complete.
*
* Returns negative errno, or else the number of bytes read.
*/
int i2c_slave_recv(struct i2c_client *client, char *buf, int count,
int min_count, int timeout_ms)
{
struct i2c_adapter *adap = client->adapter;
struct i2c_slave_priv *priv = adap->algo_data;
if (!(adap->algo->functionality(adap) & I2C_FUNC_I2C_SLAVE_SUPPORT))
BUG();
if (priv->slave_adap->slv_algo->slave_recv)
return priv->slave_adap->slv_algo->slave_recv(priv->slave_adap,
buf, count, min_count, timeout_ms);
return -ENODEV;
}
EXPORT_SYMBOL(i2c_slave_recv);
/**
* i2c_slave_start - Start the i2c slave to receive/transmit data.
* After this i2c controller starts responding master.
* The dummy-char will send to master if there is no data to send on slave tx
* buffer.
* @client: Handle to i2c-slave client.
* @dummy_char: Data which will be send to master if there is no data to be send
* in slave tx buffer.
*
* Returns negative errno, or else 0 for success.
*/
int i2c_slave_start(struct i2c_client *client, unsigned char dummy_char)
{
struct i2c_adapter *adap = client->adapter;
struct i2c_slave_priv *priv = adap->algo_data;
int slave_add;
int is_10bit_addr;
if (!(adap->algo->functionality(adap) & I2C_FUNC_I2C_SLAVE_SUPPORT))
BUG();
slave_add = client->addr;
is_10bit_addr = (client->flags & I2C_CLIENT_TEN) ? 1 : 0;
if (priv->slave_adap->slv_algo->slave_start)
return priv->slave_adap->slv_algo->slave_start(priv->slave_adap,
slave_add, is_10bit_addr, dummy_char);
return -ENODEV;
}
EXPORT_SYMBOL(i2c_slave_start);
/**
* i2c_slave_stop - Stop slave to receive/transmit data.
* After this i2c controller stops responding master.
* @client: Handle to i2c-slave client.
* @is_buffer_clear: Reset the tx and rx slave buffer or not.
*/
void i2c_slave_stop(struct i2c_client *client, int is_buffer_clear)
{
struct i2c_adapter *adap = client->adapter;
struct i2c_slave_priv *priv = adap->algo_data;
if (!(adap->algo->functionality(adap) & I2C_FUNC_I2C_SLAVE_SUPPORT))
BUG();
if (priv->slave_adap->slv_algo->slave_stop)
return priv->slave_adap->slv_algo->slave_stop(priv->slave_adap,
is_buffer_clear);
}
EXPORT_SYMBOL(i2c_slave_stop);
/**
* i2c_slave_flush_buffer - Flush the receive and transmit buffer.
* @client: Handle to i2c-slave client.
* @is_flush_tx_buffer: Reset the tx slave buffer or not.
* @is_flush_rx_buffer: Reset the rx slave buffer or not.
*
* Returns negative errno, or else 0 for success.
*/
int i2c_slave_flush_buffer(struct i2c_client *client,
int is_flush_tx_buffer, int is_flush_rx_buffer)
{
struct i2c_adapter *adap = client->adapter;
struct i2c_slave_priv *priv = adap->algo_data;
if (!(adap->algo->functionality(adap) & I2C_FUNC_I2C_SLAVE_SUPPORT))
BUG();
if (priv->slave_adap->slv_algo->slave_flush_buffer)
return priv->slave_adap->slv_algo->slave_flush_buffer(
priv->slave_adap, is_flush_tx_buffer,
is_flush_rx_buffer);
return -ENODEV;
}
EXPORT_SYMBOL(i2c_slave_flush_buffer);
/**
* i2c_slave_get_nack_cycle - Get the number of master read cycle on which
* dummy char sent. This is the way to find that how much cycle slave sent the
* NACK packet.
*
* @client: Handle to i2c-slave client.
* @is_cout_reset: Reset the nack count or not.
*
* Returns negative errno, or else 0 for success.
*/
int i2c_slave_get_nack_cycle(struct i2c_client *client,
int is_cout_reset)
{
struct i2c_adapter *adap = client->adapter;
struct i2c_slave_priv *priv = adap->algo_data;
if (!(adap->algo->functionality(adap) & I2C_FUNC_I2C_SLAVE_SUPPORT))
BUG();
if (priv->slave_adap->slv_algo->slave_get_nack_cycle)
return priv->slave_adap->slv_algo->slave_get_nack_cycle(
priv->slave_adap, is_cout_reset);
return -ENODEV;
}
EXPORT_SYMBOL(i2c_slave_get_nack_cycle);
static u32 i2c_slave_func(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C_SLAVE_SUPPORT;
}
int i2c_add_slave_adapter(struct i2c_slave_adapter *slv_adap, bool force_nr)
{
struct i2c_slave_priv *priv;
int ret;
priv = kzalloc(sizeof(struct i2c_slave_priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
/* Set up private adapter data */
priv->slave_adap = slv_adap;
slv_adap->parent_data = priv;
priv->master_algo.functionality = i2c_slave_func;
/* Now fill out new adapter structure */
snprintf(priv->master_adap.name, sizeof(priv->master_adap.name),
"i2c-%d-slave", slv_adap->nr);
priv->master_adap.owner = THIS_MODULE;
priv->master_adap.class = slv_adap->class;
priv->master_adap.algo = &priv->master_algo;
priv->master_adap.algo_data = priv;
priv->master_adap.dev.parent = slv_adap->parent_dev;
if (force_nr) {
priv->master_adap.nr = slv_adap->nr;
ret = i2c_add_numbered_adapter(&priv->master_adap);
} else {
ret = i2c_add_adapter(&priv->master_adap);
}
if (ret < 0) {
dev_err(slv_adap->parent_dev,
"failed to add slave-adapter (error=%d)\n", ret);
kfree(priv);
return ret;
}
slv_adap->dev = &priv->master_adap.dev;
dev_info(slv_adap->parent_dev, "Added slave i2c bus %d\n",
i2c_adapter_id(&priv->master_adap));
return 0;
}
EXPORT_SYMBOL_GPL(i2c_add_slave_adapter);
int i2c_del_slave_adapter(struct i2c_slave_adapter *slv_adap)
{
struct i2c_slave_priv *priv = slv_adap->parent_data;
int ret;
ret = i2c_del_adapter(&priv->master_adap);
if (ret < 0)
return ret;
kfree(priv);
return 0;
}
EXPORT_SYMBOL_GPL(i2c_del_slave_adapter);
| gpl-2.0 |
jomeister15/SGH-I727-kernel | net/core/pktgen.c | 745 | 96709 | /*
* Authors:
* Copyright 2001, 2002 by Robert Olsson <robert.olsson@its.uu.se>
* Uppsala University and
* Swedish University of Agricultural Sciences
*
* Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
* Ben Greear <greearb@candelatech.com>
* Jens Låås <jens.laas@data.slu.se>
*
* This program is free software; you can redistribute 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.
*
*
* A tool for loading the network with preconfigurated packets.
* The tool is implemented as a linux module. Parameters are output
* device, delay (to hard_xmit), number of packets, and whether
* to use multiple SKBs or just the same one.
* pktgen uses the installed interface's output routine.
*
* Additional hacking by:
*
* Jens.Laas@data.slu.se
* Improved by ANK. 010120.
* Improved by ANK even more. 010212.
* MAC address typo fixed. 010417 --ro
* Integrated. 020301 --DaveM
* Added multiskb option 020301 --DaveM
* Scaling of results. 020417--sigurdur@linpro.no
* Significant re-work of the module:
* * Convert to threaded model to more efficiently be able to transmit
* and receive on multiple interfaces at once.
* * Converted many counters to __u64 to allow longer runs.
* * Allow configuration of ranges, like min/max IP address, MACs,
* and UDP-ports, for both source and destination, and can
* set to use a random distribution or sequentially walk the range.
* * Can now change most values after starting.
* * Place 12-byte packet in UDP payload with magic number,
* sequence number, and timestamp.
* * Add receiver code that detects dropped pkts, re-ordered pkts, and
* latencies (with micro-second) precision.
* * Add IOCTL interface to easily get counters & configuration.
* --Ben Greear <greearb@candelatech.com>
*
* Renamed multiskb to clone_skb and cleaned up sending core for two distinct
* skb modes. A clone_skb=0 mode for Ben "ranges" work and a clone_skb != 0
* as a "fastpath" with a configurable number of clones after alloc's.
* clone_skb=0 means all packets are allocated this also means ranges time
* stamps etc can be used. clone_skb=100 means 1 malloc is followed by 100
* clones.
*
* Also moved to /proc/net/pktgen/
* --ro
*
* Sept 10: Fixed threading/locking. Lots of bone-headed and more clever
* mistakes. Also merged in DaveM's patch in the -pre6 patch.
* --Ben Greear <greearb@candelatech.com>
*
* Integrated to 2.5.x 021029 --Lucio Maciel (luciomaciel@zipmail.com.br)
*
*
* 021124 Finished major redesign and rewrite for new functionality.
* See Documentation/networking/pktgen.txt for how to use this.
*
* The new operation:
* For each CPU one thread/process is created at start. This process checks
* for running devices in the if_list and sends packets until count is 0 it
* also the thread checks the thread->control which is used for inter-process
* communication. controlling process "posts" operations to the threads this
* way. The if_lock should be possible to remove when add/rem_device is merged
* into this too.
*
* By design there should only be *one* "controlling" process. In practice
* multiple write accesses gives unpredictable result. Understood by "write"
* to /proc gives result code thats should be read be the "writer".
* For practical use this should be no problem.
*
* Note when adding devices to a specific CPU there good idea to also assign
* /proc/irq/XX/smp_affinity so TX-interrupts gets bound to the same CPU.
* --ro
*
* Fix refcount off by one if first packet fails, potential null deref,
* memleak 030710- KJP
*
* First "ranges" functionality for ipv6 030726 --ro
*
* Included flow support. 030802 ANK.
*
* Fixed unaligned access on IA-64 Grant Grundler <grundler@parisc-linux.org>
*
* Remove if fix from added Harald Welte <laforge@netfilter.org> 040419
* ia64 compilation fix from Aron Griffis <aron@hp.com> 040604
*
* New xmit() return, do_div and misc clean up by Stephen Hemminger
* <shemminger@osdl.org> 040923
*
* Randy Dunlap fixed u64 printk compiler waring
*
* Remove FCS from BW calculation. Lennert Buytenhek <buytenh@wantstofly.org>
* New time handling. Lennert Buytenhek <buytenh@wantstofly.org> 041213
*
* Corrections from Nikolai Malykh (nmalykh@bilim.com)
* Removed unused flags F_SET_SRCMAC & F_SET_SRCIP 041230
*
* interruptible_sleep_on_timeout() replaced Nishanth Aravamudan <nacc@us.ibm.com>
* 050103
*
* MPLS support by Steven Whitehouse <steve@chygwyn.com>
*
* 802.1Q/Q-in-Q support by Francesco Fondelli (FF) <francesco.fondelli@gmail.com>
*
* Fixed src_mac command to set source mac of packet to value specified in
* command by Adit Ranadive <adit.262@gmail.com>
*
*/
#include <linux/sys.h>
#include <linux/types.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/mutex.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/unistd.h>
#include <linux/string.h>
#include <linux/ptrace.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/capability.h>
#include <linux/hrtimer.h>
#include <linux/freezer.h>
#include <linux/delay.h>
#include <linux/timer.h>
#include <linux/list.h>
#include <linux/init.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/inet.h>
#include <linux/inetdevice.h>
#include <linux/rtnetlink.h>
#include <linux/if_arp.h>
#include <linux/if_vlan.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/udp.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/wait.h>
#include <linux/etherdevice.h>
#include <linux/kthread.h>
#include <net/net_namespace.h>
#include <net/checksum.h>
#include <net/ipv6.h>
#include <net/addrconf.h>
#ifdef CONFIG_XFRM
#include <net/xfrm.h>
#endif
#include <asm/byteorder.h>
#include <linux/rcupdate.h>
#include <linux/bitops.h>
#include <linux/io.h>
#include <linux/timex.h>
#include <linux/uaccess.h>
#include <asm/dma.h>
#include <asm/div64.h> /* do_div */
#define VERSION "2.73"
#define IP_NAME_SZ 32
#define MAX_MPLS_LABELS 16 /* This is the max label stack depth */
#define MPLS_STACK_BOTTOM htonl(0x00000100)
/* Device flag bits */
#define F_IPSRC_RND (1<<0) /* IP-Src Random */
#define F_IPDST_RND (1<<1) /* IP-Dst Random */
#define F_UDPSRC_RND (1<<2) /* UDP-Src Random */
#define F_UDPDST_RND (1<<3) /* UDP-Dst Random */
#define F_MACSRC_RND (1<<4) /* MAC-Src Random */
#define F_MACDST_RND (1<<5) /* MAC-Dst Random */
#define F_TXSIZE_RND (1<<6) /* Transmit size is random */
#define F_IPV6 (1<<7) /* Interface in IPV6 Mode */
#define F_MPLS_RND (1<<8) /* Random MPLS labels */
#define F_VID_RND (1<<9) /* Random VLAN ID */
#define F_SVID_RND (1<<10) /* Random SVLAN ID */
#define F_FLOW_SEQ (1<<11) /* Sequential flows */
#define F_IPSEC_ON (1<<12) /* ipsec on for flows */
#define F_QUEUE_MAP_RND (1<<13) /* queue map Random */
#define F_QUEUE_MAP_CPU (1<<14) /* queue map mirrors smp_processor_id() */
#define F_NODE (1<<15) /* Node memory alloc*/
/* Thread control flag bits */
#define T_STOP (1<<0) /* Stop run */
#define T_RUN (1<<1) /* Start run */
#define T_REMDEVALL (1<<2) /* Remove all devs */
#define T_REMDEV (1<<3) /* Remove one dev */
/* If lock -- can be removed after some work */
#define if_lock(t) spin_lock(&(t->if_lock));
#define if_unlock(t) spin_unlock(&(t->if_lock));
/* Used to help with determining the pkts on receive */
#define PKTGEN_MAGIC 0xbe9be955
#define PG_PROC_DIR "pktgen"
#define PGCTRL "pgctrl"
static struct proc_dir_entry *pg_proc_dir;
#define MAX_CFLOWS 65536
#define VLAN_TAG_SIZE(x) ((x)->vlan_id == 0xffff ? 0 : 4)
#define SVLAN_TAG_SIZE(x) ((x)->svlan_id == 0xffff ? 0 : 4)
struct flow_state {
__be32 cur_daddr;
int count;
#ifdef CONFIG_XFRM
struct xfrm_state *x;
#endif
__u32 flags;
};
/* flow flag bits */
#define F_INIT (1<<0) /* flow has been initialized */
struct pktgen_dev {
/*
* Try to keep frequent/infrequent used vars. separated.
*/
struct proc_dir_entry *entry; /* proc file */
struct pktgen_thread *pg_thread;/* the owner */
struct list_head list; /* chaining in the thread's run-queue */
int running; /* if false, the test will stop */
/* If min != max, then we will either do a linear iteration, or
* we will do a random selection from within the range.
*/
__u32 flags;
int removal_mark; /* non-zero => the device is marked for
* removal by worker thread */
int min_pkt_size; /* = ETH_ZLEN; */
int max_pkt_size; /* = ETH_ZLEN; */
int pkt_overhead; /* overhead for MPLS, VLANs, IPSEC etc */
int nfrags;
u64 delay; /* nano-seconds */
__u64 count; /* Default No packets to send */
__u64 sofar; /* How many pkts we've sent so far */
__u64 tx_bytes; /* How many bytes we've transmitted */
__u64 errors; /* Errors when trying to transmit, */
/* runtime counters relating to clone_skb */
__u64 allocated_skbs;
__u32 clone_count;
int last_ok; /* Was last skb sent?
* Or a failed transmit of some sort?
* This will keep sequence numbers in order
*/
ktime_t next_tx;
ktime_t started_at;
ktime_t stopped_at;
u64 idle_acc; /* nano-seconds */
__u32 seq_num;
int clone_skb; /*
* Use multiple SKBs during packet gen.
* If this number is greater than 1, then
* that many copies of the same packet will be
* sent before a new packet is allocated.
* If you want to send 1024 identical packets
* before creating a new packet,
* set clone_skb to 1024.
*/
char dst_min[IP_NAME_SZ]; /* IP, ie 1.2.3.4 */
char dst_max[IP_NAME_SZ]; /* IP, ie 1.2.3.4 */
char src_min[IP_NAME_SZ]; /* IP, ie 1.2.3.4 */
char src_max[IP_NAME_SZ]; /* IP, ie 1.2.3.4 */
struct in6_addr in6_saddr;
struct in6_addr in6_daddr;
struct in6_addr cur_in6_daddr;
struct in6_addr cur_in6_saddr;
/* For ranges */
struct in6_addr min_in6_daddr;
struct in6_addr max_in6_daddr;
struct in6_addr min_in6_saddr;
struct in6_addr max_in6_saddr;
/* If we're doing ranges, random or incremental, then this
* defines the min/max for those ranges.
*/
__be32 saddr_min; /* inclusive, source IP address */
__be32 saddr_max; /* exclusive, source IP address */
__be32 daddr_min; /* inclusive, dest IP address */
__be32 daddr_max; /* exclusive, dest IP address */
__u16 udp_src_min; /* inclusive, source UDP port */
__u16 udp_src_max; /* exclusive, source UDP port */
__u16 udp_dst_min; /* inclusive, dest UDP port */
__u16 udp_dst_max; /* exclusive, dest UDP port */
/* DSCP + ECN */
__u8 tos; /* six MSB of (former) IPv4 TOS
are for dscp codepoint */
__u8 traffic_class; /* ditto for the (former) Traffic Class in IPv6
(see RFC 3260, sec. 4) */
/* MPLS */
unsigned nr_labels; /* Depth of stack, 0 = no MPLS */
__be32 labels[MAX_MPLS_LABELS];
/* VLAN/SVLAN (802.1Q/Q-in-Q) */
__u8 vlan_p;
__u8 vlan_cfi;
__u16 vlan_id; /* 0xffff means no vlan tag */
__u8 svlan_p;
__u8 svlan_cfi;
__u16 svlan_id; /* 0xffff means no svlan tag */
__u32 src_mac_count; /* How many MACs to iterate through */
__u32 dst_mac_count; /* How many MACs to iterate through */
unsigned char dst_mac[ETH_ALEN];
unsigned char src_mac[ETH_ALEN];
__u32 cur_dst_mac_offset;
__u32 cur_src_mac_offset;
__be32 cur_saddr;
__be32 cur_daddr;
__u16 ip_id;
__u16 cur_udp_dst;
__u16 cur_udp_src;
__u16 cur_queue_map;
__u32 cur_pkt_size;
__u32 last_pkt_size;
__u8 hh[14];
/* = {
0x00, 0x80, 0xC8, 0x79, 0xB3, 0xCB,
We fill in SRC address later
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x00
};
*/
__u16 pad; /* pad out the hh struct to an even 16 bytes */
struct sk_buff *skb; /* skb we are to transmit next, used for when we
* are transmitting the same one multiple times
*/
struct net_device *odev; /* The out-going device.
* Note that the device should have it's
* pg_info pointer pointing back to this
* device.
* Set when the user specifies the out-going
* device name (not when the inject is
* started as it used to do.)
*/
char odevname[32];
struct flow_state *flows;
unsigned cflows; /* Concurrent flows (config) */
unsigned lflow; /* Flow length (config) */
unsigned nflows; /* accumulated flows (stats) */
unsigned curfl; /* current sequenced flow (state)*/
u16 queue_map_min;
u16 queue_map_max;
int node; /* Memory node */
#ifdef CONFIG_XFRM
__u8 ipsmode; /* IPSEC mode (config) */
__u8 ipsproto; /* IPSEC type (config) */
#endif
char result[512];
};
struct pktgen_hdr {
__be32 pgh_magic;
__be32 seq_num;
__be32 tv_sec;
__be32 tv_usec;
};
struct pktgen_thread {
spinlock_t if_lock; /* for list of devices */
struct list_head if_list; /* All device here */
struct list_head th_list;
struct task_struct *tsk;
char result[512];
/* Field for thread to receive "posted" events terminate,
stop ifs etc. */
u32 control;
int cpu;
wait_queue_head_t queue;
struct completion start_done;
};
#define REMOVE 1
#define FIND 0
static inline ktime_t ktime_now(void)
{
struct timespec ts;
ktime_get_ts(&ts);
return timespec_to_ktime(ts);
}
/* This works even if 32 bit because of careful byte order choice */
static inline int ktime_lt(const ktime_t cmp1, const ktime_t cmp2)
{
return cmp1.tv64 < cmp2.tv64;
}
static const char version[] =
"pktgen " VERSION ": Packet Generator for packet performance testing.\n";
static int pktgen_remove_device(struct pktgen_thread *t, struct pktgen_dev *i);
static int pktgen_add_device(struct pktgen_thread *t, const char *ifname);
static struct pktgen_dev *pktgen_find_dev(struct pktgen_thread *t,
const char *ifname, bool exact);
static int pktgen_device_event(struct notifier_block *, unsigned long, void *);
static void pktgen_run_all_threads(void);
static void pktgen_reset_all_threads(void);
static void pktgen_stop_all_threads_ifs(void);
static void pktgen_stop(struct pktgen_thread *t);
static void pktgen_clear_counters(struct pktgen_dev *pkt_dev);
static unsigned int scan_ip6(const char *s, char ip[16]);
static unsigned int fmt_ip6(char *s, const char ip[16]);
/* Module parameters, defaults. */
static int pg_count_d __read_mostly = 1000;
static int pg_delay_d __read_mostly;
static int pg_clone_skb_d __read_mostly;
static int debug __read_mostly;
static DEFINE_MUTEX(pktgen_thread_lock);
static LIST_HEAD(pktgen_threads);
static struct notifier_block pktgen_notifier_block = {
.notifier_call = pktgen_device_event,
};
/*
* /proc handling functions
*
*/
static int pgctrl_show(struct seq_file *seq, void *v)
{
seq_puts(seq, version);
return 0;
}
static ssize_t pgctrl_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
int err = 0;
char data[128];
if (!capable(CAP_NET_ADMIN)) {
err = -EPERM;
goto out;
}
if (count > sizeof(data))
count = sizeof(data);
if (copy_from_user(data, buf, count)) {
err = -EFAULT;
goto out;
}
data[count - 1] = 0; /* Make string */
if (!strcmp(data, "stop"))
pktgen_stop_all_threads_ifs();
else if (!strcmp(data, "start"))
pktgen_run_all_threads();
else if (!strcmp(data, "reset"))
pktgen_reset_all_threads();
else
printk(KERN_WARNING "pktgen: Unknown command: %s\n", data);
err = count;
out:
return err;
}
static int pgctrl_open(struct inode *inode, struct file *file)
{
return single_open(file, pgctrl_show, PDE(inode)->data);
}
static const struct file_operations pktgen_fops = {
.owner = THIS_MODULE,
.open = pgctrl_open,
.read = seq_read,
.llseek = seq_lseek,
.write = pgctrl_write,
.release = single_release,
};
static int pktgen_if_show(struct seq_file *seq, void *v)
{
const struct pktgen_dev *pkt_dev = seq->private;
ktime_t stopped;
u64 idle;
seq_printf(seq,
"Params: count %llu min_pkt_size: %u max_pkt_size: %u\n",
(unsigned long long)pkt_dev->count, pkt_dev->min_pkt_size,
pkt_dev->max_pkt_size);
seq_printf(seq,
" frags: %d delay: %llu clone_skb: %d ifname: %s\n",
pkt_dev->nfrags, (unsigned long long) pkt_dev->delay,
pkt_dev->clone_skb, pkt_dev->odevname);
seq_printf(seq, " flows: %u flowlen: %u\n", pkt_dev->cflows,
pkt_dev->lflow);
seq_printf(seq,
" queue_map_min: %u queue_map_max: %u\n",
pkt_dev->queue_map_min,
pkt_dev->queue_map_max);
if (pkt_dev->flags & F_IPV6) {
char b1[128], b2[128], b3[128];
fmt_ip6(b1, pkt_dev->in6_saddr.s6_addr);
fmt_ip6(b2, pkt_dev->min_in6_saddr.s6_addr);
fmt_ip6(b3, pkt_dev->max_in6_saddr.s6_addr);
seq_printf(seq,
" saddr: %s min_saddr: %s max_saddr: %s\n", b1,
b2, b3);
fmt_ip6(b1, pkt_dev->in6_daddr.s6_addr);
fmt_ip6(b2, pkt_dev->min_in6_daddr.s6_addr);
fmt_ip6(b3, pkt_dev->max_in6_daddr.s6_addr);
seq_printf(seq,
" daddr: %s min_daddr: %s max_daddr: %s\n", b1,
b2, b3);
} else {
seq_printf(seq,
" dst_min: %s dst_max: %s\n",
pkt_dev->dst_min, pkt_dev->dst_max);
seq_printf(seq,
" src_min: %s src_max: %s\n",
pkt_dev->src_min, pkt_dev->src_max);
}
seq_puts(seq, " src_mac: ");
seq_printf(seq, "%pM ",
is_zero_ether_addr(pkt_dev->src_mac) ?
pkt_dev->odev->dev_addr : pkt_dev->src_mac);
seq_printf(seq, "dst_mac: ");
seq_printf(seq, "%pM\n", pkt_dev->dst_mac);
seq_printf(seq,
" udp_src_min: %d udp_src_max: %d"
" udp_dst_min: %d udp_dst_max: %d\n",
pkt_dev->udp_src_min, pkt_dev->udp_src_max,
pkt_dev->udp_dst_min, pkt_dev->udp_dst_max);
seq_printf(seq,
" src_mac_count: %d dst_mac_count: %d\n",
pkt_dev->src_mac_count, pkt_dev->dst_mac_count);
if (pkt_dev->nr_labels) {
unsigned i;
seq_printf(seq, " mpls: ");
for (i = 0; i < pkt_dev->nr_labels; i++)
seq_printf(seq, "%08x%s", ntohl(pkt_dev->labels[i]),
i == pkt_dev->nr_labels-1 ? "\n" : ", ");
}
if (pkt_dev->vlan_id != 0xffff)
seq_printf(seq, " vlan_id: %u vlan_p: %u vlan_cfi: %u\n",
pkt_dev->vlan_id, pkt_dev->vlan_p,
pkt_dev->vlan_cfi);
if (pkt_dev->svlan_id != 0xffff)
seq_printf(seq, " svlan_id: %u vlan_p: %u vlan_cfi: %u\n",
pkt_dev->svlan_id, pkt_dev->svlan_p,
pkt_dev->svlan_cfi);
if (pkt_dev->tos)
seq_printf(seq, " tos: 0x%02x\n", pkt_dev->tos);
if (pkt_dev->traffic_class)
seq_printf(seq, " traffic_class: 0x%02x\n", pkt_dev->traffic_class);
if (pkt_dev->node >= 0)
seq_printf(seq, " node: %d\n", pkt_dev->node);
seq_printf(seq, " Flags: ");
if (pkt_dev->flags & F_IPV6)
seq_printf(seq, "IPV6 ");
if (pkt_dev->flags & F_IPSRC_RND)
seq_printf(seq, "IPSRC_RND ");
if (pkt_dev->flags & F_IPDST_RND)
seq_printf(seq, "IPDST_RND ");
if (pkt_dev->flags & F_TXSIZE_RND)
seq_printf(seq, "TXSIZE_RND ");
if (pkt_dev->flags & F_UDPSRC_RND)
seq_printf(seq, "UDPSRC_RND ");
if (pkt_dev->flags & F_UDPDST_RND)
seq_printf(seq, "UDPDST_RND ");
if (pkt_dev->flags & F_MPLS_RND)
seq_printf(seq, "MPLS_RND ");
if (pkt_dev->flags & F_QUEUE_MAP_RND)
seq_printf(seq, "QUEUE_MAP_RND ");
if (pkt_dev->flags & F_QUEUE_MAP_CPU)
seq_printf(seq, "QUEUE_MAP_CPU ");
if (pkt_dev->cflows) {
if (pkt_dev->flags & F_FLOW_SEQ)
seq_printf(seq, "FLOW_SEQ "); /*in sequence flows*/
else
seq_printf(seq, "FLOW_RND ");
}
#ifdef CONFIG_XFRM
if (pkt_dev->flags & F_IPSEC_ON)
seq_printf(seq, "IPSEC ");
#endif
if (pkt_dev->flags & F_MACSRC_RND)
seq_printf(seq, "MACSRC_RND ");
if (pkt_dev->flags & F_MACDST_RND)
seq_printf(seq, "MACDST_RND ");
if (pkt_dev->flags & F_VID_RND)
seq_printf(seq, "VID_RND ");
if (pkt_dev->flags & F_SVID_RND)
seq_printf(seq, "SVID_RND ");
if (pkt_dev->flags & F_NODE)
seq_printf(seq, "NODE_ALLOC ");
seq_puts(seq, "\n");
/* not really stopped, more like last-running-at */
stopped = pkt_dev->running ? ktime_now() : pkt_dev->stopped_at;
idle = pkt_dev->idle_acc;
do_div(idle, NSEC_PER_USEC);
seq_printf(seq,
"Current:\n pkts-sofar: %llu errors: %llu\n",
(unsigned long long)pkt_dev->sofar,
(unsigned long long)pkt_dev->errors);
seq_printf(seq,
" started: %lluus stopped: %lluus idle: %lluus\n",
(unsigned long long) ktime_to_us(pkt_dev->started_at),
(unsigned long long) ktime_to_us(stopped),
(unsigned long long) idle);
seq_printf(seq,
" seq_num: %d cur_dst_mac_offset: %d cur_src_mac_offset: %d\n",
pkt_dev->seq_num, pkt_dev->cur_dst_mac_offset,
pkt_dev->cur_src_mac_offset);
if (pkt_dev->flags & F_IPV6) {
char b1[128], b2[128];
fmt_ip6(b1, pkt_dev->cur_in6_daddr.s6_addr);
fmt_ip6(b2, pkt_dev->cur_in6_saddr.s6_addr);
seq_printf(seq, " cur_saddr: %s cur_daddr: %s\n", b2, b1);
} else
seq_printf(seq, " cur_saddr: 0x%x cur_daddr: 0x%x\n",
pkt_dev->cur_saddr, pkt_dev->cur_daddr);
seq_printf(seq, " cur_udp_dst: %d cur_udp_src: %d\n",
pkt_dev->cur_udp_dst, pkt_dev->cur_udp_src);
seq_printf(seq, " cur_queue_map: %u\n", pkt_dev->cur_queue_map);
seq_printf(seq, " flows: %u\n", pkt_dev->nflows);
if (pkt_dev->result[0])
seq_printf(seq, "Result: %s\n", pkt_dev->result);
else
seq_printf(seq, "Result: Idle\n");
return 0;
}
static int hex32_arg(const char __user *user_buffer, unsigned long maxlen,
__u32 *num)
{
int i = 0;
*num = 0;
for (; i < maxlen; i++) {
char c;
*num <<= 4;
if (get_user(c, &user_buffer[i]))
return -EFAULT;
if ((c >= '0') && (c <= '9'))
*num |= c - '0';
else if ((c >= 'a') && (c <= 'f'))
*num |= c - 'a' + 10;
else if ((c >= 'A') && (c <= 'F'))
*num |= c - 'A' + 10;
else
break;
}
return i;
}
static int count_trail_chars(const char __user * user_buffer,
unsigned int maxlen)
{
int i;
for (i = 0; i < maxlen; i++) {
char c;
if (get_user(c, &user_buffer[i]))
return -EFAULT;
switch (c) {
case '\"':
case '\n':
case '\r':
case '\t':
case ' ':
case '=':
break;
default:
goto done;
}
}
done:
return i;
}
static unsigned long num_arg(const char __user * user_buffer,
unsigned long maxlen, unsigned long *num)
{
int i = 0;
*num = 0;
for (; i < maxlen; i++) {
char c;
if (get_user(c, &user_buffer[i]))
return -EFAULT;
if ((c >= '0') && (c <= '9')) {
*num *= 10;
*num += c - '0';
} else
break;
}
return i;
}
static int strn_len(const char __user * user_buffer, unsigned int maxlen)
{
int i = 0;
for (; i < maxlen; i++) {
char c;
if (get_user(c, &user_buffer[i]))
return -EFAULT;
switch (c) {
case '\"':
case '\n':
case '\r':
case '\t':
case ' ':
goto done_str;
break;
default:
break;
}
}
done_str:
return i;
}
static ssize_t get_labels(const char __user *buffer, struct pktgen_dev *pkt_dev)
{
unsigned n = 0;
char c;
ssize_t i = 0;
int len;
pkt_dev->nr_labels = 0;
do {
__u32 tmp;
len = hex32_arg(&buffer[i], 8, &tmp);
if (len <= 0)
return len;
pkt_dev->labels[n] = htonl(tmp);
if (pkt_dev->labels[n] & MPLS_STACK_BOTTOM)
pkt_dev->flags |= F_MPLS_RND;
i += len;
if (get_user(c, &buffer[i]))
return -EFAULT;
i++;
n++;
if (n >= MAX_MPLS_LABELS)
return -E2BIG;
} while (c == ',');
pkt_dev->nr_labels = n;
return i;
}
static ssize_t pktgen_if_write(struct file *file,
const char __user * user_buffer, size_t count,
loff_t * offset)
{
struct seq_file *seq = (struct seq_file *)file->private_data;
struct pktgen_dev *pkt_dev = seq->private;
int i = 0, max, len;
char name[16], valstr[32];
unsigned long value = 0;
char *pg_result = NULL;
int tmp = 0;
char buf[128];
pg_result = &(pkt_dev->result[0]);
if (count < 1) {
printk(KERN_WARNING "pktgen: wrong command format\n");
return -EINVAL;
}
max = count - i;
tmp = count_trail_chars(&user_buffer[i], max);
if (tmp < 0) {
printk(KERN_WARNING "pktgen: illegal format\n");
return tmp;
}
i += tmp;
/* Read variable name */
len = strn_len(&user_buffer[i], sizeof(name) - 1);
if (len < 0)
return len;
memset(name, 0, sizeof(name));
if (copy_from_user(name, &user_buffer[i], len))
return -EFAULT;
i += len;
max = count - i;
len = count_trail_chars(&user_buffer[i], max);
if (len < 0)
return len;
i += len;
if (debug) {
char tb[count + 1];
if (copy_from_user(tb, user_buffer, count))
return -EFAULT;
tb[count] = 0;
printk(KERN_DEBUG "pktgen: %s,%lu buffer -:%s:-\n", name,
(unsigned long)count, tb);
}
if (!strcmp(name, "min_pkt_size")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value < 14 + 20 + 8)
value = 14 + 20 + 8;
if (value != pkt_dev->min_pkt_size) {
pkt_dev->min_pkt_size = value;
pkt_dev->cur_pkt_size = value;
}
sprintf(pg_result, "OK: min_pkt_size=%u",
pkt_dev->min_pkt_size);
return count;
}
if (!strcmp(name, "max_pkt_size")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value < 14 + 20 + 8)
value = 14 + 20 + 8;
if (value != pkt_dev->max_pkt_size) {
pkt_dev->max_pkt_size = value;
pkt_dev->cur_pkt_size = value;
}
sprintf(pg_result, "OK: max_pkt_size=%u",
pkt_dev->max_pkt_size);
return count;
}
/* Shortcut for min = max */
if (!strcmp(name, "pkt_size")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value < 14 + 20 + 8)
value = 14 + 20 + 8;
if (value != pkt_dev->min_pkt_size) {
pkt_dev->min_pkt_size = value;
pkt_dev->max_pkt_size = value;
pkt_dev->cur_pkt_size = value;
}
sprintf(pg_result, "OK: pkt_size=%u", pkt_dev->min_pkt_size);
return count;
}
if (!strcmp(name, "debug")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
debug = value;
sprintf(pg_result, "OK: debug=%u", debug);
return count;
}
if (!strcmp(name, "frags")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
pkt_dev->nfrags = value;
sprintf(pg_result, "OK: frags=%u", pkt_dev->nfrags);
return count;
}
if (!strcmp(name, "delay")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value == 0x7FFFFFFF)
pkt_dev->delay = ULLONG_MAX;
else
pkt_dev->delay = (u64)value;
sprintf(pg_result, "OK: delay=%llu",
(unsigned long long) pkt_dev->delay);
return count;
}
if (!strcmp(name, "udp_src_min")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value != pkt_dev->udp_src_min) {
pkt_dev->udp_src_min = value;
pkt_dev->cur_udp_src = value;
}
sprintf(pg_result, "OK: udp_src_min=%u", pkt_dev->udp_src_min);
return count;
}
if (!strcmp(name, "udp_dst_min")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value != pkt_dev->udp_dst_min) {
pkt_dev->udp_dst_min = value;
pkt_dev->cur_udp_dst = value;
}
sprintf(pg_result, "OK: udp_dst_min=%u", pkt_dev->udp_dst_min);
return count;
}
if (!strcmp(name, "udp_src_max")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value != pkt_dev->udp_src_max) {
pkt_dev->udp_src_max = value;
pkt_dev->cur_udp_src = value;
}
sprintf(pg_result, "OK: udp_src_max=%u", pkt_dev->udp_src_max);
return count;
}
if (!strcmp(name, "udp_dst_max")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value != pkt_dev->udp_dst_max) {
pkt_dev->udp_dst_max = value;
pkt_dev->cur_udp_dst = value;
}
sprintf(pg_result, "OK: udp_dst_max=%u", pkt_dev->udp_dst_max);
return count;
}
if (!strcmp(name, "clone_skb")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
pkt_dev->clone_skb = value;
sprintf(pg_result, "OK: clone_skb=%d", pkt_dev->clone_skb);
return count;
}
if (!strcmp(name, "count")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
pkt_dev->count = value;
sprintf(pg_result, "OK: count=%llu",
(unsigned long long)pkt_dev->count);
return count;
}
if (!strcmp(name, "src_mac_count")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (pkt_dev->src_mac_count != value) {
pkt_dev->src_mac_count = value;
pkt_dev->cur_src_mac_offset = 0;
}
sprintf(pg_result, "OK: src_mac_count=%d",
pkt_dev->src_mac_count);
return count;
}
if (!strcmp(name, "dst_mac_count")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (pkt_dev->dst_mac_count != value) {
pkt_dev->dst_mac_count = value;
pkt_dev->cur_dst_mac_offset = 0;
}
sprintf(pg_result, "OK: dst_mac_count=%d",
pkt_dev->dst_mac_count);
return count;
}
if (!strcmp(name, "node")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (node_possible(value)) {
pkt_dev->node = value;
sprintf(pg_result, "OK: node=%d", pkt_dev->node);
}
else
sprintf(pg_result, "ERROR: node not possible");
return count;
}
if (!strcmp(name, "flag")) {
char f[32];
memset(f, 0, 32);
len = strn_len(&user_buffer[i], sizeof(f) - 1);
if (len < 0)
return len;
if (copy_from_user(f, &user_buffer[i], len))
return -EFAULT;
i += len;
if (strcmp(f, "IPSRC_RND") == 0)
pkt_dev->flags |= F_IPSRC_RND;
else if (strcmp(f, "!IPSRC_RND") == 0)
pkt_dev->flags &= ~F_IPSRC_RND;
else if (strcmp(f, "TXSIZE_RND") == 0)
pkt_dev->flags |= F_TXSIZE_RND;
else if (strcmp(f, "!TXSIZE_RND") == 0)
pkt_dev->flags &= ~F_TXSIZE_RND;
else if (strcmp(f, "IPDST_RND") == 0)
pkt_dev->flags |= F_IPDST_RND;
else if (strcmp(f, "!IPDST_RND") == 0)
pkt_dev->flags &= ~F_IPDST_RND;
else if (strcmp(f, "UDPSRC_RND") == 0)
pkt_dev->flags |= F_UDPSRC_RND;
else if (strcmp(f, "!UDPSRC_RND") == 0)
pkt_dev->flags &= ~F_UDPSRC_RND;
else if (strcmp(f, "UDPDST_RND") == 0)
pkt_dev->flags |= F_UDPDST_RND;
else if (strcmp(f, "!UDPDST_RND") == 0)
pkt_dev->flags &= ~F_UDPDST_RND;
else if (strcmp(f, "MACSRC_RND") == 0)
pkt_dev->flags |= F_MACSRC_RND;
else if (strcmp(f, "!MACSRC_RND") == 0)
pkt_dev->flags &= ~F_MACSRC_RND;
else if (strcmp(f, "MACDST_RND") == 0)
pkt_dev->flags |= F_MACDST_RND;
else if (strcmp(f, "!MACDST_RND") == 0)
pkt_dev->flags &= ~F_MACDST_RND;
else if (strcmp(f, "MPLS_RND") == 0)
pkt_dev->flags |= F_MPLS_RND;
else if (strcmp(f, "!MPLS_RND") == 0)
pkt_dev->flags &= ~F_MPLS_RND;
else if (strcmp(f, "VID_RND") == 0)
pkt_dev->flags |= F_VID_RND;
else if (strcmp(f, "!VID_RND") == 0)
pkt_dev->flags &= ~F_VID_RND;
else if (strcmp(f, "SVID_RND") == 0)
pkt_dev->flags |= F_SVID_RND;
else if (strcmp(f, "!SVID_RND") == 0)
pkt_dev->flags &= ~F_SVID_RND;
else if (strcmp(f, "FLOW_SEQ") == 0)
pkt_dev->flags |= F_FLOW_SEQ;
else if (strcmp(f, "QUEUE_MAP_RND") == 0)
pkt_dev->flags |= F_QUEUE_MAP_RND;
else if (strcmp(f, "!QUEUE_MAP_RND") == 0)
pkt_dev->flags &= ~F_QUEUE_MAP_RND;
else if (strcmp(f, "QUEUE_MAP_CPU") == 0)
pkt_dev->flags |= F_QUEUE_MAP_CPU;
else if (strcmp(f, "!QUEUE_MAP_CPU") == 0)
pkt_dev->flags &= ~F_QUEUE_MAP_CPU;
#ifdef CONFIG_XFRM
else if (strcmp(f, "IPSEC") == 0)
pkt_dev->flags |= F_IPSEC_ON;
#endif
else if (strcmp(f, "!IPV6") == 0)
pkt_dev->flags &= ~F_IPV6;
else if (strcmp(f, "NODE_ALLOC") == 0)
pkt_dev->flags |= F_NODE;
else if (strcmp(f, "!NODE_ALLOC") == 0)
pkt_dev->flags &= ~F_NODE;
else {
sprintf(pg_result,
"Flag -:%s:- unknown\nAvailable flags, (prepend ! to un-set flag):\n%s",
f,
"IPSRC_RND, IPDST_RND, UDPSRC_RND, UDPDST_RND, "
"MACSRC_RND, MACDST_RND, TXSIZE_RND, IPV6, MPLS_RND, VID_RND, SVID_RND, FLOW_SEQ, IPSEC, NODE_ALLOC\n");
return count;
}
sprintf(pg_result, "OK: flags=0x%x", pkt_dev->flags);
return count;
}
if (!strcmp(name, "dst_min") || !strcmp(name, "dst")) {
len = strn_len(&user_buffer[i], sizeof(pkt_dev->dst_min) - 1);
if (len < 0)
return len;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
if (strcmp(buf, pkt_dev->dst_min) != 0) {
memset(pkt_dev->dst_min, 0, sizeof(pkt_dev->dst_min));
strncpy(pkt_dev->dst_min, buf, len);
pkt_dev->daddr_min = in_aton(pkt_dev->dst_min);
pkt_dev->cur_daddr = pkt_dev->daddr_min;
}
if (debug)
printk(KERN_DEBUG "pktgen: dst_min set to: %s\n",
pkt_dev->dst_min);
i += len;
sprintf(pg_result, "OK: dst_min=%s", pkt_dev->dst_min);
return count;
}
if (!strcmp(name, "dst_max")) {
len = strn_len(&user_buffer[i], sizeof(pkt_dev->dst_max) - 1);
if (len < 0)
return len;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
if (strcmp(buf, pkt_dev->dst_max) != 0) {
memset(pkt_dev->dst_max, 0, sizeof(pkt_dev->dst_max));
strncpy(pkt_dev->dst_max, buf, len);
pkt_dev->daddr_max = in_aton(pkt_dev->dst_max);
pkt_dev->cur_daddr = pkt_dev->daddr_max;
}
if (debug)
printk(KERN_DEBUG "pktgen: dst_max set to: %s\n",
pkt_dev->dst_max);
i += len;
sprintf(pg_result, "OK: dst_max=%s", pkt_dev->dst_max);
return count;
}
if (!strcmp(name, "dst6")) {
len = strn_len(&user_buffer[i], sizeof(buf) - 1);
if (len < 0)
return len;
pkt_dev->flags |= F_IPV6;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
scan_ip6(buf, pkt_dev->in6_daddr.s6_addr);
fmt_ip6(buf, pkt_dev->in6_daddr.s6_addr);
ipv6_addr_copy(&pkt_dev->cur_in6_daddr, &pkt_dev->in6_daddr);
if (debug)
printk(KERN_DEBUG "pktgen: dst6 set to: %s\n", buf);
i += len;
sprintf(pg_result, "OK: dst6=%s", buf);
return count;
}
if (!strcmp(name, "dst6_min")) {
len = strn_len(&user_buffer[i], sizeof(buf) - 1);
if (len < 0)
return len;
pkt_dev->flags |= F_IPV6;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
scan_ip6(buf, pkt_dev->min_in6_daddr.s6_addr);
fmt_ip6(buf, pkt_dev->min_in6_daddr.s6_addr);
ipv6_addr_copy(&pkt_dev->cur_in6_daddr,
&pkt_dev->min_in6_daddr);
if (debug)
printk(KERN_DEBUG "pktgen: dst6_min set to: %s\n", buf);
i += len;
sprintf(pg_result, "OK: dst6_min=%s", buf);
return count;
}
if (!strcmp(name, "dst6_max")) {
len = strn_len(&user_buffer[i], sizeof(buf) - 1);
if (len < 0)
return len;
pkt_dev->flags |= F_IPV6;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
scan_ip6(buf, pkt_dev->max_in6_daddr.s6_addr);
fmt_ip6(buf, pkt_dev->max_in6_daddr.s6_addr);
if (debug)
printk(KERN_DEBUG "pktgen: dst6_max set to: %s\n", buf);
i += len;
sprintf(pg_result, "OK: dst6_max=%s", buf);
return count;
}
if (!strcmp(name, "src6")) {
len = strn_len(&user_buffer[i], sizeof(buf) - 1);
if (len < 0)
return len;
pkt_dev->flags |= F_IPV6;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
scan_ip6(buf, pkt_dev->in6_saddr.s6_addr);
fmt_ip6(buf, pkt_dev->in6_saddr.s6_addr);
ipv6_addr_copy(&pkt_dev->cur_in6_saddr, &pkt_dev->in6_saddr);
if (debug)
printk(KERN_DEBUG "pktgen: src6 set to: %s\n", buf);
i += len;
sprintf(pg_result, "OK: src6=%s", buf);
return count;
}
if (!strcmp(name, "src_min")) {
len = strn_len(&user_buffer[i], sizeof(pkt_dev->src_min) - 1);
if (len < 0)
return len;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
if (strcmp(buf, pkt_dev->src_min) != 0) {
memset(pkt_dev->src_min, 0, sizeof(pkt_dev->src_min));
strncpy(pkt_dev->src_min, buf, len);
pkt_dev->saddr_min = in_aton(pkt_dev->src_min);
pkt_dev->cur_saddr = pkt_dev->saddr_min;
}
if (debug)
printk(KERN_DEBUG "pktgen: src_min set to: %s\n",
pkt_dev->src_min);
i += len;
sprintf(pg_result, "OK: src_min=%s", pkt_dev->src_min);
return count;
}
if (!strcmp(name, "src_max")) {
len = strn_len(&user_buffer[i], sizeof(pkt_dev->src_max) - 1);
if (len < 0)
return len;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
if (strcmp(buf, pkt_dev->src_max) != 0) {
memset(pkt_dev->src_max, 0, sizeof(pkt_dev->src_max));
strncpy(pkt_dev->src_max, buf, len);
pkt_dev->saddr_max = in_aton(pkt_dev->src_max);
pkt_dev->cur_saddr = pkt_dev->saddr_max;
}
if (debug)
printk(KERN_DEBUG "pktgen: src_max set to: %s\n",
pkt_dev->src_max);
i += len;
sprintf(pg_result, "OK: src_max=%s", pkt_dev->src_max);
return count;
}
if (!strcmp(name, "dst_mac")) {
char *v = valstr;
unsigned char old_dmac[ETH_ALEN];
unsigned char *m = pkt_dev->dst_mac;
memcpy(old_dmac, pkt_dev->dst_mac, ETH_ALEN);
len = strn_len(&user_buffer[i], sizeof(valstr) - 1);
if (len < 0)
return len;
memset(valstr, 0, sizeof(valstr));
if (copy_from_user(valstr, &user_buffer[i], len))
return -EFAULT;
i += len;
for (*m = 0; *v && m < pkt_dev->dst_mac + 6; v++) {
if (*v >= '0' && *v <= '9') {
*m *= 16;
*m += *v - '0';
}
if (*v >= 'A' && *v <= 'F') {
*m *= 16;
*m += *v - 'A' + 10;
}
if (*v >= 'a' && *v <= 'f') {
*m *= 16;
*m += *v - 'a' + 10;
}
if (*v == ':') {
m++;
*m = 0;
}
}
/* Set up Dest MAC */
if (compare_ether_addr(old_dmac, pkt_dev->dst_mac))
memcpy(&(pkt_dev->hh[0]), pkt_dev->dst_mac, ETH_ALEN);
sprintf(pg_result, "OK: dstmac");
return count;
}
if (!strcmp(name, "src_mac")) {
char *v = valstr;
unsigned char old_smac[ETH_ALEN];
unsigned char *m = pkt_dev->src_mac;
memcpy(old_smac, pkt_dev->src_mac, ETH_ALEN);
len = strn_len(&user_buffer[i], sizeof(valstr) - 1);
if (len < 0)
return len;
memset(valstr, 0, sizeof(valstr));
if (copy_from_user(valstr, &user_buffer[i], len))
return -EFAULT;
i += len;
for (*m = 0; *v && m < pkt_dev->src_mac + 6; v++) {
if (*v >= '0' && *v <= '9') {
*m *= 16;
*m += *v - '0';
}
if (*v >= 'A' && *v <= 'F') {
*m *= 16;
*m += *v - 'A' + 10;
}
if (*v >= 'a' && *v <= 'f') {
*m *= 16;
*m += *v - 'a' + 10;
}
if (*v == ':') {
m++;
*m = 0;
}
}
/* Set up Src MAC */
if (compare_ether_addr(old_smac, pkt_dev->src_mac))
memcpy(&(pkt_dev->hh[6]), pkt_dev->src_mac, ETH_ALEN);
sprintf(pg_result, "OK: srcmac");
return count;
}
if (!strcmp(name, "clear_counters")) {
pktgen_clear_counters(pkt_dev);
sprintf(pg_result, "OK: Clearing counters.\n");
return count;
}
if (!strcmp(name, "flows")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value > MAX_CFLOWS)
value = MAX_CFLOWS;
pkt_dev->cflows = value;
sprintf(pg_result, "OK: flows=%u", pkt_dev->cflows);
return count;
}
if (!strcmp(name, "flowlen")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
pkt_dev->lflow = value;
sprintf(pg_result, "OK: flowlen=%u", pkt_dev->lflow);
return count;
}
if (!strcmp(name, "queue_map_min")) {
len = num_arg(&user_buffer[i], 5, &value);
if (len < 0)
return len;
i += len;
pkt_dev->queue_map_min = value;
sprintf(pg_result, "OK: queue_map_min=%u", pkt_dev->queue_map_min);
return count;
}
if (!strcmp(name, "queue_map_max")) {
len = num_arg(&user_buffer[i], 5, &value);
if (len < 0)
return len;
i += len;
pkt_dev->queue_map_max = value;
sprintf(pg_result, "OK: queue_map_max=%u", pkt_dev->queue_map_max);
return count;
}
if (!strcmp(name, "mpls")) {
unsigned n, cnt;
len = get_labels(&user_buffer[i], pkt_dev);
if (len < 0)
return len;
i += len;
cnt = sprintf(pg_result, "OK: mpls=");
for (n = 0; n < pkt_dev->nr_labels; n++)
cnt += sprintf(pg_result + cnt,
"%08x%s", ntohl(pkt_dev->labels[n]),
n == pkt_dev->nr_labels-1 ? "" : ",");
if (pkt_dev->nr_labels && pkt_dev->vlan_id != 0xffff) {
pkt_dev->vlan_id = 0xffff; /* turn off VLAN/SVLAN */
pkt_dev->svlan_id = 0xffff;
if (debug)
printk(KERN_DEBUG "pktgen: VLAN/SVLAN auto turned off\n");
}
return count;
}
if (!strcmp(name, "vlan_id")) {
len = num_arg(&user_buffer[i], 4, &value);
if (len < 0)
return len;
i += len;
if (value <= 4095) {
pkt_dev->vlan_id = value; /* turn on VLAN */
if (debug)
printk(KERN_DEBUG "pktgen: VLAN turned on\n");
if (debug && pkt_dev->nr_labels)
printk(KERN_DEBUG "pktgen: MPLS auto turned off\n");
pkt_dev->nr_labels = 0; /* turn off MPLS */
sprintf(pg_result, "OK: vlan_id=%u", pkt_dev->vlan_id);
} else {
pkt_dev->vlan_id = 0xffff; /* turn off VLAN/SVLAN */
pkt_dev->svlan_id = 0xffff;
if (debug)
printk(KERN_DEBUG "pktgen: VLAN/SVLAN turned off\n");
}
return count;
}
if (!strcmp(name, "vlan_p")) {
len = num_arg(&user_buffer[i], 1, &value);
if (len < 0)
return len;
i += len;
if ((value <= 7) && (pkt_dev->vlan_id != 0xffff)) {
pkt_dev->vlan_p = value;
sprintf(pg_result, "OK: vlan_p=%u", pkt_dev->vlan_p);
} else {
sprintf(pg_result, "ERROR: vlan_p must be 0-7");
}
return count;
}
if (!strcmp(name, "vlan_cfi")) {
len = num_arg(&user_buffer[i], 1, &value);
if (len < 0)
return len;
i += len;
if ((value <= 1) && (pkt_dev->vlan_id != 0xffff)) {
pkt_dev->vlan_cfi = value;
sprintf(pg_result, "OK: vlan_cfi=%u", pkt_dev->vlan_cfi);
} else {
sprintf(pg_result, "ERROR: vlan_cfi must be 0-1");
}
return count;
}
if (!strcmp(name, "svlan_id")) {
len = num_arg(&user_buffer[i], 4, &value);
if (len < 0)
return len;
i += len;
if ((value <= 4095) && ((pkt_dev->vlan_id != 0xffff))) {
pkt_dev->svlan_id = value; /* turn on SVLAN */
if (debug)
printk(KERN_DEBUG "pktgen: SVLAN turned on\n");
if (debug && pkt_dev->nr_labels)
printk(KERN_DEBUG "pktgen: MPLS auto turned off\n");
pkt_dev->nr_labels = 0; /* turn off MPLS */
sprintf(pg_result, "OK: svlan_id=%u", pkt_dev->svlan_id);
} else {
pkt_dev->vlan_id = 0xffff; /* turn off VLAN/SVLAN */
pkt_dev->svlan_id = 0xffff;
if (debug)
printk(KERN_DEBUG "pktgen: VLAN/SVLAN turned off\n");
}
return count;
}
if (!strcmp(name, "svlan_p")) {
len = num_arg(&user_buffer[i], 1, &value);
if (len < 0)
return len;
i += len;
if ((value <= 7) && (pkt_dev->svlan_id != 0xffff)) {
pkt_dev->svlan_p = value;
sprintf(pg_result, "OK: svlan_p=%u", pkt_dev->svlan_p);
} else {
sprintf(pg_result, "ERROR: svlan_p must be 0-7");
}
return count;
}
if (!strcmp(name, "svlan_cfi")) {
len = num_arg(&user_buffer[i], 1, &value);
if (len < 0)
return len;
i += len;
if ((value <= 1) && (pkt_dev->svlan_id != 0xffff)) {
pkt_dev->svlan_cfi = value;
sprintf(pg_result, "OK: svlan_cfi=%u", pkt_dev->svlan_cfi);
} else {
sprintf(pg_result, "ERROR: svlan_cfi must be 0-1");
}
return count;
}
if (!strcmp(name, "tos")) {
__u32 tmp_value = 0;
len = hex32_arg(&user_buffer[i], 2, &tmp_value);
if (len < 0)
return len;
i += len;
if (len == 2) {
pkt_dev->tos = tmp_value;
sprintf(pg_result, "OK: tos=0x%02x", pkt_dev->tos);
} else {
sprintf(pg_result, "ERROR: tos must be 00-ff");
}
return count;
}
if (!strcmp(name, "traffic_class")) {
__u32 tmp_value = 0;
len = hex32_arg(&user_buffer[i], 2, &tmp_value);
if (len < 0)
return len;
i += len;
if (len == 2) {
pkt_dev->traffic_class = tmp_value;
sprintf(pg_result, "OK: traffic_class=0x%02x", pkt_dev->traffic_class);
} else {
sprintf(pg_result, "ERROR: traffic_class must be 00-ff");
}
return count;
}
sprintf(pkt_dev->result, "No such parameter \"%s\"", name);
return -EINVAL;
}
static int pktgen_if_open(struct inode *inode, struct file *file)
{
return single_open(file, pktgen_if_show, PDE(inode)->data);
}
static const struct file_operations pktgen_if_fops = {
.owner = THIS_MODULE,
.open = pktgen_if_open,
.read = seq_read,
.llseek = seq_lseek,
.write = pktgen_if_write,
.release = single_release,
};
static int pktgen_thread_show(struct seq_file *seq, void *v)
{
struct pktgen_thread *t = seq->private;
const struct pktgen_dev *pkt_dev;
BUG_ON(!t);
seq_printf(seq, "Running: ");
if_lock(t);
list_for_each_entry(pkt_dev, &t->if_list, list)
if (pkt_dev->running)
seq_printf(seq, "%s ", pkt_dev->odevname);
seq_printf(seq, "\nStopped: ");
list_for_each_entry(pkt_dev, &t->if_list, list)
if (!pkt_dev->running)
seq_printf(seq, "%s ", pkt_dev->odevname);
if (t->result[0])
seq_printf(seq, "\nResult: %s\n", t->result);
else
seq_printf(seq, "\nResult: NA\n");
if_unlock(t);
return 0;
}
static ssize_t pktgen_thread_write(struct file *file,
const char __user * user_buffer,
size_t count, loff_t * offset)
{
struct seq_file *seq = (struct seq_file *)file->private_data;
struct pktgen_thread *t = seq->private;
int i = 0, max, len, ret;
char name[40];
char *pg_result;
if (count < 1) {
// sprintf(pg_result, "Wrong command format");
return -EINVAL;
}
max = count - i;
len = count_trail_chars(&user_buffer[i], max);
if (len < 0)
return len;
i += len;
/* Read variable name */
len = strn_len(&user_buffer[i], sizeof(name) - 1);
if (len < 0)
return len;
memset(name, 0, sizeof(name));
if (copy_from_user(name, &user_buffer[i], len))
return -EFAULT;
i += len;
max = count - i;
len = count_trail_chars(&user_buffer[i], max);
if (len < 0)
return len;
i += len;
if (debug)
printk(KERN_DEBUG "pktgen: t=%s, count=%lu\n",
name, (unsigned long)count);
if (!t) {
printk(KERN_ERR "pktgen: ERROR: No thread\n");
ret = -EINVAL;
goto out;
}
pg_result = &(t->result[0]);
if (!strcmp(name, "add_device")) {
char f[32];
memset(f, 0, 32);
len = strn_len(&user_buffer[i], sizeof(f) - 1);
if (len < 0) {
ret = len;
goto out;
}
if (copy_from_user(f, &user_buffer[i], len))
return -EFAULT;
i += len;
mutex_lock(&pktgen_thread_lock);
pktgen_add_device(t, f);
mutex_unlock(&pktgen_thread_lock);
ret = count;
sprintf(pg_result, "OK: add_device=%s", f);
goto out;
}
if (!strcmp(name, "rem_device_all")) {
mutex_lock(&pktgen_thread_lock);
t->control |= T_REMDEVALL;
mutex_unlock(&pktgen_thread_lock);
schedule_timeout_interruptible(msecs_to_jiffies(125)); /* Propagate thread->control */
ret = count;
sprintf(pg_result, "OK: rem_device_all");
goto out;
}
if (!strcmp(name, "max_before_softirq")) {
sprintf(pg_result, "OK: Note! max_before_softirq is obsoleted -- Do not use");
ret = count;
goto out;
}
ret = -EINVAL;
out:
return ret;
}
static int pktgen_thread_open(struct inode *inode, struct file *file)
{
return single_open(file, pktgen_thread_show, PDE(inode)->data);
}
static const struct file_operations pktgen_thread_fops = {
.owner = THIS_MODULE,
.open = pktgen_thread_open,
.read = seq_read,
.llseek = seq_lseek,
.write = pktgen_thread_write,
.release = single_release,
};
/* Think find or remove for NN */
static struct pktgen_dev *__pktgen_NN_threads(const char *ifname, int remove)
{
struct pktgen_thread *t;
struct pktgen_dev *pkt_dev = NULL;
bool exact = (remove == FIND);
list_for_each_entry(t, &pktgen_threads, th_list) {
pkt_dev = pktgen_find_dev(t, ifname, exact);
if (pkt_dev) {
if (remove) {
if_lock(t);
pkt_dev->removal_mark = 1;
t->control |= T_REMDEV;
if_unlock(t);
}
break;
}
}
return pkt_dev;
}
/*
* mark a device for removal
*/
static void pktgen_mark_device(const char *ifname)
{
struct pktgen_dev *pkt_dev = NULL;
const int max_tries = 10, msec_per_try = 125;
int i = 0;
mutex_lock(&pktgen_thread_lock);
pr_debug("pktgen: pktgen_mark_device marking %s for removal\n", ifname);
while (1) {
pkt_dev = __pktgen_NN_threads(ifname, REMOVE);
if (pkt_dev == NULL)
break; /* success */
mutex_unlock(&pktgen_thread_lock);
pr_debug("pktgen: pktgen_mark_device waiting for %s "
"to disappear....\n", ifname);
schedule_timeout_interruptible(msecs_to_jiffies(msec_per_try));
mutex_lock(&pktgen_thread_lock);
if (++i >= max_tries) {
printk(KERN_ERR "pktgen_mark_device: timed out after "
"waiting %d msec for device %s to be removed\n",
msec_per_try * i, ifname);
break;
}
}
mutex_unlock(&pktgen_thread_lock);
}
static void pktgen_change_name(struct net_device *dev)
{
struct pktgen_thread *t;
list_for_each_entry(t, &pktgen_threads, th_list) {
struct pktgen_dev *pkt_dev;
list_for_each_entry(pkt_dev, &t->if_list, list) {
if (pkt_dev->odev != dev)
continue;
remove_proc_entry(pkt_dev->entry->name, pg_proc_dir);
pkt_dev->entry = proc_create_data(dev->name, 0600,
pg_proc_dir,
&pktgen_if_fops,
pkt_dev);
if (!pkt_dev->entry)
printk(KERN_ERR "pktgen: can't move proc "
" entry for '%s'\n", dev->name);
break;
}
}
}
static int pktgen_device_event(struct notifier_block *unused,
unsigned long event, void *ptr)
{
struct net_device *dev = ptr;
if (!net_eq(dev_net(dev), &init_net))
return NOTIFY_DONE;
/* It is OK that we do not hold the group lock right now,
* as we run under the RTNL lock.
*/
switch (event) {
case NETDEV_CHANGENAME:
pktgen_change_name(dev);
break;
case NETDEV_UNREGISTER:
pktgen_mark_device(dev->name);
break;
}
return NOTIFY_DONE;
}
static struct net_device *pktgen_dev_get_by_name(struct pktgen_dev *pkt_dev,
const char *ifname)
{
char b[IFNAMSIZ+5];
int i = 0;
for (i = 0; ifname[i] != '@'; i++) {
if (i == IFNAMSIZ)
break;
b[i] = ifname[i];
}
b[i] = 0;
return dev_get_by_name(&init_net, b);
}
/* Associate pktgen_dev with a device. */
static int pktgen_setup_dev(struct pktgen_dev *pkt_dev, const char *ifname)
{
struct net_device *odev;
int err;
/* Clean old setups */
if (pkt_dev->odev) {
dev_put(pkt_dev->odev);
pkt_dev->odev = NULL;
}
odev = pktgen_dev_get_by_name(pkt_dev, ifname);
if (!odev) {
printk(KERN_ERR "pktgen: no such netdevice: \"%s\"\n", ifname);
return -ENODEV;
}
if (odev->type != ARPHRD_ETHER) {
printk(KERN_ERR "pktgen: not an ethernet device: \"%s\"\n", ifname);
err = -EINVAL;
} else if (!netif_running(odev)) {
printk(KERN_ERR "pktgen: device is down: \"%s\"\n", ifname);
err = -ENETDOWN;
} else {
pkt_dev->odev = odev;
return 0;
}
dev_put(odev);
return err;
}
/* Read pkt_dev from the interface and set up internal pktgen_dev
* structure to have the right information to create/send packets
*/
static void pktgen_setup_inject(struct pktgen_dev *pkt_dev)
{
int ntxq;
if (!pkt_dev->odev) {
printk(KERN_ERR "pktgen: ERROR: pkt_dev->odev == NULL in "
"setup_inject.\n");
sprintf(pkt_dev->result,
"ERROR: pkt_dev->odev == NULL in setup_inject.\n");
return;
}
/* make sure that we don't pick a non-existing transmit queue */
ntxq = pkt_dev->odev->real_num_tx_queues;
if (ntxq <= pkt_dev->queue_map_min) {
printk(KERN_WARNING "pktgen: WARNING: Requested "
"queue_map_min (zero-based) (%d) exceeds valid range "
"[0 - %d] for (%d) queues on %s, resetting\n",
pkt_dev->queue_map_min, (ntxq ?: 1) - 1, ntxq,
pkt_dev->odevname);
pkt_dev->queue_map_min = ntxq - 1;
}
if (pkt_dev->queue_map_max >= ntxq) {
printk(KERN_WARNING "pktgen: WARNING: Requested "
"queue_map_max (zero-based) (%d) exceeds valid range "
"[0 - %d] for (%d) queues on %s, resetting\n",
pkt_dev->queue_map_max, (ntxq ?: 1) - 1, ntxq,
pkt_dev->odevname);
pkt_dev->queue_map_max = ntxq - 1;
}
/* Default to the interface's mac if not explicitly set. */
if (is_zero_ether_addr(pkt_dev->src_mac))
memcpy(&(pkt_dev->hh[6]), pkt_dev->odev->dev_addr, ETH_ALEN);
/* Set up Dest MAC */
memcpy(&(pkt_dev->hh[0]), pkt_dev->dst_mac, ETH_ALEN);
/* Set up pkt size */
pkt_dev->cur_pkt_size = pkt_dev->min_pkt_size;
if (pkt_dev->flags & F_IPV6) {
/*
* Skip this automatic address setting until locks or functions
* gets exported
*/
#ifdef NOTNOW
int i, set = 0, err = 1;
struct inet6_dev *idev;
for (i = 0; i < IN6_ADDR_HSIZE; i++)
if (pkt_dev->cur_in6_saddr.s6_addr[i]) {
set = 1;
break;
}
if (!set) {
/*
* Use linklevel address if unconfigured.
*
* use ipv6_get_lladdr if/when it's get exported
*/
rcu_read_lock();
idev = __in6_dev_get(pkt_dev->odev);
if (idev) {
struct inet6_ifaddr *ifp;
read_lock_bh(&idev->lock);
for (ifp = idev->addr_list; ifp;
ifp = ifp->if_next) {
if (ifp->scope == IFA_LINK &&
!(ifp->flags & IFA_F_TENTATIVE)) {
ipv6_addr_copy(&pkt_dev->
cur_in6_saddr,
&ifp->addr);
err = 0;
break;
}
}
read_unlock_bh(&idev->lock);
}
rcu_read_unlock();
if (err)
printk(KERN_ERR "pktgen: ERROR: IPv6 link "
"address not availble.\n");
}
#endif
} else {
pkt_dev->saddr_min = 0;
pkt_dev->saddr_max = 0;
if (strlen(pkt_dev->src_min) == 0) {
struct in_device *in_dev;
rcu_read_lock();
in_dev = __in_dev_get_rcu(pkt_dev->odev);
if (in_dev) {
if (in_dev->ifa_list) {
pkt_dev->saddr_min =
in_dev->ifa_list->ifa_address;
pkt_dev->saddr_max = pkt_dev->saddr_min;
}
}
rcu_read_unlock();
} else {
pkt_dev->saddr_min = in_aton(pkt_dev->src_min);
pkt_dev->saddr_max = in_aton(pkt_dev->src_max);
}
pkt_dev->daddr_min = in_aton(pkt_dev->dst_min);
pkt_dev->daddr_max = in_aton(pkt_dev->dst_max);
}
/* Initialize current values. */
pkt_dev->cur_dst_mac_offset = 0;
pkt_dev->cur_src_mac_offset = 0;
pkt_dev->cur_saddr = pkt_dev->saddr_min;
pkt_dev->cur_daddr = pkt_dev->daddr_min;
pkt_dev->cur_udp_dst = pkt_dev->udp_dst_min;
pkt_dev->cur_udp_src = pkt_dev->udp_src_min;
pkt_dev->nflows = 0;
}
static void spin(struct pktgen_dev *pkt_dev, ktime_t spin_until)
{
ktime_t start_time, end_time;
s64 remaining;
struct hrtimer_sleeper t;
hrtimer_init_on_stack(&t.timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
hrtimer_set_expires(&t.timer, spin_until);
remaining = ktime_to_us(hrtimer_expires_remaining(&t.timer));
if (remaining <= 0) {
pkt_dev->next_tx = ktime_add_ns(spin_until, pkt_dev->delay);
return;
}
start_time = ktime_now();
if (remaining < 100)
udelay(remaining); /* really small just spin */
else {
/* see do_nanosleep */
hrtimer_init_sleeper(&t, current);
do {
set_current_state(TASK_INTERRUPTIBLE);
hrtimer_start_expires(&t.timer, HRTIMER_MODE_ABS);
if (!hrtimer_active(&t.timer))
t.task = NULL;
if (likely(t.task))
schedule();
hrtimer_cancel(&t.timer);
} while (t.task && pkt_dev->running && !signal_pending(current));
__set_current_state(TASK_RUNNING);
}
end_time = ktime_now();
pkt_dev->idle_acc += ktime_to_ns(ktime_sub(end_time, start_time));
pkt_dev->next_tx = ktime_add_ns(spin_until, pkt_dev->delay);
}
static inline void set_pkt_overhead(struct pktgen_dev *pkt_dev)
{
pkt_dev->pkt_overhead = 0;
pkt_dev->pkt_overhead += pkt_dev->nr_labels*sizeof(u32);
pkt_dev->pkt_overhead += VLAN_TAG_SIZE(pkt_dev);
pkt_dev->pkt_overhead += SVLAN_TAG_SIZE(pkt_dev);
}
static inline int f_seen(const struct pktgen_dev *pkt_dev, int flow)
{
return !!(pkt_dev->flows[flow].flags & F_INIT);
}
static inline int f_pick(struct pktgen_dev *pkt_dev)
{
int flow = pkt_dev->curfl;
if (pkt_dev->flags & F_FLOW_SEQ) {
if (pkt_dev->flows[flow].count >= pkt_dev->lflow) {
/* reset time */
pkt_dev->flows[flow].count = 0;
pkt_dev->flows[flow].flags = 0;
pkt_dev->curfl += 1;
if (pkt_dev->curfl >= pkt_dev->cflows)
pkt_dev->curfl = 0; /*reset */
}
} else {
flow = random32() % pkt_dev->cflows;
pkt_dev->curfl = flow;
if (pkt_dev->flows[flow].count > pkt_dev->lflow) {
pkt_dev->flows[flow].count = 0;
pkt_dev->flows[flow].flags = 0;
}
}
return pkt_dev->curfl;
}
#ifdef CONFIG_XFRM
/* If there was already an IPSEC SA, we keep it as is, else
* we go look for it ...
*/
#define DUMMY_MARK 0
static void get_ipsec_sa(struct pktgen_dev *pkt_dev, int flow)
{
struct xfrm_state *x = pkt_dev->flows[flow].x;
if (!x) {
/*slow path: we dont already have xfrm_state*/
x = xfrm_stateonly_find(&init_net, DUMMY_MARK,
(xfrm_address_t *)&pkt_dev->cur_daddr,
(xfrm_address_t *)&pkt_dev->cur_saddr,
AF_INET,
pkt_dev->ipsmode,
pkt_dev->ipsproto, 0);
if (x) {
pkt_dev->flows[flow].x = x;
set_pkt_overhead(pkt_dev);
pkt_dev->pkt_overhead += x->props.header_len;
}
}
}
#endif
static void set_cur_queue_map(struct pktgen_dev *pkt_dev)
{
if (pkt_dev->flags & F_QUEUE_MAP_CPU)
pkt_dev->cur_queue_map = smp_processor_id();
else if (pkt_dev->queue_map_min <= pkt_dev->queue_map_max) {
__u16 t;
if (pkt_dev->flags & F_QUEUE_MAP_RND) {
t = random32() %
(pkt_dev->queue_map_max -
pkt_dev->queue_map_min + 1)
+ pkt_dev->queue_map_min;
} else {
t = pkt_dev->cur_queue_map + 1;
if (t > pkt_dev->queue_map_max)
t = pkt_dev->queue_map_min;
}
pkt_dev->cur_queue_map = t;
}
pkt_dev->cur_queue_map = pkt_dev->cur_queue_map % pkt_dev->odev->real_num_tx_queues;
}
/* Increment/randomize headers according to flags and current values
* for IP src/dest, UDP src/dst port, MAC-Addr src/dst
*/
static void mod_cur_headers(struct pktgen_dev *pkt_dev)
{
__u32 imn;
__u32 imx;
int flow = 0;
if (pkt_dev->cflows)
flow = f_pick(pkt_dev);
/* Deal with source MAC */
if (pkt_dev->src_mac_count > 1) {
__u32 mc;
__u32 tmp;
if (pkt_dev->flags & F_MACSRC_RND)
mc = random32() % pkt_dev->src_mac_count;
else {
mc = pkt_dev->cur_src_mac_offset++;
if (pkt_dev->cur_src_mac_offset >=
pkt_dev->src_mac_count)
pkt_dev->cur_src_mac_offset = 0;
}
tmp = pkt_dev->src_mac[5] + (mc & 0xFF);
pkt_dev->hh[11] = tmp;
tmp = (pkt_dev->src_mac[4] + ((mc >> 8) & 0xFF) + (tmp >> 8));
pkt_dev->hh[10] = tmp;
tmp = (pkt_dev->src_mac[3] + ((mc >> 16) & 0xFF) + (tmp >> 8));
pkt_dev->hh[9] = tmp;
tmp = (pkt_dev->src_mac[2] + ((mc >> 24) & 0xFF) + (tmp >> 8));
pkt_dev->hh[8] = tmp;
tmp = (pkt_dev->src_mac[1] + (tmp >> 8));
pkt_dev->hh[7] = tmp;
}
/* Deal with Destination MAC */
if (pkt_dev->dst_mac_count > 1) {
__u32 mc;
__u32 tmp;
if (pkt_dev->flags & F_MACDST_RND)
mc = random32() % pkt_dev->dst_mac_count;
else {
mc = pkt_dev->cur_dst_mac_offset++;
if (pkt_dev->cur_dst_mac_offset >=
pkt_dev->dst_mac_count) {
pkt_dev->cur_dst_mac_offset = 0;
}
}
tmp = pkt_dev->dst_mac[5] + (mc & 0xFF);
pkt_dev->hh[5] = tmp;
tmp = (pkt_dev->dst_mac[4] + ((mc >> 8) & 0xFF) + (tmp >> 8));
pkt_dev->hh[4] = tmp;
tmp = (pkt_dev->dst_mac[3] + ((mc >> 16) & 0xFF) + (tmp >> 8));
pkt_dev->hh[3] = tmp;
tmp = (pkt_dev->dst_mac[2] + ((mc >> 24) & 0xFF) + (tmp >> 8));
pkt_dev->hh[2] = tmp;
tmp = (pkt_dev->dst_mac[1] + (tmp >> 8));
pkt_dev->hh[1] = tmp;
}
if (pkt_dev->flags & F_MPLS_RND) {
unsigned i;
for (i = 0; i < pkt_dev->nr_labels; i++)
if (pkt_dev->labels[i] & MPLS_STACK_BOTTOM)
pkt_dev->labels[i] = MPLS_STACK_BOTTOM |
((__force __be32)random32() &
htonl(0x000fffff));
}
if ((pkt_dev->flags & F_VID_RND) && (pkt_dev->vlan_id != 0xffff)) {
pkt_dev->vlan_id = random32() & (4096-1);
}
if ((pkt_dev->flags & F_SVID_RND) && (pkt_dev->svlan_id != 0xffff)) {
pkt_dev->svlan_id = random32() & (4096 - 1);
}
if (pkt_dev->udp_src_min < pkt_dev->udp_src_max) {
if (pkt_dev->flags & F_UDPSRC_RND)
pkt_dev->cur_udp_src = random32() %
(pkt_dev->udp_src_max - pkt_dev->udp_src_min)
+ pkt_dev->udp_src_min;
else {
pkt_dev->cur_udp_src++;
if (pkt_dev->cur_udp_src >= pkt_dev->udp_src_max)
pkt_dev->cur_udp_src = pkt_dev->udp_src_min;
}
}
if (pkt_dev->udp_dst_min < pkt_dev->udp_dst_max) {
if (pkt_dev->flags & F_UDPDST_RND) {
pkt_dev->cur_udp_dst = random32() %
(pkt_dev->udp_dst_max - pkt_dev->udp_dst_min)
+ pkt_dev->udp_dst_min;
} else {
pkt_dev->cur_udp_dst++;
if (pkt_dev->cur_udp_dst >= pkt_dev->udp_dst_max)
pkt_dev->cur_udp_dst = pkt_dev->udp_dst_min;
}
}
if (!(pkt_dev->flags & F_IPV6)) {
imn = ntohl(pkt_dev->saddr_min);
imx = ntohl(pkt_dev->saddr_max);
if (imn < imx) {
__u32 t;
if (pkt_dev->flags & F_IPSRC_RND)
t = random32() % (imx - imn) + imn;
else {
t = ntohl(pkt_dev->cur_saddr);
t++;
if (t > imx)
t = imn;
}
pkt_dev->cur_saddr = htonl(t);
}
if (pkt_dev->cflows && f_seen(pkt_dev, flow)) {
pkt_dev->cur_daddr = pkt_dev->flows[flow].cur_daddr;
} else {
imn = ntohl(pkt_dev->daddr_min);
imx = ntohl(pkt_dev->daddr_max);
if (imn < imx) {
__u32 t;
__be32 s;
if (pkt_dev->flags & F_IPDST_RND) {
t = random32() % (imx - imn) + imn;
s = htonl(t);
while (ipv4_is_loopback(s) ||
ipv4_is_multicast(s) ||
ipv4_is_lbcast(s) ||
ipv4_is_zeronet(s) ||
ipv4_is_local_multicast(s)) {
t = random32() % (imx - imn) + imn;
s = htonl(t);
}
pkt_dev->cur_daddr = s;
} else {
t = ntohl(pkt_dev->cur_daddr);
t++;
if (t > imx) {
t = imn;
}
pkt_dev->cur_daddr = htonl(t);
}
}
if (pkt_dev->cflows) {
pkt_dev->flows[flow].flags |= F_INIT;
pkt_dev->flows[flow].cur_daddr =
pkt_dev->cur_daddr;
#ifdef CONFIG_XFRM
if (pkt_dev->flags & F_IPSEC_ON)
get_ipsec_sa(pkt_dev, flow);
#endif
pkt_dev->nflows++;
}
}
} else { /* IPV6 * */
if (pkt_dev->min_in6_daddr.s6_addr32[0] == 0 &&
pkt_dev->min_in6_daddr.s6_addr32[1] == 0 &&
pkt_dev->min_in6_daddr.s6_addr32[2] == 0 &&
pkt_dev->min_in6_daddr.s6_addr32[3] == 0) ;
else {
int i;
/* Only random destinations yet */
for (i = 0; i < 4; i++) {
pkt_dev->cur_in6_daddr.s6_addr32[i] =
(((__force __be32)random32() |
pkt_dev->min_in6_daddr.s6_addr32[i]) &
pkt_dev->max_in6_daddr.s6_addr32[i]);
}
}
}
if (pkt_dev->min_pkt_size < pkt_dev->max_pkt_size) {
__u32 t;
if (pkt_dev->flags & F_TXSIZE_RND) {
t = random32() %
(pkt_dev->max_pkt_size - pkt_dev->min_pkt_size)
+ pkt_dev->min_pkt_size;
} else {
t = pkt_dev->cur_pkt_size + 1;
if (t > pkt_dev->max_pkt_size)
t = pkt_dev->min_pkt_size;
}
pkt_dev->cur_pkt_size = t;
}
set_cur_queue_map(pkt_dev);
pkt_dev->flows[flow].count++;
}
#ifdef CONFIG_XFRM
static int pktgen_output_ipsec(struct sk_buff *skb, struct pktgen_dev *pkt_dev)
{
struct xfrm_state *x = pkt_dev->flows[pkt_dev->curfl].x;
int err = 0;
struct iphdr *iph;
if (!x)
return 0;
/* XXX: we dont support tunnel mode for now until
* we resolve the dst issue */
if (x->props.mode != XFRM_MODE_TRANSPORT)
return 0;
spin_lock(&x->lock);
iph = ip_hdr(skb);
err = x->outer_mode->output(x, skb);
if (err)
goto error;
err = x->type->output(x, skb);
if (err)
goto error;
x->curlft.bytes += skb->len;
x->curlft.packets++;
error:
spin_unlock(&x->lock);
return err;
}
static void free_SAs(struct pktgen_dev *pkt_dev)
{
if (pkt_dev->cflows) {
/* let go of the SAs if we have them */
int i = 0;
for (; i < pkt_dev->cflows; i++) {
struct xfrm_state *x = pkt_dev->flows[i].x;
if (x) {
xfrm_state_put(x);
pkt_dev->flows[i].x = NULL;
}
}
}
}
static int process_ipsec(struct pktgen_dev *pkt_dev,
struct sk_buff *skb, __be16 protocol)
{
if (pkt_dev->flags & F_IPSEC_ON) {
struct xfrm_state *x = pkt_dev->flows[pkt_dev->curfl].x;
int nhead = 0;
if (x) {
int ret;
__u8 *eth;
nhead = x->props.header_len - skb_headroom(skb);
if (nhead > 0) {
ret = pskb_expand_head(skb, nhead, 0, GFP_ATOMIC);
if (ret < 0) {
printk(KERN_ERR "Error expanding "
"ipsec packet %d\n", ret);
goto err;
}
}
/* ipsec is not expecting ll header */
skb_pull(skb, ETH_HLEN);
ret = pktgen_output_ipsec(skb, pkt_dev);
if (ret) {
printk(KERN_ERR "Error creating ipsec "
"packet %d\n", ret);
goto err;
}
/* restore ll */
eth = (__u8 *) skb_push(skb, ETH_HLEN);
memcpy(eth, pkt_dev->hh, 12);
*(u16 *) ð[12] = protocol;
}
}
return 1;
err:
kfree_skb(skb);
return 0;
}
#endif
static void mpls_push(__be32 *mpls, struct pktgen_dev *pkt_dev)
{
unsigned i;
for (i = 0; i < pkt_dev->nr_labels; i++)
*mpls++ = pkt_dev->labels[i] & ~MPLS_STACK_BOTTOM;
mpls--;
*mpls |= MPLS_STACK_BOTTOM;
}
static inline __be16 build_tci(unsigned int id, unsigned int cfi,
unsigned int prio)
{
return htons(id | (cfi << 12) | (prio << 13));
}
static struct sk_buff *fill_packet_ipv4(struct net_device *odev,
struct pktgen_dev *pkt_dev)
{
struct sk_buff *skb = NULL;
__u8 *eth;
struct udphdr *udph;
int datalen, iplen;
struct iphdr *iph;
struct pktgen_hdr *pgh = NULL;
__be16 protocol = htons(ETH_P_IP);
__be32 *mpls;
__be16 *vlan_tci = NULL; /* Encapsulates priority and VLAN ID */
__be16 *vlan_encapsulated_proto = NULL; /* packet type ID field (or len) for VLAN tag */
__be16 *svlan_tci = NULL; /* Encapsulates priority and SVLAN ID */
__be16 *svlan_encapsulated_proto = NULL; /* packet type ID field (or len) for SVLAN tag */
u16 queue_map;
if (pkt_dev->nr_labels)
protocol = htons(ETH_P_MPLS_UC);
if (pkt_dev->vlan_id != 0xffff)
protocol = htons(ETH_P_8021Q);
/* Update any of the values, used when we're incrementing various
* fields.
*/
queue_map = pkt_dev->cur_queue_map;
mod_cur_headers(pkt_dev);
datalen = (odev->hard_header_len + 16) & ~0xf;
if (pkt_dev->flags & F_NODE) {
int node;
if (pkt_dev->node >= 0)
node = pkt_dev->node;
else
node = numa_node_id();
skb = __alloc_skb(NET_SKB_PAD + pkt_dev->cur_pkt_size + 64
+ datalen + pkt_dev->pkt_overhead, GFP_NOWAIT, 0, node);
if (likely(skb)) {
skb_reserve(skb, NET_SKB_PAD);
skb->dev = odev;
}
}
else
skb = __netdev_alloc_skb(odev,
pkt_dev->cur_pkt_size + 64
+ datalen + pkt_dev->pkt_overhead, GFP_NOWAIT);
if (!skb) {
sprintf(pkt_dev->result, "No memory");
return NULL;
}
skb_reserve(skb, datalen);
/* Reserve for ethernet and IP header */
eth = (__u8 *) skb_push(skb, 14);
mpls = (__be32 *)skb_put(skb, pkt_dev->nr_labels*sizeof(__u32));
if (pkt_dev->nr_labels)
mpls_push(mpls, pkt_dev);
if (pkt_dev->vlan_id != 0xffff) {
if (pkt_dev->svlan_id != 0xffff) {
svlan_tci = (__be16 *)skb_put(skb, sizeof(__be16));
*svlan_tci = build_tci(pkt_dev->svlan_id,
pkt_dev->svlan_cfi,
pkt_dev->svlan_p);
svlan_encapsulated_proto = (__be16 *)skb_put(skb, sizeof(__be16));
*svlan_encapsulated_proto = htons(ETH_P_8021Q);
}
vlan_tci = (__be16 *)skb_put(skb, sizeof(__be16));
*vlan_tci = build_tci(pkt_dev->vlan_id,
pkt_dev->vlan_cfi,
pkt_dev->vlan_p);
vlan_encapsulated_proto = (__be16 *)skb_put(skb, sizeof(__be16));
*vlan_encapsulated_proto = htons(ETH_P_IP);
}
skb->network_header = skb->tail;
skb->transport_header = skb->network_header + sizeof(struct iphdr);
skb_put(skb, sizeof(struct iphdr) + sizeof(struct udphdr));
skb_set_queue_mapping(skb, queue_map);
iph = ip_hdr(skb);
udph = udp_hdr(skb);
memcpy(eth, pkt_dev->hh, 12);
*(__be16 *) & eth[12] = protocol;
/* Eth + IPh + UDPh + mpls */
datalen = pkt_dev->cur_pkt_size - 14 - 20 - 8 -
pkt_dev->pkt_overhead;
if (datalen < sizeof(struct pktgen_hdr))
datalen = sizeof(struct pktgen_hdr);
udph->source = htons(pkt_dev->cur_udp_src);
udph->dest = htons(pkt_dev->cur_udp_dst);
udph->len = htons(datalen + 8); /* DATA + udphdr */
udph->check = 0; /* No checksum */
iph->ihl = 5;
iph->version = 4;
iph->ttl = 32;
iph->tos = pkt_dev->tos;
iph->protocol = IPPROTO_UDP; /* UDP */
iph->saddr = pkt_dev->cur_saddr;
iph->daddr = pkt_dev->cur_daddr;
iph->id = htons(pkt_dev->ip_id);
pkt_dev->ip_id++;
iph->frag_off = 0;
iplen = 20 + 8 + datalen;
iph->tot_len = htons(iplen);
iph->check = 0;
iph->check = ip_fast_csum((void *)iph, iph->ihl);
skb->protocol = protocol;
skb->mac_header = (skb->network_header - ETH_HLEN -
pkt_dev->pkt_overhead);
skb->dev = odev;
skb->pkt_type = PACKET_HOST;
if (pkt_dev->nfrags <= 0) {
pgh = (struct pktgen_hdr *)skb_put(skb, datalen);
memset(pgh + 1, 0, datalen - sizeof(struct pktgen_hdr));
} else {
int frags = pkt_dev->nfrags;
int i, len;
pgh = (struct pktgen_hdr *)(((char *)(udph)) + 8);
if (frags > MAX_SKB_FRAGS)
frags = MAX_SKB_FRAGS;
if (datalen > frags * PAGE_SIZE) {
len = datalen - frags * PAGE_SIZE;
memset(skb_put(skb, len), 0, len);
datalen = frags * PAGE_SIZE;
}
i = 0;
while (datalen > 0) {
struct page *page = alloc_pages(GFP_KERNEL | __GFP_ZERO, 0);
skb_shinfo(skb)->frags[i].page = page;
skb_shinfo(skb)->frags[i].page_offset = 0;
skb_shinfo(skb)->frags[i].size =
(datalen < PAGE_SIZE ? datalen : PAGE_SIZE);
datalen -= skb_shinfo(skb)->frags[i].size;
skb->len += skb_shinfo(skb)->frags[i].size;
skb->data_len += skb_shinfo(skb)->frags[i].size;
i++;
skb_shinfo(skb)->nr_frags = i;
}
while (i < frags) {
int rem;
if (i == 0)
break;
rem = skb_shinfo(skb)->frags[i - 1].size / 2;
if (rem == 0)
break;
skb_shinfo(skb)->frags[i - 1].size -= rem;
skb_shinfo(skb)->frags[i] =
skb_shinfo(skb)->frags[i - 1];
get_page(skb_shinfo(skb)->frags[i].page);
skb_shinfo(skb)->frags[i].page =
skb_shinfo(skb)->frags[i - 1].page;
skb_shinfo(skb)->frags[i].page_offset +=
skb_shinfo(skb)->frags[i - 1].size;
skb_shinfo(skb)->frags[i].size = rem;
i++;
skb_shinfo(skb)->nr_frags = i;
}
}
/* Stamp the time, and sequence number,
* convert them to network byte order
*/
if (pgh) {
struct timeval timestamp;
pgh->pgh_magic = htonl(PKTGEN_MAGIC);
pgh->seq_num = htonl(pkt_dev->seq_num);
do_gettimeofday(×tamp);
pgh->tv_sec = htonl(timestamp.tv_sec);
pgh->tv_usec = htonl(timestamp.tv_usec);
}
#ifdef CONFIG_XFRM
if (!process_ipsec(pkt_dev, skb, protocol))
return NULL;
#endif
return skb;
}
/*
* scan_ip6, fmt_ip taken from dietlibc-0.21
* Author Felix von Leitner <felix-dietlibc@fefe.de>
*
* Slightly modified for kernel.
* Should be candidate for net/ipv4/utils.c
* --ro
*/
static unsigned int scan_ip6(const char *s, char ip[16])
{
unsigned int i;
unsigned int len = 0;
unsigned long u;
char suffix[16];
unsigned int prefixlen = 0;
unsigned int suffixlen = 0;
__be32 tmp;
char *pos;
for (i = 0; i < 16; i++)
ip[i] = 0;
for (;;) {
if (*s == ':') {
len++;
if (s[1] == ':') { /* Found "::", skip to part 2 */
s += 2;
len++;
break;
}
s++;
}
u = simple_strtoul(s, &pos, 16);
i = pos - s;
if (!i)
return 0;
if (prefixlen == 12 && s[i] == '.') {
/* the last 4 bytes may be written as IPv4 address */
tmp = in_aton(s);
memcpy((struct in_addr *)(ip + 12), &tmp, sizeof(tmp));
return i + len;
}
ip[prefixlen++] = (u >> 8);
ip[prefixlen++] = (u & 255);
s += i;
len += i;
if (prefixlen == 16)
return len;
}
/* part 2, after "::" */
for (;;) {
if (*s == ':') {
if (suffixlen == 0)
break;
s++;
len++;
} else if (suffixlen != 0)
break;
u = simple_strtol(s, &pos, 16);
i = pos - s;
if (!i) {
if (*s)
len--;
break;
}
if (suffixlen + prefixlen <= 12 && s[i] == '.') {
tmp = in_aton(s);
memcpy((struct in_addr *)(suffix + suffixlen), &tmp,
sizeof(tmp));
suffixlen += 4;
len += strlen(s);
break;
}
suffix[suffixlen++] = (u >> 8);
suffix[suffixlen++] = (u & 255);
s += i;
len += i;
if (prefixlen + suffixlen == 16)
break;
}
for (i = 0; i < suffixlen; i++)
ip[16 - suffixlen + i] = suffix[i];
return len;
}
static char tohex(char hexdigit)
{
return hexdigit > 9 ? hexdigit + 'a' - 10 : hexdigit + '0';
}
static int fmt_xlong(char *s, unsigned int i)
{
char *bak = s;
*s = tohex((i >> 12) & 0xf);
if (s != bak || *s != '0')
++s;
*s = tohex((i >> 8) & 0xf);
if (s != bak || *s != '0')
++s;
*s = tohex((i >> 4) & 0xf);
if (s != bak || *s != '0')
++s;
*s = tohex(i & 0xf);
return s - bak + 1;
}
static unsigned int fmt_ip6(char *s, const char ip[16])
{
unsigned int len;
unsigned int i;
unsigned int temp;
unsigned int compressing;
int j;
len = 0;
compressing = 0;
for (j = 0; j < 16; j += 2) {
#ifdef V4MAPPEDPREFIX
if (j == 12 && !memcmp(ip, V4mappedprefix, 12)) {
inet_ntoa_r(*(struct in_addr *)(ip + 12), s);
temp = strlen(s);
return len + temp;
}
#endif
temp = ((unsigned long)(unsigned char)ip[j] << 8) +
(unsigned long)(unsigned char)ip[j + 1];
if (temp == 0) {
if (!compressing) {
compressing = 1;
if (j == 0) {
*s++ = ':';
++len;
}
}
} else {
if (compressing) {
compressing = 0;
*s++ = ':';
++len;
}
i = fmt_xlong(s, temp);
len += i;
s += i;
if (j < 14) {
*s++ = ':';
++len;
}
}
}
if (compressing) {
*s++ = ':';
++len;
}
*s = 0;
return len;
}
static struct sk_buff *fill_packet_ipv6(struct net_device *odev,
struct pktgen_dev *pkt_dev)
{
struct sk_buff *skb = NULL;
__u8 *eth;
struct udphdr *udph;
int datalen;
struct ipv6hdr *iph;
struct pktgen_hdr *pgh = NULL;
__be16 protocol = htons(ETH_P_IPV6);
__be32 *mpls;
__be16 *vlan_tci = NULL; /* Encapsulates priority and VLAN ID */
__be16 *vlan_encapsulated_proto = NULL; /* packet type ID field (or len) for VLAN tag */
__be16 *svlan_tci = NULL; /* Encapsulates priority and SVLAN ID */
__be16 *svlan_encapsulated_proto = NULL; /* packet type ID field (or len) for SVLAN tag */
u16 queue_map;
if (pkt_dev->nr_labels)
protocol = htons(ETH_P_MPLS_UC);
if (pkt_dev->vlan_id != 0xffff)
protocol = htons(ETH_P_8021Q);
/* Update any of the values, used when we're incrementing various
* fields.
*/
queue_map = pkt_dev->cur_queue_map;
mod_cur_headers(pkt_dev);
skb = __netdev_alloc_skb(odev,
pkt_dev->cur_pkt_size + 64
+ 16 + pkt_dev->pkt_overhead, GFP_NOWAIT);
if (!skb) {
sprintf(pkt_dev->result, "No memory");
return NULL;
}
skb_reserve(skb, 16);
/* Reserve for ethernet and IP header */
eth = (__u8 *) skb_push(skb, 14);
mpls = (__be32 *)skb_put(skb, pkt_dev->nr_labels*sizeof(__u32));
if (pkt_dev->nr_labels)
mpls_push(mpls, pkt_dev);
if (pkt_dev->vlan_id != 0xffff) {
if (pkt_dev->svlan_id != 0xffff) {
svlan_tci = (__be16 *)skb_put(skb, sizeof(__be16));
*svlan_tci = build_tci(pkt_dev->svlan_id,
pkt_dev->svlan_cfi,
pkt_dev->svlan_p);
svlan_encapsulated_proto = (__be16 *)skb_put(skb, sizeof(__be16));
*svlan_encapsulated_proto = htons(ETH_P_8021Q);
}
vlan_tci = (__be16 *)skb_put(skb, sizeof(__be16));
*vlan_tci = build_tci(pkt_dev->vlan_id,
pkt_dev->vlan_cfi,
pkt_dev->vlan_p);
vlan_encapsulated_proto = (__be16 *)skb_put(skb, sizeof(__be16));
*vlan_encapsulated_proto = htons(ETH_P_IPV6);
}
skb->network_header = skb->tail;
skb->transport_header = skb->network_header + sizeof(struct ipv6hdr);
skb_put(skb, sizeof(struct ipv6hdr) + sizeof(struct udphdr));
skb_set_queue_mapping(skb, queue_map);
iph = ipv6_hdr(skb);
udph = udp_hdr(skb);
memcpy(eth, pkt_dev->hh, 12);
*(__be16 *) ð[12] = protocol;
/* Eth + IPh + UDPh + mpls */
datalen = pkt_dev->cur_pkt_size - 14 -
sizeof(struct ipv6hdr) - sizeof(struct udphdr) -
pkt_dev->pkt_overhead;
if (datalen < sizeof(struct pktgen_hdr)) {
datalen = sizeof(struct pktgen_hdr);
if (net_ratelimit())
printk(KERN_INFO "pktgen: increased datalen to %d\n",
datalen);
}
udph->source = htons(pkt_dev->cur_udp_src);
udph->dest = htons(pkt_dev->cur_udp_dst);
udph->len = htons(datalen + sizeof(struct udphdr));
udph->check = 0; /* No checksum */
*(__be32 *) iph = htonl(0x60000000); /* Version + flow */
if (pkt_dev->traffic_class) {
/* Version + traffic class + flow (0) */
*(__be32 *)iph |= htonl(0x60000000 | (pkt_dev->traffic_class << 20));
}
iph->hop_limit = 32;
iph->payload_len = htons(sizeof(struct udphdr) + datalen);
iph->nexthdr = IPPROTO_UDP;
ipv6_addr_copy(&iph->daddr, &pkt_dev->cur_in6_daddr);
ipv6_addr_copy(&iph->saddr, &pkt_dev->cur_in6_saddr);
skb->mac_header = (skb->network_header - ETH_HLEN -
pkt_dev->pkt_overhead);
skb->protocol = protocol;
skb->dev = odev;
skb->pkt_type = PACKET_HOST;
if (pkt_dev->nfrags <= 0)
pgh = (struct pktgen_hdr *)skb_put(skb, datalen);
else {
int frags = pkt_dev->nfrags;
int i;
pgh = (struct pktgen_hdr *)(((char *)(udph)) + 8);
if (frags > MAX_SKB_FRAGS)
frags = MAX_SKB_FRAGS;
if (datalen > frags * PAGE_SIZE) {
skb_put(skb, datalen - frags * PAGE_SIZE);
datalen = frags * PAGE_SIZE;
}
i = 0;
while (datalen > 0) {
struct page *page = alloc_pages(GFP_KERNEL, 0);
skb_shinfo(skb)->frags[i].page = page;
skb_shinfo(skb)->frags[i].page_offset = 0;
skb_shinfo(skb)->frags[i].size =
(datalen < PAGE_SIZE ? datalen : PAGE_SIZE);
datalen -= skb_shinfo(skb)->frags[i].size;
skb->len += skb_shinfo(skb)->frags[i].size;
skb->data_len += skb_shinfo(skb)->frags[i].size;
i++;
skb_shinfo(skb)->nr_frags = i;
}
while (i < frags) {
int rem;
if (i == 0)
break;
rem = skb_shinfo(skb)->frags[i - 1].size / 2;
if (rem == 0)
break;
skb_shinfo(skb)->frags[i - 1].size -= rem;
skb_shinfo(skb)->frags[i] =
skb_shinfo(skb)->frags[i - 1];
get_page(skb_shinfo(skb)->frags[i].page);
skb_shinfo(skb)->frags[i].page =
skb_shinfo(skb)->frags[i - 1].page;
skb_shinfo(skb)->frags[i].page_offset +=
skb_shinfo(skb)->frags[i - 1].size;
skb_shinfo(skb)->frags[i].size = rem;
i++;
skb_shinfo(skb)->nr_frags = i;
}
}
/* Stamp the time, and sequence number,
* convert them to network byte order
* should we update cloned packets too ?
*/
if (pgh) {
struct timeval timestamp;
pgh->pgh_magic = htonl(PKTGEN_MAGIC);
pgh->seq_num = htonl(pkt_dev->seq_num);
do_gettimeofday(×tamp);
pgh->tv_sec = htonl(timestamp.tv_sec);
pgh->tv_usec = htonl(timestamp.tv_usec);
}
/* pkt_dev->seq_num++; FF: you really mean this? */
return skb;
}
static struct sk_buff *fill_packet(struct net_device *odev,
struct pktgen_dev *pkt_dev)
{
if (pkt_dev->flags & F_IPV6)
return fill_packet_ipv6(odev, pkt_dev);
else
return fill_packet_ipv4(odev, pkt_dev);
}
static void pktgen_clear_counters(struct pktgen_dev *pkt_dev)
{
pkt_dev->seq_num = 1;
pkt_dev->idle_acc = 0;
pkt_dev->sofar = 0;
pkt_dev->tx_bytes = 0;
pkt_dev->errors = 0;
}
/* Set up structure for sending pkts, clear counters */
static void pktgen_run(struct pktgen_thread *t)
{
struct pktgen_dev *pkt_dev;
int started = 0;
pr_debug("pktgen: entering pktgen_run. %p\n", t);
if_lock(t);
list_for_each_entry(pkt_dev, &t->if_list, list) {
/*
* setup odev and create initial packet.
*/
pktgen_setup_inject(pkt_dev);
if (pkt_dev->odev) {
pktgen_clear_counters(pkt_dev);
pkt_dev->running = 1; /* Cranke yeself! */
pkt_dev->skb = NULL;
pkt_dev->started_at =
pkt_dev->next_tx = ktime_now();
set_pkt_overhead(pkt_dev);
strcpy(pkt_dev->result, "Starting");
started++;
} else
strcpy(pkt_dev->result, "Error starting");
}
if_unlock(t);
if (started)
t->control &= ~(T_STOP);
}
static void pktgen_stop_all_threads_ifs(void)
{
struct pktgen_thread *t;
pr_debug("pktgen: entering pktgen_stop_all_threads_ifs.\n");
mutex_lock(&pktgen_thread_lock);
list_for_each_entry(t, &pktgen_threads, th_list)
t->control |= T_STOP;
mutex_unlock(&pktgen_thread_lock);
}
static int thread_is_running(const struct pktgen_thread *t)
{
const struct pktgen_dev *pkt_dev;
list_for_each_entry(pkt_dev, &t->if_list, list)
if (pkt_dev->running)
return 1;
return 0;
}
static int pktgen_wait_thread_run(struct pktgen_thread *t)
{
if_lock(t);
while (thread_is_running(t)) {
if_unlock(t);
msleep_interruptible(100);
if (signal_pending(current))
goto signal;
if_lock(t);
}
if_unlock(t);
return 1;
signal:
return 0;
}
static int pktgen_wait_all_threads_run(void)
{
struct pktgen_thread *t;
int sig = 1;
mutex_lock(&pktgen_thread_lock);
list_for_each_entry(t, &pktgen_threads, th_list) {
sig = pktgen_wait_thread_run(t);
if (sig == 0)
break;
}
if (sig == 0)
list_for_each_entry(t, &pktgen_threads, th_list)
t->control |= (T_STOP);
mutex_unlock(&pktgen_thread_lock);
return sig;
}
static void pktgen_run_all_threads(void)
{
struct pktgen_thread *t;
pr_debug("pktgen: entering pktgen_run_all_threads.\n");
mutex_lock(&pktgen_thread_lock);
list_for_each_entry(t, &pktgen_threads, th_list)
t->control |= (T_RUN);
mutex_unlock(&pktgen_thread_lock);
/* Propagate thread->control */
schedule_timeout_interruptible(msecs_to_jiffies(125));
pktgen_wait_all_threads_run();
}
static void pktgen_reset_all_threads(void)
{
struct pktgen_thread *t;
pr_debug("pktgen: entering pktgen_reset_all_threads.\n");
mutex_lock(&pktgen_thread_lock);
list_for_each_entry(t, &pktgen_threads, th_list)
t->control |= (T_REMDEVALL);
mutex_unlock(&pktgen_thread_lock);
/* Propagate thread->control */
schedule_timeout_interruptible(msecs_to_jiffies(125));
pktgen_wait_all_threads_run();
}
static void show_results(struct pktgen_dev *pkt_dev, int nr_frags)
{
__u64 bps, mbps, pps;
char *p = pkt_dev->result;
ktime_t elapsed = ktime_sub(pkt_dev->stopped_at,
pkt_dev->started_at);
ktime_t idle = ns_to_ktime(pkt_dev->idle_acc);
p += sprintf(p, "OK: %llu(c%llu+d%llu) nsec, %llu (%dbyte,%dfrags)\n",
(unsigned long long)ktime_to_us(elapsed),
(unsigned long long)ktime_to_us(ktime_sub(elapsed, idle)),
(unsigned long long)ktime_to_us(idle),
(unsigned long long)pkt_dev->sofar,
pkt_dev->cur_pkt_size, nr_frags);
pps = div64_u64(pkt_dev->sofar * NSEC_PER_SEC,
ktime_to_ns(elapsed));
bps = pps * 8 * pkt_dev->cur_pkt_size;
mbps = bps;
do_div(mbps, 1000000);
p += sprintf(p, " %llupps %lluMb/sec (%llubps) errors: %llu",
(unsigned long long)pps,
(unsigned long long)mbps,
(unsigned long long)bps,
(unsigned long long)pkt_dev->errors);
}
/* Set stopped-at timer, remove from running list, do counters & statistics */
static int pktgen_stop_device(struct pktgen_dev *pkt_dev)
{
int nr_frags = pkt_dev->skb ? skb_shinfo(pkt_dev->skb)->nr_frags : -1;
if (!pkt_dev->running) {
printk(KERN_WARNING "pktgen: interface: %s is already "
"stopped\n", pkt_dev->odevname);
return -EINVAL;
}
kfree_skb(pkt_dev->skb);
pkt_dev->skb = NULL;
pkt_dev->stopped_at = ktime_now();
pkt_dev->running = 0;
show_results(pkt_dev, nr_frags);
return 0;
}
static struct pktgen_dev *next_to_run(struct pktgen_thread *t)
{
struct pktgen_dev *pkt_dev, *best = NULL;
if_lock(t);
list_for_each_entry(pkt_dev, &t->if_list, list) {
if (!pkt_dev->running)
continue;
if (best == NULL)
best = pkt_dev;
else if (ktime_lt(pkt_dev->next_tx, best->next_tx))
best = pkt_dev;
}
if_unlock(t);
return best;
}
static void pktgen_stop(struct pktgen_thread *t)
{
struct pktgen_dev *pkt_dev;
pr_debug("pktgen: entering pktgen_stop\n");
if_lock(t);
list_for_each_entry(pkt_dev, &t->if_list, list) {
pktgen_stop_device(pkt_dev);
}
if_unlock(t);
}
/*
* one of our devices needs to be removed - find it
* and remove it
*/
static void pktgen_rem_one_if(struct pktgen_thread *t)
{
struct list_head *q, *n;
struct pktgen_dev *cur;
pr_debug("pktgen: entering pktgen_rem_one_if\n");
if_lock(t);
list_for_each_safe(q, n, &t->if_list) {
cur = list_entry(q, struct pktgen_dev, list);
if (!cur->removal_mark)
continue;
kfree_skb(cur->skb);
cur->skb = NULL;
pktgen_remove_device(t, cur);
break;
}
if_unlock(t);
}
static void pktgen_rem_all_ifs(struct pktgen_thread *t)
{
struct list_head *q, *n;
struct pktgen_dev *cur;
/* Remove all devices, free mem */
pr_debug("pktgen: entering pktgen_rem_all_ifs\n");
if_lock(t);
list_for_each_safe(q, n, &t->if_list) {
cur = list_entry(q, struct pktgen_dev, list);
kfree_skb(cur->skb);
cur->skb = NULL;
pktgen_remove_device(t, cur);
}
if_unlock(t);
}
static void pktgen_rem_thread(struct pktgen_thread *t)
{
/* Remove from the thread list */
remove_proc_entry(t->tsk->comm, pg_proc_dir);
mutex_lock(&pktgen_thread_lock);
list_del(&t->th_list);
mutex_unlock(&pktgen_thread_lock);
}
static void pktgen_resched(struct pktgen_dev *pkt_dev)
{
ktime_t idle_start = ktime_now();
schedule();
pkt_dev->idle_acc += ktime_to_ns(ktime_sub(ktime_now(), idle_start));
}
static void pktgen_wait_for_skb(struct pktgen_dev *pkt_dev)
{
ktime_t idle_start = ktime_now();
while (atomic_read(&(pkt_dev->skb->users)) != 1) {
if (signal_pending(current))
break;
if (need_resched())
pktgen_resched(pkt_dev);
else
cpu_relax();
}
pkt_dev->idle_acc += ktime_to_ns(ktime_sub(ktime_now(), idle_start));
}
static void pktgen_xmit(struct pktgen_dev *pkt_dev)
{
struct net_device *odev = pkt_dev->odev;
netdev_tx_t (*xmit)(struct sk_buff *, struct net_device *)
= odev->netdev_ops->ndo_start_xmit;
struct netdev_queue *txq;
u16 queue_map;
int ret;
/* If device is offline, then don't send */
if (unlikely(!netif_running(odev) || !netif_carrier_ok(odev))) {
pktgen_stop_device(pkt_dev);
return;
}
/* This is max DELAY, this has special meaning of
* "never transmit"
*/
if (unlikely(pkt_dev->delay == ULLONG_MAX)) {
pkt_dev->next_tx = ktime_add_ns(ktime_now(), ULONG_MAX);
return;
}
/* If no skb or clone count exhausted then get new one */
if (!pkt_dev->skb || (pkt_dev->last_ok &&
++pkt_dev->clone_count >= pkt_dev->clone_skb)) {
/* build a new pkt */
kfree_skb(pkt_dev->skb);
pkt_dev->skb = fill_packet(odev, pkt_dev);
if (pkt_dev->skb == NULL) {
printk(KERN_ERR "pktgen: ERROR: couldn't "
"allocate skb in fill_packet.\n");
schedule();
pkt_dev->clone_count--; /* back out increment, OOM */
return;
}
pkt_dev->last_pkt_size = pkt_dev->skb->len;
pkt_dev->allocated_skbs++;
pkt_dev->clone_count = 0; /* reset counter */
}
if (pkt_dev->delay && pkt_dev->last_ok)
spin(pkt_dev, pkt_dev->next_tx);
queue_map = skb_get_queue_mapping(pkt_dev->skb);
txq = netdev_get_tx_queue(odev, queue_map);
__netif_tx_lock_bh(txq);
if (unlikely(netif_tx_queue_stopped(txq) || netif_tx_queue_frozen(txq))) {
ret = NETDEV_TX_BUSY;
pkt_dev->last_ok = 0;
goto unlock;
}
atomic_inc(&(pkt_dev->skb->users));
ret = (*xmit)(pkt_dev->skb, odev);
switch (ret) {
case NETDEV_TX_OK:
txq_trans_update(txq);
pkt_dev->last_ok = 1;
pkt_dev->sofar++;
pkt_dev->seq_num++;
pkt_dev->tx_bytes += pkt_dev->last_pkt_size;
break;
case NET_XMIT_DROP:
case NET_XMIT_CN:
case NET_XMIT_POLICED:
/* skb has been consumed */
pkt_dev->errors++;
break;
default: /* Drivers are not supposed to return other values! */
if (net_ratelimit())
pr_info("pktgen: %s xmit error: %d\n",
pkt_dev->odevname, ret);
pkt_dev->errors++;
/* fallthru */
case NETDEV_TX_LOCKED:
case NETDEV_TX_BUSY:
/* Retry it next time */
atomic_dec(&(pkt_dev->skb->users));
pkt_dev->last_ok = 0;
}
unlock:
__netif_tx_unlock_bh(txq);
/* If pkt_dev->count is zero, then run forever */
if ((pkt_dev->count != 0) && (pkt_dev->sofar >= pkt_dev->count)) {
pktgen_wait_for_skb(pkt_dev);
/* Done with this */
pktgen_stop_device(pkt_dev);
}
}
/*
* Main loop of the thread goes here
*/
static int pktgen_thread_worker(void *arg)
{
DEFINE_WAIT(wait);
struct pktgen_thread *t = arg;
struct pktgen_dev *pkt_dev = NULL;
int cpu = t->cpu;
BUG_ON(smp_processor_id() != cpu);
init_waitqueue_head(&t->queue);
complete(&t->start_done);
pr_debug("pktgen: starting pktgen/%d: pid=%d\n",
cpu, task_pid_nr(current));
set_current_state(TASK_INTERRUPTIBLE);
set_freezable();
while (!kthread_should_stop()) {
pkt_dev = next_to_run(t);
if (unlikely(!pkt_dev && t->control == 0)) {
wait_event_interruptible_timeout(t->queue,
t->control != 0,
HZ/10);
try_to_freeze();
continue;
}
__set_current_state(TASK_RUNNING);
if (likely(pkt_dev)) {
pktgen_xmit(pkt_dev);
if (need_resched())
pktgen_resched(pkt_dev);
else
cpu_relax();
}
if (t->control & T_STOP) {
pktgen_stop(t);
t->control &= ~(T_STOP);
}
if (t->control & T_RUN) {
pktgen_run(t);
t->control &= ~(T_RUN);
}
if (t->control & T_REMDEVALL) {
pktgen_rem_all_ifs(t);
t->control &= ~(T_REMDEVALL);
}
if (t->control & T_REMDEV) {
pktgen_rem_one_if(t);
t->control &= ~(T_REMDEV);
}
try_to_freeze();
set_current_state(TASK_INTERRUPTIBLE);
}
pr_debug("pktgen: %s stopping all device\n", t->tsk->comm);
pktgen_stop(t);
pr_debug("pktgen: %s removing all device\n", t->tsk->comm);
pktgen_rem_all_ifs(t);
pr_debug("pktgen: %s removing thread.\n", t->tsk->comm);
pktgen_rem_thread(t);
return 0;
}
static struct pktgen_dev *pktgen_find_dev(struct pktgen_thread *t,
const char *ifname, bool exact)
{
struct pktgen_dev *p, *pkt_dev = NULL;
size_t len = strlen(ifname);
if_lock(t);
list_for_each_entry(p, &t->if_list, list)
if (strncmp(p->odevname, ifname, len) == 0) {
if (p->odevname[len]) {
if (exact || p->odevname[len] != '@')
continue;
}
pkt_dev = p;
break;
}
if_unlock(t);
pr_debug("pktgen: find_dev(%s) returning %p\n", ifname, pkt_dev);
return pkt_dev;
}
/*
* Adds a dev at front of if_list.
*/
static int add_dev_to_thread(struct pktgen_thread *t,
struct pktgen_dev *pkt_dev)
{
int rv = 0;
if_lock(t);
if (pkt_dev->pg_thread) {
printk(KERN_ERR "pktgen: ERROR: already assigned "
"to a thread.\n");
rv = -EBUSY;
goto out;
}
list_add(&pkt_dev->list, &t->if_list);
pkt_dev->pg_thread = t;
pkt_dev->running = 0;
out:
if_unlock(t);
return rv;
}
/* Called under thread lock */
static int pktgen_add_device(struct pktgen_thread *t, const char *ifname)
{
struct pktgen_dev *pkt_dev;
int err;
int node = cpu_to_node(t->cpu);
/* We don't allow a device to be on several threads */
pkt_dev = __pktgen_NN_threads(ifname, FIND);
if (pkt_dev) {
printk(KERN_ERR "pktgen: ERROR: interface already used.\n");
return -EBUSY;
}
pkt_dev = kzalloc_node(sizeof(struct pktgen_dev), GFP_KERNEL, node);
if (!pkt_dev)
return -ENOMEM;
strcpy(pkt_dev->odevname, ifname);
pkt_dev->flows = vmalloc_node(MAX_CFLOWS * sizeof(struct flow_state),
node);
if (pkt_dev->flows == NULL) {
kfree(pkt_dev);
return -ENOMEM;
}
memset(pkt_dev->flows, 0, MAX_CFLOWS * sizeof(struct flow_state));
pkt_dev->removal_mark = 0;
pkt_dev->min_pkt_size = ETH_ZLEN;
pkt_dev->max_pkt_size = ETH_ZLEN;
pkt_dev->nfrags = 0;
pkt_dev->clone_skb = pg_clone_skb_d;
pkt_dev->delay = pg_delay_d;
pkt_dev->count = pg_count_d;
pkt_dev->sofar = 0;
pkt_dev->udp_src_min = 9; /* sink port */
pkt_dev->udp_src_max = 9;
pkt_dev->udp_dst_min = 9;
pkt_dev->udp_dst_max = 9;
pkt_dev->vlan_p = 0;
pkt_dev->vlan_cfi = 0;
pkt_dev->vlan_id = 0xffff;
pkt_dev->svlan_p = 0;
pkt_dev->svlan_cfi = 0;
pkt_dev->svlan_id = 0xffff;
pkt_dev->node = -1;
err = pktgen_setup_dev(pkt_dev, ifname);
if (err)
goto out1;
pkt_dev->entry = proc_create_data(ifname, 0600, pg_proc_dir,
&pktgen_if_fops, pkt_dev);
if (!pkt_dev->entry) {
printk(KERN_ERR "pktgen: cannot create %s/%s procfs entry.\n",
PG_PROC_DIR, ifname);
err = -EINVAL;
goto out2;
}
#ifdef CONFIG_XFRM
pkt_dev->ipsmode = XFRM_MODE_TRANSPORT;
pkt_dev->ipsproto = IPPROTO_ESP;
#endif
return add_dev_to_thread(t, pkt_dev);
out2:
dev_put(pkt_dev->odev);
out1:
#ifdef CONFIG_XFRM
free_SAs(pkt_dev);
#endif
vfree(pkt_dev->flows);
kfree(pkt_dev);
return err;
}
static int __init pktgen_create_thread(int cpu)
{
struct pktgen_thread *t;
struct proc_dir_entry *pe;
struct task_struct *p;
t = kzalloc_node(sizeof(struct pktgen_thread), GFP_KERNEL,
cpu_to_node(cpu));
if (!t) {
printk(KERN_ERR "pktgen: ERROR: out of memory, can't "
"create new thread.\n");
return -ENOMEM;
}
spin_lock_init(&t->if_lock);
t->cpu = cpu;
INIT_LIST_HEAD(&t->if_list);
list_add_tail(&t->th_list, &pktgen_threads);
init_completion(&t->start_done);
p = kthread_create(pktgen_thread_worker, t, "kpktgend_%d", cpu);
if (IS_ERR(p)) {
printk(KERN_ERR "pktgen: kernel_thread() failed "
"for cpu %d\n", t->cpu);
list_del(&t->th_list);
kfree(t);
return PTR_ERR(p);
}
kthread_bind(p, cpu);
t->tsk = p;
pe = proc_create_data(t->tsk->comm, 0600, pg_proc_dir,
&pktgen_thread_fops, t);
if (!pe) {
printk(KERN_ERR "pktgen: cannot create %s/%s procfs entry.\n",
PG_PROC_DIR, t->tsk->comm);
kthread_stop(p);
list_del(&t->th_list);
kfree(t);
return -EINVAL;
}
wake_up_process(p);
wait_for_completion(&t->start_done);
return 0;
}
/*
* Removes a device from the thread if_list.
*/
static void _rem_dev_from_if_list(struct pktgen_thread *t,
struct pktgen_dev *pkt_dev)
{
struct list_head *q, *n;
struct pktgen_dev *p;
list_for_each_safe(q, n, &t->if_list) {
p = list_entry(q, struct pktgen_dev, list);
if (p == pkt_dev)
list_del(&p->list);
}
}
static int pktgen_remove_device(struct pktgen_thread *t,
struct pktgen_dev *pkt_dev)
{
pr_debug("pktgen: remove_device pkt_dev=%p\n", pkt_dev);
if (pkt_dev->running) {
printk(KERN_WARNING "pktgen: WARNING: trying to remove a "
"running interface, stopping it now.\n");
pktgen_stop_device(pkt_dev);
}
/* Dis-associate from the interface */
if (pkt_dev->odev) {
dev_put(pkt_dev->odev);
pkt_dev->odev = NULL;
}
/* And update the thread if_list */
_rem_dev_from_if_list(t, pkt_dev);
if (pkt_dev->entry)
remove_proc_entry(pkt_dev->entry->name, pg_proc_dir);
#ifdef CONFIG_XFRM
free_SAs(pkt_dev);
#endif
vfree(pkt_dev->flows);
kfree(pkt_dev);
return 0;
}
static int __init pg_init(void)
{
int cpu;
struct proc_dir_entry *pe;
printk(KERN_INFO "%s", version);
pg_proc_dir = proc_mkdir(PG_PROC_DIR, init_net.proc_net);
if (!pg_proc_dir)
return -ENODEV;
pe = proc_create(PGCTRL, 0600, pg_proc_dir, &pktgen_fops);
if (pe == NULL) {
printk(KERN_ERR "pktgen: ERROR: cannot create %s "
"procfs entry.\n", PGCTRL);
proc_net_remove(&init_net, PG_PROC_DIR);
return -EINVAL;
}
/* Register us to receive netdevice events */
register_netdevice_notifier(&pktgen_notifier_block);
for_each_online_cpu(cpu) {
int err;
err = pktgen_create_thread(cpu);
if (err)
printk(KERN_WARNING "pktgen: WARNING: Cannot create "
"thread for cpu %d (%d)\n", cpu, err);
}
if (list_empty(&pktgen_threads)) {
printk(KERN_ERR "pktgen: ERROR: Initialization failed for "
"all threads\n");
unregister_netdevice_notifier(&pktgen_notifier_block);
remove_proc_entry(PGCTRL, pg_proc_dir);
proc_net_remove(&init_net, PG_PROC_DIR);
return -ENODEV;
}
return 0;
}
static void __exit pg_cleanup(void)
{
struct pktgen_thread *t;
struct list_head *q, *n;
wait_queue_head_t queue;
init_waitqueue_head(&queue);
/* Stop all interfaces & threads */
list_for_each_safe(q, n, &pktgen_threads) {
t = list_entry(q, struct pktgen_thread, th_list);
kthread_stop(t->tsk);
kfree(t);
}
/* Un-register us from receiving netdevice events */
unregister_netdevice_notifier(&pktgen_notifier_block);
/* Clean up proc file system */
remove_proc_entry(PGCTRL, pg_proc_dir);
proc_net_remove(&init_net, PG_PROC_DIR);
}
module_init(pg_init);
module_exit(pg_cleanup);
MODULE_AUTHOR("Robert Olsson <robert.olsson@its.uu.se>");
MODULE_DESCRIPTION("Packet Generator tool");
MODULE_LICENSE("GPL");
MODULE_VERSION(VERSION);
module_param(pg_count_d, int, 0);
MODULE_PARM_DESC(pg_count_d, "Default number of packets to inject");
module_param(pg_delay_d, int, 0);
MODULE_PARM_DESC(pg_delay_d, "Default delay between packets (nanoseconds)");
module_param(pg_clone_skb_d, int, 0);
MODULE_PARM_DESC(pg_clone_skb_d, "Default number of copies of the same packet");
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Enable debugging of pktgen module");
| gpl-2.0 |
sakindia123/kernel_3.4_samsung_exynos4 | drivers/staging/speakup/kobjects.c | 4329 | 24517 | /*
* Speakup kobject implementation
*
* Copyright (C) 2009 William Hubbs
*
* This code is based on kobject-example.c, which came with linux 2.6.x.
*
* Copyright (C) 2004-2007 Greg Kroah-Hartman <greg@kroah.com>
* Copyright (C) 2007 Novell Inc.
*
* Released under the GPL version 2 only.
*
*/
#include <linux/slab.h> /* For kmalloc. */
#include <linux/kernel.h>
#include <linux/kobject.h>
#include <linux/string.h>
#include <linux/sysfs.h>
#include <linux/ctype.h>
#include "speakup.h"
#include "spk_priv.h"
/*
* This is called when a user reads the characters or chartab sys file.
*/
static ssize_t chars_chartab_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
int i;
int len = 0;
char *cp;
char *buf_pointer = buf;
size_t bufsize = PAGE_SIZE;
unsigned long flags;
spk_lock(flags);
*buf_pointer = '\0';
for (i = 0; i < 256; i++) {
if (bufsize <= 1)
break;
if (strcmp("characters", attr->attr.name) == 0) {
len = scnprintf(buf_pointer, bufsize, "%d\t%s\n",
i, characters[i]);
} else { /* show chartab entry */
if (IS_TYPE(i, B_CTL))
cp = "B_CTL";
else if (IS_TYPE(i, WDLM))
cp = "WDLM";
else if (IS_TYPE(i, A_PUNC))
cp = "A_PUNC";
else if (IS_TYPE(i, PUNC))
cp = "PUNC";
else if (IS_TYPE(i, NUM))
cp = "NUM";
else if (IS_TYPE(i, A_CAP))
cp = "A_CAP";
else if (IS_TYPE(i, ALPHA))
cp = "ALPHA";
else if (IS_TYPE(i, B_CAPSYM))
cp = "B_CAPSYM";
else if (IS_TYPE(i, B_SYM))
cp = "B_SYM";
else
cp = "0";
len =
scnprintf(buf_pointer, bufsize, "%d\t%s\n", i, cp);
}
bufsize -= len;
buf_pointer += len;
}
spk_unlock(flags);
return buf_pointer - buf;
}
/*
* Print informational messages or warnings after updating
* character descriptions or chartab entries.
*/
static void report_char_chartab_status(int reset, int received, int used,
int rejected, int do_characters)
{
char *object_type[] = {
"character class entries",
"character descriptions",
};
int len;
char buf[80];
if (reset) {
pr_info("%s reset to defaults\n", object_type[do_characters]);
} else if (received) {
len = snprintf(buf, sizeof(buf),
" updated %d of %d %s\n",
used, received, object_type[do_characters]);
if (rejected)
snprintf(buf + (len - 1), sizeof(buf) - (len - 1),
" with %d reject%s\n",
rejected, rejected > 1 ? "s" : "");
printk(buf);
}
}
/*
* This is called when a user changes the characters or chartab parameters.
*/
static ssize_t chars_chartab_store(struct kobject *kobj,
struct kobj_attribute *attr, const char *buf, size_t count)
{
char *cp = (char *) buf;
char *end = cp + count; /* the null at the end of the buffer */
char *linefeed = NULL;
char keyword[MAX_DESC_LEN + 1];
char *outptr = NULL; /* Will hold keyword or desc. */
char *temp = NULL;
char *desc = NULL;
ssize_t retval = count;
unsigned long flags;
unsigned long index = 0;
int charclass = 0;
int received = 0;
int used = 0;
int rejected = 0;
int reset = 0;
int do_characters = !strcmp(attr->attr.name, "characters");
size_t desc_length = 0;
int i;
spk_lock(flags);
while (cp < end) {
while ((cp < end) && (*cp == ' ' || *cp == '\t'))
cp++;
if (cp == end)
break;
if ((*cp == '\n') || strchr("dDrR", *cp)) {
reset = 1;
break;
}
received++;
linefeed = strchr(cp, '\n');
if (!linefeed) {
rejected++;
break;
}
if (!isdigit(*cp)) {
rejected++;
cp = linefeed + 1;
continue;
}
index = simple_strtoul(cp, &temp, 10);
if (index > 255) {
rejected++;
cp = linefeed + 1;
continue;
}
while ((temp < linefeed) && (*temp == ' ' || *temp == '\t'))
temp++;
desc_length = linefeed - temp;
if (desc_length > MAX_DESC_LEN) {
rejected++;
cp = linefeed + 1;
continue;
}
if (do_characters) {
desc = kmalloc(desc_length + 1, GFP_ATOMIC);
if (!desc) {
retval = -ENOMEM;
reset = 1; /* just reset on error. */
break;
}
outptr = desc;
} else {
outptr = keyword;
}
for (i = 0; i < desc_length; i++)
outptr[i] = temp[i];
outptr[desc_length] = '\0';
if (do_characters) {
if (characters[index] != default_chars[index])
kfree(characters[index]);
characters[index] = desc;
used++;
} else {
charclass = chartab_get_value(keyword);
if (charclass == 0) {
rejected++;
cp = linefeed + 1;
continue;
}
if (charclass != spk_chartab[index]) {
spk_chartab[index] = charclass;
used++;
}
}
cp = linefeed + 1;
}
if (reset) {
if (do_characters)
reset_default_chars();
else
reset_default_chartab();
}
spk_unlock(flags);
report_char_chartab_status(reset, received, used, rejected,
do_characters);
return retval;
}
/*
* This is called when a user reads the keymap parameter.
*/
static ssize_t keymap_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
char *cp = buf;
int i;
int n;
int num_keys;
int nstates;
u_char *cp1;
u_char ch;
unsigned long flags;
spk_lock(flags);
cp1 = key_buf + SHIFT_TBL_SIZE;
num_keys = (int)(*cp1);
nstates = (int)cp1[1];
cp += sprintf(cp, "%d, %d, %d,\n", KEY_MAP_VER, num_keys, nstates);
cp1 += 2; /* now pointing at shift states */
/* dump num_keys+1 as first row is shift states + flags,
* each subsequent row is key + states */
for (n = 0; n <= num_keys; n++) {
for (i = 0; i <= nstates; i++) {
ch = *cp1++;
cp += sprintf(cp, "%d,", (int)ch);
*cp++ = (i < nstates) ? SPACE : '\n';
}
}
cp += sprintf(cp, "0, %d\n", KEY_MAP_VER);
spk_unlock(flags);
return (int)(cp-buf);
}
/*
* This is called when a user changes the keymap parameter.
*/
static ssize_t keymap_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count)
{
int i;
ssize_t ret = count;
char *in_buff = NULL;
char *cp;
u_char *cp1;
unsigned long flags;
spk_lock(flags);
in_buff = kmemdup(buf, count + 1, GFP_ATOMIC);
if (!in_buff) {
spk_unlock(flags);
return -ENOMEM;
}
if (strchr("dDrR", *in_buff)) {
set_key_info(key_defaults, key_buf);
pr_info("keymap set to default values\n");
kfree(in_buff);
spk_unlock(flags);
return count;
}
if (in_buff[count - 1] == '\n')
in_buff[count - 1] = '\0';
cp = in_buff;
cp1 = (u_char *)in_buff;
for (i = 0; i < 3; i++) {
cp = s2uchar(cp, cp1);
cp1++;
}
i = (int)cp1[-2]+1;
i *= (int)cp1[-1]+1;
i += 2; /* 0 and last map ver */
if (cp1[-3] != KEY_MAP_VER || cp1[-1] > 10 ||
i+SHIFT_TBL_SIZE+4 >= sizeof(key_buf)) {
pr_warn("i %d %d %d %d\n", i,
(int)cp1[-3], (int)cp1[-2], (int)cp1[-1]);
kfree(in_buff);
spk_unlock(flags);
return -EINVAL;
}
while (--i >= 0) {
cp = s2uchar(cp, cp1);
cp1++;
if (!(*cp))
break;
}
if (i != 0 || cp1[-1] != KEY_MAP_VER || cp1[-2] != 0) {
ret = -EINVAL;
pr_warn("end %d %d %d %d\n", i,
(int)cp1[-3], (int)cp1[-2], (int)cp1[-1]);
} else {
if (set_key_info(in_buff, key_buf)) {
set_key_info(key_defaults, key_buf);
ret = -EINVAL;
pr_warn("set key failed\n");
}
}
kfree(in_buff);
spk_unlock(flags);
return ret;
}
/*
* This is called when a user changes the value of the silent parameter.
*/
static ssize_t silent_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count)
{
int len;
struct vc_data *vc = vc_cons[fg_console].d;
char ch = 0;
char shut;
unsigned long flags;
len = strlen(buf);
if (len > 0 && len < 3) {
ch = buf[0];
if (ch == '\n')
ch = '0';
}
if (ch < '0' || ch > '7') {
pr_warn("silent value '%c' not in range (0,7)\n", ch);
return -EINVAL;
}
spk_lock(flags);
if (ch&2) {
shut = 1;
do_flush();
} else {
shut = 0;
}
if (ch&4)
shut |= 0x40;
if (ch&1)
spk_shut_up |= shut;
else
spk_shut_up &= ~shut;
spk_unlock(flags);
return count;
}
/*
* This is called when a user reads the synth setting.
*/
static ssize_t synth_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
int rv;
if (synth == NULL)
rv = sprintf(buf, "%s\n", "none");
else
rv = sprintf(buf, "%s\n", synth->name);
return rv;
}
/*
* This is called when a user requests to change synthesizers.
*/
static ssize_t synth_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count)
{
int len;
char new_synth_name[10];
len = strlen(buf);
if (len < 2 || len > 9)
return -EINVAL;
strncpy(new_synth_name, buf, len);
if (new_synth_name[len - 1] == '\n')
len--;
new_synth_name[len] = '\0';
strlwr(new_synth_name);
if ((synth != NULL) && (!strcmp(new_synth_name, synth->name))) {
pr_warn("%s already in use\n", new_synth_name);
} else if (synth_init(new_synth_name) != 0) {
pr_warn("failed to init synth %s\n", new_synth_name);
return -ENODEV;
}
return count;
}
/*
* This is called when text is sent to the synth via the synth_direct file.
*/
static ssize_t synth_direct_store(struct kobject *kobj,
struct kobj_attribute *attr, const char *buf, size_t count)
{
u_char tmp[256];
int len;
int bytes;
const char *ptr = buf;
if (!synth)
return -EPERM;
len = strlen(buf);
while (len > 0) {
bytes = min_t(size_t, len, 250);
strncpy(tmp, ptr, bytes);
tmp[bytes] = '\0';
xlate(tmp);
synth_printf("%s", tmp);
ptr += bytes;
len -= bytes;
}
return count;
}
/*
* This function is called when a user reads the version.
*/
static ssize_t version_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
char *cp;
cp = buf;
cp += sprintf(cp, "Speakup version %s\n", SPEAKUP_VERSION);
if (synth)
cp += sprintf(cp, "%s synthesizer driver version %s\n",
synth->name, synth->version);
return cp - buf;
}
/*
* This is called when a user reads the punctuation settings.
*/
static ssize_t punc_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
int i;
char *cp = buf;
struct st_var_header *p_header;
struct punc_var_t *var;
struct st_bits_data *pb;
short mask;
unsigned long flags;
p_header = var_header_by_name(attr->attr.name);
if (p_header == NULL) {
pr_warn("p_header is null, attr->attr.name is %s\n",
attr->attr.name);
return -EINVAL;
}
var = get_punc_var(p_header->var_id);
if (var == NULL) {
pr_warn("var is null, p_header->var_id is %i\n",
p_header->var_id);
return -EINVAL;
}
spk_lock(flags);
pb = (struct st_bits_data *) &punc_info[var->value];
mask = pb->mask;
for (i = 33; i < 128; i++) {
if (!(spk_chartab[i]&mask))
continue;
*cp++ = (char)i;
}
spk_unlock(flags);
return cp-buf;
}
/*
* This is called when a user changes the punctuation settings.
*/
static ssize_t punc_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count)
{
int x;
struct st_var_header *p_header;
struct punc_var_t *var;
char punc_buf[100];
unsigned long flags;
x = strlen(buf);
if (x < 1 || x > 99)
return -EINVAL;
p_header = var_header_by_name(attr->attr.name);
if (p_header == NULL) {
pr_warn("p_header is null, attr->attr.name is %s\n",
attr->attr.name);
return -EINVAL;
}
var = get_punc_var(p_header->var_id);
if (var == NULL) {
pr_warn("var is null, p_header->var_id is %i\n",
p_header->var_id);
return -EINVAL;
}
strncpy(punc_buf, buf, x);
while (x && punc_buf[x - 1] == '\n')
x--;
punc_buf[x] = '\0';
spk_lock(flags);
if (*punc_buf == 'd' || *punc_buf == 'r')
x = set_mask_bits(0, var->value, 3);
else
x = set_mask_bits(punc_buf, var->value, 3);
spk_unlock(flags);
return count;
}
/*
* This function is called when a user reads one of the variable parameters.
*/
ssize_t spk_var_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
int rv = 0;
struct st_var_header *param;
struct var_t *var;
char *cp1;
char *cp;
char ch;
unsigned long flags;
param = var_header_by_name(attr->attr.name);
if (param == NULL)
return -EINVAL;
spk_lock(flags);
var = (struct var_t *) param->data;
switch (param->var_type) {
case VAR_NUM:
case VAR_TIME:
if (var)
rv = sprintf(buf, "%i\n", var->u.n.value);
else
rv = sprintf(buf, "0\n");
break;
case VAR_STRING:
if (var) {
cp1 = buf;
*cp1++ = '"';
for (cp = (char *)param->p_val; (ch = *cp); cp++) {
if (ch >= ' ' && ch < '~')
*cp1++ = ch;
else
cp1 += sprintf(cp1, "\\""x%02x", ch);
}
*cp1++ = '"';
*cp1++ = '\n';
*cp1 = '\0';
rv = cp1-buf;
} else {
rv = sprintf(buf, "\"\"\n");
}
break;
default:
rv = sprintf(buf, "Bad parameter %s, type %i\n",
param->name, param->var_type);
break;
}
spk_unlock(flags);
return rv;
}
EXPORT_SYMBOL_GPL(spk_var_show);
/*
* This function is called when a user echos a value to one of the
* variable parameters.
*/
ssize_t spk_var_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count)
{
struct st_var_header *param;
int ret;
int len;
char *cp;
struct var_t *var_data;
int value;
unsigned long flags;
param = var_header_by_name(attr->attr.name);
if (param == NULL)
return -EINVAL;
if (param->data == NULL)
return 0;
ret = 0;
cp = xlate((char *) buf);
spk_lock(flags);
switch (param->var_type) {
case VAR_NUM:
case VAR_TIME:
if (*cp == 'd' || *cp == 'r' || *cp == '\0')
len = E_DEFAULT;
else if (*cp == '+' || *cp == '-')
len = E_INC;
else
len = E_SET;
speakup_s2i(cp, &value);
ret = set_num_var(value, param, len);
if (ret == E_RANGE) {
var_data = param->data;
pr_warn("value for %s out of range, expect %d to %d\n",
attr->attr.name,
var_data->u.n.low, var_data->u.n.high);
}
break;
case VAR_STRING:
len = strlen(buf);
if ((len >= 1) && (buf[len - 1] == '\n'))
--len;
if ((len >= 2) && (buf[0] == '"') && (buf[len - 1] == '"')) {
++buf;
len -= 2;
}
cp = (char *) buf;
cp[len] = '\0';
ret = set_string_var(buf, param, len);
if (ret == E_TOOLONG)
pr_warn("value too long for %s\n",
attr->attr.name);
break;
default:
pr_warn("%s unknown type %d\n",
param->name, (int)param->var_type);
break;
}
/*
* If voice was just changed, we might need to reset our default
* pitch and volume.
*/
if (strcmp(attr->attr.name, "voice") == 0) {
if (synth && synth->default_pitch) {
param = var_header_by_name("pitch");
if (param) {
set_num_var(synth->default_pitch[value], param,
E_NEW_DEFAULT);
set_num_var(0, param, E_DEFAULT);
}
}
if (synth && synth->default_vol) {
param = var_header_by_name("vol");
if (param) {
set_num_var(synth->default_vol[value], param,
E_NEW_DEFAULT);
set_num_var(0, param, E_DEFAULT);
}
}
}
spk_unlock(flags);
if (ret == SET_DEFAULT)
pr_info("%s reset to default value\n", attr->attr.name);
return count;
}
EXPORT_SYMBOL_GPL(spk_var_store);
/*
* Functions for reading and writing lists of i18n messages. Incomplete.
*/
static ssize_t message_show_helper(char *buf, enum msg_index_t first,
enum msg_index_t last)
{
size_t bufsize = PAGE_SIZE;
char *buf_pointer = buf;
int printed;
enum msg_index_t cursor;
int index = 0;
*buf_pointer = '\0'; /* buf_pointer always looking at a NUL byte. */
for (cursor = first; cursor <= last; cursor++, index++) {
if (bufsize <= 1)
break;
printed = scnprintf(buf_pointer, bufsize, "%d\t%s\n",
index, msg_get(cursor));
buf_pointer += printed;
bufsize -= printed;
}
return buf_pointer - buf;
}
static void report_msg_status(int reset, int received, int used,
int rejected, char *groupname)
{
int len;
char buf[160];
if (reset) {
pr_info("i18n messages from group %s reset to defaults\n",
groupname);
} else if (received) {
len = snprintf(buf, sizeof(buf),
" updated %d of %d i18n messages from group %s\n",
used, received, groupname);
if (rejected)
snprintf(buf + (len - 1), sizeof(buf) - (len - 1),
" with %d reject%s\n",
rejected, rejected > 1 ? "s" : "");
printk(buf);
}
}
static ssize_t message_store_helper(const char *buf, size_t count,
struct msg_group_t *group)
{
char *cp = (char *) buf;
char *end = cp + count;
char *linefeed = NULL;
char *temp = NULL;
ssize_t msg_stored = 0;
ssize_t retval = count;
size_t desc_length = 0;
unsigned long index = 0;
int received = 0;
int used = 0;
int rejected = 0;
int reset = 0;
enum msg_index_t firstmessage = group->start;
enum msg_index_t lastmessage = group->end;
enum msg_index_t curmessage;
while (cp < end) {
while ((cp < end) && (*cp == ' ' || *cp == '\t'))
cp++;
if (cp == end)
break;
if (strchr("dDrR", *cp)) {
reset = 1;
break;
}
received++;
linefeed = strchr(cp, '\n');
if (!linefeed) {
rejected++;
break;
}
if (!isdigit(*cp)) {
rejected++;
cp = linefeed + 1;
continue;
}
index = simple_strtoul(cp, &temp, 10);
while ((temp < linefeed) && (*temp == ' ' || *temp == '\t'))
temp++;
desc_length = linefeed - temp;
curmessage = firstmessage + index;
/*
* Note the check (curmessage < firstmessage). It is not
* redundant. Suppose that the user gave us an index
* equal to ULONG_MAX - 1. If firstmessage > 1, then
* firstmessage + index < firstmessage!
*/
if ((curmessage < firstmessage) || (curmessage > lastmessage)) {
rejected++;
cp = linefeed + 1;
continue;
}
msg_stored = msg_set(curmessage, temp, desc_length);
if (msg_stored < 0) {
retval = msg_stored;
if (msg_stored == -ENOMEM)
reset = 1;
break;
} else {
used++;
}
cp = linefeed + 1;
}
if (reset)
reset_msg_group(group);
report_msg_status(reset, received, used, rejected, group->name);
return retval;
}
static ssize_t message_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
ssize_t retval = 0;
struct msg_group_t *group = find_msg_group(attr->attr.name);
unsigned long flags;
BUG_ON(!group);
spk_lock(flags);
retval = message_show_helper(buf, group->start, group->end);
spk_unlock(flags);
return retval;
}
static ssize_t message_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count)
{
ssize_t retval = 0;
struct msg_group_t *group = find_msg_group(attr->attr.name);
BUG_ON(!group);
retval = message_store_helper(buf, count, group);
return retval;
}
/*
* Declare the attributes.
*/
static struct kobj_attribute keymap_attribute =
__ATTR(keymap, ROOT_W, keymap_show, keymap_store);
static struct kobj_attribute silent_attribute =
__ATTR(silent, USER_W, NULL, silent_store);
static struct kobj_attribute synth_attribute =
__ATTR(synth, USER_RW, synth_show, synth_store);
static struct kobj_attribute synth_direct_attribute =
__ATTR(synth_direct, USER_W, NULL, synth_direct_store);
static struct kobj_attribute version_attribute =
__ATTR_RO(version);
static struct kobj_attribute delimiters_attribute =
__ATTR(delimiters, USER_RW, punc_show, punc_store);
static struct kobj_attribute ex_num_attribute =
__ATTR(ex_num, USER_RW, punc_show, punc_store);
static struct kobj_attribute punc_all_attribute =
__ATTR(punc_all, USER_RW, punc_show, punc_store);
static struct kobj_attribute punc_most_attribute =
__ATTR(punc_most, USER_RW, punc_show, punc_store);
static struct kobj_attribute punc_some_attribute =
__ATTR(punc_some, USER_RW, punc_show, punc_store);
static struct kobj_attribute repeats_attribute =
__ATTR(repeats, USER_RW, punc_show, punc_store);
static struct kobj_attribute attrib_bleep_attribute =
__ATTR(attrib_bleep, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute bell_pos_attribute =
__ATTR(bell_pos, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute bleep_time_attribute =
__ATTR(bleep_time, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute bleeps_attribute =
__ATTR(bleeps, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute cursor_time_attribute =
__ATTR(cursor_time, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute key_echo_attribute =
__ATTR(key_echo, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute no_interrupt_attribute =
__ATTR(no_interrupt, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute punc_level_attribute =
__ATTR(punc_level, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute reading_punc_attribute =
__ATTR(reading_punc, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute say_control_attribute =
__ATTR(say_control, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute say_word_ctl_attribute =
__ATTR(say_word_ctl, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute spell_delay_attribute =
__ATTR(spell_delay, USER_RW, spk_var_show, spk_var_store);
/*
* These attributes are i18n related.
*/
static struct kobj_attribute announcements_attribute =
__ATTR(announcements, USER_RW, message_show, message_store);
static struct kobj_attribute characters_attribute =
__ATTR(characters, USER_RW, chars_chartab_show, chars_chartab_store);
static struct kobj_attribute chartab_attribute =
__ATTR(chartab, USER_RW, chars_chartab_show, chars_chartab_store);
static struct kobj_attribute ctl_keys_attribute =
__ATTR(ctl_keys, USER_RW, message_show, message_store);
static struct kobj_attribute colors_attribute =
__ATTR(colors, USER_RW, message_show, message_store);
static struct kobj_attribute formatted_attribute =
__ATTR(formatted, USER_RW, message_show, message_store);
static struct kobj_attribute function_names_attribute =
__ATTR(function_names, USER_RW, message_show, message_store);
static struct kobj_attribute key_names_attribute =
__ATTR(key_names, USER_RW, message_show, message_store);
static struct kobj_attribute states_attribute =
__ATTR(states, USER_RW, message_show, message_store);
/*
* Create groups of attributes so that we can create and destroy them all
* at once.
*/
static struct attribute *main_attrs[] = {
&keymap_attribute.attr,
&silent_attribute.attr,
&synth_attribute.attr,
&synth_direct_attribute.attr,
&version_attribute.attr,
&delimiters_attribute.attr,
&ex_num_attribute.attr,
&punc_all_attribute.attr,
&punc_most_attribute.attr,
&punc_some_attribute.attr,
&repeats_attribute.attr,
&attrib_bleep_attribute.attr,
&bell_pos_attribute.attr,
&bleep_time_attribute.attr,
&bleeps_attribute.attr,
&cursor_time_attribute.attr,
&key_echo_attribute.attr,
&no_interrupt_attribute.attr,
&punc_level_attribute.attr,
&reading_punc_attribute.attr,
&say_control_attribute.attr,
&say_word_ctl_attribute.attr,
&spell_delay_attribute.attr,
NULL,
};
static struct attribute *i18n_attrs[] = {
&announcements_attribute.attr,
&characters_attribute.attr,
&chartab_attribute.attr,
&ctl_keys_attribute.attr,
&colors_attribute.attr,
&formatted_attribute.attr,
&function_names_attribute.attr,
&key_names_attribute.attr,
&states_attribute.attr,
NULL,
};
/*
* An unnamed attribute group will put all of the attributes directly in
* the kobject directory. If we specify a name, a subdirectory will be
* created for the attributes with the directory being the name of the
* attribute group.
*/
static struct attribute_group main_attr_group = {
.attrs = main_attrs,
};
static struct attribute_group i18n_attr_group = {
.attrs = i18n_attrs,
.name = "i18n",
};
static struct kobject *accessibility_kobj;
struct kobject *speakup_kobj;
int speakup_kobj_init(void)
{
int retval;
/*
* Create a simple kobject with the name of "accessibility",
* located under /sys/
*
* As this is a simple directory, no uevent will be sent to
* userspace. That is why this function should not be used for
* any type of dynamic kobjects, where the name and number are
* not known ahead of time.
*/
accessibility_kobj = kobject_create_and_add("accessibility", NULL);
if (!accessibility_kobj) {
retval = -ENOMEM;
goto out;
}
speakup_kobj = kobject_create_and_add("speakup", accessibility_kobj);
if (!speakup_kobj) {
retval = -ENOMEM;
goto err_acc;
}
/* Create the files associated with this kobject */
retval = sysfs_create_group(speakup_kobj, &main_attr_group);
if (retval)
goto err_speakup;
retval = sysfs_create_group(speakup_kobj, &i18n_attr_group);
if (retval)
goto err_group;
goto out;
err_group:
sysfs_remove_group(speakup_kobj, &main_attr_group);
err_speakup:
kobject_put(speakup_kobj);
err_acc:
kobject_put(accessibility_kobj);
out:
return retval;
}
void speakup_kobj_exit(void)
{
sysfs_remove_group(speakup_kobj, &i18n_attr_group);
sysfs_remove_group(speakup_kobj, &main_attr_group);
kobject_put(speakup_kobj);
kobject_put(accessibility_kobj);
}
| gpl-2.0 |
Tommy-Geenexus/android_kernel_sony_apq8064_yuga_5.x | arch/arm/mach-s3c24xx/s3c2443.c | 4841 | 2877 | /* linux/arch/arm/mach-s3c2443/s3c2443.c
*
* Copyright (c) 2007 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
*
* Samsung S3C2443 Mobile CPU support
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/gpio.h>
#include <linux/platform_device.h>
#include <linux/serial_core.h>
#include <linux/device.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/system_misc.h>
#include <mach/regs-s3c2443-clock.h>
#include <plat/gpio-core.h>
#include <plat/gpio-cfg.h>
#include <plat/gpio-cfg-helpers.h>
#include <plat/s3c2443.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/fb-core.h>
#include <plat/nand-core.h>
#include <plat/adc-core.h>
#include <plat/rtc-core.h>
static struct map_desc s3c2443_iodesc[] __initdata = {
IODESC_ENT(WATCHDOG),
IODESC_ENT(CLKPWR),
IODESC_ENT(TIMER),
};
struct bus_type s3c2443_subsys = {
.name = "s3c2443-core",
.dev_name = "s3c2443-core",
};
static struct device s3c2443_dev = {
.bus = &s3c2443_subsys,
};
void s3c2443_restart(char mode, const char *cmd)
{
if (mode == 's')
soft_restart(0);
__raw_writel(S3C2443_SWRST_RESET, S3C2443_SWRST);
}
int __init s3c2443_init(void)
{
printk("S3C2443: Initialising architecture\n");
s3c_nand_setname("s3c2412-nand");
s3c_fb_setname("s3c2443-fb");
s3c_adc_setname("s3c2443-adc");
s3c_rtc_setname("s3c2443-rtc");
/* change WDT IRQ number */
s3c_device_wdt.resource[1].start = IRQ_S3C2443_WDT;
s3c_device_wdt.resource[1].end = IRQ_S3C2443_WDT;
return device_register(&s3c2443_dev);
}
void __init s3c2443_init_uarts(struct s3c2410_uartcfg *cfg, int no)
{
s3c24xx_init_uartdevs("s3c2440-uart", s3c2410_uart_resources, cfg, no);
}
/* s3c2443_map_io
*
* register the standard cpu IO areas, and any passed in from the
* machine specific initialisation.
*/
void __init s3c2443_map_io(void)
{
s3c24xx_gpiocfg_default.set_pull = s3c2443_gpio_setpull;
s3c24xx_gpiocfg_default.get_pull = s3c2443_gpio_getpull;
iotable_init(s3c2443_iodesc, ARRAY_SIZE(s3c2443_iodesc));
}
/* need to register the subsystem before we actually register the device, and
* we also need to ensure that it has been initialised before any of the
* drivers even try to use it (even if not on an s3c2443 based system)
* as a driver which may support both 2443 and 2440 may try and use it.
*/
static int __init s3c2443_core_init(void)
{
return subsys_system_register(&s3c2443_subsys, NULL);
}
core_initcall(s3c2443_core_init);
| gpl-2.0 |
Pafcholini/m7-Sense-4.4.2 | drivers/hwmon/smsc47m1.c | 4841 | 25661 | /*
* smsc47m1.c - Part of lm_sensors, Linux kernel modules
* for hardware monitoring
*
* Supports the SMSC LPC47B27x, LPC47M10x, LPC47M112, LPC47M13x,
* LPC47M14x, LPC47M15x, LPC47M192, LPC47M292 and LPC47M997
* Super-I/O chips.
*
* Copyright (C) 2002 Mark D. Studebaker <mdsxyz123@yahoo.com>
* Copyright (C) 2004-2007 Jean Delvare <khali@linux-fr.org>
* Ported to Linux 2.6 by Gabriele Gorla <gorlik@yahoo.com>
* and Jean Delvare
*
* This program is free software; you can redistribute 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.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/ioport.h>
#include <linux/jiffies.h>
#include <linux/platform_device.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <linux/sysfs.h>
#include <linux/acpi.h>
#include <linux/io.h>
static unsigned short force_id;
module_param(force_id, ushort, 0);
MODULE_PARM_DESC(force_id, "Override the detected device ID");
static struct platform_device *pdev;
#define DRVNAME "smsc47m1"
enum chips { smsc47m1, smsc47m2 };
/* Super-I/0 registers and commands */
#define REG 0x2e /* The register to read/write */
#define VAL 0x2f /* The value to read/write */
static inline void
superio_outb(int reg, int val)
{
outb(reg, REG);
outb(val, VAL);
}
static inline int
superio_inb(int reg)
{
outb(reg, REG);
return inb(VAL);
}
/* logical device for fans is 0x0A */
#define superio_select() superio_outb(0x07, 0x0A)
static inline void
superio_enter(void)
{
outb(0x55, REG);
}
static inline void
superio_exit(void)
{
outb(0xAA, REG);
}
#define SUPERIO_REG_ACT 0x30
#define SUPERIO_REG_BASE 0x60
#define SUPERIO_REG_DEVID 0x20
#define SUPERIO_REG_DEVREV 0x21
/* Logical device registers */
#define SMSC_EXTENT 0x80
/* nr is 0 or 1 in the macros below */
#define SMSC47M1_REG_ALARM 0x04
#define SMSC47M1_REG_TPIN(nr) (0x34 - (nr))
#define SMSC47M1_REG_PPIN(nr) (0x36 - (nr))
#define SMSC47M1_REG_FANDIV 0x58
static const u8 SMSC47M1_REG_FAN[3] = { 0x59, 0x5a, 0x6b };
static const u8 SMSC47M1_REG_FAN_PRELOAD[3] = { 0x5b, 0x5c, 0x6c };
static const u8 SMSC47M1_REG_PWM[3] = { 0x56, 0x57, 0x69 };
#define SMSC47M2_REG_ALARM6 0x09
#define SMSC47M2_REG_TPIN1 0x38
#define SMSC47M2_REG_TPIN2 0x37
#define SMSC47M2_REG_TPIN3 0x2d
#define SMSC47M2_REG_PPIN3 0x2c
#define SMSC47M2_REG_FANDIV3 0x6a
#define MIN_FROM_REG(reg, div) ((reg) >= 192 ? 0 : \
983040 / ((192 - (reg)) * (div)))
#define FAN_FROM_REG(reg, div, preload) ((reg) <= (preload) || (reg) == 255 ? \
0 : \
983040 / (((reg) - (preload)) * (div)))
#define DIV_FROM_REG(reg) (1 << (reg))
#define PWM_FROM_REG(reg) (((reg) & 0x7E) << 1)
#define PWM_EN_FROM_REG(reg) ((~(reg)) & 0x01)
#define PWM_TO_REG(reg) (((reg) >> 1) & 0x7E)
struct smsc47m1_data {
unsigned short addr;
const char *name;
enum chips type;
struct device *hwmon_dev;
struct mutex update_lock;
unsigned long last_updated; /* In jiffies */
u8 fan[3]; /* Register value */
u8 fan_preload[3]; /* Register value */
u8 fan_div[3]; /* Register encoding, shifted right */
u8 alarms; /* Register encoding */
u8 pwm[3]; /* Register value (bit 0 is disable) */
};
struct smsc47m1_sio_data {
enum chips type;
u8 activate; /* Remember initial device state */
};
static int __exit smsc47m1_remove(struct platform_device *pdev);
static struct smsc47m1_data *smsc47m1_update_device(struct device *dev,
int init);
static inline int smsc47m1_read_value(struct smsc47m1_data *data, u8 reg)
{
return inb_p(data->addr + reg);
}
static inline void smsc47m1_write_value(struct smsc47m1_data *data, u8 reg,
u8 value)
{
outb_p(value, data->addr + reg);
}
static struct platform_driver smsc47m1_driver = {
.driver = {
.owner = THIS_MODULE,
.name = DRVNAME,
},
.remove = __exit_p(smsc47m1_remove),
};
static ssize_t get_fan(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct smsc47m1_data *data = smsc47m1_update_device(dev, 0);
int nr = attr->index;
/*
* This chip (stupidly) stops monitoring fan speed if PWM is
* enabled and duty cycle is 0%. This is fine if the monitoring
* and control concern the same fan, but troublesome if they are
* not (which could as well happen).
*/
int rpm = (data->pwm[nr] & 0x7F) == 0x00 ? 0 :
FAN_FROM_REG(data->fan[nr],
DIV_FROM_REG(data->fan_div[nr]),
data->fan_preload[nr]);
return sprintf(buf, "%d\n", rpm);
}
static ssize_t get_fan_min(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct smsc47m1_data *data = smsc47m1_update_device(dev, 0);
int nr = attr->index;
int rpm = MIN_FROM_REG(data->fan_preload[nr],
DIV_FROM_REG(data->fan_div[nr]));
return sprintf(buf, "%d\n", rpm);
}
static ssize_t get_fan_div(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct smsc47m1_data *data = smsc47m1_update_device(dev, 0);
return sprintf(buf, "%d\n", DIV_FROM_REG(data->fan_div[attr->index]));
}
static ssize_t get_fan_alarm(struct device *dev, struct device_attribute
*devattr, char *buf)
{
int bitnr = to_sensor_dev_attr(devattr)->index;
struct smsc47m1_data *data = smsc47m1_update_device(dev, 0);
return sprintf(buf, "%u\n", (data->alarms >> bitnr) & 1);
}
static ssize_t get_pwm(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct smsc47m1_data *data = smsc47m1_update_device(dev, 0);
return sprintf(buf, "%d\n", PWM_FROM_REG(data->pwm[attr->index]));
}
static ssize_t get_pwm_en(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct smsc47m1_data *data = smsc47m1_update_device(dev, 0);
return sprintf(buf, "%d\n", PWM_EN_FROM_REG(data->pwm[attr->index]));
}
static ssize_t get_alarms(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct smsc47m1_data *data = smsc47m1_update_device(dev, 0);
return sprintf(buf, "%d\n", data->alarms);
}
static ssize_t set_fan_min(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct smsc47m1_data *data = dev_get_drvdata(dev);
int nr = attr->index;
long rpmdiv;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
rpmdiv = val * DIV_FROM_REG(data->fan_div[nr]);
if (983040 > 192 * rpmdiv || 2 * rpmdiv > 983040) {
mutex_unlock(&data->update_lock);
return -EINVAL;
}
data->fan_preload[nr] = 192 - ((983040 + rpmdiv / 2) / rpmdiv);
smsc47m1_write_value(data, SMSC47M1_REG_FAN_PRELOAD[nr],
data->fan_preload[nr]);
mutex_unlock(&data->update_lock);
return count;
}
/*
* Note: we save and restore the fan minimum here, because its value is
* determined in part by the fan clock divider. This follows the principle
* of least surprise; the user doesn't expect the fan minimum to change just
* because the divider changed.
*/
static ssize_t set_fan_div(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct smsc47m1_data *data = dev_get_drvdata(dev);
int nr = attr->index;
long new_div;
int err;
long tmp;
u8 old_div = DIV_FROM_REG(data->fan_div[nr]);
err = kstrtol(buf, 10, &new_div);
if (err)
return err;
if (new_div == old_div) /* No change */
return count;
mutex_lock(&data->update_lock);
switch (new_div) {
case 1:
data->fan_div[nr] = 0;
break;
case 2:
data->fan_div[nr] = 1;
break;
case 4:
data->fan_div[nr] = 2;
break;
case 8:
data->fan_div[nr] = 3;
break;
default:
mutex_unlock(&data->update_lock);
return -EINVAL;
}
switch (nr) {
case 0:
case 1:
tmp = smsc47m1_read_value(data, SMSC47M1_REG_FANDIV)
& ~(0x03 << (4 + 2 * nr));
tmp |= data->fan_div[nr] << (4 + 2 * nr);
smsc47m1_write_value(data, SMSC47M1_REG_FANDIV, tmp);
break;
case 2:
tmp = smsc47m1_read_value(data, SMSC47M2_REG_FANDIV3) & 0xCF;
tmp |= data->fan_div[2] << 4;
smsc47m1_write_value(data, SMSC47M2_REG_FANDIV3, tmp);
break;
}
/* Preserve fan min */
tmp = 192 - (old_div * (192 - data->fan_preload[nr])
+ new_div / 2) / new_div;
data->fan_preload[nr] = SENSORS_LIMIT(tmp, 0, 191);
smsc47m1_write_value(data, SMSC47M1_REG_FAN_PRELOAD[nr],
data->fan_preload[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t set_pwm(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct smsc47m1_data *data = dev_get_drvdata(dev);
int nr = attr->index;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
if (val < 0 || val > 255)
return -EINVAL;
mutex_lock(&data->update_lock);
data->pwm[nr] &= 0x81; /* Preserve additional bits */
data->pwm[nr] |= PWM_TO_REG(val);
smsc47m1_write_value(data, SMSC47M1_REG_PWM[nr],
data->pwm[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t set_pwm_en(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct smsc47m1_data *data = dev_get_drvdata(dev);
int nr = attr->index;
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
if (val > 1)
return -EINVAL;
mutex_lock(&data->update_lock);
data->pwm[nr] &= 0xFE; /* preserve the other bits */
data->pwm[nr] |= !val;
smsc47m1_write_value(data, SMSC47M1_REG_PWM[nr],
data->pwm[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define fan_present(offset) \
static SENSOR_DEVICE_ATTR(fan##offset##_input, S_IRUGO, get_fan, \
NULL, offset - 1); \
static SENSOR_DEVICE_ATTR(fan##offset##_min, S_IRUGO | S_IWUSR, \
get_fan_min, set_fan_min, offset - 1); \
static SENSOR_DEVICE_ATTR(fan##offset##_div, S_IRUGO | S_IWUSR, \
get_fan_div, set_fan_div, offset - 1); \
static SENSOR_DEVICE_ATTR(fan##offset##_alarm, S_IRUGO, get_fan_alarm, \
NULL, offset - 1); \
static SENSOR_DEVICE_ATTR(pwm##offset, S_IRUGO | S_IWUSR, \
get_pwm, set_pwm, offset - 1); \
static SENSOR_DEVICE_ATTR(pwm##offset##_enable, S_IRUGO | S_IWUSR, \
get_pwm_en, set_pwm_en, offset - 1)
fan_present(1);
fan_present(2);
fan_present(3);
static DEVICE_ATTR(alarms, S_IRUGO, get_alarms, NULL);
static ssize_t show_name(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct smsc47m1_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%s\n", data->name);
}
static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
static struct attribute *smsc47m1_attributes_fan1[] = {
&sensor_dev_attr_fan1_input.dev_attr.attr,
&sensor_dev_attr_fan1_min.dev_attr.attr,
&sensor_dev_attr_fan1_div.dev_attr.attr,
&sensor_dev_attr_fan1_alarm.dev_attr.attr,
NULL
};
static const struct attribute_group smsc47m1_group_fan1 = {
.attrs = smsc47m1_attributes_fan1,
};
static struct attribute *smsc47m1_attributes_fan2[] = {
&sensor_dev_attr_fan2_input.dev_attr.attr,
&sensor_dev_attr_fan2_min.dev_attr.attr,
&sensor_dev_attr_fan2_div.dev_attr.attr,
&sensor_dev_attr_fan2_alarm.dev_attr.attr,
NULL
};
static const struct attribute_group smsc47m1_group_fan2 = {
.attrs = smsc47m1_attributes_fan2,
};
static struct attribute *smsc47m1_attributes_fan3[] = {
&sensor_dev_attr_fan3_input.dev_attr.attr,
&sensor_dev_attr_fan3_min.dev_attr.attr,
&sensor_dev_attr_fan3_div.dev_attr.attr,
&sensor_dev_attr_fan3_alarm.dev_attr.attr,
NULL
};
static const struct attribute_group smsc47m1_group_fan3 = {
.attrs = smsc47m1_attributes_fan3,
};
static struct attribute *smsc47m1_attributes_pwm1[] = {
&sensor_dev_attr_pwm1.dev_attr.attr,
&sensor_dev_attr_pwm1_enable.dev_attr.attr,
NULL
};
static const struct attribute_group smsc47m1_group_pwm1 = {
.attrs = smsc47m1_attributes_pwm1,
};
static struct attribute *smsc47m1_attributes_pwm2[] = {
&sensor_dev_attr_pwm2.dev_attr.attr,
&sensor_dev_attr_pwm2_enable.dev_attr.attr,
NULL
};
static const struct attribute_group smsc47m1_group_pwm2 = {
.attrs = smsc47m1_attributes_pwm2,
};
static struct attribute *smsc47m1_attributes_pwm3[] = {
&sensor_dev_attr_pwm3.dev_attr.attr,
&sensor_dev_attr_pwm3_enable.dev_attr.attr,
NULL
};
static const struct attribute_group smsc47m1_group_pwm3 = {
.attrs = smsc47m1_attributes_pwm3,
};
static struct attribute *smsc47m1_attributes[] = {
&dev_attr_alarms.attr,
&dev_attr_name.attr,
NULL
};
static const struct attribute_group smsc47m1_group = {
.attrs = smsc47m1_attributes,
};
static int __init smsc47m1_find(struct smsc47m1_sio_data *sio_data)
{
u8 val;
unsigned short addr;
superio_enter();
val = force_id ? force_id : superio_inb(SUPERIO_REG_DEVID);
/*
* SMSC LPC47M10x/LPC47M112/LPC47M13x (device id 0x59), LPC47M14x
* (device id 0x5F) and LPC47B27x (device id 0x51) have fan control.
* The LPC47M15x and LPC47M192 chips "with hardware monitoring block"
* can do much more besides (device id 0x60).
* The LPC47M997 is undocumented, but seems to be compatible with
* the LPC47M192, and has the same device id.
* The LPC47M292 (device id 0x6B) is somewhat compatible, but it
* supports a 3rd fan, and the pin configuration registers are
* unfortunately different.
* The LPC47M233 has the same device id (0x6B) but is not compatible.
* We check the high bit of the device revision register to
* differentiate them.
*/
switch (val) {
case 0x51:
pr_info("Found SMSC LPC47B27x\n");
sio_data->type = smsc47m1;
break;
case 0x59:
pr_info("Found SMSC LPC47M10x/LPC47M112/LPC47M13x\n");
sio_data->type = smsc47m1;
break;
case 0x5F:
pr_info("Found SMSC LPC47M14x\n");
sio_data->type = smsc47m1;
break;
case 0x60:
pr_info("Found SMSC LPC47M15x/LPC47M192/LPC47M997\n");
sio_data->type = smsc47m1;
break;
case 0x6B:
if (superio_inb(SUPERIO_REG_DEVREV) & 0x80) {
pr_debug("Found SMSC LPC47M233, unsupported\n");
superio_exit();
return -ENODEV;
}
pr_info("Found SMSC LPC47M292\n");
sio_data->type = smsc47m2;
break;
default:
superio_exit();
return -ENODEV;
}
superio_select();
addr = (superio_inb(SUPERIO_REG_BASE) << 8)
| superio_inb(SUPERIO_REG_BASE + 1);
if (addr == 0) {
pr_info("Device address not set, will not use\n");
superio_exit();
return -ENODEV;
}
/*
* Enable only if address is set (needed at least on the
* Compaq Presario S4000NX)
*/
sio_data->activate = superio_inb(SUPERIO_REG_ACT);
if ((sio_data->activate & 0x01) == 0) {
pr_info("Enabling device\n");
superio_outb(SUPERIO_REG_ACT, sio_data->activate | 0x01);
}
superio_exit();
return addr;
}
/* Restore device to its initial state */
static void smsc47m1_restore(const struct smsc47m1_sio_data *sio_data)
{
if ((sio_data->activate & 0x01) == 0) {
superio_enter();
superio_select();
pr_info("Disabling device\n");
superio_outb(SUPERIO_REG_ACT, sio_data->activate);
superio_exit();
}
}
#define CHECK 1
#define REQUEST 2
#define RELEASE 3
/*
* This function can be used to:
* - test for resource conflicts with ACPI
* - request the resources
* - release the resources
* We only allocate the I/O ports we really need, to minimize the risk of
* conflicts with ACPI or with other drivers.
*/
static int smsc47m1_handle_resources(unsigned short address, enum chips type,
int action, struct device *dev)
{
static const u8 ports_m1[] = {
/* register, region length */
0x04, 1,
0x33, 4,
0x56, 7,
};
static const u8 ports_m2[] = {
/* register, region length */
0x04, 1,
0x09, 1,
0x2c, 2,
0x35, 4,
0x56, 7,
0x69, 4,
};
int i, ports_size, err;
const u8 *ports;
switch (type) {
case smsc47m1:
default:
ports = ports_m1;
ports_size = ARRAY_SIZE(ports_m1);
break;
case smsc47m2:
ports = ports_m2;
ports_size = ARRAY_SIZE(ports_m2);
break;
}
for (i = 0; i + 1 < ports_size; i += 2) {
unsigned short start = address + ports[i];
unsigned short len = ports[i + 1];
switch (action) {
case CHECK:
/* Only check for conflicts */
err = acpi_check_region(start, len, DRVNAME);
if (err)
return err;
break;
case REQUEST:
/* Request the resources */
if (!request_region(start, len, DRVNAME)) {
dev_err(dev, "Region 0x%hx-0x%hx already in "
"use!\n", start, start + len);
/* Undo all requests */
for (i -= 2; i >= 0; i -= 2)
release_region(address + ports[i],
ports[i + 1]);
return -EBUSY;
}
break;
case RELEASE:
/* Release the resources */
release_region(start, len);
break;
}
}
return 0;
}
static void smsc47m1_remove_files(struct device *dev)
{
sysfs_remove_group(&dev->kobj, &smsc47m1_group);
sysfs_remove_group(&dev->kobj, &smsc47m1_group_fan1);
sysfs_remove_group(&dev->kobj, &smsc47m1_group_fan2);
sysfs_remove_group(&dev->kobj, &smsc47m1_group_fan3);
sysfs_remove_group(&dev->kobj, &smsc47m1_group_pwm1);
sysfs_remove_group(&dev->kobj, &smsc47m1_group_pwm2);
sysfs_remove_group(&dev->kobj, &smsc47m1_group_pwm3);
}
static int __init smsc47m1_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct smsc47m1_sio_data *sio_data = dev->platform_data;
struct smsc47m1_data *data;
struct resource *res;
int err;
int fan1, fan2, fan3, pwm1, pwm2, pwm3;
static const char * const names[] = {
"smsc47m1",
"smsc47m2",
};
res = platform_get_resource(pdev, IORESOURCE_IO, 0);
err = smsc47m1_handle_resources(res->start, sio_data->type,
REQUEST, dev);
if (err < 0)
return err;
data = kzalloc(sizeof(struct smsc47m1_data), GFP_KERNEL);
if (!data) {
err = -ENOMEM;
goto error_release;
}
data->addr = res->start;
data->type = sio_data->type;
data->name = names[sio_data->type];
mutex_init(&data->update_lock);
platform_set_drvdata(pdev, data);
/*
* If no function is properly configured, there's no point in
* actually registering the chip.
*/
pwm1 = (smsc47m1_read_value(data, SMSC47M1_REG_PPIN(0)) & 0x05)
== 0x04;
pwm2 = (smsc47m1_read_value(data, SMSC47M1_REG_PPIN(1)) & 0x05)
== 0x04;
if (data->type == smsc47m2) {
fan1 = (smsc47m1_read_value(data, SMSC47M2_REG_TPIN1)
& 0x0d) == 0x09;
fan2 = (smsc47m1_read_value(data, SMSC47M2_REG_TPIN2)
& 0x0d) == 0x09;
fan3 = (smsc47m1_read_value(data, SMSC47M2_REG_TPIN3)
& 0x0d) == 0x0d;
pwm3 = (smsc47m1_read_value(data, SMSC47M2_REG_PPIN3)
& 0x0d) == 0x08;
} else {
fan1 = (smsc47m1_read_value(data, SMSC47M1_REG_TPIN(0))
& 0x05) == 0x05;
fan2 = (smsc47m1_read_value(data, SMSC47M1_REG_TPIN(1))
& 0x05) == 0x05;
fan3 = 0;
pwm3 = 0;
}
if (!(fan1 || fan2 || fan3 || pwm1 || pwm2 || pwm3)) {
dev_warn(dev, "Device not configured, will not use\n");
err = -ENODEV;
goto error_free;
}
/*
* Some values (fan min, clock dividers, pwm registers) may be
* needed before any update is triggered, so we better read them
* at least once here. We don't usually do it that way, but in
* this particular case, manually reading 5 registers out of 8
* doesn't make much sense and we're better using the existing
* function.
*/
smsc47m1_update_device(dev, 1);
/* Register sysfs hooks */
if (fan1) {
err = sysfs_create_group(&dev->kobj,
&smsc47m1_group_fan1);
if (err)
goto error_remove_files;
} else
dev_dbg(dev, "Fan 1 not enabled by hardware, skipping\n");
if (fan2) {
err = sysfs_create_group(&dev->kobj,
&smsc47m1_group_fan2);
if (err)
goto error_remove_files;
} else
dev_dbg(dev, "Fan 2 not enabled by hardware, skipping\n");
if (fan3) {
err = sysfs_create_group(&dev->kobj,
&smsc47m1_group_fan3);
if (err)
goto error_remove_files;
} else if (data->type == smsc47m2)
dev_dbg(dev, "Fan 3 not enabled by hardware, skipping\n");
if (pwm1) {
err = sysfs_create_group(&dev->kobj,
&smsc47m1_group_pwm1);
if (err)
goto error_remove_files;
} else
dev_dbg(dev, "PWM 1 not enabled by hardware, skipping\n");
if (pwm2) {
err = sysfs_create_group(&dev->kobj,
&smsc47m1_group_pwm2);
if (err)
goto error_remove_files;
} else
dev_dbg(dev, "PWM 2 not enabled by hardware, skipping\n");
if (pwm3) {
err = sysfs_create_group(&dev->kobj,
&smsc47m1_group_pwm3);
if (err)
goto error_remove_files;
} else if (data->type == smsc47m2)
dev_dbg(dev, "PWM 3 not enabled by hardware, skipping\n");
err = sysfs_create_group(&dev->kobj, &smsc47m1_group);
if (err)
goto error_remove_files;
data->hwmon_dev = hwmon_device_register(dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
goto error_remove_files;
}
return 0;
error_remove_files:
smsc47m1_remove_files(dev);
error_free:
platform_set_drvdata(pdev, NULL);
kfree(data);
error_release:
smsc47m1_handle_resources(res->start, sio_data->type, RELEASE, dev);
return err;
}
static int __exit smsc47m1_remove(struct platform_device *pdev)
{
struct smsc47m1_data *data = platform_get_drvdata(pdev);
struct resource *res;
hwmon_device_unregister(data->hwmon_dev);
smsc47m1_remove_files(&pdev->dev);
res = platform_get_resource(pdev, IORESOURCE_IO, 0);
smsc47m1_handle_resources(res->start, data->type, RELEASE, &pdev->dev);
platform_set_drvdata(pdev, NULL);
kfree(data);
return 0;
}
static struct smsc47m1_data *smsc47m1_update_device(struct device *dev,
int init)
{
struct smsc47m1_data *data = dev_get_drvdata(dev);
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + HZ + HZ / 2) || init) {
int i, fan_nr;
fan_nr = data->type == smsc47m2 ? 3 : 2;
for (i = 0; i < fan_nr; i++) {
data->fan[i] = smsc47m1_read_value(data,
SMSC47M1_REG_FAN[i]);
data->fan_preload[i] = smsc47m1_read_value(data,
SMSC47M1_REG_FAN_PRELOAD[i]);
data->pwm[i] = smsc47m1_read_value(data,
SMSC47M1_REG_PWM[i]);
}
i = smsc47m1_read_value(data, SMSC47M1_REG_FANDIV);
data->fan_div[0] = (i >> 4) & 0x03;
data->fan_div[1] = i >> 6;
data->alarms = smsc47m1_read_value(data,
SMSC47M1_REG_ALARM) >> 6;
/* Clear alarms if needed */
if (data->alarms)
smsc47m1_write_value(data, SMSC47M1_REG_ALARM, 0xC0);
if (fan_nr >= 3) {
data->fan_div[2] = (smsc47m1_read_value(data,
SMSC47M2_REG_FANDIV3) >> 4) & 0x03;
data->alarms |= (smsc47m1_read_value(data,
SMSC47M2_REG_ALARM6) & 0x40) >> 4;
/* Clear alarm if needed */
if (data->alarms & 0x04)
smsc47m1_write_value(data,
SMSC47M2_REG_ALARM6,
0x40);
}
data->last_updated = jiffies;
}
mutex_unlock(&data->update_lock);
return data;
}
static int __init smsc47m1_device_add(unsigned short address,
const struct smsc47m1_sio_data *sio_data)
{
struct resource res = {
.start = address,
.end = address + SMSC_EXTENT - 1,
.name = DRVNAME,
.flags = IORESOURCE_IO,
};
int err;
err = smsc47m1_handle_resources(address, sio_data->type, CHECK, NULL);
if (err)
goto exit;
pdev = platform_device_alloc(DRVNAME, address);
if (!pdev) {
err = -ENOMEM;
pr_err("Device allocation failed\n");
goto exit;
}
err = platform_device_add_resources(pdev, &res, 1);
if (err) {
pr_err("Device resource addition failed (%d)\n", err);
goto exit_device_put;
}
err = platform_device_add_data(pdev, sio_data,
sizeof(struct smsc47m1_sio_data));
if (err) {
pr_err("Platform data allocation failed\n");
goto exit_device_put;
}
err = platform_device_add(pdev);
if (err) {
pr_err("Device addition failed (%d)\n", err);
goto exit_device_put;
}
return 0;
exit_device_put:
platform_device_put(pdev);
exit:
return err;
}
static int __init sm_smsc47m1_init(void)
{
int err;
unsigned short address;
struct smsc47m1_sio_data sio_data;
err = smsc47m1_find(&sio_data);
if (err < 0)
return err;
address = err;
/* Sets global pdev as a side effect */
err = smsc47m1_device_add(address, &sio_data);
if (err)
return err;
err = platform_driver_probe(&smsc47m1_driver, smsc47m1_probe);
if (err)
goto exit_device;
return 0;
exit_device:
platform_device_unregister(pdev);
smsc47m1_restore(&sio_data);
return err;
}
static void __exit sm_smsc47m1_exit(void)
{
platform_driver_unregister(&smsc47m1_driver);
smsc47m1_restore(pdev->dev.platform_data);
platform_device_unregister(pdev);
}
MODULE_AUTHOR("Mark D. Studebaker <mdsxyz123@yahoo.com>");
MODULE_DESCRIPTION("SMSC LPC47M1xx fan sensors driver");
MODULE_LICENSE("GPL");
module_init(sm_smsc47m1_init);
module_exit(sm_smsc47m1_exit);
| gpl-2.0 |
jcadduono/nethunter_kernel_mako_flo | drivers/staging/rts_pstor/rtsx_card.c | 8169 | 30221 | /* Driver for Realtek PCI-Express card reader
*
* Copyright(c) 2009 Realtek Semiconductor Corp. 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, 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/>.
*
* Author:
* wwang (wei_wang@realsil.com.cn)
* No. 450, Shenhu Road, Suzhou Industry Park, Suzhou, China
*/
#include <linux/blkdev.h>
#include <linux/kthread.h>
#include <linux/sched.h>
#include <linux/workqueue.h>
#include <linux/kernel.h>
#include "rtsx.h"
#include "rtsx_transport.h"
#include "rtsx_scsi.h"
#include "rtsx_card.h"
#include "rtsx_sys.h"
#include "general.h"
#include "sd.h"
#include "xd.h"
#include "ms.h"
void do_remaining_work(struct rtsx_chip *chip)
{
struct sd_info *sd_card = &(chip->sd_card);
#ifdef XD_DELAY_WRITE
struct xd_info *xd_card = &(chip->xd_card);
#endif
struct ms_info *ms_card = &(chip->ms_card);
if (chip->card_ready & SD_CARD) {
if (sd_card->seq_mode) {
rtsx_set_stat(chip, RTSX_STAT_RUN);
sd_card->cleanup_counter++;
} else {
sd_card->cleanup_counter = 0;
}
}
#ifdef XD_DELAY_WRITE
if (chip->card_ready & XD_CARD) {
if (xd_card->delay_write.delay_write_flag) {
rtsx_set_stat(chip, RTSX_STAT_RUN);
xd_card->cleanup_counter++;
} else {
xd_card->cleanup_counter = 0;
}
}
#endif
if (chip->card_ready & MS_CARD) {
if (CHK_MSPRO(ms_card)) {
if (ms_card->seq_mode) {
rtsx_set_stat(chip, RTSX_STAT_RUN);
ms_card->cleanup_counter++;
} else {
ms_card->cleanup_counter = 0;
}
} else {
#ifdef MS_DELAY_WRITE
if (ms_card->delay_write.delay_write_flag) {
rtsx_set_stat(chip, RTSX_STAT_RUN);
ms_card->cleanup_counter++;
} else {
ms_card->cleanup_counter = 0;
}
#endif
}
}
if (sd_card->cleanup_counter > POLLING_WAIT_CNT)
sd_cleanup_work(chip);
if (xd_card->cleanup_counter > POLLING_WAIT_CNT)
xd_cleanup_work(chip);
if (ms_card->cleanup_counter > POLLING_WAIT_CNT)
ms_cleanup_work(chip);
}
void try_to_switch_sdio_ctrl(struct rtsx_chip *chip)
{
u8 reg1 = 0, reg2 = 0;
rtsx_read_register(chip, 0xFF34, ®1);
rtsx_read_register(chip, 0xFF38, ®2);
RTSX_DEBUGP("reg 0xFF34: 0x%x, reg 0xFF38: 0x%x\n", reg1, reg2);
if ((reg1 & 0xC0) && (reg2 & 0xC0)) {
chip->sd_int = 1;
rtsx_write_register(chip, SDIO_CTRL, 0xFF, SDIO_BUS_CTRL | SDIO_CD_CTRL);
rtsx_write_register(chip, PWR_GATE_CTRL, LDO3318_PWR_MASK, LDO_ON);
}
}
#ifdef SUPPORT_SDIO_ASPM
void dynamic_configure_sdio_aspm(struct rtsx_chip *chip)
{
u8 buf[12], reg;
int i;
for (i = 0; i < 12; i++)
rtsx_read_register(chip, 0xFF08 + i, &buf[i]);
rtsx_read_register(chip, 0xFF25, ®);
if ((memcmp(buf, chip->sdio_raw_data, 12) != 0) || (reg & 0x03)) {
chip->sdio_counter = 0;
chip->sdio_idle = 0;
} else {
if (!chip->sdio_idle) {
chip->sdio_counter++;
if (chip->sdio_counter >= SDIO_IDLE_COUNT) {
chip->sdio_counter = 0;
chip->sdio_idle = 1;
}
}
}
memcpy(chip->sdio_raw_data, buf, 12);
if (chip->sdio_idle) {
if (!chip->sdio_aspm) {
RTSX_DEBUGP("SDIO enter ASPM!\n");
rtsx_write_register(chip, ASPM_FORCE_CTL, 0xFC,
0x30 | (chip->aspm_level[1] << 2));
chip->sdio_aspm = 1;
}
} else {
if (chip->sdio_aspm) {
RTSX_DEBUGP("SDIO exit ASPM!\n");
rtsx_write_register(chip, ASPM_FORCE_CTL, 0xFC, 0x30);
chip->sdio_aspm = 0;
}
}
}
#endif
void do_reset_sd_card(struct rtsx_chip *chip)
{
int retval;
RTSX_DEBUGP("%s: %d, card2lun = 0x%x\n", __func__,
chip->sd_reset_counter, chip->card2lun[SD_CARD]);
if (chip->card2lun[SD_CARD] >= MAX_ALLOWED_LUN_CNT) {
clear_bit(SD_NR, &(chip->need_reset));
chip->sd_reset_counter = 0;
chip->sd_show_cnt = 0;
return;
}
chip->rw_fail_cnt[chip->card2lun[SD_CARD]] = 0;
rtsx_set_stat(chip, RTSX_STAT_RUN);
rtsx_write_register(chip, SDIO_CTRL, 0xFF, 0);
retval = reset_sd_card(chip);
if (chip->need_release & SD_CARD)
return;
if (retval == STATUS_SUCCESS) {
clear_bit(SD_NR, &(chip->need_reset));
chip->sd_reset_counter = 0;
chip->sd_show_cnt = 0;
chip->card_ready |= SD_CARD;
chip->card_fail &= ~SD_CARD;
chip->rw_card[chip->card2lun[SD_CARD]] = sd_rw;
} else {
if (chip->sd_io || (chip->sd_reset_counter >= MAX_RESET_CNT)) {
clear_bit(SD_NR, &(chip->need_reset));
chip->sd_reset_counter = 0;
chip->sd_show_cnt = 0;
} else {
chip->sd_reset_counter++;
}
chip->card_ready &= ~SD_CARD;
chip->card_fail |= SD_CARD;
chip->capacity[chip->card2lun[SD_CARD]] = 0;
chip->rw_card[chip->card2lun[SD_CARD]] = NULL;
rtsx_write_register(chip, CARD_OE, SD_OUTPUT_EN, 0);
if (!chip->ft2_fast_mode)
card_power_off(chip, SD_CARD);
if (chip->sd_io) {
chip->sd_int = 0;
try_to_switch_sdio_ctrl(chip);
} else {
disable_card_clock(chip, SD_CARD);
}
}
}
void do_reset_xd_card(struct rtsx_chip *chip)
{
int retval;
RTSX_DEBUGP("%s: %d, card2lun = 0x%x\n", __func__,
chip->xd_reset_counter, chip->card2lun[XD_CARD]);
if (chip->card2lun[XD_CARD] >= MAX_ALLOWED_LUN_CNT) {
clear_bit(XD_NR, &(chip->need_reset));
chip->xd_reset_counter = 0;
chip->xd_show_cnt = 0;
return;
}
chip->rw_fail_cnt[chip->card2lun[XD_CARD]] = 0;
rtsx_set_stat(chip, RTSX_STAT_RUN);
rtsx_write_register(chip, SDIO_CTRL, 0xFF, 0);
retval = reset_xd_card(chip);
if (chip->need_release & XD_CARD)
return;
if (retval == STATUS_SUCCESS) {
clear_bit(XD_NR, &(chip->need_reset));
chip->xd_reset_counter = 0;
chip->card_ready |= XD_CARD;
chip->card_fail &= ~XD_CARD;
chip->rw_card[chip->card2lun[XD_CARD]] = xd_rw;
} else {
if (chip->xd_reset_counter >= MAX_RESET_CNT) {
clear_bit(XD_NR, &(chip->need_reset));
chip->xd_reset_counter = 0;
chip->xd_show_cnt = 0;
} else {
chip->xd_reset_counter++;
}
chip->card_ready &= ~XD_CARD;
chip->card_fail |= XD_CARD;
chip->capacity[chip->card2lun[XD_CARD]] = 0;
chip->rw_card[chip->card2lun[XD_CARD]] = NULL;
rtsx_write_register(chip, CARD_OE, XD_OUTPUT_EN, 0);
if (!chip->ft2_fast_mode)
card_power_off(chip, XD_CARD);
disable_card_clock(chip, XD_CARD);
}
}
void do_reset_ms_card(struct rtsx_chip *chip)
{
int retval;
RTSX_DEBUGP("%s: %d, card2lun = 0x%x\n", __func__,
chip->ms_reset_counter, chip->card2lun[MS_CARD]);
if (chip->card2lun[MS_CARD] >= MAX_ALLOWED_LUN_CNT) {
clear_bit(MS_NR, &(chip->need_reset));
chip->ms_reset_counter = 0;
chip->ms_show_cnt = 0;
return;
}
chip->rw_fail_cnt[chip->card2lun[MS_CARD]] = 0;
rtsx_set_stat(chip, RTSX_STAT_RUN);
rtsx_write_register(chip, SDIO_CTRL, 0xFF, 0);
retval = reset_ms_card(chip);
if (chip->need_release & MS_CARD)
return;
if (retval == STATUS_SUCCESS) {
clear_bit(MS_NR, &(chip->need_reset));
chip->ms_reset_counter = 0;
chip->card_ready |= MS_CARD;
chip->card_fail &= ~MS_CARD;
chip->rw_card[chip->card2lun[MS_CARD]] = ms_rw;
} else {
if (chip->ms_reset_counter >= MAX_RESET_CNT) {
clear_bit(MS_NR, &(chip->need_reset));
chip->ms_reset_counter = 0;
chip->ms_show_cnt = 0;
} else {
chip->ms_reset_counter++;
}
chip->card_ready &= ~MS_CARD;
chip->card_fail |= MS_CARD;
chip->capacity[chip->card2lun[MS_CARD]] = 0;
chip->rw_card[chip->card2lun[MS_CARD]] = NULL;
rtsx_write_register(chip, CARD_OE, MS_OUTPUT_EN, 0);
if (!chip->ft2_fast_mode)
card_power_off(chip, MS_CARD);
disable_card_clock(chip, MS_CARD);
}
}
static void release_sdio(struct rtsx_chip *chip)
{
if (chip->sd_io) {
rtsx_write_register(chip, CARD_STOP, SD_STOP | SD_CLR_ERR,
SD_STOP | SD_CLR_ERR);
if (chip->chip_insert_with_sdio) {
chip->chip_insert_with_sdio = 0;
if (CHECK_PID(chip, 0x5288)) {
rtsx_write_register(chip, 0xFE5A, 0x08, 0x00);
} else {
rtsx_write_register(chip, 0xFE70, 0x80, 0x00);
}
}
rtsx_write_register(chip, SDIO_CTRL, SDIO_CD_CTRL, 0);
chip->sd_io = 0;
}
}
void rtsx_power_off_card(struct rtsx_chip *chip)
{
if ((chip->card_ready & SD_CARD) || chip->sd_io) {
sd_cleanup_work(chip);
sd_power_off_card3v3(chip);
}
if (chip->card_ready & XD_CARD) {
xd_cleanup_work(chip);
xd_power_off_card3v3(chip);
}
if (chip->card_ready & MS_CARD) {
ms_cleanup_work(chip);
ms_power_off_card3v3(chip);
}
}
void rtsx_release_cards(struct rtsx_chip *chip)
{
chip->int_reg = rtsx_readl(chip, RTSX_BIPR);
if ((chip->card_ready & SD_CARD) || chip->sd_io) {
if (chip->int_reg & SD_EXIST)
sd_cleanup_work(chip);
release_sd_card(chip);
}
if (chip->card_ready & XD_CARD) {
if (chip->int_reg & XD_EXIST)
xd_cleanup_work(chip);
release_xd_card(chip);
}
if (chip->card_ready & MS_CARD) {
if (chip->int_reg & MS_EXIST)
ms_cleanup_work(chip);
release_ms_card(chip);
}
}
void rtsx_reset_cards(struct rtsx_chip *chip)
{
if (!chip->need_reset)
return;
rtsx_set_stat(chip, RTSX_STAT_RUN);
rtsx_force_power_on(chip, SSC_PDCTL | OC_PDCTL);
rtsx_disable_aspm(chip);
if ((chip->need_reset & SD_CARD) && chip->chip_insert_with_sdio)
clear_bit(SD_NR, &(chip->need_reset));
if (chip->need_reset & XD_CARD) {
chip->card_exist |= XD_CARD;
if (chip->xd_show_cnt >= MAX_SHOW_CNT) {
do_reset_xd_card(chip);
} else {
chip->xd_show_cnt++;
}
}
if (CHECK_PID(chip, 0x5288) && CHECK_BARO_PKG(chip, QFN)) {
if (chip->card_exist & XD_CARD) {
clear_bit(SD_NR, &(chip->need_reset));
clear_bit(MS_NR, &(chip->need_reset));
}
}
if (chip->need_reset & SD_CARD) {
chip->card_exist |= SD_CARD;
if (chip->sd_show_cnt >= MAX_SHOW_CNT) {
rtsx_write_register(chip, RBCTL, RB_FLUSH, RB_FLUSH);
do_reset_sd_card(chip);
} else {
chip->sd_show_cnt++;
}
}
if (chip->need_reset & MS_CARD) {
chip->card_exist |= MS_CARD;
if (chip->ms_show_cnt >= MAX_SHOW_CNT) {
do_reset_ms_card(chip);
} else {
chip->ms_show_cnt++;
}
}
}
void rtsx_reinit_cards(struct rtsx_chip *chip, int reset_chip)
{
rtsx_set_stat(chip, RTSX_STAT_RUN);
rtsx_force_power_on(chip, SSC_PDCTL | OC_PDCTL);
if (reset_chip)
rtsx_reset_chip(chip);
chip->int_reg = rtsx_readl(chip, RTSX_BIPR);
if ((chip->int_reg & SD_EXIST) && (chip->need_reinit & SD_CARD)) {
release_sdio(chip);
release_sd_card(chip);
wait_timeout(100);
chip->card_exist |= SD_CARD;
do_reset_sd_card(chip);
}
if ((chip->int_reg & XD_EXIST) && (chip->need_reinit & XD_CARD)) {
release_xd_card(chip);
wait_timeout(100);
chip->card_exist |= XD_CARD;
do_reset_xd_card(chip);
}
if ((chip->int_reg & MS_EXIST) && (chip->need_reinit & MS_CARD)) {
release_ms_card(chip);
wait_timeout(100);
chip->card_exist |= MS_CARD;
do_reset_ms_card(chip);
}
chip->need_reinit = 0;
}
#ifdef DISABLE_CARD_INT
void card_cd_debounce(struct rtsx_chip *chip, unsigned long *need_reset, unsigned long *need_release)
{
u8 release_map = 0, reset_map = 0;
chip->int_reg = rtsx_readl(chip, RTSX_BIPR);
if (chip->card_exist) {
if (chip->card_exist & XD_CARD) {
if (!(chip->int_reg & XD_EXIST))
release_map |= XD_CARD;
} else if (chip->card_exist & SD_CARD) {
if (!(chip->int_reg & SD_EXIST))
release_map |= SD_CARD;
} else if (chip->card_exist & MS_CARD) {
if (!(chip->int_reg & MS_EXIST))
release_map |= MS_CARD;
}
} else {
if (chip->int_reg & XD_EXIST) {
reset_map |= XD_CARD;
} else if (chip->int_reg & SD_EXIST) {
reset_map |= SD_CARD;
} else if (chip->int_reg & MS_EXIST) {
reset_map |= MS_CARD;
}
}
if (reset_map) {
int xd_cnt = 0, sd_cnt = 0, ms_cnt = 0;
int i;
for (i = 0; i < (DEBOUNCE_CNT); i++) {
chip->int_reg = rtsx_readl(chip, RTSX_BIPR);
if (chip->int_reg & XD_EXIST) {
xd_cnt++;
} else {
xd_cnt = 0;
}
if (chip->int_reg & SD_EXIST) {
sd_cnt++;
} else {
sd_cnt = 0;
}
if (chip->int_reg & MS_EXIST) {
ms_cnt++;
} else {
ms_cnt = 0;
}
wait_timeout(30);
}
reset_map = 0;
if (!(chip->card_exist & XD_CARD) && (xd_cnt > (DEBOUNCE_CNT-1)))
reset_map |= XD_CARD;
if (!(chip->card_exist & SD_CARD) && (sd_cnt > (DEBOUNCE_CNT-1)))
reset_map |= SD_CARD;
if (!(chip->card_exist & MS_CARD) && (ms_cnt > (DEBOUNCE_CNT-1)))
reset_map |= MS_CARD;
}
if (CHECK_PID(chip, 0x5288) && CHECK_BARO_PKG(chip, QFN))
rtsx_write_register(chip, HOST_SLEEP_STATE, 0xC0, 0x00);
if (need_reset)
*need_reset = reset_map;
if (need_release)
*need_release = release_map;
}
#endif
void rtsx_init_cards(struct rtsx_chip *chip)
{
if (RTSX_TST_DELINK(chip) && (rtsx_get_stat(chip) != RTSX_STAT_SS)) {
RTSX_DEBUGP("Reset chip in polling thread!\n");
rtsx_reset_chip(chip);
RTSX_CLR_DELINK(chip);
}
#ifdef DISABLE_CARD_INT
card_cd_debounce(chip, &(chip->need_reset), &(chip->need_release));
#endif
if (chip->need_release) {
if (CHECK_PID(chip, 0x5288) && CHECK_BARO_PKG(chip, QFN)) {
if (chip->int_reg & XD_EXIST) {
clear_bit(SD_NR, &(chip->need_release));
clear_bit(MS_NR, &(chip->need_release));
}
}
if (!(chip->card_exist & SD_CARD) && !chip->sd_io)
clear_bit(SD_NR, &(chip->need_release));
if (!(chip->card_exist & XD_CARD))
clear_bit(XD_NR, &(chip->need_release));
if (!(chip->card_exist & MS_CARD))
clear_bit(MS_NR, &(chip->need_release));
RTSX_DEBUGP("chip->need_release = 0x%x\n", (unsigned int)(chip->need_release));
#ifdef SUPPORT_OCP
if (chip->need_release) {
if (CHECK_PID(chip, 0x5209)) {
u8 mask = 0, val = 0;
if (CHECK_LUN_MODE(chip, SD_MS_2LUN)) {
if (chip->ocp_stat & (MS_OC_NOW | MS_OC_EVER)) {
mask |= MS_OCP_INT_CLR | MS_OC_CLR;
val |= MS_OCP_INT_CLR | MS_OC_CLR;
}
}
if (chip->ocp_stat & (SD_OC_NOW | SD_OC_EVER)) {
mask |= SD_OCP_INT_CLR | SD_OC_CLR;
val |= SD_OCP_INT_CLR | SD_OC_CLR;
}
if (mask)
rtsx_write_register(chip, OCPCTL, mask, val);
} else {
if (chip->ocp_stat & (CARD_OC_NOW | CARD_OC_EVER))
rtsx_write_register(chip, OCPCLR,
CARD_OC_INT_CLR | CARD_OC_CLR,
CARD_OC_INT_CLR | CARD_OC_CLR);
}
chip->ocp_stat = 0;
}
#endif
if (chip->need_release) {
rtsx_set_stat(chip, RTSX_STAT_RUN);
rtsx_force_power_on(chip, SSC_PDCTL | OC_PDCTL);
}
if (chip->need_release & SD_CARD) {
clear_bit(SD_NR, &(chip->need_release));
chip->card_exist &= ~SD_CARD;
chip->card_ejected &= ~SD_CARD;
chip->card_fail &= ~SD_CARD;
CLR_BIT(chip->lun_mc, chip->card2lun[SD_CARD]);
chip->rw_fail_cnt[chip->card2lun[SD_CARD]] = 0;
rtsx_write_register(chip, RBCTL, RB_FLUSH, RB_FLUSH);
release_sdio(chip);
release_sd_card(chip);
}
if (chip->need_release & XD_CARD) {
clear_bit(XD_NR, &(chip->need_release));
chip->card_exist &= ~XD_CARD;
chip->card_ejected &= ~XD_CARD;
chip->card_fail &= ~XD_CARD;
CLR_BIT(chip->lun_mc, chip->card2lun[XD_CARD]);
chip->rw_fail_cnt[chip->card2lun[XD_CARD]] = 0;
release_xd_card(chip);
if (CHECK_PID(chip, 0x5288) && CHECK_BARO_PKG(chip, QFN))
rtsx_write_register(chip, HOST_SLEEP_STATE, 0xC0, 0xC0);
}
if (chip->need_release & MS_CARD) {
clear_bit(MS_NR, &(chip->need_release));
chip->card_exist &= ~MS_CARD;
chip->card_ejected &= ~MS_CARD;
chip->card_fail &= ~MS_CARD;
CLR_BIT(chip->lun_mc, chip->card2lun[MS_CARD]);
chip->rw_fail_cnt[chip->card2lun[MS_CARD]] = 0;
release_ms_card(chip);
}
RTSX_DEBUGP("chip->card_exist = 0x%x\n", chip->card_exist);
if (!chip->card_exist)
turn_off_led(chip, LED_GPIO);
}
if (chip->need_reset) {
RTSX_DEBUGP("chip->need_reset = 0x%x\n", (unsigned int)(chip->need_reset));
rtsx_reset_cards(chip);
}
if (chip->need_reinit) {
RTSX_DEBUGP("chip->need_reinit = 0x%x\n", (unsigned int)(chip->need_reinit));
rtsx_reinit_cards(chip, 0);
}
}
static inline u8 double_depth(u8 depth)
{
return ((depth > 1) ? (depth - 1) : depth);
}
int switch_ssc_clock(struct rtsx_chip *chip, int clk)
{
struct sd_info *sd_card = &(chip->sd_card);
struct ms_info *ms_card = &(chip->ms_card);
int retval;
u8 N = (u8)(clk - 2), min_N, max_N;
u8 mcu_cnt, div, max_div, ssc_depth, ssc_depth_mask;
int sd_vpclk_phase_reset = 0;
if (chip->cur_clk == clk)
return STATUS_SUCCESS;
if (CHECK_PID(chip, 0x5209)) {
min_N = 80;
max_N = 208;
max_div = CLK_DIV_8;
} else {
min_N = 60;
max_N = 120;
max_div = CLK_DIV_4;
}
if (CHECK_PID(chip, 0x5209) && (chip->cur_card == SD_CARD)) {
struct sd_info *sd_card = &(chip->sd_card);
if (CHK_SD30_SPEED(sd_card) || CHK_MMC_DDR52(sd_card))
sd_vpclk_phase_reset = 1;
}
RTSX_DEBUGP("Switch SSC clock to %dMHz (cur_clk = %d)\n", clk, chip->cur_clk);
if ((clk <= 2) || (N > max_N)) {
TRACE_RET(chip, STATUS_FAIL);
}
mcu_cnt = (u8)(125/clk + 3);
if (CHECK_PID(chip, 0x5209)) {
if (mcu_cnt > 15)
mcu_cnt = 15;
} else {
if (mcu_cnt > 7)
mcu_cnt = 7;
}
div = CLK_DIV_1;
while ((N < min_N) && (div < max_div)) {
N = (N + 2) * 2 - 2;
div++;
}
RTSX_DEBUGP("N = %d, div = %d\n", N, div);
if (chip->ssc_en) {
if (CHECK_PID(chip, 0x5209)) {
if (chip->cur_card == SD_CARD) {
if (CHK_SD_SDR104(sd_card)) {
ssc_depth = chip->ssc_depth_sd_sdr104;
} else if (CHK_SD_SDR50(sd_card)) {
ssc_depth = chip->ssc_depth_sd_sdr50;
} else if (CHK_SD_DDR50(sd_card)) {
ssc_depth = double_depth(chip->ssc_depth_sd_ddr50);
} else if (CHK_SD_HS(sd_card)) {
ssc_depth = double_depth(chip->ssc_depth_sd_hs);
} else if (CHK_MMC_52M(sd_card) || CHK_MMC_DDR52(sd_card)) {
ssc_depth = double_depth(chip->ssc_depth_mmc_52m);
} else {
ssc_depth = double_depth(chip->ssc_depth_low_speed);
}
} else if (chip->cur_card == MS_CARD) {
if (CHK_MSPRO(ms_card)) {
if (CHK_HG8BIT(ms_card)) {
ssc_depth = double_depth(chip->ssc_depth_ms_hg);
} else {
ssc_depth = double_depth(chip->ssc_depth_ms_4bit);
}
} else {
if (CHK_MS4BIT(ms_card)) {
ssc_depth = double_depth(chip->ssc_depth_ms_4bit);
} else {
ssc_depth = double_depth(chip->ssc_depth_low_speed);
}
}
} else {
ssc_depth = double_depth(chip->ssc_depth_low_speed);
}
if (ssc_depth) {
if (div == CLK_DIV_2) {
if (ssc_depth > 1) {
ssc_depth -= 1;
} else {
ssc_depth = SSC_DEPTH_4M;
}
} else if (div == CLK_DIV_4) {
if (ssc_depth > 2) {
ssc_depth -= 2;
} else {
ssc_depth = SSC_DEPTH_4M;
}
} else if (div == CLK_DIV_8) {
if (ssc_depth > 3) {
ssc_depth -= 3;
} else {
ssc_depth = SSC_DEPTH_4M;
}
}
}
} else {
ssc_depth = 0x01;
N -= 2;
}
} else {
ssc_depth = 0;
}
if (CHECK_PID(chip, 0x5209)) {
ssc_depth_mask = SSC_DEPTH_MASK;
} else {
ssc_depth_mask = 0x03;
}
RTSX_DEBUGP("ssc_depth = %d\n", ssc_depth);
rtsx_init_cmd(chip);
rtsx_add_cmd(chip, WRITE_REG_CMD, CLK_CTL, CLK_LOW_FREQ, CLK_LOW_FREQ);
rtsx_add_cmd(chip, WRITE_REG_CMD, CLK_DIV, 0xFF, (div << 4) | mcu_cnt);
rtsx_add_cmd(chip, WRITE_REG_CMD, SSC_CTL1, SSC_RSTB, 0);
rtsx_add_cmd(chip, WRITE_REG_CMD, SSC_CTL2, ssc_depth_mask, ssc_depth);
rtsx_add_cmd(chip, WRITE_REG_CMD, SSC_DIV_N_0, 0xFF, N);
rtsx_add_cmd(chip, WRITE_REG_CMD, SSC_CTL1, SSC_RSTB, SSC_RSTB);
if (sd_vpclk_phase_reset) {
rtsx_add_cmd(chip, WRITE_REG_CMD, SD_VPCLK0_CTL, PHASE_NOT_RESET, 0);
rtsx_add_cmd(chip, WRITE_REG_CMD, SD_VPCLK0_CTL, PHASE_NOT_RESET, PHASE_NOT_RESET);
}
retval = rtsx_send_cmd(chip, 0, WAIT_TIME);
if (retval < 0) {
TRACE_RET(chip, STATUS_ERROR);
}
udelay(10);
RTSX_WRITE_REG(chip, CLK_CTL, CLK_LOW_FREQ, 0);
chip->cur_clk = clk;
return STATUS_SUCCESS;
}
int switch_normal_clock(struct rtsx_chip *chip, int clk)
{
u8 sel, div, mcu_cnt;
int sd_vpclk_phase_reset = 0;
if (chip->cur_clk == clk)
return STATUS_SUCCESS;
if (CHECK_PID(chip, 0x5209) && (chip->cur_card == SD_CARD)) {
struct sd_info *sd_card = &(chip->sd_card);
if (CHK_SD30_SPEED(sd_card) || CHK_MMC_DDR52(sd_card))
sd_vpclk_phase_reset = 1;
}
switch (clk) {
case CLK_20:
RTSX_DEBUGP("Switch clock to 20MHz\n");
sel = SSC_80;
div = CLK_DIV_4;
mcu_cnt = 7;
break;
case CLK_30:
RTSX_DEBUGP("Switch clock to 30MHz\n");
sel = SSC_120;
div = CLK_DIV_4;
mcu_cnt = 7;
break;
case CLK_40:
RTSX_DEBUGP("Switch clock to 40MHz\n");
sel = SSC_80;
div = CLK_DIV_2;
mcu_cnt = 7;
break;
case CLK_50:
RTSX_DEBUGP("Switch clock to 50MHz\n");
sel = SSC_100;
div = CLK_DIV_2;
mcu_cnt = 6;
break;
case CLK_60:
RTSX_DEBUGP("Switch clock to 60MHz\n");
sel = SSC_120;
div = CLK_DIV_2;
mcu_cnt = 6;
break;
case CLK_80:
RTSX_DEBUGP("Switch clock to 80MHz\n");
sel = SSC_80;
div = CLK_DIV_1;
mcu_cnt = 5;
break;
case CLK_100:
RTSX_DEBUGP("Switch clock to 100MHz\n");
sel = SSC_100;
div = CLK_DIV_1;
mcu_cnt = 5;
break;
case CLK_120:
RTSX_DEBUGP("Switch clock to 120MHz\n");
sel = SSC_120;
div = CLK_DIV_1;
mcu_cnt = 5;
break;
case CLK_150:
RTSX_DEBUGP("Switch clock to 150MHz\n");
sel = SSC_150;
div = CLK_DIV_1;
mcu_cnt = 4;
break;
case CLK_200:
RTSX_DEBUGP("Switch clock to 200MHz\n");
sel = SSC_200;
div = CLK_DIV_1;
mcu_cnt = 4;
break;
default:
RTSX_DEBUGP("Try to switch to an illegal clock (%d)\n", clk);
TRACE_RET(chip, STATUS_FAIL);
}
RTSX_WRITE_REG(chip, CLK_CTL, 0xFF, CLK_LOW_FREQ);
if (sd_vpclk_phase_reset) {
RTSX_WRITE_REG(chip, SD_VPCLK0_CTL, PHASE_NOT_RESET, 0);
RTSX_WRITE_REG(chip, SD_VPCLK1_CTL, PHASE_NOT_RESET, 0);
}
RTSX_WRITE_REG(chip, CLK_DIV, 0xFF, (div << 4) | mcu_cnt);
RTSX_WRITE_REG(chip, CLK_SEL, 0xFF, sel);
if (sd_vpclk_phase_reset) {
udelay(200);
RTSX_WRITE_REG(chip, SD_VPCLK0_CTL, PHASE_NOT_RESET, PHASE_NOT_RESET);
RTSX_WRITE_REG(chip, SD_VPCLK1_CTL, PHASE_NOT_RESET, PHASE_NOT_RESET);
udelay(200);
}
RTSX_WRITE_REG(chip, CLK_CTL, 0xFF, 0);
chip->cur_clk = clk;
return STATUS_SUCCESS;
}
void trans_dma_enable(enum dma_data_direction dir, struct rtsx_chip *chip, u32 byte_cnt, u8 pack_size)
{
if (pack_size > DMA_1024)
pack_size = DMA_512;
rtsx_add_cmd(chip, WRITE_REG_CMD, IRQSTAT0, DMA_DONE_INT, DMA_DONE_INT);
rtsx_add_cmd(chip, WRITE_REG_CMD, DMATC3, 0xFF, (u8)(byte_cnt >> 24));
rtsx_add_cmd(chip, WRITE_REG_CMD, DMATC2, 0xFF, (u8)(byte_cnt >> 16));
rtsx_add_cmd(chip, WRITE_REG_CMD, DMATC1, 0xFF, (u8)(byte_cnt >> 8));
rtsx_add_cmd(chip, WRITE_REG_CMD, DMATC0, 0xFF, (u8)byte_cnt);
if (dir == DMA_FROM_DEVICE) {
rtsx_add_cmd(chip, WRITE_REG_CMD, DMACTL, 0x03 | DMA_PACK_SIZE_MASK,
DMA_DIR_FROM_CARD | DMA_EN | pack_size);
} else {
rtsx_add_cmd(chip, WRITE_REG_CMD, DMACTL, 0x03 | DMA_PACK_SIZE_MASK,
DMA_DIR_TO_CARD | DMA_EN | pack_size);
}
rtsx_add_cmd(chip, WRITE_REG_CMD, CARD_DATA_SOURCE, 0x01, RING_BUFFER);
}
int enable_card_clock(struct rtsx_chip *chip, u8 card)
{
u8 clk_en = 0;
if (card & XD_CARD)
clk_en |= XD_CLK_EN;
if (card & SD_CARD)
clk_en |= SD_CLK_EN;
if (card & MS_CARD)
clk_en |= MS_CLK_EN;
RTSX_WRITE_REG(chip, CARD_CLK_EN, clk_en, clk_en);
return STATUS_SUCCESS;
}
int disable_card_clock(struct rtsx_chip *chip, u8 card)
{
u8 clk_en = 0;
if (card & XD_CARD)
clk_en |= XD_CLK_EN;
if (card & SD_CARD)
clk_en |= SD_CLK_EN;
if (card & MS_CARD)
clk_en |= MS_CLK_EN;
RTSX_WRITE_REG(chip, CARD_CLK_EN, clk_en, 0);
return STATUS_SUCCESS;
}
int card_power_on(struct rtsx_chip *chip, u8 card)
{
int retval;
u8 mask, val1, val2;
if (CHECK_LUN_MODE(chip, SD_MS_2LUN) && (card == MS_CARD)) {
mask = MS_POWER_MASK;
val1 = MS_PARTIAL_POWER_ON;
val2 = MS_POWER_ON;
} else {
mask = SD_POWER_MASK;
val1 = SD_PARTIAL_POWER_ON;
val2 = SD_POWER_ON;
}
rtsx_init_cmd(chip);
rtsx_add_cmd(chip, WRITE_REG_CMD, CARD_PWR_CTL, mask, val1);
if (CHECK_PID(chip, 0x5209) && (card == SD_CARD)) {
rtsx_add_cmd(chip, WRITE_REG_CMD, PWR_GATE_CTRL, LDO3318_PWR_MASK, LDO_SUSPEND);
}
retval = rtsx_send_cmd(chip, 0, 100);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, STATUS_FAIL);
}
udelay(chip->pmos_pwr_on_interval);
rtsx_init_cmd(chip);
rtsx_add_cmd(chip, WRITE_REG_CMD, CARD_PWR_CTL, mask, val2);
if (CHECK_PID(chip, 0x5209) && (card == SD_CARD)) {
rtsx_add_cmd(chip, WRITE_REG_CMD, PWR_GATE_CTRL, LDO3318_PWR_MASK, LDO_ON);
}
retval = rtsx_send_cmd(chip, 0, 100);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, STATUS_FAIL);
}
return STATUS_SUCCESS;
}
int card_power_off(struct rtsx_chip *chip, u8 card)
{
u8 mask, val;
if (CHECK_LUN_MODE(chip, SD_MS_2LUN) && (card == MS_CARD)) {
mask = MS_POWER_MASK;
val = MS_POWER_OFF;
} else {
mask = SD_POWER_MASK;
val = SD_POWER_OFF;
}
if (CHECK_PID(chip, 0x5209)) {
mask |= PMOS_STRG_MASK;
val |= PMOS_STRG_400mA;
}
RTSX_WRITE_REG(chip, CARD_PWR_CTL, mask, val);
if (CHECK_PID(chip, 0x5209) && (card == SD_CARD)) {
RTSX_WRITE_REG(chip, PWR_GATE_CTRL, LDO3318_PWR_MASK, LDO_OFF);
}
return STATUS_SUCCESS;
}
int card_rw(struct scsi_cmnd *srb, struct rtsx_chip *chip, u32 sec_addr, u16 sec_cnt)
{
int retval;
unsigned int lun = SCSI_LUN(srb);
int i;
if (chip->rw_card[lun] == NULL) {
TRACE_RET(chip, STATUS_FAIL);
}
for (i = 0; i < 3; i++) {
chip->rw_need_retry = 0;
retval = chip->rw_card[lun](srb, chip, sec_addr, sec_cnt);
if (retval != STATUS_SUCCESS) {
if (rtsx_check_chip_exist(chip) != STATUS_SUCCESS) {
rtsx_release_chip(chip);
TRACE_RET(chip, STATUS_FAIL);
}
if (detect_card_cd(chip, chip->cur_card) != STATUS_SUCCESS) {
TRACE_RET(chip, STATUS_FAIL);
}
if (!chip->rw_need_retry) {
RTSX_DEBUGP("RW fail, but no need to retry\n");
break;
}
} else {
chip->rw_need_retry = 0;
break;
}
RTSX_DEBUGP("Retry RW, (i = %d)\n", i);
}
return retval;
}
int card_share_mode(struct rtsx_chip *chip, int card)
{
u8 mask, value;
if (CHECK_PID(chip, 0x5209) || CHECK_PID(chip, 0x5208)) {
mask = CARD_SHARE_MASK;
if (card == SD_CARD) {
value = CARD_SHARE_48_SD;
} else if (card == MS_CARD) {
value = CARD_SHARE_48_MS;
} else if (card == XD_CARD) {
value = CARD_SHARE_48_XD;
} else {
TRACE_RET(chip, STATUS_FAIL);
}
} else if (CHECK_PID(chip, 0x5288)) {
mask = 0x03;
if (card == SD_CARD) {
value = CARD_SHARE_BAROSSA_SD;
} else if (card == MS_CARD) {
value = CARD_SHARE_BAROSSA_MS;
} else if (card == XD_CARD) {
value = CARD_SHARE_BAROSSA_XD;
} else {
TRACE_RET(chip, STATUS_FAIL);
}
} else {
TRACE_RET(chip, STATUS_FAIL);
}
RTSX_WRITE_REG(chip, CARD_SHARE_MODE, mask, value);
return STATUS_SUCCESS;
}
int select_card(struct rtsx_chip *chip, int card)
{
int retval;
if (chip->cur_card != card) {
u8 mod;
if (card == SD_CARD) {
mod = SD_MOD_SEL;
} else if (card == MS_CARD) {
mod = MS_MOD_SEL;
} else if (card == XD_CARD) {
mod = XD_MOD_SEL;
} else if (card == SPI_CARD) {
mod = SPI_MOD_SEL;
} else {
TRACE_RET(chip, STATUS_FAIL);
}
RTSX_WRITE_REG(chip, CARD_SELECT, 0x07, mod);
chip->cur_card = card;
retval = card_share_mode(chip, card);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, STATUS_FAIL);
}
}
return STATUS_SUCCESS;
}
void toggle_gpio(struct rtsx_chip *chip, u8 gpio)
{
u8 temp_reg;
rtsx_read_register(chip, CARD_GPIO, &temp_reg);
temp_reg ^= (0x01 << gpio);
rtsx_write_register(chip, CARD_GPIO, 0xFF, temp_reg);
}
void turn_on_led(struct rtsx_chip *chip, u8 gpio)
{
if (CHECK_PID(chip, 0x5288)) {
rtsx_write_register(chip, CARD_GPIO, (u8)(1 << gpio), (u8)(1 << gpio));
} else {
rtsx_write_register(chip, CARD_GPIO, (u8)(1 << gpio), 0);
}
}
void turn_off_led(struct rtsx_chip *chip, u8 gpio)
{
if (CHECK_PID(chip, 0x5288)) {
rtsx_write_register(chip, CARD_GPIO, (u8)(1 << gpio), 0);
} else {
rtsx_write_register(chip, CARD_GPIO, (u8)(1 << gpio), (u8)(1 << gpio));
}
}
int detect_card_cd(struct rtsx_chip *chip, int card)
{
u32 card_cd, status;
if (card == SD_CARD) {
card_cd = SD_EXIST;
} else if (card == MS_CARD) {
card_cd = MS_EXIST;
} else if (card == XD_CARD) {
card_cd = XD_EXIST;
} else {
RTSX_DEBUGP("Wrong card type: 0x%x\n", card);
TRACE_RET(chip, STATUS_FAIL);
}
status = rtsx_readl(chip, RTSX_BIPR);
if (!(status & card_cd)) {
TRACE_RET(chip, STATUS_FAIL);
}
return STATUS_SUCCESS;
}
int check_card_exist(struct rtsx_chip *chip, unsigned int lun)
{
if (chip->card_exist & chip->lun2card[lun]) {
return 1;
}
return 0;
}
int check_card_ready(struct rtsx_chip *chip, unsigned int lun)
{
if (chip->card_ready & chip->lun2card[lun]) {
return 1;
}
return 0;
}
int check_card_wp(struct rtsx_chip *chip, unsigned int lun)
{
if (chip->card_wp & chip->lun2card[lun]) {
return 1;
}
return 0;
}
int check_card_fail(struct rtsx_chip *chip, unsigned int lun)
{
if (chip->card_fail & chip->lun2card[lun]) {
return 1;
}
return 0;
}
int check_card_ejected(struct rtsx_chip *chip, unsigned int lun)
{
if (chip->card_ejected & chip->lun2card[lun]) {
return 1;
}
return 0;
}
u8 get_lun_card(struct rtsx_chip *chip, unsigned int lun)
{
if ((chip->card_ready & chip->lun2card[lun]) == XD_CARD) {
return (u8)XD_CARD;
} else if ((chip->card_ready & chip->lun2card[lun]) == SD_CARD) {
return (u8)SD_CARD;
} else if ((chip->card_ready & chip->lun2card[lun]) == MS_CARD) {
return (u8)MS_CARD;
}
return 0;
}
void eject_card(struct rtsx_chip *chip, unsigned int lun)
{
do_remaining_work(chip);
if ((chip->card_ready & chip->lun2card[lun]) == SD_CARD) {
release_sd_card(chip);
chip->card_ejected |= SD_CARD;
chip->card_ready &= ~SD_CARD;
chip->capacity[lun] = 0;
} else if ((chip->card_ready & chip->lun2card[lun]) == XD_CARD) {
release_xd_card(chip);
chip->card_ejected |= XD_CARD;
chip->card_ready &= ~XD_CARD;
chip->capacity[lun] = 0;
} else if ((chip->card_ready & chip->lun2card[lun]) == MS_CARD) {
release_ms_card(chip);
chip->card_ejected |= MS_CARD;
chip->card_ready &= ~MS_CARD;
chip->capacity[lun] = 0;
}
}
| gpl-2.0 |
friedrich420/N4-AEL-Kernel-N910F_EUR-Source- | sound/pci/mixart/mixart_mixer.c | 12777 | 47715 | /*
* Driver for Digigram miXart soundcards
*
* mixer callbacks
*
* Copyright (c) 2003 by Digigram <alsa@digigram.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/time.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <sound/core.h>
#include "mixart.h"
#include "mixart_core.h"
#include "mixart_hwdep.h"
#include <sound/control.h>
#include <sound/tlv.h>
#include "mixart_mixer.h"
static u32 mixart_analog_level[256] = {
0xc2c00000, /* [000] -96.0 dB */
0xc2bf0000, /* [001] -95.5 dB */
0xc2be0000, /* [002] -95.0 dB */
0xc2bd0000, /* [003] -94.5 dB */
0xc2bc0000, /* [004] -94.0 dB */
0xc2bb0000, /* [005] -93.5 dB */
0xc2ba0000, /* [006] -93.0 dB */
0xc2b90000, /* [007] -92.5 dB */
0xc2b80000, /* [008] -92.0 dB */
0xc2b70000, /* [009] -91.5 dB */
0xc2b60000, /* [010] -91.0 dB */
0xc2b50000, /* [011] -90.5 dB */
0xc2b40000, /* [012] -90.0 dB */
0xc2b30000, /* [013] -89.5 dB */
0xc2b20000, /* [014] -89.0 dB */
0xc2b10000, /* [015] -88.5 dB */
0xc2b00000, /* [016] -88.0 dB */
0xc2af0000, /* [017] -87.5 dB */
0xc2ae0000, /* [018] -87.0 dB */
0xc2ad0000, /* [019] -86.5 dB */
0xc2ac0000, /* [020] -86.0 dB */
0xc2ab0000, /* [021] -85.5 dB */
0xc2aa0000, /* [022] -85.0 dB */
0xc2a90000, /* [023] -84.5 dB */
0xc2a80000, /* [024] -84.0 dB */
0xc2a70000, /* [025] -83.5 dB */
0xc2a60000, /* [026] -83.0 dB */
0xc2a50000, /* [027] -82.5 dB */
0xc2a40000, /* [028] -82.0 dB */
0xc2a30000, /* [029] -81.5 dB */
0xc2a20000, /* [030] -81.0 dB */
0xc2a10000, /* [031] -80.5 dB */
0xc2a00000, /* [032] -80.0 dB */
0xc29f0000, /* [033] -79.5 dB */
0xc29e0000, /* [034] -79.0 dB */
0xc29d0000, /* [035] -78.5 dB */
0xc29c0000, /* [036] -78.0 dB */
0xc29b0000, /* [037] -77.5 dB */
0xc29a0000, /* [038] -77.0 dB */
0xc2990000, /* [039] -76.5 dB */
0xc2980000, /* [040] -76.0 dB */
0xc2970000, /* [041] -75.5 dB */
0xc2960000, /* [042] -75.0 dB */
0xc2950000, /* [043] -74.5 dB */
0xc2940000, /* [044] -74.0 dB */
0xc2930000, /* [045] -73.5 dB */
0xc2920000, /* [046] -73.0 dB */
0xc2910000, /* [047] -72.5 dB */
0xc2900000, /* [048] -72.0 dB */
0xc28f0000, /* [049] -71.5 dB */
0xc28e0000, /* [050] -71.0 dB */
0xc28d0000, /* [051] -70.5 dB */
0xc28c0000, /* [052] -70.0 dB */
0xc28b0000, /* [053] -69.5 dB */
0xc28a0000, /* [054] -69.0 dB */
0xc2890000, /* [055] -68.5 dB */
0xc2880000, /* [056] -68.0 dB */
0xc2870000, /* [057] -67.5 dB */
0xc2860000, /* [058] -67.0 dB */
0xc2850000, /* [059] -66.5 dB */
0xc2840000, /* [060] -66.0 dB */
0xc2830000, /* [061] -65.5 dB */
0xc2820000, /* [062] -65.0 dB */
0xc2810000, /* [063] -64.5 dB */
0xc2800000, /* [064] -64.0 dB */
0xc27e0000, /* [065] -63.5 dB */
0xc27c0000, /* [066] -63.0 dB */
0xc27a0000, /* [067] -62.5 dB */
0xc2780000, /* [068] -62.0 dB */
0xc2760000, /* [069] -61.5 dB */
0xc2740000, /* [070] -61.0 dB */
0xc2720000, /* [071] -60.5 dB */
0xc2700000, /* [072] -60.0 dB */
0xc26e0000, /* [073] -59.5 dB */
0xc26c0000, /* [074] -59.0 dB */
0xc26a0000, /* [075] -58.5 dB */
0xc2680000, /* [076] -58.0 dB */
0xc2660000, /* [077] -57.5 dB */
0xc2640000, /* [078] -57.0 dB */
0xc2620000, /* [079] -56.5 dB */
0xc2600000, /* [080] -56.0 dB */
0xc25e0000, /* [081] -55.5 dB */
0xc25c0000, /* [082] -55.0 dB */
0xc25a0000, /* [083] -54.5 dB */
0xc2580000, /* [084] -54.0 dB */
0xc2560000, /* [085] -53.5 dB */
0xc2540000, /* [086] -53.0 dB */
0xc2520000, /* [087] -52.5 dB */
0xc2500000, /* [088] -52.0 dB */
0xc24e0000, /* [089] -51.5 dB */
0xc24c0000, /* [090] -51.0 dB */
0xc24a0000, /* [091] -50.5 dB */
0xc2480000, /* [092] -50.0 dB */
0xc2460000, /* [093] -49.5 dB */
0xc2440000, /* [094] -49.0 dB */
0xc2420000, /* [095] -48.5 dB */
0xc2400000, /* [096] -48.0 dB */
0xc23e0000, /* [097] -47.5 dB */
0xc23c0000, /* [098] -47.0 dB */
0xc23a0000, /* [099] -46.5 dB */
0xc2380000, /* [100] -46.0 dB */
0xc2360000, /* [101] -45.5 dB */
0xc2340000, /* [102] -45.0 dB */
0xc2320000, /* [103] -44.5 dB */
0xc2300000, /* [104] -44.0 dB */
0xc22e0000, /* [105] -43.5 dB */
0xc22c0000, /* [106] -43.0 dB */
0xc22a0000, /* [107] -42.5 dB */
0xc2280000, /* [108] -42.0 dB */
0xc2260000, /* [109] -41.5 dB */
0xc2240000, /* [110] -41.0 dB */
0xc2220000, /* [111] -40.5 dB */
0xc2200000, /* [112] -40.0 dB */
0xc21e0000, /* [113] -39.5 dB */
0xc21c0000, /* [114] -39.0 dB */
0xc21a0000, /* [115] -38.5 dB */
0xc2180000, /* [116] -38.0 dB */
0xc2160000, /* [117] -37.5 dB */
0xc2140000, /* [118] -37.0 dB */
0xc2120000, /* [119] -36.5 dB */
0xc2100000, /* [120] -36.0 dB */
0xc20e0000, /* [121] -35.5 dB */
0xc20c0000, /* [122] -35.0 dB */
0xc20a0000, /* [123] -34.5 dB */
0xc2080000, /* [124] -34.0 dB */
0xc2060000, /* [125] -33.5 dB */
0xc2040000, /* [126] -33.0 dB */
0xc2020000, /* [127] -32.5 dB */
0xc2000000, /* [128] -32.0 dB */
0xc1fc0000, /* [129] -31.5 dB */
0xc1f80000, /* [130] -31.0 dB */
0xc1f40000, /* [131] -30.5 dB */
0xc1f00000, /* [132] -30.0 dB */
0xc1ec0000, /* [133] -29.5 dB */
0xc1e80000, /* [134] -29.0 dB */
0xc1e40000, /* [135] -28.5 dB */
0xc1e00000, /* [136] -28.0 dB */
0xc1dc0000, /* [137] -27.5 dB */
0xc1d80000, /* [138] -27.0 dB */
0xc1d40000, /* [139] -26.5 dB */
0xc1d00000, /* [140] -26.0 dB */
0xc1cc0000, /* [141] -25.5 dB */
0xc1c80000, /* [142] -25.0 dB */
0xc1c40000, /* [143] -24.5 dB */
0xc1c00000, /* [144] -24.0 dB */
0xc1bc0000, /* [145] -23.5 dB */
0xc1b80000, /* [146] -23.0 dB */
0xc1b40000, /* [147] -22.5 dB */
0xc1b00000, /* [148] -22.0 dB */
0xc1ac0000, /* [149] -21.5 dB */
0xc1a80000, /* [150] -21.0 dB */
0xc1a40000, /* [151] -20.5 dB */
0xc1a00000, /* [152] -20.0 dB */
0xc19c0000, /* [153] -19.5 dB */
0xc1980000, /* [154] -19.0 dB */
0xc1940000, /* [155] -18.5 dB */
0xc1900000, /* [156] -18.0 dB */
0xc18c0000, /* [157] -17.5 dB */
0xc1880000, /* [158] -17.0 dB */
0xc1840000, /* [159] -16.5 dB */
0xc1800000, /* [160] -16.0 dB */
0xc1780000, /* [161] -15.5 dB */
0xc1700000, /* [162] -15.0 dB */
0xc1680000, /* [163] -14.5 dB */
0xc1600000, /* [164] -14.0 dB */
0xc1580000, /* [165] -13.5 dB */
0xc1500000, /* [166] -13.0 dB */
0xc1480000, /* [167] -12.5 dB */
0xc1400000, /* [168] -12.0 dB */
0xc1380000, /* [169] -11.5 dB */
0xc1300000, /* [170] -11.0 dB */
0xc1280000, /* [171] -10.5 dB */
0xc1200000, /* [172] -10.0 dB */
0xc1180000, /* [173] -9.5 dB */
0xc1100000, /* [174] -9.0 dB */
0xc1080000, /* [175] -8.5 dB */
0xc1000000, /* [176] -8.0 dB */
0xc0f00000, /* [177] -7.5 dB */
0xc0e00000, /* [178] -7.0 dB */
0xc0d00000, /* [179] -6.5 dB */
0xc0c00000, /* [180] -6.0 dB */
0xc0b00000, /* [181] -5.5 dB */
0xc0a00000, /* [182] -5.0 dB */
0xc0900000, /* [183] -4.5 dB */
0xc0800000, /* [184] -4.0 dB */
0xc0600000, /* [185] -3.5 dB */
0xc0400000, /* [186] -3.0 dB */
0xc0200000, /* [187] -2.5 dB */
0xc0000000, /* [188] -2.0 dB */
0xbfc00000, /* [189] -1.5 dB */
0xbf800000, /* [190] -1.0 dB */
0xbf000000, /* [191] -0.5 dB */
0x00000000, /* [192] 0.0 dB */
0x3f000000, /* [193] 0.5 dB */
0x3f800000, /* [194] 1.0 dB */
0x3fc00000, /* [195] 1.5 dB */
0x40000000, /* [196] 2.0 dB */
0x40200000, /* [197] 2.5 dB */
0x40400000, /* [198] 3.0 dB */
0x40600000, /* [199] 3.5 dB */
0x40800000, /* [200] 4.0 dB */
0x40900000, /* [201] 4.5 dB */
0x40a00000, /* [202] 5.0 dB */
0x40b00000, /* [203] 5.5 dB */
0x40c00000, /* [204] 6.0 dB */
0x40d00000, /* [205] 6.5 dB */
0x40e00000, /* [206] 7.0 dB */
0x40f00000, /* [207] 7.5 dB */
0x41000000, /* [208] 8.0 dB */
0x41080000, /* [209] 8.5 dB */
0x41100000, /* [210] 9.0 dB */
0x41180000, /* [211] 9.5 dB */
0x41200000, /* [212] 10.0 dB */
0x41280000, /* [213] 10.5 dB */
0x41300000, /* [214] 11.0 dB */
0x41380000, /* [215] 11.5 dB */
0x41400000, /* [216] 12.0 dB */
0x41480000, /* [217] 12.5 dB */
0x41500000, /* [218] 13.0 dB */
0x41580000, /* [219] 13.5 dB */
0x41600000, /* [220] 14.0 dB */
0x41680000, /* [221] 14.5 dB */
0x41700000, /* [222] 15.0 dB */
0x41780000, /* [223] 15.5 dB */
0x41800000, /* [224] 16.0 dB */
0x41840000, /* [225] 16.5 dB */
0x41880000, /* [226] 17.0 dB */
0x418c0000, /* [227] 17.5 dB */
0x41900000, /* [228] 18.0 dB */
0x41940000, /* [229] 18.5 dB */
0x41980000, /* [230] 19.0 dB */
0x419c0000, /* [231] 19.5 dB */
0x41a00000, /* [232] 20.0 dB */
0x41a40000, /* [233] 20.5 dB */
0x41a80000, /* [234] 21.0 dB */
0x41ac0000, /* [235] 21.5 dB */
0x41b00000, /* [236] 22.0 dB */
0x41b40000, /* [237] 22.5 dB */
0x41b80000, /* [238] 23.0 dB */
0x41bc0000, /* [239] 23.5 dB */
0x41c00000, /* [240] 24.0 dB */
0x41c40000, /* [241] 24.5 dB */
0x41c80000, /* [242] 25.0 dB */
0x41cc0000, /* [243] 25.5 dB */
0x41d00000, /* [244] 26.0 dB */
0x41d40000, /* [245] 26.5 dB */
0x41d80000, /* [246] 27.0 dB */
0x41dc0000, /* [247] 27.5 dB */
0x41e00000, /* [248] 28.0 dB */
0x41e40000, /* [249] 28.5 dB */
0x41e80000, /* [250] 29.0 dB */
0x41ec0000, /* [251] 29.5 dB */
0x41f00000, /* [252] 30.0 dB */
0x41f40000, /* [253] 30.5 dB */
0x41f80000, /* [254] 31.0 dB */
0x41fc0000, /* [255] 31.5 dB */
};
#define MIXART_ANALOG_CAPTURE_LEVEL_MIN 0 /* -96.0 dB + 8.0 dB = -88.0 dB */
#define MIXART_ANALOG_CAPTURE_LEVEL_MAX 255 /* 31.5 dB + 8.0 dB = 39.5 dB */
#define MIXART_ANALOG_CAPTURE_ZERO_LEVEL 176 /* -8.0 dB + 8.0 dB = 0.0 dB */
#define MIXART_ANALOG_PLAYBACK_LEVEL_MIN 0 /* -96.0 dB + 1.5 dB = -94.5 dB (possible is down to (-114.0+1.5)dB) */
#define MIXART_ANALOG_PLAYBACK_LEVEL_MAX 192 /* 0.0 dB + 1.5 dB = 1.5 dB */
#define MIXART_ANALOG_PLAYBACK_ZERO_LEVEL 189 /* -1.5 dB + 1.5 dB = 0.0 dB */
static int mixart_update_analog_audio_level(struct snd_mixart* chip, int is_capture)
{
int i, err;
struct mixart_msg request;
struct mixart_io_level io_level;
struct mixart_return_uid resp;
memset(&io_level, 0, sizeof(io_level));
io_level.channel = -1; /* left and right */
for(i=0; i<2; i++) {
if(is_capture) {
io_level.level[i].analog_level = mixart_analog_level[chip->analog_capture_volume[i]];
} else {
if(chip->analog_playback_active[i])
io_level.level[i].analog_level = mixart_analog_level[chip->analog_playback_volume[i]];
else
io_level.level[i].analog_level = mixart_analog_level[MIXART_ANALOG_PLAYBACK_LEVEL_MIN];
}
}
if(is_capture) request.uid = chip->uid_in_analog_physio;
else request.uid = chip->uid_out_analog_physio;
request.message_id = MSG_PHYSICALIO_SET_LEVEL;
request.data = &io_level;
request.size = sizeof(io_level);
err = snd_mixart_send_msg(chip->mgr, &request, sizeof(resp), &resp);
if((err<0) || (resp.error_code)) {
snd_printk(KERN_DEBUG "error MSG_PHYSICALIO_SET_LEVEL card(%d) is_capture(%d) error_code(%x)\n", chip->chip_idx, is_capture, resp.error_code);
return -EINVAL;
}
return 0;
}
/*
* analog level control
*/
static int mixart_analog_vol_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
if(kcontrol->private_value == 0) { /* playback */
uinfo->value.integer.min = MIXART_ANALOG_PLAYBACK_LEVEL_MIN; /* -96 dB */
uinfo->value.integer.max = MIXART_ANALOG_PLAYBACK_LEVEL_MAX; /* 0 dB */
} else { /* capture */
uinfo->value.integer.min = MIXART_ANALOG_CAPTURE_LEVEL_MIN; /* -96 dB */
uinfo->value.integer.max = MIXART_ANALOG_CAPTURE_LEVEL_MAX; /* 31.5 dB */
}
return 0;
}
static int mixart_analog_vol_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_mixart *chip = snd_kcontrol_chip(kcontrol);
mutex_lock(&chip->mgr->mixer_mutex);
if(kcontrol->private_value == 0) { /* playback */
ucontrol->value.integer.value[0] = chip->analog_playback_volume[0];
ucontrol->value.integer.value[1] = chip->analog_playback_volume[1];
} else { /* capture */
ucontrol->value.integer.value[0] = chip->analog_capture_volume[0];
ucontrol->value.integer.value[1] = chip->analog_capture_volume[1];
}
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int mixart_analog_vol_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_mixart *chip = snd_kcontrol_chip(kcontrol);
int changed = 0;
int is_capture, i;
mutex_lock(&chip->mgr->mixer_mutex);
is_capture = (kcontrol->private_value != 0);
for (i = 0; i < 2; i++) {
int new_volume = ucontrol->value.integer.value[i];
int *stored_volume = is_capture ?
&chip->analog_capture_volume[i] :
&chip->analog_playback_volume[i];
if (is_capture) {
if (new_volume < MIXART_ANALOG_CAPTURE_LEVEL_MIN ||
new_volume > MIXART_ANALOG_CAPTURE_LEVEL_MAX)
continue;
} else {
if (new_volume < MIXART_ANALOG_PLAYBACK_LEVEL_MIN ||
new_volume > MIXART_ANALOG_PLAYBACK_LEVEL_MAX)
continue;
}
if (*stored_volume != new_volume) {
*stored_volume = new_volume;
changed = 1;
}
}
if (changed)
mixart_update_analog_audio_level(chip, is_capture);
mutex_unlock(&chip->mgr->mixer_mutex);
return changed;
}
static const DECLARE_TLV_DB_SCALE(db_scale_analog, -9600, 50, 0);
static struct snd_kcontrol_new mixart_control_analog_level = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
/* name will be filled later */
.info = mixart_analog_vol_info,
.get = mixart_analog_vol_get,
.put = mixart_analog_vol_put,
.tlv = { .p = db_scale_analog },
};
/* shared */
#define mixart_sw_info snd_ctl_boolean_stereo_info
static int mixart_audio_sw_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_mixart *chip = snd_kcontrol_chip(kcontrol);
mutex_lock(&chip->mgr->mixer_mutex);
ucontrol->value.integer.value[0] = chip->analog_playback_active[0];
ucontrol->value.integer.value[1] = chip->analog_playback_active[1];
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int mixart_audio_sw_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_mixart *chip = snd_kcontrol_chip(kcontrol);
int i, changed = 0;
mutex_lock(&chip->mgr->mixer_mutex);
for (i = 0; i < 2; i++) {
if (chip->analog_playback_active[i] !=
ucontrol->value.integer.value[i]) {
chip->analog_playback_active[i] =
!!ucontrol->value.integer.value[i];
changed = 1;
}
}
if (changed) /* update playback levels */
mixart_update_analog_audio_level(chip, 0);
mutex_unlock(&chip->mgr->mixer_mutex);
return changed;
}
static struct snd_kcontrol_new mixart_control_output_switch = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Master Playback Switch",
.info = mixart_sw_info, /* shared */
.get = mixart_audio_sw_get,
.put = mixart_audio_sw_put
};
static u32 mixart_digital_level[256] = {
0x00000000, /* [000] = 0.00e+000 = mute if <= -109.5dB */
0x366e1c7a, /* [001] = 3.55e-006 = pow(10.0, 0.05 * -109.0dB) */
0x367c3860, /* [002] = 3.76e-006 = pow(10.0, 0.05 * -108.5dB) */
0x36859525, /* [003] = 3.98e-006 = pow(10.0, 0.05 * -108.0dB) */
0x368d7f74, /* [004] = 4.22e-006 = pow(10.0, 0.05 * -107.5dB) */
0x3695e1d4, /* [005] = 4.47e-006 = pow(10.0, 0.05 * -107.0dB) */
0x369ec362, /* [006] = 4.73e-006 = pow(10.0, 0.05 * -106.5dB) */
0x36a82ba8, /* [007] = 5.01e-006 = pow(10.0, 0.05 * -106.0dB) */
0x36b222a0, /* [008] = 5.31e-006 = pow(10.0, 0.05 * -105.5dB) */
0x36bcb0c1, /* [009] = 5.62e-006 = pow(10.0, 0.05 * -105.0dB) */
0x36c7defd, /* [010] = 5.96e-006 = pow(10.0, 0.05 * -104.5dB) */
0x36d3b6d3, /* [011] = 6.31e-006 = pow(10.0, 0.05 * -104.0dB) */
0x36e0424e, /* [012] = 6.68e-006 = pow(10.0, 0.05 * -103.5dB) */
0x36ed8c14, /* [013] = 7.08e-006 = pow(10.0, 0.05 * -103.0dB) */
0x36fb9f6c, /* [014] = 7.50e-006 = pow(10.0, 0.05 * -102.5dB) */
0x37054423, /* [015] = 7.94e-006 = pow(10.0, 0.05 * -102.0dB) */
0x370d29a5, /* [016] = 8.41e-006 = pow(10.0, 0.05 * -101.5dB) */
0x371586f0, /* [017] = 8.91e-006 = pow(10.0, 0.05 * -101.0dB) */
0x371e631b, /* [018] = 9.44e-006 = pow(10.0, 0.05 * -100.5dB) */
0x3727c5ac, /* [019] = 1.00e-005 = pow(10.0, 0.05 * -100.0dB) */
0x3731b69a, /* [020] = 1.06e-005 = pow(10.0, 0.05 * -99.5dB) */
0x373c3e53, /* [021] = 1.12e-005 = pow(10.0, 0.05 * -99.0dB) */
0x374765c8, /* [022] = 1.19e-005 = pow(10.0, 0.05 * -98.5dB) */
0x3753366f, /* [023] = 1.26e-005 = pow(10.0, 0.05 * -98.0dB) */
0x375fba4f, /* [024] = 1.33e-005 = pow(10.0, 0.05 * -97.5dB) */
0x376cfc07, /* [025] = 1.41e-005 = pow(10.0, 0.05 * -97.0dB) */
0x377b06d5, /* [026] = 1.50e-005 = pow(10.0, 0.05 * -96.5dB) */
0x3784f352, /* [027] = 1.58e-005 = pow(10.0, 0.05 * -96.0dB) */
0x378cd40b, /* [028] = 1.68e-005 = pow(10.0, 0.05 * -95.5dB) */
0x37952c42, /* [029] = 1.78e-005 = pow(10.0, 0.05 * -95.0dB) */
0x379e030e, /* [030] = 1.88e-005 = pow(10.0, 0.05 * -94.5dB) */
0x37a75fef, /* [031] = 2.00e-005 = pow(10.0, 0.05 * -94.0dB) */
0x37b14ad5, /* [032] = 2.11e-005 = pow(10.0, 0.05 * -93.5dB) */
0x37bbcc2c, /* [033] = 2.24e-005 = pow(10.0, 0.05 * -93.0dB) */
0x37c6ecdd, /* [034] = 2.37e-005 = pow(10.0, 0.05 * -92.5dB) */
0x37d2b65a, /* [035] = 2.51e-005 = pow(10.0, 0.05 * -92.0dB) */
0x37df32a3, /* [036] = 2.66e-005 = pow(10.0, 0.05 * -91.5dB) */
0x37ec6c50, /* [037] = 2.82e-005 = pow(10.0, 0.05 * -91.0dB) */
0x37fa6e9b, /* [038] = 2.99e-005 = pow(10.0, 0.05 * -90.5dB) */
0x3804a2b3, /* [039] = 3.16e-005 = pow(10.0, 0.05 * -90.0dB) */
0x380c7ea4, /* [040] = 3.35e-005 = pow(10.0, 0.05 * -89.5dB) */
0x3814d1cc, /* [041] = 3.55e-005 = pow(10.0, 0.05 * -89.0dB) */
0x381da33c, /* [042] = 3.76e-005 = pow(10.0, 0.05 * -88.5dB) */
0x3826fa6f, /* [043] = 3.98e-005 = pow(10.0, 0.05 * -88.0dB) */
0x3830df51, /* [044] = 4.22e-005 = pow(10.0, 0.05 * -87.5dB) */
0x383b5a49, /* [045] = 4.47e-005 = pow(10.0, 0.05 * -87.0dB) */
0x3846743b, /* [046] = 4.73e-005 = pow(10.0, 0.05 * -86.5dB) */
0x38523692, /* [047] = 5.01e-005 = pow(10.0, 0.05 * -86.0dB) */
0x385eab48, /* [048] = 5.31e-005 = pow(10.0, 0.05 * -85.5dB) */
0x386bdcf1, /* [049] = 5.62e-005 = pow(10.0, 0.05 * -85.0dB) */
0x3879d6bc, /* [050] = 5.96e-005 = pow(10.0, 0.05 * -84.5dB) */
0x38845244, /* [051] = 6.31e-005 = pow(10.0, 0.05 * -84.0dB) */
0x388c2971, /* [052] = 6.68e-005 = pow(10.0, 0.05 * -83.5dB) */
0x3894778d, /* [053] = 7.08e-005 = pow(10.0, 0.05 * -83.0dB) */
0x389d43a4, /* [054] = 7.50e-005 = pow(10.0, 0.05 * -82.5dB) */
0x38a6952c, /* [055] = 7.94e-005 = pow(10.0, 0.05 * -82.0dB) */
0x38b0740f, /* [056] = 8.41e-005 = pow(10.0, 0.05 * -81.5dB) */
0x38bae8ac, /* [057] = 8.91e-005 = pow(10.0, 0.05 * -81.0dB) */
0x38c5fbe2, /* [058] = 9.44e-005 = pow(10.0, 0.05 * -80.5dB) */
0x38d1b717, /* [059] = 1.00e-004 = pow(10.0, 0.05 * -80.0dB) */
0x38de2440, /* [060] = 1.06e-004 = pow(10.0, 0.05 * -79.5dB) */
0x38eb4de8, /* [061] = 1.12e-004 = pow(10.0, 0.05 * -79.0dB) */
0x38f93f3a, /* [062] = 1.19e-004 = pow(10.0, 0.05 * -78.5dB) */
0x39040206, /* [063] = 1.26e-004 = pow(10.0, 0.05 * -78.0dB) */
0x390bd472, /* [064] = 1.33e-004 = pow(10.0, 0.05 * -77.5dB) */
0x39141d84, /* [065] = 1.41e-004 = pow(10.0, 0.05 * -77.0dB) */
0x391ce445, /* [066] = 1.50e-004 = pow(10.0, 0.05 * -76.5dB) */
0x39263027, /* [067] = 1.58e-004 = pow(10.0, 0.05 * -76.0dB) */
0x3930090d, /* [068] = 1.68e-004 = pow(10.0, 0.05 * -75.5dB) */
0x393a7753, /* [069] = 1.78e-004 = pow(10.0, 0.05 * -75.0dB) */
0x394583d2, /* [070] = 1.88e-004 = pow(10.0, 0.05 * -74.5dB) */
0x395137ea, /* [071] = 2.00e-004 = pow(10.0, 0.05 * -74.0dB) */
0x395d9d8a, /* [072] = 2.11e-004 = pow(10.0, 0.05 * -73.5dB) */
0x396abf37, /* [073] = 2.24e-004 = pow(10.0, 0.05 * -73.0dB) */
0x3978a814, /* [074] = 2.37e-004 = pow(10.0, 0.05 * -72.5dB) */
0x3983b1f8, /* [075] = 2.51e-004 = pow(10.0, 0.05 * -72.0dB) */
0x398b7fa6, /* [076] = 2.66e-004 = pow(10.0, 0.05 * -71.5dB) */
0x3993c3b2, /* [077] = 2.82e-004 = pow(10.0, 0.05 * -71.0dB) */
0x399c8521, /* [078] = 2.99e-004 = pow(10.0, 0.05 * -70.5dB) */
0x39a5cb5f, /* [079] = 3.16e-004 = pow(10.0, 0.05 * -70.0dB) */
0x39af9e4d, /* [080] = 3.35e-004 = pow(10.0, 0.05 * -69.5dB) */
0x39ba063f, /* [081] = 3.55e-004 = pow(10.0, 0.05 * -69.0dB) */
0x39c50c0b, /* [082] = 3.76e-004 = pow(10.0, 0.05 * -68.5dB) */
0x39d0b90a, /* [083] = 3.98e-004 = pow(10.0, 0.05 * -68.0dB) */
0x39dd1726, /* [084] = 4.22e-004 = pow(10.0, 0.05 * -67.5dB) */
0x39ea30db, /* [085] = 4.47e-004 = pow(10.0, 0.05 * -67.0dB) */
0x39f81149, /* [086] = 4.73e-004 = pow(10.0, 0.05 * -66.5dB) */
0x3a03621b, /* [087] = 5.01e-004 = pow(10.0, 0.05 * -66.0dB) */
0x3a0b2b0d, /* [088] = 5.31e-004 = pow(10.0, 0.05 * -65.5dB) */
0x3a136a16, /* [089] = 5.62e-004 = pow(10.0, 0.05 * -65.0dB) */
0x3a1c2636, /* [090] = 5.96e-004 = pow(10.0, 0.05 * -64.5dB) */
0x3a2566d5, /* [091] = 6.31e-004 = pow(10.0, 0.05 * -64.0dB) */
0x3a2f33cd, /* [092] = 6.68e-004 = pow(10.0, 0.05 * -63.5dB) */
0x3a399570, /* [093] = 7.08e-004 = pow(10.0, 0.05 * -63.0dB) */
0x3a44948c, /* [094] = 7.50e-004 = pow(10.0, 0.05 * -62.5dB) */
0x3a503a77, /* [095] = 7.94e-004 = pow(10.0, 0.05 * -62.0dB) */
0x3a5c9112, /* [096] = 8.41e-004 = pow(10.0, 0.05 * -61.5dB) */
0x3a69a2d7, /* [097] = 8.91e-004 = pow(10.0, 0.05 * -61.0dB) */
0x3a777ada, /* [098] = 9.44e-004 = pow(10.0, 0.05 * -60.5dB) */
0x3a83126f, /* [099] = 1.00e-003 = pow(10.0, 0.05 * -60.0dB) */
0x3a8ad6a8, /* [100] = 1.06e-003 = pow(10.0, 0.05 * -59.5dB) */
0x3a9310b1, /* [101] = 1.12e-003 = pow(10.0, 0.05 * -59.0dB) */
0x3a9bc784, /* [102] = 1.19e-003 = pow(10.0, 0.05 * -58.5dB) */
0x3aa50287, /* [103] = 1.26e-003 = pow(10.0, 0.05 * -58.0dB) */
0x3aaec98e, /* [104] = 1.33e-003 = pow(10.0, 0.05 * -57.5dB) */
0x3ab924e5, /* [105] = 1.41e-003 = pow(10.0, 0.05 * -57.0dB) */
0x3ac41d56, /* [106] = 1.50e-003 = pow(10.0, 0.05 * -56.5dB) */
0x3acfbc31, /* [107] = 1.58e-003 = pow(10.0, 0.05 * -56.0dB) */
0x3adc0b51, /* [108] = 1.68e-003 = pow(10.0, 0.05 * -55.5dB) */
0x3ae91528, /* [109] = 1.78e-003 = pow(10.0, 0.05 * -55.0dB) */
0x3af6e4c6, /* [110] = 1.88e-003 = pow(10.0, 0.05 * -54.5dB) */
0x3b02c2f2, /* [111] = 2.00e-003 = pow(10.0, 0.05 * -54.0dB) */
0x3b0a8276, /* [112] = 2.11e-003 = pow(10.0, 0.05 * -53.5dB) */
0x3b12b782, /* [113] = 2.24e-003 = pow(10.0, 0.05 * -53.0dB) */
0x3b1b690d, /* [114] = 2.37e-003 = pow(10.0, 0.05 * -52.5dB) */
0x3b249e76, /* [115] = 2.51e-003 = pow(10.0, 0.05 * -52.0dB) */
0x3b2e5f8f, /* [116] = 2.66e-003 = pow(10.0, 0.05 * -51.5dB) */
0x3b38b49f, /* [117] = 2.82e-003 = pow(10.0, 0.05 * -51.0dB) */
0x3b43a669, /* [118] = 2.99e-003 = pow(10.0, 0.05 * -50.5dB) */
0x3b4f3e37, /* [119] = 3.16e-003 = pow(10.0, 0.05 * -50.0dB) */
0x3b5b85e0, /* [120] = 3.35e-003 = pow(10.0, 0.05 * -49.5dB) */
0x3b6887cf, /* [121] = 3.55e-003 = pow(10.0, 0.05 * -49.0dB) */
0x3b764f0e, /* [122] = 3.76e-003 = pow(10.0, 0.05 * -48.5dB) */
0x3b8273a6, /* [123] = 3.98e-003 = pow(10.0, 0.05 * -48.0dB) */
0x3b8a2e77, /* [124] = 4.22e-003 = pow(10.0, 0.05 * -47.5dB) */
0x3b925e89, /* [125] = 4.47e-003 = pow(10.0, 0.05 * -47.0dB) */
0x3b9b0ace, /* [126] = 4.73e-003 = pow(10.0, 0.05 * -46.5dB) */
0x3ba43aa2, /* [127] = 5.01e-003 = pow(10.0, 0.05 * -46.0dB) */
0x3badf5d1, /* [128] = 5.31e-003 = pow(10.0, 0.05 * -45.5dB) */
0x3bb8449c, /* [129] = 5.62e-003 = pow(10.0, 0.05 * -45.0dB) */
0x3bc32fc3, /* [130] = 5.96e-003 = pow(10.0, 0.05 * -44.5dB) */
0x3bcec08a, /* [131] = 6.31e-003 = pow(10.0, 0.05 * -44.0dB) */
0x3bdb00c0, /* [132] = 6.68e-003 = pow(10.0, 0.05 * -43.5dB) */
0x3be7facc, /* [133] = 7.08e-003 = pow(10.0, 0.05 * -43.0dB) */
0x3bf5b9b0, /* [134] = 7.50e-003 = pow(10.0, 0.05 * -42.5dB) */
0x3c02248a, /* [135] = 7.94e-003 = pow(10.0, 0.05 * -42.0dB) */
0x3c09daac, /* [136] = 8.41e-003 = pow(10.0, 0.05 * -41.5dB) */
0x3c1205c6, /* [137] = 8.91e-003 = pow(10.0, 0.05 * -41.0dB) */
0x3c1aacc8, /* [138] = 9.44e-003 = pow(10.0, 0.05 * -40.5dB) */
0x3c23d70a, /* [139] = 1.00e-002 = pow(10.0, 0.05 * -40.0dB) */
0x3c2d8c52, /* [140] = 1.06e-002 = pow(10.0, 0.05 * -39.5dB) */
0x3c37d4dd, /* [141] = 1.12e-002 = pow(10.0, 0.05 * -39.0dB) */
0x3c42b965, /* [142] = 1.19e-002 = pow(10.0, 0.05 * -38.5dB) */
0x3c4e4329, /* [143] = 1.26e-002 = pow(10.0, 0.05 * -38.0dB) */
0x3c5a7bf1, /* [144] = 1.33e-002 = pow(10.0, 0.05 * -37.5dB) */
0x3c676e1e, /* [145] = 1.41e-002 = pow(10.0, 0.05 * -37.0dB) */
0x3c7524ac, /* [146] = 1.50e-002 = pow(10.0, 0.05 * -36.5dB) */
0x3c81d59f, /* [147] = 1.58e-002 = pow(10.0, 0.05 * -36.0dB) */
0x3c898712, /* [148] = 1.68e-002 = pow(10.0, 0.05 * -35.5dB) */
0x3c91ad39, /* [149] = 1.78e-002 = pow(10.0, 0.05 * -35.0dB) */
0x3c9a4efc, /* [150] = 1.88e-002 = pow(10.0, 0.05 * -34.5dB) */
0x3ca373af, /* [151] = 2.00e-002 = pow(10.0, 0.05 * -34.0dB) */
0x3cad2314, /* [152] = 2.11e-002 = pow(10.0, 0.05 * -33.5dB) */
0x3cb76563, /* [153] = 2.24e-002 = pow(10.0, 0.05 * -33.0dB) */
0x3cc24350, /* [154] = 2.37e-002 = pow(10.0, 0.05 * -32.5dB) */
0x3ccdc614, /* [155] = 2.51e-002 = pow(10.0, 0.05 * -32.0dB) */
0x3cd9f773, /* [156] = 2.66e-002 = pow(10.0, 0.05 * -31.5dB) */
0x3ce6e1c6, /* [157] = 2.82e-002 = pow(10.0, 0.05 * -31.0dB) */
0x3cf49003, /* [158] = 2.99e-002 = pow(10.0, 0.05 * -30.5dB) */
0x3d0186e2, /* [159] = 3.16e-002 = pow(10.0, 0.05 * -30.0dB) */
0x3d0933ac, /* [160] = 3.35e-002 = pow(10.0, 0.05 * -29.5dB) */
0x3d1154e1, /* [161] = 3.55e-002 = pow(10.0, 0.05 * -29.0dB) */
0x3d19f169, /* [162] = 3.76e-002 = pow(10.0, 0.05 * -28.5dB) */
0x3d231090, /* [163] = 3.98e-002 = pow(10.0, 0.05 * -28.0dB) */
0x3d2cba15, /* [164] = 4.22e-002 = pow(10.0, 0.05 * -27.5dB) */
0x3d36f62b, /* [165] = 4.47e-002 = pow(10.0, 0.05 * -27.0dB) */
0x3d41cd81, /* [166] = 4.73e-002 = pow(10.0, 0.05 * -26.5dB) */
0x3d4d494a, /* [167] = 5.01e-002 = pow(10.0, 0.05 * -26.0dB) */
0x3d597345, /* [168] = 5.31e-002 = pow(10.0, 0.05 * -25.5dB) */
0x3d6655c3, /* [169] = 5.62e-002 = pow(10.0, 0.05 * -25.0dB) */
0x3d73fbb4, /* [170] = 5.96e-002 = pow(10.0, 0.05 * -24.5dB) */
0x3d813856, /* [171] = 6.31e-002 = pow(10.0, 0.05 * -24.0dB) */
0x3d88e078, /* [172] = 6.68e-002 = pow(10.0, 0.05 * -23.5dB) */
0x3d90fcbf, /* [173] = 7.08e-002 = pow(10.0, 0.05 * -23.0dB) */
0x3d99940e, /* [174] = 7.50e-002 = pow(10.0, 0.05 * -22.5dB) */
0x3da2adad, /* [175] = 7.94e-002 = pow(10.0, 0.05 * -22.0dB) */
0x3dac5156, /* [176] = 8.41e-002 = pow(10.0, 0.05 * -21.5dB) */
0x3db68738, /* [177] = 8.91e-002 = pow(10.0, 0.05 * -21.0dB) */
0x3dc157fb, /* [178] = 9.44e-002 = pow(10.0, 0.05 * -20.5dB) */
0x3dcccccd, /* [179] = 1.00e-001 = pow(10.0, 0.05 * -20.0dB) */
0x3dd8ef67, /* [180] = 1.06e-001 = pow(10.0, 0.05 * -19.5dB) */
0x3de5ca15, /* [181] = 1.12e-001 = pow(10.0, 0.05 * -19.0dB) */
0x3df367bf, /* [182] = 1.19e-001 = pow(10.0, 0.05 * -18.5dB) */
0x3e00e9f9, /* [183] = 1.26e-001 = pow(10.0, 0.05 * -18.0dB) */
0x3e088d77, /* [184] = 1.33e-001 = pow(10.0, 0.05 * -17.5dB) */
0x3e10a4d3, /* [185] = 1.41e-001 = pow(10.0, 0.05 * -17.0dB) */
0x3e1936ec, /* [186] = 1.50e-001 = pow(10.0, 0.05 * -16.5dB) */
0x3e224b06, /* [187] = 1.58e-001 = pow(10.0, 0.05 * -16.0dB) */
0x3e2be8d7, /* [188] = 1.68e-001 = pow(10.0, 0.05 * -15.5dB) */
0x3e361887, /* [189] = 1.78e-001 = pow(10.0, 0.05 * -15.0dB) */
0x3e40e2bb, /* [190] = 1.88e-001 = pow(10.0, 0.05 * -14.5dB) */
0x3e4c509b, /* [191] = 2.00e-001 = pow(10.0, 0.05 * -14.0dB) */
0x3e586bd9, /* [192] = 2.11e-001 = pow(10.0, 0.05 * -13.5dB) */
0x3e653ebb, /* [193] = 2.24e-001 = pow(10.0, 0.05 * -13.0dB) */
0x3e72d424, /* [194] = 2.37e-001 = pow(10.0, 0.05 * -12.5dB) */
0x3e809bcc, /* [195] = 2.51e-001 = pow(10.0, 0.05 * -12.0dB) */
0x3e883aa8, /* [196] = 2.66e-001 = pow(10.0, 0.05 * -11.5dB) */
0x3e904d1c, /* [197] = 2.82e-001 = pow(10.0, 0.05 * -11.0dB) */
0x3e98da02, /* [198] = 2.99e-001 = pow(10.0, 0.05 * -10.5dB) */
0x3ea1e89b, /* [199] = 3.16e-001 = pow(10.0, 0.05 * -10.0dB) */
0x3eab8097, /* [200] = 3.35e-001 = pow(10.0, 0.05 * -9.5dB) */
0x3eb5aa1a, /* [201] = 3.55e-001 = pow(10.0, 0.05 * -9.0dB) */
0x3ec06dc3, /* [202] = 3.76e-001 = pow(10.0, 0.05 * -8.5dB) */
0x3ecbd4b4, /* [203] = 3.98e-001 = pow(10.0, 0.05 * -8.0dB) */
0x3ed7e89b, /* [204] = 4.22e-001 = pow(10.0, 0.05 * -7.5dB) */
0x3ee4b3b6, /* [205] = 4.47e-001 = pow(10.0, 0.05 * -7.0dB) */
0x3ef240e2, /* [206] = 4.73e-001 = pow(10.0, 0.05 * -6.5dB) */
0x3f004dce, /* [207] = 5.01e-001 = pow(10.0, 0.05 * -6.0dB) */
0x3f07e80b, /* [208] = 5.31e-001 = pow(10.0, 0.05 * -5.5dB) */
0x3f0ff59a, /* [209] = 5.62e-001 = pow(10.0, 0.05 * -5.0dB) */
0x3f187d50, /* [210] = 5.96e-001 = pow(10.0, 0.05 * -4.5dB) */
0x3f21866c, /* [211] = 6.31e-001 = pow(10.0, 0.05 * -4.0dB) */
0x3f2b1896, /* [212] = 6.68e-001 = pow(10.0, 0.05 * -3.5dB) */
0x3f353bef, /* [213] = 7.08e-001 = pow(10.0, 0.05 * -3.0dB) */
0x3f3ff911, /* [214] = 7.50e-001 = pow(10.0, 0.05 * -2.5dB) */
0x3f4b5918, /* [215] = 7.94e-001 = pow(10.0, 0.05 * -2.0dB) */
0x3f5765ac, /* [216] = 8.41e-001 = pow(10.0, 0.05 * -1.5dB) */
0x3f642905, /* [217] = 8.91e-001 = pow(10.0, 0.05 * -1.0dB) */
0x3f71adf9, /* [218] = 9.44e-001 = pow(10.0, 0.05 * -0.5dB) */
0x3f800000, /* [219] = 1.00e+000 = pow(10.0, 0.05 * 0.0dB) */
0x3f8795a0, /* [220] = 1.06e+000 = pow(10.0, 0.05 * 0.5dB) */
0x3f8f9e4d, /* [221] = 1.12e+000 = pow(10.0, 0.05 * 1.0dB) */
0x3f9820d7, /* [222] = 1.19e+000 = pow(10.0, 0.05 * 1.5dB) */
0x3fa12478, /* [223] = 1.26e+000 = pow(10.0, 0.05 * 2.0dB) */
0x3faab0d5, /* [224] = 1.33e+000 = pow(10.0, 0.05 * 2.5dB) */
0x3fb4ce08, /* [225] = 1.41e+000 = pow(10.0, 0.05 * 3.0dB) */
0x3fbf84a6, /* [226] = 1.50e+000 = pow(10.0, 0.05 * 3.5dB) */
0x3fcaddc8, /* [227] = 1.58e+000 = pow(10.0, 0.05 * 4.0dB) */
0x3fd6e30d, /* [228] = 1.68e+000 = pow(10.0, 0.05 * 4.5dB) */
0x3fe39ea9, /* [229] = 1.78e+000 = pow(10.0, 0.05 * 5.0dB) */
0x3ff11b6a, /* [230] = 1.88e+000 = pow(10.0, 0.05 * 5.5dB) */
0x3fff64c1, /* [231] = 2.00e+000 = pow(10.0, 0.05 * 6.0dB) */
0x40074368, /* [232] = 2.11e+000 = pow(10.0, 0.05 * 6.5dB) */
0x400f4735, /* [233] = 2.24e+000 = pow(10.0, 0.05 * 7.0dB) */
0x4017c496, /* [234] = 2.37e+000 = pow(10.0, 0.05 * 7.5dB) */
0x4020c2bf, /* [235] = 2.51e+000 = pow(10.0, 0.05 * 8.0dB) */
0x402a4952, /* [236] = 2.66e+000 = pow(10.0, 0.05 * 8.5dB) */
0x40346063, /* [237] = 2.82e+000 = pow(10.0, 0.05 * 9.0dB) */
0x403f1082, /* [238] = 2.99e+000 = pow(10.0, 0.05 * 9.5dB) */
0x404a62c2, /* [239] = 3.16e+000 = pow(10.0, 0.05 * 10.0dB) */
0x405660bd, /* [240] = 3.35e+000 = pow(10.0, 0.05 * 10.5dB) */
0x406314a0, /* [241] = 3.55e+000 = pow(10.0, 0.05 * 11.0dB) */
0x40708933, /* [242] = 3.76e+000 = pow(10.0, 0.05 * 11.5dB) */
0x407ec9e1, /* [243] = 3.98e+000 = pow(10.0, 0.05 * 12.0dB) */
0x4086f161, /* [244] = 4.22e+000 = pow(10.0, 0.05 * 12.5dB) */
0x408ef052, /* [245] = 4.47e+000 = pow(10.0, 0.05 * 13.0dB) */
0x4097688d, /* [246] = 4.73e+000 = pow(10.0, 0.05 * 13.5dB) */
0x40a06142, /* [247] = 5.01e+000 = pow(10.0, 0.05 * 14.0dB) */
0x40a9e20e, /* [248] = 5.31e+000 = pow(10.0, 0.05 * 14.5dB) */
0x40b3f300, /* [249] = 5.62e+000 = pow(10.0, 0.05 * 15.0dB) */
0x40be9ca5, /* [250] = 5.96e+000 = pow(10.0, 0.05 * 15.5dB) */
0x40c9e807, /* [251] = 6.31e+000 = pow(10.0, 0.05 * 16.0dB) */
0x40d5debc, /* [252] = 6.68e+000 = pow(10.0, 0.05 * 16.5dB) */
0x40e28aeb, /* [253] = 7.08e+000 = pow(10.0, 0.05 * 17.0dB) */
0x40eff755, /* [254] = 7.50e+000 = pow(10.0, 0.05 * 17.5dB) */
0x40fe2f5e, /* [255] = 7.94e+000 = pow(10.0, 0.05 * 18.0dB) */
};
#define MIXART_DIGITAL_LEVEL_MIN 0 /* -109.5 dB */
#define MIXART_DIGITAL_LEVEL_MAX 255 /* 18.0 dB */
#define MIXART_DIGITAL_ZERO_LEVEL 219 /* 0.0 dB */
int mixart_update_playback_stream_level(struct snd_mixart* chip, int is_aes, int idx)
{
int err, i;
int volume[2];
struct mixart_msg request;
struct mixart_set_out_stream_level_req set_level;
u32 status;
struct mixart_pipe *pipe;
memset(&set_level, 0, sizeof(set_level));
set_level.nb_of_stream = 1;
set_level.stream_level.desc.stream_idx = idx;
if(is_aes) {
pipe = &chip->pipe_out_dig; /* AES playback */
idx += MIXART_PLAYBACK_STREAMS;
} else {
pipe = &chip->pipe_out_ana; /* analog playback */
}
/* only when pipe exists ! */
if(pipe->status == PIPE_UNDEFINED)
return 0;
set_level.stream_level.desc.uid_pipe = pipe->group_uid;
for(i=0; i<2; i++) {
if(chip->digital_playback_active[idx][i])
volume[i] = chip->digital_playback_volume[idx][i];
else
volume[i] = MIXART_DIGITAL_LEVEL_MIN;
}
set_level.stream_level.out_level.valid_mask1 = MIXART_OUT_STREAM_SET_LEVEL_LEFT_AUDIO1 | MIXART_OUT_STREAM_SET_LEVEL_RIGHT_AUDIO2;
set_level.stream_level.out_level.left_to_out1_level = mixart_digital_level[volume[0]];
set_level.stream_level.out_level.right_to_out2_level = mixart_digital_level[volume[1]];
request.message_id = MSG_STREAM_SET_OUT_STREAM_LEVEL;
request.uid = (struct mixart_uid){0,0};
request.data = &set_level;
request.size = sizeof(set_level);
err = snd_mixart_send_msg(chip->mgr, &request, sizeof(status), &status);
if((err<0) || status) {
snd_printk(KERN_DEBUG "error MSG_STREAM_SET_OUT_STREAM_LEVEL card(%d) status(%x)\n", chip->chip_idx, status);
return -EINVAL;
}
return 0;
}
int mixart_update_capture_stream_level(struct snd_mixart* chip, int is_aes)
{
int err, i, idx;
struct mixart_pipe *pipe;
struct mixart_msg request;
struct mixart_set_in_audio_level_req set_level;
u32 status;
if(is_aes) {
idx = 1;
pipe = &chip->pipe_in_dig;
} else {
idx = 0;
pipe = &chip->pipe_in_ana;
}
/* only when pipe exists ! */
if(pipe->status == PIPE_UNDEFINED)
return 0;
memset(&set_level, 0, sizeof(set_level));
set_level.audio_count = 2;
set_level.level[0].connector = pipe->uid_left_connector;
set_level.level[1].connector = pipe->uid_right_connector;
for(i=0; i<2; i++) {
set_level.level[i].valid_mask1 = MIXART_AUDIO_LEVEL_DIGITAL_MASK;
set_level.level[i].digital_level = mixart_digital_level[chip->digital_capture_volume[idx][i]];
}
request.message_id = MSG_STREAM_SET_IN_AUDIO_LEVEL;
request.uid = (struct mixart_uid){0,0};
request.data = &set_level;
request.size = sizeof(set_level);
err = snd_mixart_send_msg(chip->mgr, &request, sizeof(status), &status);
if((err<0) || status) {
snd_printk(KERN_DEBUG "error MSG_STREAM_SET_IN_AUDIO_LEVEL card(%d) status(%x)\n", chip->chip_idx, status);
return -EINVAL;
}
return 0;
}
/* shared */
static int mixart_digital_vol_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = MIXART_DIGITAL_LEVEL_MIN; /* -109.5 dB */
uinfo->value.integer.max = MIXART_DIGITAL_LEVEL_MAX; /* 18.0 dB */
return 0;
}
#define MIXART_VOL_REC_MASK 1
#define MIXART_VOL_AES_MASK 2
static int mixart_pcm_vol_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_mixart *chip = snd_kcontrol_chip(kcontrol);
int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); /* index */
int *stored_volume;
int is_capture = kcontrol->private_value & MIXART_VOL_REC_MASK;
int is_aes = kcontrol->private_value & MIXART_VOL_AES_MASK;
mutex_lock(&chip->mgr->mixer_mutex);
if(is_capture) {
if(is_aes) stored_volume = chip->digital_capture_volume[1]; /* AES capture */
else stored_volume = chip->digital_capture_volume[0]; /* analog capture */
} else {
snd_BUG_ON(idx >= MIXART_PLAYBACK_STREAMS);
if(is_aes) stored_volume = chip->digital_playback_volume[MIXART_PLAYBACK_STREAMS + idx]; /* AES playback */
else stored_volume = chip->digital_playback_volume[idx]; /* analog playback */
}
ucontrol->value.integer.value[0] = stored_volume[0];
ucontrol->value.integer.value[1] = stored_volume[1];
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int mixart_pcm_vol_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_mixart *chip = snd_kcontrol_chip(kcontrol);
int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); /* index */
int changed = 0;
int is_capture = kcontrol->private_value & MIXART_VOL_REC_MASK;
int is_aes = kcontrol->private_value & MIXART_VOL_AES_MASK;
int* stored_volume;
int i;
mutex_lock(&chip->mgr->mixer_mutex);
if (is_capture) {
if (is_aes) /* AES capture */
stored_volume = chip->digital_capture_volume[1];
else /* analog capture */
stored_volume = chip->digital_capture_volume[0];
} else {
snd_BUG_ON(idx >= MIXART_PLAYBACK_STREAMS);
if (is_aes) /* AES playback */
stored_volume = chip->digital_playback_volume[MIXART_PLAYBACK_STREAMS + idx];
else /* analog playback */
stored_volume = chip->digital_playback_volume[idx];
}
for (i = 0; i < 2; i++) {
int vol = ucontrol->value.integer.value[i];
if (vol < MIXART_DIGITAL_LEVEL_MIN ||
vol > MIXART_DIGITAL_LEVEL_MAX)
continue;
if (stored_volume[i] != vol) {
stored_volume[i] = vol;
changed = 1;
}
}
if (changed) {
if (is_capture)
mixart_update_capture_stream_level(chip, is_aes);
else
mixart_update_playback_stream_level(chip, is_aes, idx);
}
mutex_unlock(&chip->mgr->mixer_mutex);
return changed;
}
static const DECLARE_TLV_DB_SCALE(db_scale_digital, -10950, 50, 0);
static struct snd_kcontrol_new snd_mixart_pcm_vol =
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
/* name will be filled later */
/* count will be filled later */
.info = mixart_digital_vol_info, /* shared */
.get = mixart_pcm_vol_get,
.put = mixart_pcm_vol_put,
.tlv = { .p = db_scale_digital },
};
static int mixart_pcm_sw_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_mixart *chip = snd_kcontrol_chip(kcontrol);
int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); /* index */
snd_BUG_ON(idx >= MIXART_PLAYBACK_STREAMS);
mutex_lock(&chip->mgr->mixer_mutex);
if(kcontrol->private_value & MIXART_VOL_AES_MASK) /* AES playback */
idx += MIXART_PLAYBACK_STREAMS;
ucontrol->value.integer.value[0] = chip->digital_playback_active[idx][0];
ucontrol->value.integer.value[1] = chip->digital_playback_active[idx][1];
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int mixart_pcm_sw_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_mixart *chip = snd_kcontrol_chip(kcontrol);
int changed = 0;
int is_aes = kcontrol->private_value & MIXART_VOL_AES_MASK;
int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); /* index */
int i, j;
snd_BUG_ON(idx >= MIXART_PLAYBACK_STREAMS);
mutex_lock(&chip->mgr->mixer_mutex);
j = idx;
if (is_aes)
j += MIXART_PLAYBACK_STREAMS;
for (i = 0; i < 2; i++) {
if (chip->digital_playback_active[j][i] !=
ucontrol->value.integer.value[i]) {
chip->digital_playback_active[j][i] =
!!ucontrol->value.integer.value[i];
changed = 1;
}
}
if (changed)
mixart_update_playback_stream_level(chip, is_aes, idx);
mutex_unlock(&chip->mgr->mixer_mutex);
return changed;
}
static struct snd_kcontrol_new mixart_control_pcm_switch = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
/* name will be filled later */
.count = MIXART_PLAYBACK_STREAMS,
.info = mixart_sw_info, /* shared */
.get = mixart_pcm_sw_get,
.put = mixart_pcm_sw_put
};
static int mixart_update_monitoring(struct snd_mixart* chip, int channel)
{
int err;
struct mixart_msg request;
struct mixart_set_out_audio_level audio_level;
u32 resp;
if(chip->pipe_out_ana.status == PIPE_UNDEFINED)
return -EINVAL; /* no pipe defined */
if(!channel) request.uid = chip->pipe_out_ana.uid_left_connector;
else request.uid = chip->pipe_out_ana.uid_right_connector;
request.message_id = MSG_CONNECTOR_SET_OUT_AUDIO_LEVEL;
request.data = &audio_level;
request.size = sizeof(audio_level);
memset(&audio_level, 0, sizeof(audio_level));
audio_level.valid_mask1 = MIXART_AUDIO_LEVEL_MONITOR_MASK | MIXART_AUDIO_LEVEL_MUTE_M1_MASK;
audio_level.monitor_level = mixart_digital_level[chip->monitoring_volume[channel!=0]];
audio_level.monitor_mute1 = !chip->monitoring_active[channel!=0];
err = snd_mixart_send_msg(chip->mgr, &request, sizeof(resp), &resp);
if((err<0) || resp) {
snd_printk(KERN_DEBUG "error MSG_CONNECTOR_SET_OUT_AUDIO_LEVEL card(%d) resp(%x)\n", chip->chip_idx, resp);
return -EINVAL;
}
return 0;
}
/*
* monitoring level control
*/
static int mixart_monitor_vol_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_mixart *chip = snd_kcontrol_chip(kcontrol);
mutex_lock(&chip->mgr->mixer_mutex);
ucontrol->value.integer.value[0] = chip->monitoring_volume[0];
ucontrol->value.integer.value[1] = chip->monitoring_volume[1];
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int mixart_monitor_vol_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_mixart *chip = snd_kcontrol_chip(kcontrol);
int changed = 0;
int i;
mutex_lock(&chip->mgr->mixer_mutex);
for (i = 0; i < 2; i++) {
if (chip->monitoring_volume[i] !=
ucontrol->value.integer.value[i]) {
chip->monitoring_volume[i] =
!!ucontrol->value.integer.value[i];
mixart_update_monitoring(chip, i);
changed = 1;
}
}
mutex_unlock(&chip->mgr->mixer_mutex);
return changed;
}
static struct snd_kcontrol_new mixart_control_monitor_vol = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
.name = "Monitoring Volume",
.info = mixart_digital_vol_info, /* shared */
.get = mixart_monitor_vol_get,
.put = mixart_monitor_vol_put,
.tlv = { .p = db_scale_digital },
};
/*
* monitoring switch control
*/
static int mixart_monitor_sw_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_mixart *chip = snd_kcontrol_chip(kcontrol);
mutex_lock(&chip->mgr->mixer_mutex);
ucontrol->value.integer.value[0] = chip->monitoring_active[0];
ucontrol->value.integer.value[1] = chip->monitoring_active[1];
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int mixart_monitor_sw_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_mixart *chip = snd_kcontrol_chip(kcontrol);
int changed = 0;
int i;
mutex_lock(&chip->mgr->mixer_mutex);
for (i = 0; i < 2; i++) {
if (chip->monitoring_active[i] !=
ucontrol->value.integer.value[i]) {
chip->monitoring_active[i] =
!!ucontrol->value.integer.value[i];
changed |= (1<<i); /* mask 0x01 ans 0x02 */
}
}
if (changed) {
/* allocate or release resources for monitoring */
int allocate = chip->monitoring_active[0] ||
chip->monitoring_active[1];
if (allocate) {
/* allocate the playback pipe for monitoring */
snd_mixart_add_ref_pipe(chip, MIXART_PCM_ANALOG, 0, 1);
/* allocate the capture pipe for monitoring */
snd_mixart_add_ref_pipe(chip, MIXART_PCM_ANALOG, 1, 1);
}
if (changed & 0x01)
mixart_update_monitoring(chip, 0);
if (changed & 0x02)
mixart_update_monitoring(chip, 1);
if (!allocate) {
/* release the capture pipe for monitoring */
snd_mixart_kill_ref_pipe(chip->mgr,
&chip->pipe_in_ana, 1);
/* release the playback pipe for monitoring */
snd_mixart_kill_ref_pipe(chip->mgr,
&chip->pipe_out_ana, 1);
}
}
mutex_unlock(&chip->mgr->mixer_mutex);
return (changed != 0);
}
static struct snd_kcontrol_new mixart_control_monitor_sw = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Monitoring Switch",
.info = mixart_sw_info, /* shared */
.get = mixart_monitor_sw_get,
.put = mixart_monitor_sw_put
};
static void mixart_reset_audio_levels(struct snd_mixart *chip)
{
/* analog volumes can be set even if there is no pipe */
mixart_update_analog_audio_level(chip, 0);
/* analog levels for capture only on the first two chips */
if(chip->chip_idx < 2) {
mixart_update_analog_audio_level(chip, 1);
}
return;
}
int snd_mixart_create_mixer(struct mixart_mgr *mgr)
{
struct snd_mixart *chip;
int err, i;
mutex_init(&mgr->mixer_mutex); /* can be in another place */
for(i=0; i<mgr->num_cards; i++) {
struct snd_kcontrol_new temp;
chip = mgr->chip[i];
/* analog output level control */
temp = mixart_control_analog_level;
temp.name = "Master Playback Volume";
temp.private_value = 0; /* playback */
if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&temp, chip))) < 0)
return err;
/* output mute controls */
if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&mixart_control_output_switch, chip))) < 0)
return err;
/* analog input level control only on first two chips !*/
if(i<2) {
temp = mixart_control_analog_level;
temp.name = "Master Capture Volume";
temp.private_value = 1; /* capture */
if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&temp, chip))) < 0)
return err;
}
temp = snd_mixart_pcm_vol;
temp.name = "PCM Playback Volume";
temp.count = MIXART_PLAYBACK_STREAMS;
temp.private_value = 0; /* playback analog */
if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&temp, chip))) < 0)
return err;
temp.name = "PCM Capture Volume";
temp.count = 1;
temp.private_value = MIXART_VOL_REC_MASK; /* capture analog */
if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&temp, chip))) < 0)
return err;
if(mgr->board_type == MIXART_DAUGHTER_TYPE_AES) {
temp.name = "AES Playback Volume";
temp.count = MIXART_PLAYBACK_STREAMS;
temp.private_value = MIXART_VOL_AES_MASK; /* playback AES/EBU */
if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&temp, chip))) < 0)
return err;
temp.name = "AES Capture Volume";
temp.count = 0;
temp.private_value = MIXART_VOL_REC_MASK | MIXART_VOL_AES_MASK; /* capture AES/EBU */
if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&temp, chip))) < 0)
return err;
}
temp = mixart_control_pcm_switch;
temp.name = "PCM Playback Switch";
temp.private_value = 0; /* playback analog */
if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&temp, chip))) < 0)
return err;
if(mgr->board_type == MIXART_DAUGHTER_TYPE_AES) {
temp.name = "AES Playback Switch";
temp.private_value = MIXART_VOL_AES_MASK; /* playback AES/EBU */
if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&temp, chip))) < 0)
return err;
}
/* monitoring */
if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&mixart_control_monitor_vol, chip))) < 0)
return err;
if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&mixart_control_monitor_sw, chip))) < 0)
return err;
/* init all mixer data and program the master volumes/switches */
mixart_reset_audio_levels(chip);
}
return 0;
}
| gpl-2.0 |
russelldias98/linux_kernel_3.0.68 | drivers/net/enic/vnic_vic.c | 13289 | 2047 | /*
* Copyright 2010 Cisco Systems, Inc. All rights reserved.
*
* This program is free software; you may 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.
*
* 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 <linux/kernel.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/slab.h>
#include "vnic_vic.h"
struct vic_provinfo *vic_provinfo_alloc(gfp_t flags, const u8 *oui,
const u8 type)
{
struct vic_provinfo *vp;
if (!oui)
return NULL;
vp = kzalloc(VIC_PROVINFO_MAX_DATA, flags);
if (!vp)
return NULL;
memcpy(vp->oui, oui, sizeof(vp->oui));
vp->type = type;
vp->length = htonl(sizeof(vp->num_tlvs));
return vp;
}
void vic_provinfo_free(struct vic_provinfo *vp)
{
kfree(vp);
}
int vic_provinfo_add_tlv(struct vic_provinfo *vp, u16 type, u16 length,
const void *value)
{
struct vic_provinfo_tlv *tlv;
if (!vp || !value)
return -EINVAL;
if (ntohl(vp->length) + offsetof(struct vic_provinfo_tlv, value) +
length > VIC_PROVINFO_MAX_TLV_DATA)
return -ENOMEM;
tlv = (struct vic_provinfo_tlv *)((u8 *)vp->tlv +
ntohl(vp->length) - sizeof(vp->num_tlvs));
tlv->type = htons(type);
tlv->length = htons(length);
memcpy(tlv->value, value, length);
vp->num_tlvs = htonl(ntohl(vp->num_tlvs) + 1);
vp->length = htonl(ntohl(vp->length) +
offsetof(struct vic_provinfo_tlv, value) + length);
return 0;
}
size_t vic_provinfo_size(struct vic_provinfo *vp)
{
return vp ? ntohl(vp->length) + sizeof(*vp) - sizeof(vp->num_tlvs) : 0;
}
| gpl-2.0 |
heukelum/linux | drivers/gpu/drm/nouveau/nvkm/subdev/therm/g84.c | 746 | 7330 | /*
* Copyright 2012 Red Hat Inc.
*
* 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: Ben Skeggs
* Martin Peres
*/
#include "priv.h"
#include <subdev/fuse.h>
int
g84_temp_get(struct nvkm_therm *therm)
{
struct nvkm_device *device = therm->subdev.device;
if (nvkm_fuse_read(device->fuse, 0x1a8) == 1)
return nvkm_rd32(device, 0x20400);
else
return -ENODEV;
}
void
g84_sensor_setup(struct nvkm_therm *therm)
{
struct nvkm_device *device = therm->subdev.device;
/* enable temperature reading for cards with insane defaults */
if (nvkm_fuse_read(device->fuse, 0x1a8) == 1) {
nvkm_mask(device, 0x20008, 0x80008000, 0x80000000);
nvkm_mask(device, 0x2000c, 0x80000003, 0x00000000);
mdelay(20); /* wait for the temperature to stabilize */
}
}
static void
g84_therm_program_alarms(struct nvkm_therm *therm)
{
struct nvbios_therm_sensor *sensor = &therm->bios_sensor;
struct nvkm_subdev *subdev = &therm->subdev;
struct nvkm_device *device = subdev->device;
unsigned long flags;
spin_lock_irqsave(&therm->sensor.alarm_program_lock, flags);
/* enable RISING and FALLING IRQs for shutdown, THRS 0, 1, 2 and 4 */
nvkm_wr32(device, 0x20000, 0x000003ff);
/* shutdown: The computer should be shutdown when reached */
nvkm_wr32(device, 0x20484, sensor->thrs_shutdown.hysteresis);
nvkm_wr32(device, 0x20480, sensor->thrs_shutdown.temp);
/* THRS_1 : fan boost*/
nvkm_wr32(device, 0x204c4, sensor->thrs_fan_boost.temp);
/* THRS_2 : critical */
nvkm_wr32(device, 0x204c0, sensor->thrs_critical.temp);
/* THRS_4 : down clock */
nvkm_wr32(device, 0x20414, sensor->thrs_down_clock.temp);
spin_unlock_irqrestore(&therm->sensor.alarm_program_lock, flags);
nvkm_debug(subdev,
"Programmed thresholds [ %d(%d), %d(%d), %d(%d), %d(%d) ]\n",
sensor->thrs_fan_boost.temp,
sensor->thrs_fan_boost.hysteresis,
sensor->thrs_down_clock.temp,
sensor->thrs_down_clock.hysteresis,
sensor->thrs_critical.temp,
sensor->thrs_critical.hysteresis,
sensor->thrs_shutdown.temp,
sensor->thrs_shutdown.hysteresis);
}
/* must be called with alarm_program_lock taken ! */
static void
g84_therm_threshold_hyst_emulation(struct nvkm_therm *therm,
uint32_t thrs_reg, u8 status_bit,
const struct nvbios_therm_threshold *thrs,
enum nvkm_therm_thrs thrs_name)
{
struct nvkm_device *device = therm->subdev.device;
enum nvkm_therm_thrs_direction direction;
enum nvkm_therm_thrs_state prev_state, new_state;
int temp, cur;
prev_state = nvkm_therm_sensor_get_threshold_state(therm, thrs_name);
temp = nvkm_rd32(device, thrs_reg);
/* program the next threshold */
if (temp == thrs->temp) {
nvkm_wr32(device, thrs_reg, thrs->temp - thrs->hysteresis);
new_state = NVKM_THERM_THRS_HIGHER;
} else {
nvkm_wr32(device, thrs_reg, thrs->temp);
new_state = NVKM_THERM_THRS_LOWER;
}
/* fix the state (in case someone reprogrammed the alarms) */
cur = therm->func->temp_get(therm);
if (new_state == NVKM_THERM_THRS_LOWER && cur > thrs->temp)
new_state = NVKM_THERM_THRS_HIGHER;
else if (new_state == NVKM_THERM_THRS_HIGHER &&
cur < thrs->temp - thrs->hysteresis)
new_state = NVKM_THERM_THRS_LOWER;
nvkm_therm_sensor_set_threshold_state(therm, thrs_name, new_state);
/* find the direction */
if (prev_state < new_state)
direction = NVKM_THERM_THRS_RISING;
else if (prev_state > new_state)
direction = NVKM_THERM_THRS_FALLING;
else
return;
/* advertise a change in direction */
nvkm_therm_sensor_event(therm, thrs_name, direction);
}
static void
g84_therm_intr(struct nvkm_therm *therm)
{
struct nvkm_subdev *subdev = &therm->subdev;
struct nvkm_device *device = subdev->device;
struct nvbios_therm_sensor *sensor = &therm->bios_sensor;
unsigned long flags;
uint32_t intr;
spin_lock_irqsave(&therm->sensor.alarm_program_lock, flags);
intr = nvkm_rd32(device, 0x20100) & 0x3ff;
/* THRS_4: downclock */
if (intr & 0x002) {
g84_therm_threshold_hyst_emulation(therm, 0x20414, 24,
&sensor->thrs_down_clock,
NVKM_THERM_THRS_DOWNCLOCK);
intr &= ~0x002;
}
/* shutdown */
if (intr & 0x004) {
g84_therm_threshold_hyst_emulation(therm, 0x20480, 20,
&sensor->thrs_shutdown,
NVKM_THERM_THRS_SHUTDOWN);
intr &= ~0x004;
}
/* THRS_1 : fan boost */
if (intr & 0x008) {
g84_therm_threshold_hyst_emulation(therm, 0x204c4, 21,
&sensor->thrs_fan_boost,
NVKM_THERM_THRS_FANBOOST);
intr &= ~0x008;
}
/* THRS_2 : critical */
if (intr & 0x010) {
g84_therm_threshold_hyst_emulation(therm, 0x204c0, 22,
&sensor->thrs_critical,
NVKM_THERM_THRS_CRITICAL);
intr &= ~0x010;
}
if (intr)
nvkm_error(subdev, "intr %08x\n", intr);
/* ACK everything */
nvkm_wr32(device, 0x20100, 0xffffffff);
nvkm_wr32(device, 0x1100, 0x10000); /* PBUS */
spin_unlock_irqrestore(&therm->sensor.alarm_program_lock, flags);
}
void
g84_therm_fini(struct nvkm_therm *therm)
{
struct nvkm_device *device = therm->subdev.device;
/* Disable PTherm IRQs */
nvkm_wr32(device, 0x20000, 0x00000000);
/* ACK all PTherm IRQs */
nvkm_wr32(device, 0x20100, 0xffffffff);
nvkm_wr32(device, 0x1100, 0x10000); /* PBUS */
}
static void
g84_therm_init(struct nvkm_therm *therm)
{
g84_sensor_setup(therm);
}
static const struct nvkm_therm_func
g84_therm = {
.init = g84_therm_init,
.fini = g84_therm_fini,
.intr = g84_therm_intr,
.pwm_ctrl = nv50_fan_pwm_ctrl,
.pwm_get = nv50_fan_pwm_get,
.pwm_set = nv50_fan_pwm_set,
.pwm_clock = nv50_fan_pwm_clock,
.temp_get = g84_temp_get,
.program_alarms = g84_therm_program_alarms,
};
int
g84_therm_new(struct nvkm_device *device, int index, struct nvkm_therm **ptherm)
{
struct nvkm_therm *therm;
int ret;
ret = nvkm_therm_new_(&g84_therm, device, index, &therm);
*ptherm = therm;
if (ret)
return ret;
/* init the thresholds */
nvkm_therm_sensor_set_threshold_state(therm, NVKM_THERM_THRS_SHUTDOWN,
NVKM_THERM_THRS_LOWER);
nvkm_therm_sensor_set_threshold_state(therm, NVKM_THERM_THRS_FANBOOST,
NVKM_THERM_THRS_LOWER);
nvkm_therm_sensor_set_threshold_state(therm, NVKM_THERM_THRS_CRITICAL,
NVKM_THERM_THRS_LOWER);
nvkm_therm_sensor_set_threshold_state(therm, NVKM_THERM_THRS_DOWNCLOCK,
NVKM_THERM_THRS_LOWER);
return 0;
}
| gpl-2.0 |
rezvorck/android_kernel_s450m_4g_mm | drivers/power/collie_battery.c | 1002 | 9463 | /*
* Battery and Power Management code for the Sharp SL-5x00
*
* Copyright (C) 2009 Thomas Kunze
*
* based on tosa_battery.c
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/power_supply.h>
#include <linux/delay.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/gpio.h>
#include <linux/mfd/ucb1x00.h>
#include <asm/mach/sharpsl_param.h>
#include <asm/mach-types.h>
#include <mach/collie.h>
static DEFINE_MUTEX(bat_lock); /* protects gpio pins */
static struct work_struct bat_work;
static struct ucb1x00 *ucb;
struct collie_bat {
int status;
struct power_supply psy;
int full_chrg;
struct mutex work_lock; /* protects data */
bool (*is_present)(struct collie_bat *bat);
int gpio_full;
int gpio_charge_on;
int technology;
int gpio_bat;
int adc_bat;
int adc_bat_divider;
int bat_max;
int bat_min;
int gpio_temp;
int adc_temp;
int adc_temp_divider;
};
static struct collie_bat collie_bat_main;
static unsigned long collie_read_bat(struct collie_bat *bat)
{
unsigned long value = 0;
if (bat->gpio_bat < 0 || bat->adc_bat < 0)
return 0;
mutex_lock(&bat_lock);
gpio_set_value(bat->gpio_bat, 1);
msleep(5);
ucb1x00_adc_enable(ucb);
value = ucb1x00_adc_read(ucb, bat->adc_bat, UCB_SYNC);
ucb1x00_adc_disable(ucb);
gpio_set_value(bat->gpio_bat, 0);
mutex_unlock(&bat_lock);
value = value * 1000000 / bat->adc_bat_divider;
return value;
}
static unsigned long collie_read_temp(struct collie_bat *bat)
{
unsigned long value = 0;
if (bat->gpio_temp < 0 || bat->adc_temp < 0)
return 0;
mutex_lock(&bat_lock);
gpio_set_value(bat->gpio_temp, 1);
msleep(5);
ucb1x00_adc_enable(ucb);
value = ucb1x00_adc_read(ucb, bat->adc_temp, UCB_SYNC);
ucb1x00_adc_disable(ucb);
gpio_set_value(bat->gpio_temp, 0);
mutex_unlock(&bat_lock);
value = value * 10000 / bat->adc_temp_divider;
return value;
}
static int collie_bat_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
int ret = 0;
struct collie_bat *bat = container_of(psy, struct collie_bat, psy);
if (bat->is_present && !bat->is_present(bat)
&& psp != POWER_SUPPLY_PROP_PRESENT) {
return -ENODEV;
}
switch (psp) {
case POWER_SUPPLY_PROP_STATUS:
val->intval = bat->status;
break;
case POWER_SUPPLY_PROP_TECHNOLOGY:
val->intval = bat->technology;
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
val->intval = collie_read_bat(bat);
break;
case POWER_SUPPLY_PROP_VOLTAGE_MAX:
if (bat->full_chrg == -1)
val->intval = bat->bat_max;
else
val->intval = bat->full_chrg;
break;
case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN:
val->intval = bat->bat_max;
break;
case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
val->intval = bat->bat_min;
break;
case POWER_SUPPLY_PROP_TEMP:
val->intval = collie_read_temp(bat);
break;
case POWER_SUPPLY_PROP_PRESENT:
val->intval = bat->is_present ? bat->is_present(bat) : 1;
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static void collie_bat_external_power_changed(struct power_supply *psy)
{
schedule_work(&bat_work);
}
static irqreturn_t collie_bat_gpio_isr(int irq, void *data)
{
pr_info("collie_bat_gpio irq\n");
schedule_work(&bat_work);
return IRQ_HANDLED;
}
static void collie_bat_update(struct collie_bat *bat)
{
int old;
struct power_supply *psy = &bat->psy;
mutex_lock(&bat->work_lock);
old = bat->status;
if (bat->is_present && !bat->is_present(bat)) {
printk(KERN_NOTICE "%s not present\n", psy->name);
bat->status = POWER_SUPPLY_STATUS_UNKNOWN;
bat->full_chrg = -1;
} else if (power_supply_am_i_supplied(psy)) {
if (bat->status == POWER_SUPPLY_STATUS_DISCHARGING) {
gpio_set_value(bat->gpio_charge_on, 1);
mdelay(15);
}
if (gpio_get_value(bat->gpio_full)) {
if (old == POWER_SUPPLY_STATUS_CHARGING ||
bat->full_chrg == -1)
bat->full_chrg = collie_read_bat(bat);
gpio_set_value(bat->gpio_charge_on, 0);
bat->status = POWER_SUPPLY_STATUS_FULL;
} else {
gpio_set_value(bat->gpio_charge_on, 1);
bat->status = POWER_SUPPLY_STATUS_CHARGING;
}
} else {
gpio_set_value(bat->gpio_charge_on, 0);
bat->status = POWER_SUPPLY_STATUS_DISCHARGING;
}
if (old != bat->status)
power_supply_changed(psy);
mutex_unlock(&bat->work_lock);
}
static void collie_bat_work(struct work_struct *work)
{
collie_bat_update(&collie_bat_main);
}
static enum power_supply_property collie_bat_main_props[] = {
POWER_SUPPLY_PROP_STATUS,
POWER_SUPPLY_PROP_TECHNOLOGY,
POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN,
POWER_SUPPLY_PROP_VOLTAGE_MAX,
POWER_SUPPLY_PROP_PRESENT,
POWER_SUPPLY_PROP_TEMP,
};
static enum power_supply_property collie_bat_bu_props[] = {
POWER_SUPPLY_PROP_STATUS,
POWER_SUPPLY_PROP_TECHNOLOGY,
POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN,
POWER_SUPPLY_PROP_VOLTAGE_MAX,
POWER_SUPPLY_PROP_PRESENT,
};
static struct collie_bat collie_bat_main = {
.status = POWER_SUPPLY_STATUS_DISCHARGING,
.full_chrg = -1,
.psy = {
.name = "main-battery",
.type = POWER_SUPPLY_TYPE_BATTERY,
.properties = collie_bat_main_props,
.num_properties = ARRAY_SIZE(collie_bat_main_props),
.get_property = collie_bat_get_property,
.external_power_changed = collie_bat_external_power_changed,
.use_for_apm = 1,
},
.gpio_full = COLLIE_GPIO_CO,
.gpio_charge_on = COLLIE_GPIO_CHARGE_ON,
.technology = POWER_SUPPLY_TECHNOLOGY_LIPO,
.gpio_bat = COLLIE_GPIO_MBAT_ON,
.adc_bat = UCB_ADC_INP_AD1,
.adc_bat_divider = 155,
.bat_max = 4310000,
.bat_min = 1551 * 1000000 / 414,
.gpio_temp = COLLIE_GPIO_TMP_ON,
.adc_temp = UCB_ADC_INP_AD0,
.adc_temp_divider = 10000,
};
static struct collie_bat collie_bat_bu = {
.status = POWER_SUPPLY_STATUS_UNKNOWN,
.full_chrg = -1,
.psy = {
.name = "backup-battery",
.type = POWER_SUPPLY_TYPE_BATTERY,
.properties = collie_bat_bu_props,
.num_properties = ARRAY_SIZE(collie_bat_bu_props),
.get_property = collie_bat_get_property,
.external_power_changed = collie_bat_external_power_changed,
},
.gpio_full = -1,
.gpio_charge_on = -1,
.technology = POWER_SUPPLY_TECHNOLOGY_LiMn,
.gpio_bat = COLLIE_GPIO_BBAT_ON,
.adc_bat = UCB_ADC_INP_AD1,
.adc_bat_divider = 155,
.bat_max = 3000000,
.bat_min = 1900000,
.gpio_temp = -1,
.adc_temp = -1,
.adc_temp_divider = -1,
};
static struct gpio collie_batt_gpios[] = {
{ COLLIE_GPIO_CO, GPIOF_IN, "main battery full" },
{ COLLIE_GPIO_MAIN_BAT_LOW, GPIOF_IN, "main battery low" },
{ COLLIE_GPIO_CHARGE_ON, GPIOF_OUT_INIT_LOW, "main charge on" },
{ COLLIE_GPIO_MBAT_ON, GPIOF_OUT_INIT_LOW, "main battery" },
{ COLLIE_GPIO_TMP_ON, GPIOF_OUT_INIT_LOW, "main battery temp" },
{ COLLIE_GPIO_BBAT_ON, GPIOF_OUT_INIT_LOW, "backup battery" },
};
#ifdef CONFIG_PM
static int collie_bat_suspend(struct ucb1x00_dev *dev)
{
/* flush all pending status updates */
flush_work(&bat_work);
return 0;
}
static int collie_bat_resume(struct ucb1x00_dev *dev)
{
/* things may have changed while we were away */
schedule_work(&bat_work);
return 0;
}
#else
#define collie_bat_suspend NULL
#define collie_bat_resume NULL
#endif
static int collie_bat_probe(struct ucb1x00_dev *dev)
{
int ret;
if (!machine_is_collie())
return -ENODEV;
ucb = dev->ucb;
ret = gpio_request_array(collie_batt_gpios,
ARRAY_SIZE(collie_batt_gpios));
if (ret)
return ret;
mutex_init(&collie_bat_main.work_lock);
INIT_WORK(&bat_work, collie_bat_work);
ret = power_supply_register(&dev->ucb->dev, &collie_bat_main.psy);
if (ret)
goto err_psy_reg_main;
ret = power_supply_register(&dev->ucb->dev, &collie_bat_bu.psy);
if (ret)
goto err_psy_reg_bu;
ret = request_irq(gpio_to_irq(COLLIE_GPIO_CO),
collie_bat_gpio_isr,
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
"main full", &collie_bat_main);
if (!ret) {
schedule_work(&bat_work);
return 0;
}
power_supply_unregister(&collie_bat_bu.psy);
err_psy_reg_bu:
power_supply_unregister(&collie_bat_main.psy);
err_psy_reg_main:
/* see comment in collie_bat_remove */
cancel_work_sync(&bat_work);
gpio_free_array(collie_batt_gpios, ARRAY_SIZE(collie_batt_gpios));
return ret;
}
static void collie_bat_remove(struct ucb1x00_dev *dev)
{
free_irq(gpio_to_irq(COLLIE_GPIO_CO), &collie_bat_main);
power_supply_unregister(&collie_bat_bu.psy);
power_supply_unregister(&collie_bat_main.psy);
/*
* Now cancel the bat_work. We won't get any more schedules,
* since all sources (isr and external_power_changed) are
* unregistered now.
*/
cancel_work_sync(&bat_work);
gpio_free_array(collie_batt_gpios, ARRAY_SIZE(collie_batt_gpios));
}
static struct ucb1x00_driver collie_bat_driver = {
.add = collie_bat_probe,
.remove = collie_bat_remove,
.suspend = collie_bat_suspend,
.resume = collie_bat_resume,
};
static int __init collie_bat_init(void)
{
return ucb1x00_register_driver(&collie_bat_driver);
}
static void __exit collie_bat_exit(void)
{
ucb1x00_unregister_driver(&collie_bat_driver);
}
module_init(collie_bat_init);
module_exit(collie_bat_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Thomas Kunze");
MODULE_DESCRIPTION("Collie battery driver");
| gpl-2.0 |
Splitter/android_kernel_htc_msm7x30 | kernel/freezer.c | 1514 | 3915 | /*
* kernel/freezer.c - Function to freeze a process
*
* Originally from kernel/power/process.c
*/
#include <linux/interrupt.h>
#include <linux/suspend.h>
#include <linux/module.h>
#include <linux/syscalls.h>
#include <linux/freezer.h>
/*
* freezing is complete, mark current process as frozen
*/
static inline void frozen_process(void)
{
if (!unlikely(current->flags & PF_NOFREEZE)) {
current->flags |= PF_FROZEN;
wmb();
}
clear_freeze_flag(current);
}
/* Refrigerator is place where frozen processes are stored :-). */
void refrigerator(void)
{
/* Hmm, should we be allowed to suspend when there are realtime
processes around? */
long save;
task_lock(current);
if (freezing(current)) {
frozen_process();
task_unlock(current);
} else {
task_unlock(current);
return;
}
save = current->state;
pr_debug("%s entered refrigerator\n", current->comm);
spin_lock_irq(¤t->sighand->siglock);
recalc_sigpending(); /* We sent fake signal, clean it up */
spin_unlock_irq(¤t->sighand->siglock);
/* prevent accounting of that task to load */
current->flags |= PF_FREEZING;
for (;;) {
set_current_state(TASK_UNINTERRUPTIBLE);
if (!frozen(current))
break;
schedule();
}
/* Remove the accounting blocker */
current->flags &= ~PF_FREEZING;
pr_debug("%s left refrigerator\n", current->comm);
__set_current_state(save);
}
EXPORT_SYMBOL(refrigerator);
static void fake_signal_wake_up(struct task_struct *p)
{
unsigned long flags;
spin_lock_irqsave(&p->sighand->siglock, flags);
signal_wake_up(p, 0);
spin_unlock_irqrestore(&p->sighand->siglock, flags);
}
/**
* freeze_task - send a freeze request to given task
* @p: task to send the request to
* @sig_only: if set, the request will only be sent if the task has the
* PF_FREEZER_NOSIG flag unset
* Return value: 'false', if @sig_only is set and the task has
* PF_FREEZER_NOSIG set or the task is frozen, 'true', otherwise
*
* The freeze request is sent by setting the tasks's TIF_FREEZE flag and
* either sending a fake signal to it or waking it up, depending on whether
* or not it has PF_FREEZER_NOSIG set. If @sig_only is set and the task
* has PF_FREEZER_NOSIG set (ie. it is a typical kernel thread), its
* TIF_FREEZE flag will not be set.
*/
bool freeze_task(struct task_struct *p, bool sig_only)
{
/*
* We first check if the task is freezing and next if it has already
* been frozen to avoid the race with frozen_process() which first marks
* the task as frozen and next clears its TIF_FREEZE.
*/
if (!freezing(p)) {
rmb();
if (frozen(p))
return false;
if (!sig_only || should_send_signal(p))
set_freeze_flag(p);
else
return false;
}
if (should_send_signal(p)) {
if (!signal_pending(p))
fake_signal_wake_up(p);
} else if (sig_only) {
return false;
} else {
wake_up_state(p, TASK_INTERRUPTIBLE);
}
return true;
}
void cancel_freezing(struct task_struct *p)
{
unsigned long flags;
if (freezing(p)) {
pr_debug(" clean up: %s\n", p->comm);
clear_freeze_flag(p);
spin_lock_irqsave(&p->sighand->siglock, flags);
recalc_sigpending_and_wake(p);
spin_unlock_irqrestore(&p->sighand->siglock, flags);
}
}
static int __thaw_process(struct task_struct *p)
{
if (frozen(p)) {
p->flags &= ~PF_FROZEN;
return 1;
}
clear_freeze_flag(p);
return 0;
}
/*
* Wake up a frozen process
*
* task_lock() is needed to prevent the race with refrigerator() which may
* occur if the freezing of tasks fails. Namely, without the lock, if the
* freezing of tasks failed, thaw_tasks() might have run before a task in
* refrigerator() could call frozen_process(), in which case the task would be
* frozen and no one would thaw it.
*/
int thaw_process(struct task_struct *p)
{
task_lock(p);
if (__thaw_process(p) == 1) {
task_unlock(p);
wake_up_process(p);
return 1;
}
task_unlock(p);
return 0;
}
EXPORT_SYMBOL(thaw_process);
| gpl-2.0 |
jameskdev/lge-kernel-msm8960-common | fs/ext4/mballoc.c | 1514 | 141220 | /*
* Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
* Written by Alex Tomas <alex@clusterfs.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 Licens
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-
*/
/*
* mballoc.c contains the multiblocks allocation routines
*/
#include "ext4_jbd2.h"
#include "mballoc.h"
#include <linux/debugfs.h>
#include <linux/slab.h>
#include <trace/events/ext4.h>
/*
* MUSTDO:
* - test ext4_ext_search_left() and ext4_ext_search_right()
* - search for metadata in few groups
*
* TODO v4:
* - normalization should take into account whether file is still open
* - discard preallocations if no free space left (policy?)
* - don't normalize tails
* - quota
* - reservation for superuser
*
* TODO v3:
* - bitmap read-ahead (proposed by Oleg Drokin aka green)
* - track min/max extents in each group for better group selection
* - mb_mark_used() may allocate chunk right after splitting buddy
* - tree of groups sorted by number of free blocks
* - error handling
*/
/*
* The allocation request involve request for multiple number of blocks
* near to the goal(block) value specified.
*
* During initialization phase of the allocator we decide to use the
* group preallocation or inode preallocation depending on the size of
* the file. The size of the file could be the resulting file size we
* would have after allocation, or the current file size, which ever
* is larger. If the size is less than sbi->s_mb_stream_request we
* select to use the group preallocation. The default value of
* s_mb_stream_request is 16 blocks. This can also be tuned via
* /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
* terms of number of blocks.
*
* The main motivation for having small file use group preallocation is to
* ensure that we have small files closer together on the disk.
*
* First stage the allocator looks at the inode prealloc list,
* ext4_inode_info->i_prealloc_list, which contains list of prealloc
* spaces for this particular inode. The inode prealloc space is
* represented as:
*
* pa_lstart -> the logical start block for this prealloc space
* pa_pstart -> the physical start block for this prealloc space
* pa_len -> length for this prealloc space (in clusters)
* pa_free -> free space available in this prealloc space (in clusters)
*
* The inode preallocation space is used looking at the _logical_ start
* block. If only the logical file block falls within the range of prealloc
* space we will consume the particular prealloc space. This makes sure that
* we have contiguous physical blocks representing the file blocks
*
* The important thing to be noted in case of inode prealloc space is that
* we don't modify the values associated to inode prealloc space except
* pa_free.
*
* If we are not able to find blocks in the inode prealloc space and if we
* have the group allocation flag set then we look at the locality group
* prealloc space. These are per CPU prealloc list represented as
*
* ext4_sb_info.s_locality_groups[smp_processor_id()]
*
* The reason for having a per cpu locality group is to reduce the contention
* between CPUs. It is possible to get scheduled at this point.
*
* The locality group prealloc space is used looking at whether we have
* enough free space (pa_free) within the prealloc space.
*
* If we can't allocate blocks via inode prealloc or/and locality group
* prealloc then we look at the buddy cache. The buddy cache is represented
* by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
* mapped to the buddy and bitmap information regarding different
* groups. The buddy information is attached to buddy cache inode so that
* we can access them through the page cache. The information regarding
* each group is loaded via ext4_mb_load_buddy. The information involve
* block bitmap and buddy information. The information are stored in the
* inode as:
*
* { page }
* [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
*
*
* one block each for bitmap and buddy information. So for each group we
* take up 2 blocks. A page can contain blocks_per_page (PAGE_CACHE_SIZE /
* blocksize) blocks. So it can have information regarding groups_per_page
* which is blocks_per_page/2
*
* The buddy cache inode is not stored on disk. The inode is thrown
* away when the filesystem is unmounted.
*
* We look for count number of blocks in the buddy cache. If we were able
* to locate that many free blocks we return with additional information
* regarding rest of the contiguous physical block available
*
* Before allocating blocks via buddy cache we normalize the request
* blocks. This ensure we ask for more blocks that we needed. The extra
* blocks that we get after allocation is added to the respective prealloc
* list. In case of inode preallocation we follow a list of heuristics
* based on file size. This can be found in ext4_mb_normalize_request. If
* we are doing a group prealloc we try to normalize the request to
* sbi->s_mb_group_prealloc. The default value of s_mb_group_prealloc is
* dependent on the cluster size; for non-bigalloc file systems, it is
* 512 blocks. This can be tuned via
* /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
* terms of number of blocks. If we have mounted the file system with -O
* stripe=<value> option the group prealloc request is normalized to the
* the smallest multiple of the stripe value (sbi->s_stripe) which is
* greater than the default mb_group_prealloc.
*
* The regular allocator (using the buddy cache) supports a few tunables.
*
* /sys/fs/ext4/<partition>/mb_min_to_scan
* /sys/fs/ext4/<partition>/mb_max_to_scan
* /sys/fs/ext4/<partition>/mb_order2_req
*
* The regular allocator uses buddy scan only if the request len is power of
* 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
* value of s_mb_order2_reqs can be tuned via
* /sys/fs/ext4/<partition>/mb_order2_req. If the request len is equal to
* stripe size (sbi->s_stripe), we try to search for contiguous block in
* stripe size. This should result in better allocation on RAID setups. If
* not, we search in the specific group using bitmap for best extents. The
* tunable min_to_scan and max_to_scan control the behaviour here.
* min_to_scan indicate how long the mballoc __must__ look for a best
* extent and max_to_scan indicates how long the mballoc __can__ look for a
* best extent in the found extents. Searching for the blocks starts with
* the group specified as the goal value in allocation context via
* ac_g_ex. Each group is first checked based on the criteria whether it
* can be used for allocation. ext4_mb_good_group explains how the groups are
* checked.
*
* Both the prealloc space are getting populated as above. So for the first
* request we will hit the buddy cache which will result in this prealloc
* space getting filled. The prealloc space is then later used for the
* subsequent request.
*/
/*
* mballoc operates on the following data:
* - on-disk bitmap
* - in-core buddy (actually includes buddy and bitmap)
* - preallocation descriptors (PAs)
*
* there are two types of preallocations:
* - inode
* assiged to specific inode and can be used for this inode only.
* it describes part of inode's space preallocated to specific
* physical blocks. any block from that preallocated can be used
* independent. the descriptor just tracks number of blocks left
* unused. so, before taking some block from descriptor, one must
* make sure corresponded logical block isn't allocated yet. this
* also means that freeing any block within descriptor's range
* must discard all preallocated blocks.
* - locality group
* assigned to specific locality group which does not translate to
* permanent set of inodes: inode can join and leave group. space
* from this type of preallocation can be used for any inode. thus
* it's consumed from the beginning to the end.
*
* relation between them can be expressed as:
* in-core buddy = on-disk bitmap + preallocation descriptors
*
* this mean blocks mballoc considers used are:
* - allocated blocks (persistent)
* - preallocated blocks (non-persistent)
*
* consistency in mballoc world means that at any time a block is either
* free or used in ALL structures. notice: "any time" should not be read
* literally -- time is discrete and delimited by locks.
*
* to keep it simple, we don't use block numbers, instead we count number of
* blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
*
* all operations can be expressed as:
* - init buddy: buddy = on-disk + PAs
* - new PA: buddy += N; PA = N
* - use inode PA: on-disk += N; PA -= N
* - discard inode PA buddy -= on-disk - PA; PA = 0
* - use locality group PA on-disk += N; PA -= N
* - discard locality group PA buddy -= PA; PA = 0
* note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
* is used in real operation because we can't know actual used
* bits from PA, only from on-disk bitmap
*
* if we follow this strict logic, then all operations above should be atomic.
* given some of them can block, we'd have to use something like semaphores
* killing performance on high-end SMP hardware. let's try to relax it using
* the following knowledge:
* 1) if buddy is referenced, it's already initialized
* 2) while block is used in buddy and the buddy is referenced,
* nobody can re-allocate that block
* 3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
* bit set and PA claims same block, it's OK. IOW, one can set bit in
* on-disk bitmap if buddy has same bit set or/and PA covers corresponded
* block
*
* so, now we're building a concurrency table:
* - init buddy vs.
* - new PA
* blocks for PA are allocated in the buddy, buddy must be referenced
* until PA is linked to allocation group to avoid concurrent buddy init
* - use inode PA
* we need to make sure that either on-disk bitmap or PA has uptodate data
* given (3) we care that PA-=N operation doesn't interfere with init
* - discard inode PA
* the simplest way would be to have buddy initialized by the discard
* - use locality group PA
* again PA-=N must be serialized with init
* - discard locality group PA
* the simplest way would be to have buddy initialized by the discard
* - new PA vs.
* - use inode PA
* i_data_sem serializes them
* - discard inode PA
* discard process must wait until PA isn't used by another process
* - use locality group PA
* some mutex should serialize them
* - discard locality group PA
* discard process must wait until PA isn't used by another process
* - use inode PA
* - use inode PA
* i_data_sem or another mutex should serializes them
* - discard inode PA
* discard process must wait until PA isn't used by another process
* - use locality group PA
* nothing wrong here -- they're different PAs covering different blocks
* - discard locality group PA
* discard process must wait until PA isn't used by another process
*
* now we're ready to make few consequences:
* - PA is referenced and while it is no discard is possible
* - PA is referenced until block isn't marked in on-disk bitmap
* - PA changes only after on-disk bitmap
* - discard must not compete with init. either init is done before
* any discard or they're serialized somehow
* - buddy init as sum of on-disk bitmap and PAs is done atomically
*
* a special case when we've used PA to emptiness. no need to modify buddy
* in this case, but we should care about concurrent init
*
*/
/*
* Logic in few words:
*
* - allocation:
* load group
* find blocks
* mark bits in on-disk bitmap
* release group
*
* - use preallocation:
* find proper PA (per-inode or group)
* load group
* mark bits in on-disk bitmap
* release group
* release PA
*
* - free:
* load group
* mark bits in on-disk bitmap
* release group
*
* - discard preallocations in group:
* mark PAs deleted
* move them onto local list
* load on-disk bitmap
* load group
* remove PA from object (inode or locality group)
* mark free blocks in-core
*
* - discard inode's preallocations:
*/
/*
* Locking rules
*
* Locks:
* - bitlock on a group (group)
* - object (inode/locality) (object)
* - per-pa lock (pa)
*
* Paths:
* - new pa
* object
* group
*
* - find and use pa:
* pa
*
* - release consumed pa:
* pa
* group
* object
*
* - generate in-core bitmap:
* group
* pa
*
* - discard all for given object (inode, locality group):
* object
* pa
* group
*
* - discard all for given group:
* group
* pa
* group
* object
*
*/
static struct kmem_cache *ext4_pspace_cachep;
static struct kmem_cache *ext4_ac_cachep;
static struct kmem_cache *ext4_free_data_cachep;
/* We create slab caches for groupinfo data structures based on the
* superblock block size. There will be one per mounted filesystem for
* each unique s_blocksize_bits */
#define NR_GRPINFO_CACHES 8
static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
static const char *ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
"ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
"ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
"ext4_groupinfo_64k", "ext4_groupinfo_128k"
};
static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
ext4_group_t group);
static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
ext4_group_t group);
static void ext4_free_data_callback(struct super_block *sb,
struct ext4_journal_cb_entry *jce, int rc);
static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
{
#if BITS_PER_LONG == 64
*bit += ((unsigned long) addr & 7UL) << 3;
addr = (void *) ((unsigned long) addr & ~7UL);
#elif BITS_PER_LONG == 32
*bit += ((unsigned long) addr & 3UL) << 3;
addr = (void *) ((unsigned long) addr & ~3UL);
#else
#error "how many bits you are?!"
#endif
return addr;
}
static inline int mb_test_bit(int bit, void *addr)
{
/*
* ext4_test_bit on architecture like powerpc
* needs unsigned long aligned address
*/
addr = mb_correct_addr_and_bit(&bit, addr);
return ext4_test_bit(bit, addr);
}
static inline void mb_set_bit(int bit, void *addr)
{
addr = mb_correct_addr_and_bit(&bit, addr);
ext4_set_bit(bit, addr);
}
static inline void mb_clear_bit(int bit, void *addr)
{
addr = mb_correct_addr_and_bit(&bit, addr);
ext4_clear_bit(bit, addr);
}
static inline int mb_find_next_zero_bit(void *addr, int max, int start)
{
int fix = 0, ret, tmpmax;
addr = mb_correct_addr_and_bit(&fix, addr);
tmpmax = max + fix;
start += fix;
ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
if (ret > max)
return max;
return ret;
}
static inline int mb_find_next_bit(void *addr, int max, int start)
{
int fix = 0, ret, tmpmax;
addr = mb_correct_addr_and_bit(&fix, addr);
tmpmax = max + fix;
start += fix;
ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
if (ret > max)
return max;
return ret;
}
static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
{
char *bb;
BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
BUG_ON(max == NULL);
if (order > e4b->bd_blkbits + 1) {
*max = 0;
return NULL;
}
/* at order 0 we see each particular block */
if (order == 0) {
*max = 1 << (e4b->bd_blkbits + 3);
return e4b->bd_bitmap;
}
bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
*max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
return bb;
}
#ifdef DOUBLE_CHECK
static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
int first, int count)
{
int i;
struct super_block *sb = e4b->bd_sb;
if (unlikely(e4b->bd_info->bb_bitmap == NULL))
return;
assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
for (i = 0; i < count; i++) {
if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
ext4_fsblk_t blocknr;
blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
ext4_grp_locked_error(sb, e4b->bd_group,
inode ? inode->i_ino : 0,
blocknr,
"freeing block already freed "
"(bit %u)",
first + i);
}
mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
}
}
static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
{
int i;
if (unlikely(e4b->bd_info->bb_bitmap == NULL))
return;
assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
for (i = 0; i < count; i++) {
BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
}
}
static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
{
if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
unsigned char *b1, *b2;
int i;
b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
b2 = (unsigned char *) bitmap;
for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
if (b1[i] != b2[i]) {
ext4_msg(e4b->bd_sb, KERN_ERR,
"corruption in group %u "
"at byte %u(%u): %x in copy != %x "
"on disk/prealloc",
e4b->bd_group, i, i * 8, b1[i], b2[i]);
BUG();
}
}
}
}
#else
static inline void mb_free_blocks_double(struct inode *inode,
struct ext4_buddy *e4b, int first, int count)
{
return;
}
static inline void mb_mark_used_double(struct ext4_buddy *e4b,
int first, int count)
{
return;
}
static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
{
return;
}
#endif
#ifdef AGGRESSIVE_CHECK
#define MB_CHECK_ASSERT(assert) \
do { \
if (!(assert)) { \
printk(KERN_EMERG \
"Assertion failure in %s() at %s:%d: \"%s\"\n", \
function, file, line, # assert); \
BUG(); \
} \
} while (0)
static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
const char *function, int line)
{
struct super_block *sb = e4b->bd_sb;
int order = e4b->bd_blkbits + 1;
int max;
int max2;
int i;
int j;
int k;
int count;
struct ext4_group_info *grp;
int fragments = 0;
int fstart;
struct list_head *cur;
void *buddy;
void *buddy2;
{
static int mb_check_counter;
if (mb_check_counter++ % 100 != 0)
return 0;
}
while (order > 1) {
buddy = mb_find_buddy(e4b, order, &max);
MB_CHECK_ASSERT(buddy);
buddy2 = mb_find_buddy(e4b, order - 1, &max2);
MB_CHECK_ASSERT(buddy2);
MB_CHECK_ASSERT(buddy != buddy2);
MB_CHECK_ASSERT(max * 2 == max2);
count = 0;
for (i = 0; i < max; i++) {
if (mb_test_bit(i, buddy)) {
/* only single bit in buddy2 may be 1 */
if (!mb_test_bit(i << 1, buddy2)) {
MB_CHECK_ASSERT(
mb_test_bit((i<<1)+1, buddy2));
} else if (!mb_test_bit((i << 1) + 1, buddy2)) {
MB_CHECK_ASSERT(
mb_test_bit(i << 1, buddy2));
}
continue;
}
/* both bits in buddy2 must be 1 */
MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
for (j = 0; j < (1 << order); j++) {
k = (i * (1 << order)) + j;
MB_CHECK_ASSERT(
!mb_test_bit(k, e4b->bd_bitmap));
}
count++;
}
MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
order--;
}
fstart = -1;
buddy = mb_find_buddy(e4b, 0, &max);
for (i = 0; i < max; i++) {
if (!mb_test_bit(i, buddy)) {
MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
if (fstart == -1) {
fragments++;
fstart = i;
}
continue;
}
fstart = -1;
/* check used bits only */
for (j = 0; j < e4b->bd_blkbits + 1; j++) {
buddy2 = mb_find_buddy(e4b, j, &max2);
k = i >> j;
MB_CHECK_ASSERT(k < max2);
MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
}
}
MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
grp = ext4_get_group_info(sb, e4b->bd_group);
list_for_each(cur, &grp->bb_prealloc_list) {
ext4_group_t groupnr;
struct ext4_prealloc_space *pa;
pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
MB_CHECK_ASSERT(groupnr == e4b->bd_group);
for (i = 0; i < pa->pa_len; i++)
MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
}
return 0;
}
#undef MB_CHECK_ASSERT
#define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
__FILE__, __func__, __LINE__)
#else
#define mb_check_buddy(e4b)
#endif
/*
* Divide blocks started from @first with length @len into
* smaller chunks with power of 2 blocks.
* Clear the bits in bitmap which the blocks of the chunk(s) covered,
* then increase bb_counters[] for corresponded chunk size.
*/
static void ext4_mb_mark_free_simple(struct super_block *sb,
void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
struct ext4_group_info *grp)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_grpblk_t min;
ext4_grpblk_t max;
ext4_grpblk_t chunk;
unsigned short border;
BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
border = 2 << sb->s_blocksize_bits;
while (len > 0) {
/* find how many blocks can be covered since this position */
max = ffs(first | border) - 1;
/* find how many blocks of power 2 we need to mark */
min = fls(len) - 1;
if (max < min)
min = max;
chunk = 1 << min;
/* mark multiblock chunks only */
grp->bb_counters[min]++;
if (min > 0)
mb_clear_bit(first >> min,
buddy + sbi->s_mb_offsets[min]);
len -= chunk;
first += chunk;
}
}
/*
* Cache the order of the largest free extent we have available in this block
* group.
*/
static void
mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
{
int i;
int bits;
grp->bb_largest_free_order = -1; /* uninit */
bits = sb->s_blocksize_bits + 1;
for (i = bits; i >= 0; i--) {
if (grp->bb_counters[i] > 0) {
grp->bb_largest_free_order = i;
break;
}
}
}
static noinline_for_stack
void ext4_mb_generate_buddy(struct super_block *sb,
void *buddy, void *bitmap, ext4_group_t group)
{
struct ext4_group_info *grp = ext4_get_group_info(sb, group);
ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
ext4_grpblk_t i = 0;
ext4_grpblk_t first;
ext4_grpblk_t len;
unsigned free = 0;
unsigned fragments = 0;
unsigned long long period = get_cycles();
/* initialize buddy from bitmap which is aggregation
* of on-disk bitmap and preallocations */
i = mb_find_next_zero_bit(bitmap, max, 0);
grp->bb_first_free = i;
while (i < max) {
fragments++;
first = i;
i = mb_find_next_bit(bitmap, max, i);
len = i - first;
free += len;
if (len > 1)
ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
else
grp->bb_counters[0]++;
if (i < max)
i = mb_find_next_zero_bit(bitmap, max, i);
}
grp->bb_fragments = fragments;
if (free != grp->bb_free) {
ext4_grp_locked_error(sb, group, 0, 0,
"%u clusters in bitmap, %u in gd",
free, grp->bb_free);
/*
* If we intent to continue, we consider group descritor
* corrupt and update bb_free using bitmap value
*/
grp->bb_free = free;
}
mb_set_largest_free_order(sb, grp);
clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
period = get_cycles() - period;
spin_lock(&EXT4_SB(sb)->s_bal_lock);
EXT4_SB(sb)->s_mb_buddies_generated++;
EXT4_SB(sb)->s_mb_generation_time += period;
spin_unlock(&EXT4_SB(sb)->s_bal_lock);
}
/* The buddy information is attached the buddy cache inode
* for convenience. The information regarding each group
* is loaded via ext4_mb_load_buddy. The information involve
* block bitmap and buddy information. The information are
* stored in the inode as
*
* { page }
* [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
*
*
* one block each for bitmap and buddy information.
* So for each group we take up 2 blocks. A page can
* contain blocks_per_page (PAGE_CACHE_SIZE / blocksize) blocks.
* So it can have information regarding groups_per_page which
* is blocks_per_page/2
*
* Locking note: This routine takes the block group lock of all groups
* for this page; do not hold this lock when calling this routine!
*/
static int ext4_mb_init_cache(struct page *page, char *incore)
{
ext4_group_t ngroups;
int blocksize;
int blocks_per_page;
int groups_per_page;
int err = 0;
int i;
ext4_group_t first_group, group;
int first_block;
struct super_block *sb;
struct buffer_head *bhs;
struct buffer_head **bh;
struct inode *inode;
char *data;
char *bitmap;
struct ext4_group_info *grinfo;
mb_debug(1, "init page %lu\n", page->index);
inode = page->mapping->host;
sb = inode->i_sb;
ngroups = ext4_get_groups_count(sb);
blocksize = 1 << inode->i_blkbits;
blocks_per_page = PAGE_CACHE_SIZE / blocksize;
groups_per_page = blocks_per_page >> 1;
if (groups_per_page == 0)
groups_per_page = 1;
/* allocate buffer_heads to read bitmaps */
if (groups_per_page > 1) {
i = sizeof(struct buffer_head *) * groups_per_page;
bh = kzalloc(i, GFP_NOFS);
if (bh == NULL) {
err = -ENOMEM;
goto out;
}
} else
bh = &bhs;
first_group = page->index * blocks_per_page / 2;
/* read all groups the page covers into the cache */
for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
if (group >= ngroups)
break;
grinfo = ext4_get_group_info(sb, group);
/*
* If page is uptodate then we came here after online resize
* which added some new uninitialized group info structs, so
* we must skip all initialized uptodate buddies on the page,
* which may be currently in use by an allocating task.
*/
if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
bh[i] = NULL;
continue;
}
if (!(bh[i] = ext4_read_block_bitmap_nowait(sb, group))) {
err = -ENOMEM;
goto out;
}
mb_debug(1, "read bitmap for group %u\n", group);
}
/* wait for I/O completion */
for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
if (bh[i] && ext4_wait_block_bitmap(sb, group, bh[i])) {
err = -EIO;
goto out;
}
}
first_block = page->index * blocks_per_page;
for (i = 0; i < blocks_per_page; i++) {
int group;
group = (first_block + i) >> 1;
if (group >= ngroups)
break;
if (!bh[group - first_group])
/* skip initialized uptodate buddy */
continue;
/*
* data carry information regarding this
* particular group in the format specified
* above
*
*/
data = page_address(page) + (i * blocksize);
bitmap = bh[group - first_group]->b_data;
/*
* We place the buddy block and bitmap block
* close together
*/
if ((first_block + i) & 1) {
/* this is block of buddy */
BUG_ON(incore == NULL);
mb_debug(1, "put buddy for group %u in page %lu/%x\n",
group, page->index, i * blocksize);
trace_ext4_mb_buddy_bitmap_load(sb, group);
grinfo = ext4_get_group_info(sb, group);
grinfo->bb_fragments = 0;
memset(grinfo->bb_counters, 0,
sizeof(*grinfo->bb_counters) *
(sb->s_blocksize_bits+2));
/*
* incore got set to the group block bitmap below
*/
ext4_lock_group(sb, group);
/* init the buddy */
memset(data, 0xff, blocksize);
ext4_mb_generate_buddy(sb, data, incore, group);
ext4_unlock_group(sb, group);
incore = NULL;
} else {
/* this is block of bitmap */
BUG_ON(incore != NULL);
mb_debug(1, "put bitmap for group %u in page %lu/%x\n",
group, page->index, i * blocksize);
trace_ext4_mb_bitmap_load(sb, group);
/* see comments in ext4_mb_put_pa() */
ext4_lock_group(sb, group);
memcpy(data, bitmap, blocksize);
/* mark all preallocated blks used in in-core bitmap */
ext4_mb_generate_from_pa(sb, data, group);
ext4_mb_generate_from_freelist(sb, data, group);
ext4_unlock_group(sb, group);
/* set incore so that the buddy information can be
* generated using this
*/
incore = data;
}
}
SetPageUptodate(page);
out:
if (bh) {
for (i = 0; i < groups_per_page; i++)
brelse(bh[i]);
if (bh != &bhs)
kfree(bh);
}
return err;
}
/*
* Lock the buddy and bitmap pages. This make sure other parallel init_group
* on the same buddy page doesn't happen whild holding the buddy page lock.
* Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
* are on the same page e4b->bd_buddy_page is NULL and return value is 0.
*/
static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
ext4_group_t group, struct ext4_buddy *e4b)
{
struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
int block, pnum, poff;
int blocks_per_page;
struct page *page;
e4b->bd_buddy_page = NULL;
e4b->bd_bitmap_page = NULL;
blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
/*
* the buddy cache inode stores the block bitmap
* and buddy information in consecutive blocks.
* So for each group we need two blocks.
*/
block = group * 2;
pnum = block / blocks_per_page;
poff = block % blocks_per_page;
page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
if (!page)
return -EIO;
BUG_ON(page->mapping != inode->i_mapping);
e4b->bd_bitmap_page = page;
e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
if (blocks_per_page >= 2) {
/* buddy and bitmap are on the same page */
return 0;
}
block++;
pnum = block / blocks_per_page;
poff = block % blocks_per_page;
page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
if (!page)
return -EIO;
BUG_ON(page->mapping != inode->i_mapping);
e4b->bd_buddy_page = page;
return 0;
}
static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
{
if (e4b->bd_bitmap_page) {
unlock_page(e4b->bd_bitmap_page);
page_cache_release(e4b->bd_bitmap_page);
}
if (e4b->bd_buddy_page) {
unlock_page(e4b->bd_buddy_page);
page_cache_release(e4b->bd_buddy_page);
}
}
/*
* Locking note: This routine calls ext4_mb_init_cache(), which takes the
* block group lock of all groups for this page; do not hold the BG lock when
* calling this routine!
*/
static noinline_for_stack
int ext4_mb_init_group(struct super_block *sb, ext4_group_t group)
{
struct ext4_group_info *this_grp;
struct ext4_buddy e4b;
struct page *page;
int ret = 0;
mb_debug(1, "init group %u\n", group);
this_grp = ext4_get_group_info(sb, group);
/*
* This ensures that we don't reinit the buddy cache
* page which map to the group from which we are already
* allocating. If we are looking at the buddy cache we would
* have taken a reference using ext4_mb_load_buddy and that
* would have pinned buddy page to page cache.
*/
ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b);
if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
/*
* somebody initialized the group
* return without doing anything
*/
goto err;
}
page = e4b.bd_bitmap_page;
ret = ext4_mb_init_cache(page, NULL);
if (ret)
goto err;
if (!PageUptodate(page)) {
ret = -EIO;
goto err;
}
mark_page_accessed(page);
if (e4b.bd_buddy_page == NULL) {
/*
* If both the bitmap and buddy are in
* the same page we don't need to force
* init the buddy
*/
ret = 0;
goto err;
}
/* init buddy cache */
page = e4b.bd_buddy_page;
ret = ext4_mb_init_cache(page, e4b.bd_bitmap);
if (ret)
goto err;
if (!PageUptodate(page)) {
ret = -EIO;
goto err;
}
mark_page_accessed(page);
err:
ext4_mb_put_buddy_page_lock(&e4b);
return ret;
}
/*
* Locking note: This routine calls ext4_mb_init_cache(), which takes the
* block group lock of all groups for this page; do not hold the BG lock when
* calling this routine!
*/
static noinline_for_stack int
ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
struct ext4_buddy *e4b)
{
int blocks_per_page;
int block;
int pnum;
int poff;
struct page *page;
int ret;
struct ext4_group_info *grp;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct inode *inode = sbi->s_buddy_cache;
mb_debug(1, "load group %u\n", group);
blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
grp = ext4_get_group_info(sb, group);
e4b->bd_blkbits = sb->s_blocksize_bits;
e4b->bd_info = grp;
e4b->bd_sb = sb;
e4b->bd_group = group;
e4b->bd_buddy_page = NULL;
e4b->bd_bitmap_page = NULL;
if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
/*
* we need full data about the group
* to make a good selection
*/
ret = ext4_mb_init_group(sb, group);
if (ret)
return ret;
}
/*
* the buddy cache inode stores the block bitmap
* and buddy information in consecutive blocks.
* So for each group we need two blocks.
*/
block = group * 2;
pnum = block / blocks_per_page;
poff = block % blocks_per_page;
/* we could use find_or_create_page(), but it locks page
* what we'd like to avoid in fast path ... */
page = find_get_page(inode->i_mapping, pnum);
if (page == NULL || !PageUptodate(page)) {
if (page)
/*
* drop the page reference and try
* to get the page with lock. If we
* are not uptodate that implies
* somebody just created the page but
* is yet to initialize the same. So
* wait for it to initialize.
*/
page_cache_release(page);
page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
if (page) {
BUG_ON(page->mapping != inode->i_mapping);
if (!PageUptodate(page)) {
ret = ext4_mb_init_cache(page, NULL);
if (ret) {
unlock_page(page);
goto err;
}
mb_cmp_bitmaps(e4b, page_address(page) +
(poff * sb->s_blocksize));
}
unlock_page(page);
}
}
if (page == NULL || !PageUptodate(page)) {
ret = -EIO;
goto err;
}
e4b->bd_bitmap_page = page;
e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
mark_page_accessed(page);
block++;
pnum = block / blocks_per_page;
poff = block % blocks_per_page;
page = find_get_page(inode->i_mapping, pnum);
if (page == NULL || !PageUptodate(page)) {
if (page)
page_cache_release(page);
page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
if (page) {
BUG_ON(page->mapping != inode->i_mapping);
if (!PageUptodate(page)) {
ret = ext4_mb_init_cache(page, e4b->bd_bitmap);
if (ret) {
unlock_page(page);
goto err;
}
}
unlock_page(page);
}
}
if (page == NULL || !PageUptodate(page)) {
ret = -EIO;
goto err;
}
e4b->bd_buddy_page = page;
e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
mark_page_accessed(page);
BUG_ON(e4b->bd_bitmap_page == NULL);
BUG_ON(e4b->bd_buddy_page == NULL);
return 0;
err:
if (page)
page_cache_release(page);
if (e4b->bd_bitmap_page)
page_cache_release(e4b->bd_bitmap_page);
if (e4b->bd_buddy_page)
page_cache_release(e4b->bd_buddy_page);
e4b->bd_buddy = NULL;
e4b->bd_bitmap = NULL;
return ret;
}
static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
{
if (e4b->bd_bitmap_page)
page_cache_release(e4b->bd_bitmap_page);
if (e4b->bd_buddy_page)
page_cache_release(e4b->bd_buddy_page);
}
static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
{
int order = 1;
void *bb;
BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
bb = e4b->bd_buddy;
while (order <= e4b->bd_blkbits + 1) {
block = block >> 1;
if (!mb_test_bit(block, bb)) {
/* this block is part of buddy of order 'order' */
return order;
}
bb += 1 << (e4b->bd_blkbits - order);
order++;
}
return 0;
}
static void mb_clear_bits(void *bm, int cur, int len)
{
__u32 *addr;
len = cur + len;
while (cur < len) {
if ((cur & 31) == 0 && (len - cur) >= 32) {
/* fast path: clear whole word at once */
addr = bm + (cur >> 3);
*addr = 0;
cur += 32;
continue;
}
mb_clear_bit(cur, bm);
cur++;
}
}
void ext4_set_bits(void *bm, int cur, int len)
{
__u32 *addr;
len = cur + len;
while (cur < len) {
if ((cur & 31) == 0 && (len - cur) >= 32) {
/* fast path: set whole word at once */
addr = bm + (cur >> 3);
*addr = 0xffffffff;
cur += 32;
continue;
}
mb_set_bit(cur, bm);
cur++;
}
}
static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
int first, int count)
{
int block = 0;
int max = 0;
int order;
void *buddy;
void *buddy2;
struct super_block *sb = e4b->bd_sb;
BUG_ON(first + count > (sb->s_blocksize << 3));
assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
mb_check_buddy(e4b);
mb_free_blocks_double(inode, e4b, first, count);
e4b->bd_info->bb_free += count;
if (first < e4b->bd_info->bb_first_free)
e4b->bd_info->bb_first_free = first;
/* let's maintain fragments counter */
if (first != 0)
block = !mb_test_bit(first - 1, e4b->bd_bitmap);
if (first + count < EXT4_SB(sb)->s_mb_maxs[0])
max = !mb_test_bit(first + count, e4b->bd_bitmap);
if (block && max)
e4b->bd_info->bb_fragments--;
else if (!block && !max)
e4b->bd_info->bb_fragments++;
/* let's maintain buddy itself */
while (count-- > 0) {
block = first++;
order = 0;
if (!mb_test_bit(block, e4b->bd_bitmap)) {
ext4_fsblk_t blocknr;
blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
blocknr += EXT4_C2B(EXT4_SB(sb), block);
ext4_grp_locked_error(sb, e4b->bd_group,
inode ? inode->i_ino : 0,
blocknr,
"freeing already freed block "
"(bit %u)", block);
}
mb_clear_bit(block, e4b->bd_bitmap);
e4b->bd_info->bb_counters[order]++;
/* start of the buddy */
buddy = mb_find_buddy(e4b, order, &max);
do {
block &= ~1UL;
if (mb_test_bit(block, buddy) ||
mb_test_bit(block + 1, buddy))
break;
/* both the buddies are free, try to coalesce them */
buddy2 = mb_find_buddy(e4b, order + 1, &max);
if (!buddy2)
break;
if (order > 0) {
/* for special purposes, we don't set
* free bits in bitmap */
mb_set_bit(block, buddy);
mb_set_bit(block + 1, buddy);
}
e4b->bd_info->bb_counters[order]--;
e4b->bd_info->bb_counters[order]--;
block = block >> 1;
order++;
e4b->bd_info->bb_counters[order]++;
mb_clear_bit(block, buddy2);
buddy = buddy2;
} while (1);
}
mb_set_largest_free_order(sb, e4b->bd_info);
mb_check_buddy(e4b);
}
static int mb_find_extent(struct ext4_buddy *e4b, int order, int block,
int needed, struct ext4_free_extent *ex)
{
int next = block;
int max;
void *buddy;
assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
BUG_ON(ex == NULL);
buddy = mb_find_buddy(e4b, order, &max);
BUG_ON(buddy == NULL);
BUG_ON(block >= max);
if (mb_test_bit(block, buddy)) {
ex->fe_len = 0;
ex->fe_start = 0;
ex->fe_group = 0;
return 0;
}
/* FIXME dorp order completely ? */
if (likely(order == 0)) {
/* find actual order */
order = mb_find_order_for_block(e4b, block);
block = block >> order;
}
ex->fe_len = 1 << order;
ex->fe_start = block << order;
ex->fe_group = e4b->bd_group;
/* calc difference from given start */
next = next - ex->fe_start;
ex->fe_len -= next;
ex->fe_start += next;
while (needed > ex->fe_len &&
(buddy = mb_find_buddy(e4b, order, &max))) {
if (block + 1 >= max)
break;
next = (block + 1) * (1 << order);
if (mb_test_bit(next, e4b->bd_bitmap))
break;
order = mb_find_order_for_block(e4b, next);
block = next >> order;
ex->fe_len += 1 << order;
}
BUG_ON(ex->fe_start + ex->fe_len > (1 << (e4b->bd_blkbits + 3)));
return ex->fe_len;
}
static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
{
int ord;
int mlen = 0;
int max = 0;
int cur;
int start = ex->fe_start;
int len = ex->fe_len;
unsigned ret = 0;
int len0 = len;
void *buddy;
BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
BUG_ON(e4b->bd_group != ex->fe_group);
assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
mb_check_buddy(e4b);
mb_mark_used_double(e4b, start, len);
e4b->bd_info->bb_free -= len;
if (e4b->bd_info->bb_first_free == start)
e4b->bd_info->bb_first_free += len;
/* let's maintain fragments counter */
if (start != 0)
mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
max = !mb_test_bit(start + len, e4b->bd_bitmap);
if (mlen && max)
e4b->bd_info->bb_fragments++;
else if (!mlen && !max)
e4b->bd_info->bb_fragments--;
/* let's maintain buddy itself */
while (len) {
ord = mb_find_order_for_block(e4b, start);
if (((start >> ord) << ord) == start && len >= (1 << ord)) {
/* the whole chunk may be allocated at once! */
mlen = 1 << ord;
buddy = mb_find_buddy(e4b, ord, &max);
BUG_ON((start >> ord) >= max);
mb_set_bit(start >> ord, buddy);
e4b->bd_info->bb_counters[ord]--;
start += mlen;
len -= mlen;
BUG_ON(len < 0);
continue;
}
/* store for history */
if (ret == 0)
ret = len | (ord << 16);
/* we have to split large buddy */
BUG_ON(ord <= 0);
buddy = mb_find_buddy(e4b, ord, &max);
mb_set_bit(start >> ord, buddy);
e4b->bd_info->bb_counters[ord]--;
ord--;
cur = (start >> ord) & ~1U;
buddy = mb_find_buddy(e4b, ord, &max);
mb_clear_bit(cur, buddy);
mb_clear_bit(cur + 1, buddy);
e4b->bd_info->bb_counters[ord]++;
e4b->bd_info->bb_counters[ord]++;
}
mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
ext4_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
mb_check_buddy(e4b);
return ret;
}
/*
* Must be called under group lock!
*/
static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
struct ext4_buddy *e4b)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
int ret;
BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
BUG_ON(ac->ac_status == AC_STATUS_FOUND);
ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
ret = mb_mark_used(e4b, &ac->ac_b_ex);
/* preallocation can change ac_b_ex, thus we store actually
* allocated blocks for history */
ac->ac_f_ex = ac->ac_b_ex;
ac->ac_status = AC_STATUS_FOUND;
ac->ac_tail = ret & 0xffff;
ac->ac_buddy = ret >> 16;
/*
* take the page reference. We want the page to be pinned
* so that we don't get a ext4_mb_init_cache_call for this
* group until we update the bitmap. That would mean we
* double allocate blocks. The reference is dropped
* in ext4_mb_release_context
*/
ac->ac_bitmap_page = e4b->bd_bitmap_page;
get_page(ac->ac_bitmap_page);
ac->ac_buddy_page = e4b->bd_buddy_page;
get_page(ac->ac_buddy_page);
/* store last allocated for subsequent stream allocation */
if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
spin_lock(&sbi->s_md_lock);
sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
spin_unlock(&sbi->s_md_lock);
}
}
/*
* regular allocator, for general purposes allocation
*/
static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
struct ext4_buddy *e4b,
int finish_group)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
struct ext4_free_extent *bex = &ac->ac_b_ex;
struct ext4_free_extent *gex = &ac->ac_g_ex;
struct ext4_free_extent ex;
int max;
if (ac->ac_status == AC_STATUS_FOUND)
return;
/*
* We don't want to scan for a whole year
*/
if (ac->ac_found > sbi->s_mb_max_to_scan &&
!(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
ac->ac_status = AC_STATUS_BREAK;
return;
}
/*
* Haven't found good chunk so far, let's continue
*/
if (bex->fe_len < gex->fe_len)
return;
if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
&& bex->fe_group == e4b->bd_group) {
/* recheck chunk's availability - we don't know
* when it was found (within this lock-unlock
* period or not) */
max = mb_find_extent(e4b, 0, bex->fe_start, gex->fe_len, &ex);
if (max >= gex->fe_len) {
ext4_mb_use_best_found(ac, e4b);
return;
}
}
}
/*
* The routine checks whether found extent is good enough. If it is,
* then the extent gets marked used and flag is set to the context
* to stop scanning. Otherwise, the extent is compared with the
* previous found extent and if new one is better, then it's stored
* in the context. Later, the best found extent will be used, if
* mballoc can't find good enough extent.
*
* FIXME: real allocation policy is to be designed yet!
*/
static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
struct ext4_free_extent *ex,
struct ext4_buddy *e4b)
{
struct ext4_free_extent *bex = &ac->ac_b_ex;
struct ext4_free_extent *gex = &ac->ac_g_ex;
BUG_ON(ex->fe_len <= 0);
BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
ac->ac_found++;
/*
* The special case - take what you catch first
*/
if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
*bex = *ex;
ext4_mb_use_best_found(ac, e4b);
return;
}
/*
* Let's check whether the chuck is good enough
*/
if (ex->fe_len == gex->fe_len) {
*bex = *ex;
ext4_mb_use_best_found(ac, e4b);
return;
}
/*
* If this is first found extent, just store it in the context
*/
if (bex->fe_len == 0) {
*bex = *ex;
return;
}
/*
* If new found extent is better, store it in the context
*/
if (bex->fe_len < gex->fe_len) {
/* if the request isn't satisfied, any found extent
* larger than previous best one is better */
if (ex->fe_len > bex->fe_len)
*bex = *ex;
} else if (ex->fe_len > gex->fe_len) {
/* if the request is satisfied, then we try to find
* an extent that still satisfy the request, but is
* smaller than previous one */
if (ex->fe_len < bex->fe_len)
*bex = *ex;
}
ext4_mb_check_limits(ac, e4b, 0);
}
static noinline_for_stack
int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
struct ext4_buddy *e4b)
{
struct ext4_free_extent ex = ac->ac_b_ex;
ext4_group_t group = ex.fe_group;
int max;
int err;
BUG_ON(ex.fe_len <= 0);
err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
if (err)
return err;
ext4_lock_group(ac->ac_sb, group);
max = mb_find_extent(e4b, 0, ex.fe_start, ex.fe_len, &ex);
if (max > 0) {
ac->ac_b_ex = ex;
ext4_mb_use_best_found(ac, e4b);
}
ext4_unlock_group(ac->ac_sb, group);
ext4_mb_unload_buddy(e4b);
return 0;
}
static noinline_for_stack
int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
struct ext4_buddy *e4b)
{
ext4_group_t group = ac->ac_g_ex.fe_group;
int max;
int err;
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
struct ext4_free_extent ex;
if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
return 0;
err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
if (err)
return err;
ext4_lock_group(ac->ac_sb, group);
max = mb_find_extent(e4b, 0, ac->ac_g_ex.fe_start,
ac->ac_g_ex.fe_len, &ex);
if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
ext4_fsblk_t start;
start = ext4_group_first_block_no(ac->ac_sb, e4b->bd_group) +
ex.fe_start;
/* use do_div to get remainder (would be 64-bit modulo) */
if (do_div(start, sbi->s_stripe) == 0) {
ac->ac_found++;
ac->ac_b_ex = ex;
ext4_mb_use_best_found(ac, e4b);
}
} else if (max >= ac->ac_g_ex.fe_len) {
BUG_ON(ex.fe_len <= 0);
BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
ac->ac_found++;
ac->ac_b_ex = ex;
ext4_mb_use_best_found(ac, e4b);
} else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
/* Sometimes, caller may want to merge even small
* number of blocks to an existing extent */
BUG_ON(ex.fe_len <= 0);
BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
ac->ac_found++;
ac->ac_b_ex = ex;
ext4_mb_use_best_found(ac, e4b);
}
ext4_unlock_group(ac->ac_sb, group);
ext4_mb_unload_buddy(e4b);
return 0;
}
/*
* The routine scans buddy structures (not bitmap!) from given order
* to max order and tries to find big enough chunk to satisfy the req
*/
static noinline_for_stack
void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
struct ext4_buddy *e4b)
{
struct super_block *sb = ac->ac_sb;
struct ext4_group_info *grp = e4b->bd_info;
void *buddy;
int i;
int k;
int max;
BUG_ON(ac->ac_2order <= 0);
for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
if (grp->bb_counters[i] == 0)
continue;
buddy = mb_find_buddy(e4b, i, &max);
BUG_ON(buddy == NULL);
k = mb_find_next_zero_bit(buddy, max, 0);
BUG_ON(k >= max);
ac->ac_found++;
ac->ac_b_ex.fe_len = 1 << i;
ac->ac_b_ex.fe_start = k << i;
ac->ac_b_ex.fe_group = e4b->bd_group;
ext4_mb_use_best_found(ac, e4b);
BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
if (EXT4_SB(sb)->s_mb_stats)
atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
break;
}
}
/*
* The routine scans the group and measures all found extents.
* In order to optimize scanning, caller must pass number of
* free blocks in the group, so the routine can know upper limit.
*/
static noinline_for_stack
void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
struct ext4_buddy *e4b)
{
struct super_block *sb = ac->ac_sb;
void *bitmap = e4b->bd_bitmap;
struct ext4_free_extent ex;
int i;
int free;
free = e4b->bd_info->bb_free;
BUG_ON(free <= 0);
i = e4b->bd_info->bb_first_free;
while (free && ac->ac_status == AC_STATUS_CONTINUE) {
i = mb_find_next_zero_bit(bitmap,
EXT4_CLUSTERS_PER_GROUP(sb), i);
if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
/*
* IF we have corrupt bitmap, we won't find any
* free blocks even though group info says we
* we have free blocks
*/
ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
"%d free clusters as per "
"group info. But bitmap says 0",
free);
break;
}
mb_find_extent(e4b, 0, i, ac->ac_g_ex.fe_len, &ex);
BUG_ON(ex.fe_len <= 0);
if (free < ex.fe_len) {
ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
"%d free clusters as per "
"group info. But got %d blocks",
free, ex.fe_len);
/*
* The number of free blocks differs. This mostly
* indicate that the bitmap is corrupt. So exit
* without claiming the space.
*/
break;
}
ext4_mb_measure_extent(ac, &ex, e4b);
i += ex.fe_len;
free -= ex.fe_len;
}
ext4_mb_check_limits(ac, e4b, 1);
}
/*
* This is a special case for storages like raid5
* we try to find stripe-aligned chunks for stripe-size-multiple requests
*/
static noinline_for_stack
void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
struct ext4_buddy *e4b)
{
struct super_block *sb = ac->ac_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
void *bitmap = e4b->bd_bitmap;
struct ext4_free_extent ex;
ext4_fsblk_t first_group_block;
ext4_fsblk_t a;
ext4_grpblk_t i;
int max;
BUG_ON(sbi->s_stripe == 0);
/* find first stripe-aligned block in group */
first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
a = first_group_block + sbi->s_stripe - 1;
do_div(a, sbi->s_stripe);
i = (a * sbi->s_stripe) - first_group_block;
while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
if (!mb_test_bit(i, bitmap)) {
max = mb_find_extent(e4b, 0, i, sbi->s_stripe, &ex);
if (max >= sbi->s_stripe) {
ac->ac_found++;
ac->ac_b_ex = ex;
ext4_mb_use_best_found(ac, e4b);
break;
}
}
i += sbi->s_stripe;
}
}
/* This is now called BEFORE we load the buddy bitmap. */
static int ext4_mb_good_group(struct ext4_allocation_context *ac,
ext4_group_t group, int cr)
{
unsigned free, fragments;
int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
BUG_ON(cr < 0 || cr >= 4);
/* We only do this if the grp has never been initialized */
if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
int ret = ext4_mb_init_group(ac->ac_sb, group);
if (ret)
return 0;
}
free = grp->bb_free;
fragments = grp->bb_fragments;
if (free == 0)
return 0;
if (fragments == 0)
return 0;
switch (cr) {
case 0:
BUG_ON(ac->ac_2order == 0);
if (grp->bb_largest_free_order < ac->ac_2order)
return 0;
/* Avoid using the first bg of a flexgroup for data files */
if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
(flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
((group % flex_size) == 0))
return 0;
return 1;
case 1:
if ((free / fragments) >= ac->ac_g_ex.fe_len)
return 1;
break;
case 2:
if (free >= ac->ac_g_ex.fe_len)
return 1;
break;
case 3:
return 1;
default:
BUG();
}
return 0;
}
static noinline_for_stack int
ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
{
ext4_group_t ngroups, group, i;
int cr;
int err = 0;
struct ext4_sb_info *sbi;
struct super_block *sb;
struct ext4_buddy e4b;
sb = ac->ac_sb;
sbi = EXT4_SB(sb);
ngroups = ext4_get_groups_count(sb);
/* non-extent files are limited to low blocks/groups */
if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
ngroups = sbi->s_blockfile_groups;
BUG_ON(ac->ac_status == AC_STATUS_FOUND);
/* first, try the goal */
err = ext4_mb_find_by_goal(ac, &e4b);
if (err || ac->ac_status == AC_STATUS_FOUND)
goto out;
if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
goto out;
/*
* ac->ac2_order is set only if the fe_len is a power of 2
* if ac2_order is set we also set criteria to 0 so that we
* try exact allocation using buddy.
*/
i = fls(ac->ac_g_ex.fe_len);
ac->ac_2order = 0;
/*
* We search using buddy data only if the order of the request
* is greater than equal to the sbi_s_mb_order2_reqs
* You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
*/
if (i >= sbi->s_mb_order2_reqs) {
/*
* This should tell if fe_len is exactly power of 2
*/
if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
ac->ac_2order = i - 1;
}
/* if stream allocation is enabled, use global goal */
if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
/* TBD: may be hot point */
spin_lock(&sbi->s_md_lock);
ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
spin_unlock(&sbi->s_md_lock);
}
/* Let's just scan groups to find more-less suitable blocks */
cr = ac->ac_2order ? 0 : 1;
/*
* cr == 0 try to get exact allocation,
* cr == 3 try to get anything
*/
repeat:
for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
ac->ac_criteria = cr;
/*
* searching for the right group start
* from the goal value specified
*/
group = ac->ac_g_ex.fe_group;
for (i = 0; i < ngroups; group++, i++) {
if (group == ngroups)
group = 0;
/* This now checks without needing the buddy page */
if (!ext4_mb_good_group(ac, group, cr))
continue;
err = ext4_mb_load_buddy(sb, group, &e4b);
if (err)
goto out;
ext4_lock_group(sb, group);
/*
* We need to check again after locking the
* block group
*/
if (!ext4_mb_good_group(ac, group, cr)) {
ext4_unlock_group(sb, group);
ext4_mb_unload_buddy(&e4b);
continue;
}
ac->ac_groups_scanned++;
if (cr == 0)
ext4_mb_simple_scan_group(ac, &e4b);
else if (cr == 1 && sbi->s_stripe &&
!(ac->ac_g_ex.fe_len % sbi->s_stripe))
ext4_mb_scan_aligned(ac, &e4b);
else
ext4_mb_complex_scan_group(ac, &e4b);
ext4_unlock_group(sb, group);
ext4_mb_unload_buddy(&e4b);
if (ac->ac_status != AC_STATUS_CONTINUE)
break;
}
}
if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
!(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
/*
* We've been searching too long. Let's try to allocate
* the best chunk we've found so far
*/
ext4_mb_try_best_found(ac, &e4b);
if (ac->ac_status != AC_STATUS_FOUND) {
/*
* Someone more lucky has already allocated it.
* The only thing we can do is just take first
* found block(s)
printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
*/
ac->ac_b_ex.fe_group = 0;
ac->ac_b_ex.fe_start = 0;
ac->ac_b_ex.fe_len = 0;
ac->ac_status = AC_STATUS_CONTINUE;
ac->ac_flags |= EXT4_MB_HINT_FIRST;
cr = 3;
atomic_inc(&sbi->s_mb_lost_chunks);
goto repeat;
}
}
out:
return err;
}
static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
{
struct super_block *sb = seq->private;
ext4_group_t group;
if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
return NULL;
group = *pos + 1;
return (void *) ((unsigned long) group);
}
static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct super_block *sb = seq->private;
ext4_group_t group;
++*pos;
if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
return NULL;
group = *pos + 1;
return (void *) ((unsigned long) group);
}
static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
{
struct super_block *sb = seq->private;
ext4_group_t group = (ext4_group_t) ((unsigned long) v);
int i;
int err;
struct ext4_buddy e4b;
struct sg {
struct ext4_group_info info;
ext4_grpblk_t counters[16];
} sg;
group--;
if (group == 0)
seq_printf(seq, "#%-5s: %-5s %-5s %-5s "
"[ %-5s %-5s %-5s %-5s %-5s %-5s %-5s "
"%-5s %-5s %-5s %-5s %-5s %-5s %-5s ]\n",
"group", "free", "frags", "first",
"2^0", "2^1", "2^2", "2^3", "2^4", "2^5", "2^6",
"2^7", "2^8", "2^9", "2^10", "2^11", "2^12", "2^13");
i = (sb->s_blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
sizeof(struct ext4_group_info);
err = ext4_mb_load_buddy(sb, group, &e4b);
if (err) {
seq_printf(seq, "#%-5u: I/O error\n", group);
return 0;
}
ext4_lock_group(sb, group);
memcpy(&sg, ext4_get_group_info(sb, group), i);
ext4_unlock_group(sb, group);
ext4_mb_unload_buddy(&e4b);
seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
sg.info.bb_fragments, sg.info.bb_first_free);
for (i = 0; i <= 13; i++)
seq_printf(seq, " %-5u", i <= sb->s_blocksize_bits + 1 ?
sg.info.bb_counters[i] : 0);
seq_printf(seq, " ]\n");
return 0;
}
static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
{
}
static const struct seq_operations ext4_mb_seq_groups_ops = {
.start = ext4_mb_seq_groups_start,
.next = ext4_mb_seq_groups_next,
.stop = ext4_mb_seq_groups_stop,
.show = ext4_mb_seq_groups_show,
};
static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
{
struct super_block *sb = PDE(inode)->data;
int rc;
rc = seq_open(file, &ext4_mb_seq_groups_ops);
if (rc == 0) {
struct seq_file *m = file->private_data;
m->private = sb;
}
return rc;
}
static const struct file_operations ext4_mb_seq_groups_fops = {
.owner = THIS_MODULE,
.open = ext4_mb_seq_groups_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
{
int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
BUG_ON(!cachep);
return cachep;
}
/* Create and initialize ext4_group_info data for the given group. */
int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
struct ext4_group_desc *desc)
{
int i;
int metalen = 0;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_info **meta_group_info;
struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
/*
* First check if this group is the first of a reserved block.
* If it's true, we have to allocate a new table of pointers
* to ext4_group_info structures
*/
if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
metalen = sizeof(*meta_group_info) <<
EXT4_DESC_PER_BLOCK_BITS(sb);
meta_group_info = kmalloc(metalen, GFP_KERNEL);
if (meta_group_info == NULL) {
ext4_msg(sb, KERN_ERR, "can't allocate mem "
"for a buddy group");
goto exit_meta_group_info;
}
sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)] =
meta_group_info;
}
meta_group_info =
sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)];
i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
meta_group_info[i] = kmem_cache_alloc(cachep, GFP_KERNEL);
if (meta_group_info[i] == NULL) {
ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
goto exit_group_info;
}
memset(meta_group_info[i], 0, kmem_cache_size(cachep));
set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
&(meta_group_info[i]->bb_state));
/*
* initialize bb_free to be able to skip
* empty groups without initialization
*/
if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
meta_group_info[i]->bb_free =
ext4_free_clusters_after_init(sb, group, desc);
} else {
meta_group_info[i]->bb_free =
ext4_free_group_clusters(sb, desc);
}
INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
init_rwsem(&meta_group_info[i]->alloc_sem);
meta_group_info[i]->bb_free_root = RB_ROOT;
meta_group_info[i]->bb_largest_free_order = -1; /* uninit */
#ifdef DOUBLE_CHECK
{
struct buffer_head *bh;
meta_group_info[i]->bb_bitmap =
kmalloc(sb->s_blocksize, GFP_KERNEL);
BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
bh = ext4_read_block_bitmap(sb, group);
BUG_ON(bh == NULL);
memcpy(meta_group_info[i]->bb_bitmap, bh->b_data,
sb->s_blocksize);
put_bh(bh);
}
#endif
return 0;
exit_group_info:
/* If a meta_group_info table has been allocated, release it now */
if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
kfree(sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)]);
sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)] = NULL;
}
exit_meta_group_info:
return -ENOMEM;
} /* ext4_mb_add_groupinfo */
static int ext4_mb_init_backend(struct super_block *sb)
{
ext4_group_t ngroups = ext4_get_groups_count(sb);
ext4_group_t i;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int num_meta_group_infos;
int num_meta_group_infos_max;
int array_size;
struct ext4_group_desc *desc;
struct kmem_cache *cachep;
/* This is the number of blocks used by GDT */
num_meta_group_infos = (ngroups + EXT4_DESC_PER_BLOCK(sb) -
1) >> EXT4_DESC_PER_BLOCK_BITS(sb);
/*
* This is the total number of blocks used by GDT including
* the number of reserved blocks for GDT.
* The s_group_info array is allocated with this value
* to allow a clean online resize without a complex
* manipulation of pointer.
* The drawback is the unused memory when no resize
* occurs but it's very low in terms of pages
* (see comments below)
* Need to handle this properly when META_BG resizing is allowed
*/
num_meta_group_infos_max = num_meta_group_infos +
le16_to_cpu(es->s_reserved_gdt_blocks);
/*
* array_size is the size of s_group_info array. We round it
* to the next power of two because this approximation is done
* internally by kmalloc so we can have some more memory
* for free here (e.g. may be used for META_BG resize).
*/
array_size = 1;
while (array_size < sizeof(*sbi->s_group_info) *
num_meta_group_infos_max)
array_size = array_size << 1;
/* An 8TB filesystem with 64-bit pointers requires a 4096 byte
* kmalloc. A 128kb malloc should suffice for a 256TB filesystem.
* So a two level scheme suffices for now. */
sbi->s_group_info = ext4_kvzalloc(array_size, GFP_KERNEL);
if (sbi->s_group_info == NULL) {
ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
return -ENOMEM;
}
sbi->s_buddy_cache = new_inode(sb);
if (sbi->s_buddy_cache == NULL) {
ext4_msg(sb, KERN_ERR, "can't get new inode");
goto err_freesgi;
}
/* To avoid potentially colliding with an valid on-disk inode number,
* use EXT4_BAD_INO for the buddy cache inode number. This inode is
* not in the inode hash, so it should never be found by iget(), but
* this will avoid confusion if it ever shows up during debugging. */
sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
for (i = 0; i < ngroups; i++) {
desc = ext4_get_group_desc(sb, i, NULL);
if (desc == NULL) {
ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
goto err_freebuddy;
}
if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
goto err_freebuddy;
}
return 0;
err_freebuddy:
cachep = get_groupinfo_cache(sb->s_blocksize_bits);
while (i-- > 0)
kmem_cache_free(cachep, ext4_get_group_info(sb, i));
i = num_meta_group_infos;
while (i-- > 0)
kfree(sbi->s_group_info[i]);
iput(sbi->s_buddy_cache);
err_freesgi:
ext4_kvfree(sbi->s_group_info);
return -ENOMEM;
}
static void ext4_groupinfo_destroy_slabs(void)
{
int i;
for (i = 0; i < NR_GRPINFO_CACHES; i++) {
if (ext4_groupinfo_caches[i])
kmem_cache_destroy(ext4_groupinfo_caches[i]);
ext4_groupinfo_caches[i] = NULL;
}
}
static int ext4_groupinfo_create_slab(size_t size)
{
static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
int slab_size;
int blocksize_bits = order_base_2(size);
int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
struct kmem_cache *cachep;
if (cache_index >= NR_GRPINFO_CACHES)
return -EINVAL;
if (unlikely(cache_index < 0))
cache_index = 0;
mutex_lock(&ext4_grpinfo_slab_create_mutex);
if (ext4_groupinfo_caches[cache_index]) {
mutex_unlock(&ext4_grpinfo_slab_create_mutex);
return 0; /* Already created */
}
slab_size = offsetof(struct ext4_group_info,
bb_counters[blocksize_bits + 2]);
cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
slab_size, 0, SLAB_RECLAIM_ACCOUNT,
NULL);
ext4_groupinfo_caches[cache_index] = cachep;
mutex_unlock(&ext4_grpinfo_slab_create_mutex);
if (!cachep) {
printk(KERN_EMERG
"EXT4-fs: no memory for groupinfo slab cache\n");
return -ENOMEM;
}
return 0;
}
int ext4_mb_init(struct super_block *sb, int needs_recovery)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
unsigned i, j;
unsigned offset;
unsigned max;
int ret;
i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_offsets);
sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
if (sbi->s_mb_offsets == NULL) {
ret = -ENOMEM;
goto out;
}
i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_maxs);
sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
if (sbi->s_mb_maxs == NULL) {
ret = -ENOMEM;
goto out;
}
ret = ext4_groupinfo_create_slab(sb->s_blocksize);
if (ret < 0)
goto out;
/* order 0 is regular bitmap */
sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
sbi->s_mb_offsets[0] = 0;
i = 1;
offset = 0;
max = sb->s_blocksize << 2;
do {
sbi->s_mb_offsets[i] = offset;
sbi->s_mb_maxs[i] = max;
offset += 1 << (sb->s_blocksize_bits - i);
max = max >> 1;
i++;
} while (i <= sb->s_blocksize_bits + 1);
spin_lock_init(&sbi->s_md_lock);
spin_lock_init(&sbi->s_bal_lock);
sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
sbi->s_mb_stats = MB_DEFAULT_STATS;
sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
/*
* The default group preallocation is 512, which for 4k block
* sizes translates to 2 megabytes. However for bigalloc file
* systems, this is probably too big (i.e, if the cluster size
* is 1 megabyte, then group preallocation size becomes half a
* gigabyte!). As a default, we will keep a two megabyte
* group pralloc size for cluster sizes up to 64k, and after
* that, we will force a minimum group preallocation size of
* 32 clusters. This translates to 8 megs when the cluster
* size is 256k, and 32 megs when the cluster size is 1 meg,
* which seems reasonable as a default.
*/
sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
sbi->s_cluster_bits, 32);
/*
* If there is a s_stripe > 1, then we set the s_mb_group_prealloc
* to the lowest multiple of s_stripe which is bigger than
* the s_mb_group_prealloc as determined above. We want
* the preallocation size to be an exact multiple of the
* RAID stripe size so that preallocations don't fragment
* the stripes.
*/
if (sbi->s_stripe > 1) {
sbi->s_mb_group_prealloc = roundup(
sbi->s_mb_group_prealloc, sbi->s_stripe);
}
sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
if (sbi->s_locality_groups == NULL) {
ret = -ENOMEM;
goto out_free_groupinfo_slab;
}
for_each_possible_cpu(i) {
struct ext4_locality_group *lg;
lg = per_cpu_ptr(sbi->s_locality_groups, i);
mutex_init(&lg->lg_mutex);
for (j = 0; j < PREALLOC_TB_SIZE; j++)
INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
spin_lock_init(&lg->lg_prealloc_lock);
}
/* init file for buddy data */
ret = ext4_mb_init_backend(sb);
if (ret != 0)
goto out_free_locality_groups;
if (sbi->s_proc)
proc_create_data("mb_groups", S_IRUGO, sbi->s_proc,
&ext4_mb_seq_groups_fops, sb);
return 0;
out_free_locality_groups:
free_percpu(sbi->s_locality_groups);
sbi->s_locality_groups = NULL;
out_free_groupinfo_slab:
ext4_groupinfo_destroy_slabs();
out:
kfree(sbi->s_mb_offsets);
sbi->s_mb_offsets = NULL;
kfree(sbi->s_mb_maxs);
sbi->s_mb_maxs = NULL;
return ret;
}
/* need to called with the ext4 group lock held */
static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
{
struct ext4_prealloc_space *pa;
struct list_head *cur, *tmp;
int count = 0;
list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
list_del(&pa->pa_group_list);
count++;
kmem_cache_free(ext4_pspace_cachep, pa);
}
if (count)
mb_debug(1, "mballoc: %u PAs left\n", count);
}
int ext4_mb_release(struct super_block *sb)
{
ext4_group_t ngroups = ext4_get_groups_count(sb);
ext4_group_t i;
int num_meta_group_infos;
struct ext4_group_info *grinfo;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
if (sbi->s_group_info) {
for (i = 0; i < ngroups; i++) {
grinfo = ext4_get_group_info(sb, i);
#ifdef DOUBLE_CHECK
kfree(grinfo->bb_bitmap);
#endif
ext4_lock_group(sb, i);
ext4_mb_cleanup_pa(grinfo);
ext4_unlock_group(sb, i);
kmem_cache_free(cachep, grinfo);
}
num_meta_group_infos = (ngroups +
EXT4_DESC_PER_BLOCK(sb) - 1) >>
EXT4_DESC_PER_BLOCK_BITS(sb);
for (i = 0; i < num_meta_group_infos; i++)
kfree(sbi->s_group_info[i]);
ext4_kvfree(sbi->s_group_info);
}
kfree(sbi->s_mb_offsets);
kfree(sbi->s_mb_maxs);
if (sbi->s_buddy_cache)
iput(sbi->s_buddy_cache);
if (sbi->s_mb_stats) {
ext4_msg(sb, KERN_INFO,
"mballoc: %u blocks %u reqs (%u success)",
atomic_read(&sbi->s_bal_allocated),
atomic_read(&sbi->s_bal_reqs),
atomic_read(&sbi->s_bal_success));
ext4_msg(sb, KERN_INFO,
"mballoc: %u extents scanned, %u goal hits, "
"%u 2^N hits, %u breaks, %u lost",
atomic_read(&sbi->s_bal_ex_scanned),
atomic_read(&sbi->s_bal_goals),
atomic_read(&sbi->s_bal_2orders),
atomic_read(&sbi->s_bal_breaks),
atomic_read(&sbi->s_mb_lost_chunks));
ext4_msg(sb, KERN_INFO,
"mballoc: %lu generated and it took %Lu",
sbi->s_mb_buddies_generated,
sbi->s_mb_generation_time);
ext4_msg(sb, KERN_INFO,
"mballoc: %u preallocated, %u discarded",
atomic_read(&sbi->s_mb_preallocated),
atomic_read(&sbi->s_mb_discarded));
}
free_percpu(sbi->s_locality_groups);
if (sbi->s_proc)
remove_proc_entry("mb_groups", sbi->s_proc);
return 0;
}
static inline int ext4_issue_discard(struct super_block *sb,
ext4_group_t block_group, ext4_grpblk_t cluster, int count)
{
ext4_fsblk_t discard_block;
discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
ext4_group_first_block_no(sb, block_group));
count = EXT4_C2B(EXT4_SB(sb), count);
trace_ext4_discard_blocks(sb,
(unsigned long long) discard_block, count);
return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
}
/*
* This function is called by the jbd2 layer once the commit has finished,
* so we know we can free the blocks that were released with that commit.
*/
static void ext4_free_data_callback(struct super_block *sb,
struct ext4_journal_cb_entry *jce,
int rc)
{
struct ext4_free_data *entry = (struct ext4_free_data *)jce;
struct ext4_buddy e4b;
struct ext4_group_info *db;
int err, count = 0, count2 = 0;
mb_debug(1, "gonna free %u blocks in group %u (0x%p):",
entry->efd_count, entry->efd_group, entry);
if (test_opt(sb, DISCARD))
ext4_issue_discard(sb, entry->efd_group,
entry->efd_start_cluster, entry->efd_count);
err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
/* we expect to find existing buddy because it's pinned */
BUG_ON(err != 0);
db = e4b.bd_info;
/* there are blocks to put in buddy to make them really free */
count += entry->efd_count;
count2++;
ext4_lock_group(sb, entry->efd_group);
/* Take it out of per group rb tree */
rb_erase(&entry->efd_node, &(db->bb_free_root));
mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
/*
* Clear the trimmed flag for the group so that the next
* ext4_trim_fs can trim it.
* If the volume is mounted with -o discard, online discard
* is supported and the free blocks will be trimmed online.
*/
if (!test_opt(sb, DISCARD))
EXT4_MB_GRP_CLEAR_TRIMMED(db);
if (!db->bb_free_root.rb_node) {
/* No more items in the per group rb tree
* balance refcounts from ext4_mb_free_metadata()
*/
page_cache_release(e4b.bd_buddy_page);
page_cache_release(e4b.bd_bitmap_page);
}
ext4_unlock_group(sb, entry->efd_group);
kmem_cache_free(ext4_free_data_cachep, entry);
ext4_mb_unload_buddy(&e4b);
mb_debug(1, "freed %u blocks in %u structures\n", count, count2);
}
#ifdef CONFIG_EXT4_DEBUG
u8 mb_enable_debug __read_mostly;
static struct dentry *debugfs_dir;
static struct dentry *debugfs_debug;
static void __init ext4_create_debugfs_entry(void)
{
debugfs_dir = debugfs_create_dir("ext4", NULL);
if (debugfs_dir)
debugfs_debug = debugfs_create_u8("mballoc-debug",
S_IRUGO | S_IWUSR,
debugfs_dir,
&mb_enable_debug);
}
static void ext4_remove_debugfs_entry(void)
{
debugfs_remove(debugfs_debug);
debugfs_remove(debugfs_dir);
}
#else
static void __init ext4_create_debugfs_entry(void)
{
}
static void ext4_remove_debugfs_entry(void)
{
}
#endif
int __init ext4_init_mballoc(void)
{
ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
SLAB_RECLAIM_ACCOUNT);
if (ext4_pspace_cachep == NULL)
return -ENOMEM;
ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
SLAB_RECLAIM_ACCOUNT);
if (ext4_ac_cachep == NULL) {
kmem_cache_destroy(ext4_pspace_cachep);
return -ENOMEM;
}
ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
SLAB_RECLAIM_ACCOUNT);
if (ext4_free_data_cachep == NULL) {
kmem_cache_destroy(ext4_pspace_cachep);
kmem_cache_destroy(ext4_ac_cachep);
return -ENOMEM;
}
ext4_create_debugfs_entry();
return 0;
}
void ext4_exit_mballoc(void)
{
/*
* Wait for completion of call_rcu()'s on ext4_pspace_cachep
* before destroying the slab cache.
*/
rcu_barrier();
kmem_cache_destroy(ext4_pspace_cachep);
kmem_cache_destroy(ext4_ac_cachep);
kmem_cache_destroy(ext4_free_data_cachep);
ext4_groupinfo_destroy_slabs();
ext4_remove_debugfs_entry();
}
/*
* Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
* Returns 0 if success or error code
*/
static noinline_for_stack int
ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
handle_t *handle, unsigned int reserv_clstrs)
{
struct buffer_head *bitmap_bh = NULL;
struct ext4_group_desc *gdp;
struct buffer_head *gdp_bh;
struct ext4_sb_info *sbi;
struct super_block *sb;
ext4_fsblk_t block;
int err, len;
BUG_ON(ac->ac_status != AC_STATUS_FOUND);
BUG_ON(ac->ac_b_ex.fe_len <= 0);
sb = ac->ac_sb;
sbi = EXT4_SB(sb);
err = -EIO;
bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
if (!bitmap_bh)
goto out_err;
err = ext4_journal_get_write_access(handle, bitmap_bh);
if (err)
goto out_err;
err = -EIO;
gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
if (!gdp)
goto out_err;
ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
ext4_free_group_clusters(sb, gdp));
err = ext4_journal_get_write_access(handle, gdp_bh);
if (err)
goto out_err;
block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
if (!ext4_data_block_valid(sbi, block, len)) {
ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
"fs metadata", block, block+len);
/* File system mounted not to panic on error
* Fix the bitmap and repeat the block allocation
* We leak some of the blocks here.
*/
ext4_lock_group(sb, ac->ac_b_ex.fe_group);
ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
ac->ac_b_ex.fe_len);
ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
if (!err)
err = -EAGAIN;
goto out_err;
}
ext4_lock_group(sb, ac->ac_b_ex.fe_group);
#ifdef AGGRESSIVE_CHECK
{
int i;
for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
bitmap_bh->b_data));
}
}
#endif
ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
ac->ac_b_ex.fe_len);
if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
ext4_free_group_clusters_set(sb, gdp,
ext4_free_clusters_after_init(sb,
ac->ac_b_ex.fe_group, gdp));
}
len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
ext4_free_group_clusters_set(sb, gdp, len);
gdp->bg_checksum = ext4_group_desc_csum(sbi, ac->ac_b_ex.fe_group, gdp);
ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
/*
* Now reduce the dirty block count also. Should not go negative
*/
if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
/* release all the reserved blocks if non delalloc */
percpu_counter_sub(&sbi->s_dirtyclusters_counter,
reserv_clstrs);
if (sbi->s_log_groups_per_flex) {
ext4_group_t flex_group = ext4_flex_group(sbi,
ac->ac_b_ex.fe_group);
atomic_sub(ac->ac_b_ex.fe_len,
&sbi->s_flex_groups[flex_group].free_clusters);
}
err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
if (err)
goto out_err;
err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
out_err:
ext4_mark_super_dirty(sb);
brelse(bitmap_bh);
return err;
}
/*
* here we normalize request for locality group
* Group request are normalized to s_mb_group_prealloc, which goes to
* s_strip if we set the same via mount option.
* s_mb_group_prealloc can be configured via
* /sys/fs/ext4/<partition>/mb_group_prealloc
*
* XXX: should we try to preallocate more than the group has now?
*/
static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
{
struct super_block *sb = ac->ac_sb;
struct ext4_locality_group *lg = ac->ac_lg;
BUG_ON(lg == NULL);
ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
mb_debug(1, "#%u: goal %u blocks for locality group\n",
current->pid, ac->ac_g_ex.fe_len);
}
/*
* Normalization means making request better in terms of
* size and alignment
*/
static noinline_for_stack void
ext4_mb_normalize_request(struct ext4_allocation_context *ac,
struct ext4_allocation_request *ar)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
int bsbits, max;
ext4_lblk_t end;
loff_t size, start_off;
loff_t orig_size __maybe_unused;
ext4_lblk_t start;
struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
struct ext4_prealloc_space *pa;
/* do normalize only data requests, metadata requests
do not need preallocation */
if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
return;
/* sometime caller may want exact blocks */
if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
return;
/* caller may indicate that preallocation isn't
* required (it's a tail, for example) */
if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
return;
if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
ext4_mb_normalize_group_request(ac);
return ;
}
bsbits = ac->ac_sb->s_blocksize_bits;
/* first, let's learn actual file size
* given current request is allocated */
size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
size = size << bsbits;
if (size < i_size_read(ac->ac_inode))
size = i_size_read(ac->ac_inode);
orig_size = size;
/* max size of free chunks */
max = 2 << bsbits;
#define NRL_CHECK_SIZE(req, size, max, chunk_size) \
(req <= (size) || max <= (chunk_size))
/* first, try to predict filesize */
/* XXX: should this table be tunable? */
start_off = 0;
if (size <= 16 * 1024) {
size = 16 * 1024;
} else if (size <= 32 * 1024) {
size = 32 * 1024;
} else if (size <= 64 * 1024) {
size = 64 * 1024;
} else if (size <= 128 * 1024) {
size = 128 * 1024;
} else if (size <= 256 * 1024) {
size = 256 * 1024;
} else if (size <= 512 * 1024) {
size = 512 * 1024;
} else if (size <= 1024 * 1024) {
size = 1024 * 1024;
} else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
(21 - bsbits)) << 21;
size = 2 * 1024 * 1024;
} else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
(22 - bsbits)) << 22;
size = 4 * 1024 * 1024;
} else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
(8<<20)>>bsbits, max, 8 * 1024)) {
start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
(23 - bsbits)) << 23;
size = 8 * 1024 * 1024;
} else {
start_off = (loff_t)ac->ac_o_ex.fe_logical << bsbits;
size = ac->ac_o_ex.fe_len << bsbits;
}
size = size >> bsbits;
start = start_off >> bsbits;
/* don't cover already allocated blocks in selected range */
if (ar->pleft && start <= ar->lleft) {
size -= ar->lleft + 1 - start;
start = ar->lleft + 1;
}
if (ar->pright && start + size - 1 >= ar->lright)
size -= start + size - ar->lright;
end = start + size;
/* check we don't cross already preallocated blocks */
rcu_read_lock();
list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
ext4_lblk_t pa_end;
if (pa->pa_deleted)
continue;
spin_lock(&pa->pa_lock);
if (pa->pa_deleted) {
spin_unlock(&pa->pa_lock);
continue;
}
pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
pa->pa_len);
/* PA must not overlap original request */
BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
ac->ac_o_ex.fe_logical < pa->pa_lstart));
/* skip PAs this normalized request doesn't overlap with */
if (pa->pa_lstart >= end || pa_end <= start) {
spin_unlock(&pa->pa_lock);
continue;
}
BUG_ON(pa->pa_lstart <= start && pa_end >= end);
/* adjust start or end to be adjacent to this pa */
if (pa_end <= ac->ac_o_ex.fe_logical) {
BUG_ON(pa_end < start);
start = pa_end;
} else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
BUG_ON(pa->pa_lstart > end);
end = pa->pa_lstart;
}
spin_unlock(&pa->pa_lock);
}
rcu_read_unlock();
size = end - start;
/* XXX: extra loop to check we really don't overlap preallocations */
rcu_read_lock();
list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
ext4_lblk_t pa_end;
spin_lock(&pa->pa_lock);
if (pa->pa_deleted == 0) {
pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
pa->pa_len);
BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
}
spin_unlock(&pa->pa_lock);
}
rcu_read_unlock();
if (start + size <= ac->ac_o_ex.fe_logical &&
start > ac->ac_o_ex.fe_logical) {
ext4_msg(ac->ac_sb, KERN_ERR,
"start %lu, size %lu, fe_logical %lu",
(unsigned long) start, (unsigned long) size,
(unsigned long) ac->ac_o_ex.fe_logical);
}
BUG_ON(start + size <= ac->ac_o_ex.fe_logical &&
start > ac->ac_o_ex.fe_logical);
BUG_ON(size <= 0 || size > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
/* now prepare goal request */
/* XXX: is it better to align blocks WRT to logical
* placement or satisfy big request as is */
ac->ac_g_ex.fe_logical = start;
ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
/* define goal start in order to merge */
if (ar->pright && (ar->lright == (start + size))) {
/* merge to the right */
ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
&ac->ac_f_ex.fe_group,
&ac->ac_f_ex.fe_start);
ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
}
if (ar->pleft && (ar->lleft + 1 == start)) {
/* merge to the left */
ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
&ac->ac_f_ex.fe_group,
&ac->ac_f_ex.fe_start);
ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
}
mb_debug(1, "goal: %u(was %u) blocks at %u\n", (unsigned) size,
(unsigned) orig_size, (unsigned) start);
}
static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
atomic_inc(&sbi->s_bal_reqs);
atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
atomic_inc(&sbi->s_bal_success);
atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
atomic_inc(&sbi->s_bal_goals);
if (ac->ac_found > sbi->s_mb_max_to_scan)
atomic_inc(&sbi->s_bal_breaks);
}
if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
trace_ext4_mballoc_alloc(ac);
else
trace_ext4_mballoc_prealloc(ac);
}
/*
* Called on failure; free up any blocks from the inode PA for this
* context. We don't need this for MB_GROUP_PA because we only change
* pa_free in ext4_mb_release_context(), but on failure, we've already
* zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
*/
static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
{
struct ext4_prealloc_space *pa = ac->ac_pa;
int len;
if (pa && pa->pa_type == MB_INODE_PA) {
len = ac->ac_b_ex.fe_len;
pa->pa_free += len;
}
}
/*
* use blocks preallocated to inode
*/
static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
struct ext4_prealloc_space *pa)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
ext4_fsblk_t start;
ext4_fsblk_t end;
int len;
/* found preallocated blocks, use them */
start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
len = EXT4_NUM_B2C(sbi, end - start);
ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
&ac->ac_b_ex.fe_start);
ac->ac_b_ex.fe_len = len;
ac->ac_status = AC_STATUS_FOUND;
ac->ac_pa = pa;
BUG_ON(start < pa->pa_pstart);
BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
BUG_ON(pa->pa_free < len);
pa->pa_free -= len;
mb_debug(1, "use %llu/%u from inode pa %p\n", start, len, pa);
}
/*
* use blocks preallocated to locality group
*/
static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
struct ext4_prealloc_space *pa)
{
unsigned int len = ac->ac_o_ex.fe_len;
ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
&ac->ac_b_ex.fe_group,
&ac->ac_b_ex.fe_start);
ac->ac_b_ex.fe_len = len;
ac->ac_status = AC_STATUS_FOUND;
ac->ac_pa = pa;
/* we don't correct pa_pstart or pa_plen here to avoid
* possible race when the group is being loaded concurrently
* instead we correct pa later, after blocks are marked
* in on-disk bitmap -- see ext4_mb_release_context()
* Other CPUs are prevented from allocating from this pa by lg_mutex
*/
mb_debug(1, "use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
}
/*
* Return the prealloc space that have minimal distance
* from the goal block. @cpa is the prealloc
* space that is having currently known minimal distance
* from the goal block.
*/
static struct ext4_prealloc_space *
ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
struct ext4_prealloc_space *pa,
struct ext4_prealloc_space *cpa)
{
ext4_fsblk_t cur_distance, new_distance;
if (cpa == NULL) {
atomic_inc(&pa->pa_count);
return pa;
}
cur_distance = abs(goal_block - cpa->pa_pstart);
new_distance = abs(goal_block - pa->pa_pstart);
if (cur_distance <= new_distance)
return cpa;
/* drop the previous reference */
atomic_dec(&cpa->pa_count);
atomic_inc(&pa->pa_count);
return pa;
}
/*
* search goal blocks in preallocated space
*/
static noinline_for_stack int
ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
int order, i;
struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
struct ext4_locality_group *lg;
struct ext4_prealloc_space *pa, *cpa = NULL;
ext4_fsblk_t goal_block;
/* only data can be preallocated */
if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
return 0;
/* first, try per-file preallocation */
rcu_read_lock();
list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
/* all fields in this condition don't change,
* so we can skip locking for them */
if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
ac->ac_o_ex.fe_logical >= (pa->pa_lstart +
EXT4_C2B(sbi, pa->pa_len)))
continue;
/* non-extent files can't have physical blocks past 2^32 */
if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len) >
EXT4_MAX_BLOCK_FILE_PHYS))
continue;
/* found preallocated blocks, use them */
spin_lock(&pa->pa_lock);
if (pa->pa_deleted == 0 && pa->pa_free) {
atomic_inc(&pa->pa_count);
ext4_mb_use_inode_pa(ac, pa);
spin_unlock(&pa->pa_lock);
ac->ac_criteria = 10;
rcu_read_unlock();
return 1;
}
spin_unlock(&pa->pa_lock);
}
rcu_read_unlock();
/* can we use group allocation? */
if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
return 0;
/* inode may have no locality group for some reason */
lg = ac->ac_lg;
if (lg == NULL)
return 0;
order = fls(ac->ac_o_ex.fe_len) - 1;
if (order > PREALLOC_TB_SIZE - 1)
/* The max size of hash table is PREALLOC_TB_SIZE */
order = PREALLOC_TB_SIZE - 1;
goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
/*
* search for the prealloc space that is having
* minimal distance from the goal block.
*/
for (i = order; i < PREALLOC_TB_SIZE; i++) {
rcu_read_lock();
list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
pa_inode_list) {
spin_lock(&pa->pa_lock);
if (pa->pa_deleted == 0 &&
pa->pa_free >= ac->ac_o_ex.fe_len) {
cpa = ext4_mb_check_group_pa(goal_block,
pa, cpa);
}
spin_unlock(&pa->pa_lock);
}
rcu_read_unlock();
}
if (cpa) {
ext4_mb_use_group_pa(ac, cpa);
ac->ac_criteria = 20;
return 1;
}
return 0;
}
/*
* the function goes through all block freed in the group
* but not yet committed and marks them used in in-core bitmap.
* buddy must be generated from this bitmap
* Need to be called with the ext4 group lock held
*/
static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
ext4_group_t group)
{
struct rb_node *n;
struct ext4_group_info *grp;
struct ext4_free_data *entry;
grp = ext4_get_group_info(sb, group);
n = rb_first(&(grp->bb_free_root));
while (n) {
entry = rb_entry(n, struct ext4_free_data, efd_node);
ext4_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
n = rb_next(n);
}
return;
}
/*
* the function goes through all preallocation in this group and marks them
* used in in-core bitmap. buddy must be generated from this bitmap
* Need to be called with ext4 group lock held
*/
static noinline_for_stack
void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
ext4_group_t group)
{
struct ext4_group_info *grp = ext4_get_group_info(sb, group);
struct ext4_prealloc_space *pa;
struct list_head *cur;
ext4_group_t groupnr;
ext4_grpblk_t start;
int preallocated = 0;
int len;
/* all form of preallocation discards first load group,
* so the only competing code is preallocation use.
* we don't need any locking here
* notice we do NOT ignore preallocations with pa_deleted
* otherwise we could leave used blocks available for
* allocation in buddy when concurrent ext4_mb_put_pa()
* is dropping preallocation
*/
list_for_each(cur, &grp->bb_prealloc_list) {
pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
spin_lock(&pa->pa_lock);
ext4_get_group_no_and_offset(sb, pa->pa_pstart,
&groupnr, &start);
len = pa->pa_len;
spin_unlock(&pa->pa_lock);
if (unlikely(len == 0))
continue;
BUG_ON(groupnr != group);
ext4_set_bits(bitmap, start, len);
preallocated += len;
}
mb_debug(1, "prellocated %u for group %u\n", preallocated, group);
}
static void ext4_mb_pa_callback(struct rcu_head *head)
{
struct ext4_prealloc_space *pa;
pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
kmem_cache_free(ext4_pspace_cachep, pa);
}
/*
* drops a reference to preallocated space descriptor
* if this was the last reference and the space is consumed
*/
static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
struct super_block *sb, struct ext4_prealloc_space *pa)
{
ext4_group_t grp;
ext4_fsblk_t grp_blk;
if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0)
return;
/* in this short window concurrent discard can set pa_deleted */
spin_lock(&pa->pa_lock);
if (pa->pa_deleted == 1) {
spin_unlock(&pa->pa_lock);
return;
}
pa->pa_deleted = 1;
spin_unlock(&pa->pa_lock);
grp_blk = pa->pa_pstart;
/*
* If doing group-based preallocation, pa_pstart may be in the
* next group when pa is used up
*/
if (pa->pa_type == MB_GROUP_PA)
grp_blk--;
ext4_get_group_no_and_offset(sb, grp_blk, &grp, NULL);
/*
* possible race:
*
* P1 (buddy init) P2 (regular allocation)
* find block B in PA
* copy on-disk bitmap to buddy
* mark B in on-disk bitmap
* drop PA from group
* mark all PAs in buddy
*
* thus, P1 initializes buddy with B available. to prevent this
* we make "copy" and "mark all PAs" atomic and serialize "drop PA"
* against that pair
*/
ext4_lock_group(sb, grp);
list_del(&pa->pa_group_list);
ext4_unlock_group(sb, grp);
spin_lock(pa->pa_obj_lock);
list_del_rcu(&pa->pa_inode_list);
spin_unlock(pa->pa_obj_lock);
call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
}
/*
* creates new preallocated space for given inode
*/
static noinline_for_stack int
ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
{
struct super_block *sb = ac->ac_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_prealloc_space *pa;
struct ext4_group_info *grp;
struct ext4_inode_info *ei;
/* preallocate only when found space is larger then requested */
BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
BUG_ON(ac->ac_status != AC_STATUS_FOUND);
BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
if (pa == NULL)
return -ENOMEM;
if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
int winl;
int wins;
int win;
int offs;
/* we can't allocate as much as normalizer wants.
* so, found space must get proper lstart
* to cover original request */
BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
/* we're limited by original request in that
* logical block must be covered any way
* winl is window we can move our chunk within */
winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
/* also, we should cover whole original request */
wins = EXT4_C2B(sbi, ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len);
/* the smallest one defines real window */
win = min(winl, wins);
offs = ac->ac_o_ex.fe_logical %
EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
if (offs && offs < win)
win = offs;
ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical -
EXT4_B2C(sbi, win);
BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
}
/* preallocation can change ac_b_ex, thus we store actually
* allocated blocks for history */
ac->ac_f_ex = ac->ac_b_ex;
pa->pa_lstart = ac->ac_b_ex.fe_logical;
pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
pa->pa_len = ac->ac_b_ex.fe_len;
pa->pa_free = pa->pa_len;
atomic_set(&pa->pa_count, 1);
spin_lock_init(&pa->pa_lock);
INIT_LIST_HEAD(&pa->pa_inode_list);
INIT_LIST_HEAD(&pa->pa_group_list);
pa->pa_deleted = 0;
pa->pa_type = MB_INODE_PA;
mb_debug(1, "new inode pa %p: %llu/%u for %u\n", pa,
pa->pa_pstart, pa->pa_len, pa->pa_lstart);
trace_ext4_mb_new_inode_pa(ac, pa);
ext4_mb_use_inode_pa(ac, pa);
atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
ei = EXT4_I(ac->ac_inode);
grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
pa->pa_obj_lock = &ei->i_prealloc_lock;
pa->pa_inode = ac->ac_inode;
ext4_lock_group(sb, ac->ac_b_ex.fe_group);
list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
spin_lock(pa->pa_obj_lock);
list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
spin_unlock(pa->pa_obj_lock);
return 0;
}
/*
* creates new preallocated space for locality group inodes belongs to
*/
static noinline_for_stack int
ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
{
struct super_block *sb = ac->ac_sb;
struct ext4_locality_group *lg;
struct ext4_prealloc_space *pa;
struct ext4_group_info *grp;
/* preallocate only when found space is larger then requested */
BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
BUG_ON(ac->ac_status != AC_STATUS_FOUND);
BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
BUG_ON(ext4_pspace_cachep == NULL);
pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
if (pa == NULL)
return -ENOMEM;
/* preallocation can change ac_b_ex, thus we store actually
* allocated blocks for history */
ac->ac_f_ex = ac->ac_b_ex;
pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
pa->pa_lstart = pa->pa_pstart;
pa->pa_len = ac->ac_b_ex.fe_len;
pa->pa_free = pa->pa_len;
atomic_set(&pa->pa_count, 1);
spin_lock_init(&pa->pa_lock);
INIT_LIST_HEAD(&pa->pa_inode_list);
INIT_LIST_HEAD(&pa->pa_group_list);
pa->pa_deleted = 0;
pa->pa_type = MB_GROUP_PA;
mb_debug(1, "new group pa %p: %llu/%u for %u\n", pa,
pa->pa_pstart, pa->pa_len, pa->pa_lstart);
trace_ext4_mb_new_group_pa(ac, pa);
ext4_mb_use_group_pa(ac, pa);
atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
lg = ac->ac_lg;
BUG_ON(lg == NULL);
pa->pa_obj_lock = &lg->lg_prealloc_lock;
pa->pa_inode = NULL;
ext4_lock_group(sb, ac->ac_b_ex.fe_group);
list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
/*
* We will later add the new pa to the right bucket
* after updating the pa_free in ext4_mb_release_context
*/
return 0;
}
static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
{
int err;
if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
err = ext4_mb_new_group_pa(ac);
else
err = ext4_mb_new_inode_pa(ac);
return err;
}
/*
* finds all unused blocks in on-disk bitmap, frees them in
* in-core bitmap and buddy.
* @pa must be unlinked from inode and group lists, so that
* nobody else can find/use it.
* the caller MUST hold group/inode locks.
* TODO: optimize the case when there are no in-core structures yet
*/
static noinline_for_stack int
ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
struct ext4_prealloc_space *pa)
{
struct super_block *sb = e4b->bd_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
unsigned int end;
unsigned int next;
ext4_group_t group;
ext4_grpblk_t bit;
unsigned long long grp_blk_start;
int err = 0;
int free = 0;
BUG_ON(pa->pa_deleted == 0);
ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
end = bit + pa->pa_len;
while (bit < end) {
bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
if (bit >= end)
break;
next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
mb_debug(1, " free preallocated %u/%u in group %u\n",
(unsigned) ext4_group_first_block_no(sb, group) + bit,
(unsigned) next - bit, (unsigned) group);
free += next - bit;
trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
EXT4_C2B(sbi, bit)),
next - bit);
mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
bit = next + 1;
}
if (free != pa->pa_free) {
ext4_msg(e4b->bd_sb, KERN_CRIT,
"pa %p: logic %lu, phys. %lu, len %lu",
pa, (unsigned long) pa->pa_lstart,
(unsigned long) pa->pa_pstart,
(unsigned long) pa->pa_len);
ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
free, pa->pa_free);
/*
* pa is already deleted so we use the value obtained
* from the bitmap and continue.
*/
}
atomic_add(free, &sbi->s_mb_discarded);
return err;
}
static noinline_for_stack int
ext4_mb_release_group_pa(struct ext4_buddy *e4b,
struct ext4_prealloc_space *pa)
{
struct super_block *sb = e4b->bd_sb;
ext4_group_t group;
ext4_grpblk_t bit;
trace_ext4_mb_release_group_pa(sb, pa);
BUG_ON(pa->pa_deleted == 0);
ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
return 0;
}
/*
* releases all preallocations in given group
*
* first, we need to decide discard policy:
* - when do we discard
* 1) ENOSPC
* - how many do we discard
* 1) how many requested
*/
static noinline_for_stack int
ext4_mb_discard_group_preallocations(struct super_block *sb,
ext4_group_t group, int needed)
{
struct ext4_group_info *grp = ext4_get_group_info(sb, group);
struct buffer_head *bitmap_bh = NULL;
struct ext4_prealloc_space *pa, *tmp;
struct list_head list;
struct ext4_buddy e4b;
int err;
int busy = 0;
int free = 0;
mb_debug(1, "discard preallocation for group %u\n", group);
if (list_empty(&grp->bb_prealloc_list))
return 0;
bitmap_bh = ext4_read_block_bitmap(sb, group);
if (bitmap_bh == NULL) {
ext4_error(sb, "Error reading block bitmap for %u", group);
return 0;
}
err = ext4_mb_load_buddy(sb, group, &e4b);
if (err) {
ext4_error(sb, "Error loading buddy information for %u", group);
put_bh(bitmap_bh);
return 0;
}
if (needed == 0)
needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
INIT_LIST_HEAD(&list);
repeat:
ext4_lock_group(sb, group);
list_for_each_entry_safe(pa, tmp,
&grp->bb_prealloc_list, pa_group_list) {
spin_lock(&pa->pa_lock);
if (atomic_read(&pa->pa_count)) {
spin_unlock(&pa->pa_lock);
busy = 1;
continue;
}
if (pa->pa_deleted) {
spin_unlock(&pa->pa_lock);
continue;
}
/* seems this one can be freed ... */
pa->pa_deleted = 1;
/* we can trust pa_free ... */
free += pa->pa_free;
spin_unlock(&pa->pa_lock);
list_del(&pa->pa_group_list);
list_add(&pa->u.pa_tmp_list, &list);
}
/* if we still need more blocks and some PAs were used, try again */
if (free < needed && busy) {
busy = 0;
ext4_unlock_group(sb, group);
/*
* Yield the CPU here so that we don't get soft lockup
* in non preempt case.
*/
yield();
goto repeat;
}
/* found anything to free? */
if (list_empty(&list)) {
BUG_ON(free != 0);
goto out;
}
/* now free all selected PAs */
list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
/* remove from object (inode or locality group) */
spin_lock(pa->pa_obj_lock);
list_del_rcu(&pa->pa_inode_list);
spin_unlock(pa->pa_obj_lock);
if (pa->pa_type == MB_GROUP_PA)
ext4_mb_release_group_pa(&e4b, pa);
else
ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
list_del(&pa->u.pa_tmp_list);
call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
}
out:
ext4_unlock_group(sb, group);
ext4_mb_unload_buddy(&e4b);
put_bh(bitmap_bh);
return free;
}
/*
* releases all non-used preallocated blocks for given inode
*
* It's important to discard preallocations under i_data_sem
* We don't want another block to be served from the prealloc
* space when we are discarding the inode prealloc space.
*
* FIXME!! Make sure it is valid at all the call sites
*/
void ext4_discard_preallocations(struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
struct super_block *sb = inode->i_sb;
struct buffer_head *bitmap_bh = NULL;
struct ext4_prealloc_space *pa, *tmp;
ext4_group_t group = 0;
struct list_head list;
struct ext4_buddy e4b;
int err;
if (!S_ISREG(inode->i_mode)) {
/*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
return;
}
mb_debug(1, "discard preallocation for inode %lu\n", inode->i_ino);
trace_ext4_discard_preallocations(inode);
INIT_LIST_HEAD(&list);
repeat:
/* first, collect all pa's in the inode */
spin_lock(&ei->i_prealloc_lock);
while (!list_empty(&ei->i_prealloc_list)) {
pa = list_entry(ei->i_prealloc_list.next,
struct ext4_prealloc_space, pa_inode_list);
BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
spin_lock(&pa->pa_lock);
if (atomic_read(&pa->pa_count)) {
/* this shouldn't happen often - nobody should
* use preallocation while we're discarding it */
spin_unlock(&pa->pa_lock);
spin_unlock(&ei->i_prealloc_lock);
ext4_msg(sb, KERN_ERR,
"uh-oh! used pa while discarding");
WARN_ON(1);
schedule_timeout_uninterruptible(HZ);
goto repeat;
}
if (pa->pa_deleted == 0) {
pa->pa_deleted = 1;
spin_unlock(&pa->pa_lock);
list_del_rcu(&pa->pa_inode_list);
list_add(&pa->u.pa_tmp_list, &list);
continue;
}
/* someone is deleting pa right now */
spin_unlock(&pa->pa_lock);
spin_unlock(&ei->i_prealloc_lock);
/* we have to wait here because pa_deleted
* doesn't mean pa is already unlinked from
* the list. as we might be called from
* ->clear_inode() the inode will get freed
* and concurrent thread which is unlinking
* pa from inode's list may access already
* freed memory, bad-bad-bad */
/* XXX: if this happens too often, we can
* add a flag to force wait only in case
* of ->clear_inode(), but not in case of
* regular truncate */
schedule_timeout_uninterruptible(HZ);
goto repeat;
}
spin_unlock(&ei->i_prealloc_lock);
list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
BUG_ON(pa->pa_type != MB_INODE_PA);
ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
err = ext4_mb_load_buddy(sb, group, &e4b);
if (err) {
ext4_error(sb, "Error loading buddy information for %u",
group);
continue;
}
bitmap_bh = ext4_read_block_bitmap(sb, group);
if (bitmap_bh == NULL) {
ext4_error(sb, "Error reading block bitmap for %u",
group);
ext4_mb_unload_buddy(&e4b);
continue;
}
ext4_lock_group(sb, group);
list_del(&pa->pa_group_list);
ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
ext4_unlock_group(sb, group);
ext4_mb_unload_buddy(&e4b);
put_bh(bitmap_bh);
list_del(&pa->u.pa_tmp_list);
call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
}
}
#ifdef CONFIG_EXT4_DEBUG
static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
{
struct super_block *sb = ac->ac_sb;
ext4_group_t ngroups, i;
if (!mb_enable_debug ||
(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED))
return;
ext4_msg(ac->ac_sb, KERN_ERR, "Can't allocate:"
" Allocation context details:");
ext4_msg(ac->ac_sb, KERN_ERR, "status %d flags %d",
ac->ac_status, ac->ac_flags);
ext4_msg(ac->ac_sb, KERN_ERR, "orig %lu/%lu/%lu@%lu, "
"goal %lu/%lu/%lu@%lu, "
"best %lu/%lu/%lu@%lu cr %d",
(unsigned long)ac->ac_o_ex.fe_group,
(unsigned long)ac->ac_o_ex.fe_start,
(unsigned long)ac->ac_o_ex.fe_len,
(unsigned long)ac->ac_o_ex.fe_logical,
(unsigned long)ac->ac_g_ex.fe_group,
(unsigned long)ac->ac_g_ex.fe_start,
(unsigned long)ac->ac_g_ex.fe_len,
(unsigned long)ac->ac_g_ex.fe_logical,
(unsigned long)ac->ac_b_ex.fe_group,
(unsigned long)ac->ac_b_ex.fe_start,
(unsigned long)ac->ac_b_ex.fe_len,
(unsigned long)ac->ac_b_ex.fe_logical,
(int)ac->ac_criteria);
ext4_msg(ac->ac_sb, KERN_ERR, "%lu scanned, %d found",
ac->ac_ex_scanned, ac->ac_found);
ext4_msg(ac->ac_sb, KERN_ERR, "groups: ");
ngroups = ext4_get_groups_count(sb);
for (i = 0; i < ngroups; i++) {
struct ext4_group_info *grp = ext4_get_group_info(sb, i);
struct ext4_prealloc_space *pa;
ext4_grpblk_t start;
struct list_head *cur;
ext4_lock_group(sb, i);
list_for_each(cur, &grp->bb_prealloc_list) {
pa = list_entry(cur, struct ext4_prealloc_space,
pa_group_list);
spin_lock(&pa->pa_lock);
ext4_get_group_no_and_offset(sb, pa->pa_pstart,
NULL, &start);
spin_unlock(&pa->pa_lock);
printk(KERN_ERR "PA:%u:%d:%u \n", i,
start, pa->pa_len);
}
ext4_unlock_group(sb, i);
if (grp->bb_free == 0)
continue;
printk(KERN_ERR "%u: %d/%d \n",
i, grp->bb_free, grp->bb_fragments);
}
printk(KERN_ERR "\n");
}
#else
static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
{
return;
}
#endif
/*
* We use locality group preallocation for small size file. The size of the
* file is determined by the current size or the resulting size after
* allocation which ever is larger
*
* One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
*/
static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
int bsbits = ac->ac_sb->s_blocksize_bits;
loff_t size, isize;
if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
return;
if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
return;
size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
>> bsbits;
if ((size == isize) &&
!ext4_fs_is_busy(sbi) &&
(atomic_read(&ac->ac_inode->i_writecount) == 0)) {
ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
return;
}
if (sbi->s_mb_group_prealloc <= 0) {
ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
return;
}
/* don't use group allocation for large files */
size = max(size, isize);
if (size > sbi->s_mb_stream_request) {
ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
return;
}
BUG_ON(ac->ac_lg != NULL);
/*
* locality group prealloc space are per cpu. The reason for having
* per cpu locality group is to reduce the contention between block
* request from multiple CPUs.
*/
ac->ac_lg = __this_cpu_ptr(sbi->s_locality_groups);
/* we're going to use group allocation */
ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
/* serialize all allocations in the group */
mutex_lock(&ac->ac_lg->lg_mutex);
}
static noinline_for_stack int
ext4_mb_initialize_context(struct ext4_allocation_context *ac,
struct ext4_allocation_request *ar)
{
struct super_block *sb = ar->inode->i_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
ext4_group_t group;
unsigned int len;
ext4_fsblk_t goal;
ext4_grpblk_t block;
/* we can't allocate > group size */
len = ar->len;
/* just a dirty hack to filter too big requests */
if (len >= EXT4_CLUSTERS_PER_GROUP(sb) - 10)
len = EXT4_CLUSTERS_PER_GROUP(sb) - 10;
/* start searching from the goal */
goal = ar->goal;
if (goal < le32_to_cpu(es->s_first_data_block) ||
goal >= ext4_blocks_count(es))
goal = le32_to_cpu(es->s_first_data_block);
ext4_get_group_no_and_offset(sb, goal, &group, &block);
/* set up allocation goals */
memset(ac, 0, sizeof(struct ext4_allocation_context));
ac->ac_b_ex.fe_logical = ar->logical & ~(sbi->s_cluster_ratio - 1);
ac->ac_status = AC_STATUS_CONTINUE;
ac->ac_sb = sb;
ac->ac_inode = ar->inode;
ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
ac->ac_o_ex.fe_group = group;
ac->ac_o_ex.fe_start = block;
ac->ac_o_ex.fe_len = len;
ac->ac_g_ex = ac->ac_o_ex;
ac->ac_flags = ar->flags;
/* we have to define context: we'll we work with a file or
* locality group. this is a policy, actually */
ext4_mb_group_or_file(ac);
mb_debug(1, "init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
"left: %u/%u, right %u/%u to %swritable\n",
(unsigned) ar->len, (unsigned) ar->logical,
(unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
(unsigned) ar->lleft, (unsigned) ar->pleft,
(unsigned) ar->lright, (unsigned) ar->pright,
atomic_read(&ar->inode->i_writecount) ? "" : "non-");
return 0;
}
static noinline_for_stack void
ext4_mb_discard_lg_preallocations(struct super_block *sb,
struct ext4_locality_group *lg,
int order, int total_entries)
{
ext4_group_t group = 0;
struct ext4_buddy e4b;
struct list_head discard_list;
struct ext4_prealloc_space *pa, *tmp;
mb_debug(1, "discard locality group preallocation\n");
INIT_LIST_HEAD(&discard_list);
spin_lock(&lg->lg_prealloc_lock);
list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
pa_inode_list) {
spin_lock(&pa->pa_lock);
if (atomic_read(&pa->pa_count)) {
/*
* This is the pa that we just used
* for block allocation. So don't
* free that
*/
spin_unlock(&pa->pa_lock);
continue;
}
if (pa->pa_deleted) {
spin_unlock(&pa->pa_lock);
continue;
}
/* only lg prealloc space */
BUG_ON(pa->pa_type != MB_GROUP_PA);
/* seems this one can be freed ... */
pa->pa_deleted = 1;
spin_unlock(&pa->pa_lock);
list_del_rcu(&pa->pa_inode_list);
list_add(&pa->u.pa_tmp_list, &discard_list);
total_entries--;
if (total_entries <= 5) {
/*
* we want to keep only 5 entries
* allowing it to grow to 8. This
* mak sure we don't call discard
* soon for this list.
*/
break;
}
}
spin_unlock(&lg->lg_prealloc_lock);
list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
if (ext4_mb_load_buddy(sb, group, &e4b)) {
ext4_error(sb, "Error loading buddy information for %u",
group);
continue;
}
ext4_lock_group(sb, group);
list_del(&pa->pa_group_list);
ext4_mb_release_group_pa(&e4b, pa);
ext4_unlock_group(sb, group);
ext4_mb_unload_buddy(&e4b);
list_del(&pa->u.pa_tmp_list);
call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
}
}
/*
* We have incremented pa_count. So it cannot be freed at this
* point. Also we hold lg_mutex. So no parallel allocation is
* possible from this lg. That means pa_free cannot be updated.
*
* A parallel ext4_mb_discard_group_preallocations is possible.
* which can cause the lg_prealloc_list to be updated.
*/
static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
{
int order, added = 0, lg_prealloc_count = 1;
struct super_block *sb = ac->ac_sb;
struct ext4_locality_group *lg = ac->ac_lg;
struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
order = fls(pa->pa_free) - 1;
if (order > PREALLOC_TB_SIZE - 1)
/* The max size of hash table is PREALLOC_TB_SIZE */
order = PREALLOC_TB_SIZE - 1;
/* Add the prealloc space to lg */
rcu_read_lock();
list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
pa_inode_list) {
spin_lock(&tmp_pa->pa_lock);
if (tmp_pa->pa_deleted) {
spin_unlock(&tmp_pa->pa_lock);
continue;
}
if (!added && pa->pa_free < tmp_pa->pa_free) {
/* Add to the tail of the previous entry */
list_add_tail_rcu(&pa->pa_inode_list,
&tmp_pa->pa_inode_list);
added = 1;
/*
* we want to count the total
* number of entries in the list
*/
}
spin_unlock(&tmp_pa->pa_lock);
lg_prealloc_count++;
}
if (!added)
list_add_tail_rcu(&pa->pa_inode_list,
&lg->lg_prealloc_list[order]);
rcu_read_unlock();
/* Now trim the list to be not more than 8 elements */
if (lg_prealloc_count > 8) {
ext4_mb_discard_lg_preallocations(sb, lg,
order, lg_prealloc_count);
return;
}
return ;
}
/*
* release all resource we used in allocation
*/
static int ext4_mb_release_context(struct ext4_allocation_context *ac)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
struct ext4_prealloc_space *pa = ac->ac_pa;
if (pa) {
if (pa->pa_type == MB_GROUP_PA) {
/* see comment in ext4_mb_use_group_pa() */
spin_lock(&pa->pa_lock);
pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
pa->pa_free -= ac->ac_b_ex.fe_len;
pa->pa_len -= ac->ac_b_ex.fe_len;
spin_unlock(&pa->pa_lock);
}
}
if (pa) {
/*
* We want to add the pa to the right bucket.
* Remove it from the list and while adding
* make sure the list to which we are adding
* doesn't grow big.
*/
if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
spin_lock(pa->pa_obj_lock);
list_del_rcu(&pa->pa_inode_list);
spin_unlock(pa->pa_obj_lock);
ext4_mb_add_n_trim(ac);
}
ext4_mb_put_pa(ac, ac->ac_sb, pa);
}
if (ac->ac_bitmap_page)
page_cache_release(ac->ac_bitmap_page);
if (ac->ac_buddy_page)
page_cache_release(ac->ac_buddy_page);
if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
mutex_unlock(&ac->ac_lg->lg_mutex);
ext4_mb_collect_stats(ac);
return 0;
}
static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
{
ext4_group_t i, ngroups = ext4_get_groups_count(sb);
int ret;
int freed = 0;
trace_ext4_mb_discard_preallocations(sb, needed);
for (i = 0; i < ngroups && needed > 0; i++) {
ret = ext4_mb_discard_group_preallocations(sb, i, needed);
freed += ret;
needed -= ret;
}
return freed;
}
/*
* Main entry point into mballoc to allocate blocks
* it tries to use preallocation first, then falls back
* to usual allocation
*/
ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
struct ext4_allocation_request *ar, int *errp)
{
int freed;
struct ext4_allocation_context *ac = NULL;
struct ext4_sb_info *sbi;
struct super_block *sb;
ext4_fsblk_t block = 0;
unsigned int inquota = 0;
unsigned int reserv_clstrs = 0;
sb = ar->inode->i_sb;
sbi = EXT4_SB(sb);
trace_ext4_request_blocks(ar);
/* Allow to use superuser reservation for quota file */
if (IS_NOQUOTA(ar->inode))
ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
/*
* For delayed allocation, we could skip the ENOSPC and
* EDQUOT check, as blocks and quotas have been already
* reserved when data being copied into pagecache.
*/
if (ext4_test_inode_state(ar->inode, EXT4_STATE_DELALLOC_RESERVED))
ar->flags |= EXT4_MB_DELALLOC_RESERVED;
else {
/* Without delayed allocation we need to verify
* there is enough free blocks to do block allocation
* and verify allocation doesn't exceed the quota limits.
*/
while (ar->len &&
ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
/* let others to free the space */
yield();
ar->len = ar->len >> 1;
}
if (!ar->len) {
*errp = -ENOSPC;
return 0;
}
reserv_clstrs = ar->len;
if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
dquot_alloc_block_nofail(ar->inode,
EXT4_C2B(sbi, ar->len));
} else {
while (ar->len &&
dquot_alloc_block(ar->inode,
EXT4_C2B(sbi, ar->len))) {
ar->flags |= EXT4_MB_HINT_NOPREALLOC;
ar->len--;
}
}
inquota = ar->len;
if (ar->len == 0) {
*errp = -EDQUOT;
goto out;
}
}
ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
if (!ac) {
ar->len = 0;
*errp = -ENOMEM;
goto out;
}
*errp = ext4_mb_initialize_context(ac, ar);
if (*errp) {
ar->len = 0;
goto out;
}
ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
if (!ext4_mb_use_preallocated(ac)) {
ac->ac_op = EXT4_MB_HISTORY_ALLOC;
ext4_mb_normalize_request(ac, ar);
repeat:
/* allocate space in core */
*errp = ext4_mb_regular_allocator(ac);
if (*errp)
goto errout;
/* as we've just preallocated more space than
* user requested orinally, we store allocated
* space in a special descriptor */
if (ac->ac_status == AC_STATUS_FOUND &&
ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
ext4_mb_new_preallocation(ac);
}
if (likely(ac->ac_status == AC_STATUS_FOUND)) {
*errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
if (*errp == -EAGAIN) {
/*
* drop the reference that we took
* in ext4_mb_use_best_found
*/
ext4_mb_release_context(ac);
ac->ac_b_ex.fe_group = 0;
ac->ac_b_ex.fe_start = 0;
ac->ac_b_ex.fe_len = 0;
ac->ac_status = AC_STATUS_CONTINUE;
goto repeat;
} else if (*errp)
errout:
ext4_discard_allocated_blocks(ac);
else {
block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
ar->len = ac->ac_b_ex.fe_len;
}
} else {
freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
if (freed)
goto repeat;
*errp = -ENOSPC;
}
if (*errp) {
ac->ac_b_ex.fe_len = 0;
ar->len = 0;
ext4_mb_show_ac(ac);
}
ext4_mb_release_context(ac);
out:
if (ac)
kmem_cache_free(ext4_ac_cachep, ac);
if (inquota && ar->len < inquota)
dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
if (!ar->len) {
if (!ext4_test_inode_state(ar->inode,
EXT4_STATE_DELALLOC_RESERVED))
/* release all the reserved blocks if non delalloc */
percpu_counter_sub(&sbi->s_dirtyclusters_counter,
reserv_clstrs);
}
trace_ext4_allocate_blocks(ar, (unsigned long long)block);
return block;
}
/*
* We can merge two free data extents only if the physical blocks
* are contiguous, AND the extents were freed by the same transaction,
* AND the blocks are associated with the same group.
*/
static int can_merge(struct ext4_free_data *entry1,
struct ext4_free_data *entry2)
{
if ((entry1->efd_tid == entry2->efd_tid) &&
(entry1->efd_group == entry2->efd_group) &&
((entry1->efd_start_cluster + entry1->efd_count) == entry2->efd_start_cluster))
return 1;
return 0;
}
static noinline_for_stack int
ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
struct ext4_free_data *new_entry)
{
ext4_group_t group = e4b->bd_group;
ext4_grpblk_t cluster;
struct ext4_free_data *entry;
struct ext4_group_info *db = e4b->bd_info;
struct super_block *sb = e4b->bd_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct rb_node **n = &db->bb_free_root.rb_node, *node;
struct rb_node *parent = NULL, *new_node;
BUG_ON(!ext4_handle_valid(handle));
BUG_ON(e4b->bd_bitmap_page == NULL);
BUG_ON(e4b->bd_buddy_page == NULL);
new_node = &new_entry->efd_node;
cluster = new_entry->efd_start_cluster;
if (!*n) {
/* first free block exent. We need to
protect buddy cache from being freed,
* otherwise we'll refresh it from
* on-disk bitmap and lose not-yet-available
* blocks */
page_cache_get(e4b->bd_buddy_page);
page_cache_get(e4b->bd_bitmap_page);
}
while (*n) {
parent = *n;
entry = rb_entry(parent, struct ext4_free_data, efd_node);
if (cluster < entry->efd_start_cluster)
n = &(*n)->rb_left;
else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
n = &(*n)->rb_right;
else {
ext4_grp_locked_error(sb, group, 0,
ext4_group_first_block_no(sb, group) +
EXT4_C2B(sbi, cluster),
"Block already on to-be-freed list");
return 0;
}
}
rb_link_node(new_node, parent, n);
rb_insert_color(new_node, &db->bb_free_root);
/* Now try to see the extent can be merged to left and right */
node = rb_prev(new_node);
if (node) {
entry = rb_entry(node, struct ext4_free_data, efd_node);
if (can_merge(entry, new_entry)) {
new_entry->efd_start_cluster = entry->efd_start_cluster;
new_entry->efd_count += entry->efd_count;
rb_erase(node, &(db->bb_free_root));
ext4_journal_callback_del(handle, &entry->efd_jce);
kmem_cache_free(ext4_free_data_cachep, entry);
}
}
node = rb_next(new_node);
if (node) {
entry = rb_entry(node, struct ext4_free_data, efd_node);
if (can_merge(new_entry, entry)) {
new_entry->efd_count += entry->efd_count;
rb_erase(node, &(db->bb_free_root));
ext4_journal_callback_del(handle, &entry->efd_jce);
kmem_cache_free(ext4_free_data_cachep, entry);
}
}
/* Add the extent to transaction's private list */
ext4_journal_callback_add(handle, ext4_free_data_callback,
&new_entry->efd_jce);
return 0;
}
/**
* ext4_free_blocks() -- Free given blocks and update quota
* @handle: handle for this transaction
* @inode: inode
* @block: start physical block to free
* @count: number of blocks to count
* @flags: flags used by ext4_free_blocks
*/
void ext4_free_blocks(handle_t *handle, struct inode *inode,
struct buffer_head *bh, ext4_fsblk_t block,
unsigned long count, int flags)
{
struct buffer_head *bitmap_bh = NULL;
struct super_block *sb = inode->i_sb;
struct ext4_group_desc *gdp;
unsigned long freed = 0;
unsigned int overflow;
ext4_grpblk_t bit;
struct buffer_head *gd_bh;
ext4_group_t block_group;
struct ext4_sb_info *sbi;
struct ext4_buddy e4b;
unsigned int count_clusters;
int err = 0;
int ret;
if (bh) {
if (block)
BUG_ON(block != bh->b_blocknr);
else
block = bh->b_blocknr;
}
sbi = EXT4_SB(sb);
if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
!ext4_data_block_valid(sbi, block, count)) {
ext4_error(sb, "Freeing blocks not in datazone - "
"block = %llu, count = %lu", block, count);
goto error_return;
}
ext4_debug("freeing block %llu\n", block);
trace_ext4_free_blocks(inode, block, count, flags);
if (flags & EXT4_FREE_BLOCKS_FORGET) {
struct buffer_head *tbh = bh;
int i;
BUG_ON(bh && (count > 1));
for (i = 0; i < count; i++) {
if (!bh)
tbh = sb_find_get_block(inode->i_sb,
block + i);
if (unlikely(!tbh))
continue;
ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
inode, tbh, block + i);
}
}
/*
* We need to make sure we don't reuse the freed block until
* after the transaction is committed, which we can do by
* treating the block as metadata, below. We make an
* exception if the inode is to be written in writeback mode
* since writeback mode has weak data consistency guarantees.
*/
if (!ext4_should_writeback_data(inode))
flags |= EXT4_FREE_BLOCKS_METADATA;
/*
* If the extent to be freed does not begin on a cluster
* boundary, we need to deal with partial clusters at the
* beginning and end of the extent. Normally we will free
* blocks at the beginning or the end unless we are explicitly
* requested to avoid doing so.
*/
overflow = block & (sbi->s_cluster_ratio - 1);
if (overflow) {
if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
overflow = sbi->s_cluster_ratio - overflow;
block += overflow;
if (count > overflow)
count -= overflow;
else
return;
} else {
block -= overflow;
count += overflow;
}
}
overflow = count & (sbi->s_cluster_ratio - 1);
if (overflow) {
if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
if (count > overflow)
count -= overflow;
else
return;
} else
count += sbi->s_cluster_ratio - overflow;
}
do_more:
overflow = 0;
ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
/*
* Check to see if we are freeing blocks across a group
* boundary.
*/
if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
overflow = EXT4_C2B(sbi, bit) + count -
EXT4_BLOCKS_PER_GROUP(sb);
count -= overflow;
}
count_clusters = EXT4_B2C(sbi, count);
bitmap_bh = ext4_read_block_bitmap(sb, block_group);
if (!bitmap_bh) {
err = -EIO;
goto error_return;
}
gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
if (!gdp) {
err = -EIO;
goto error_return;
}
if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
in_range(block, ext4_inode_table(sb, gdp),
EXT4_SB(sb)->s_itb_per_group) ||
in_range(block + count - 1, ext4_inode_table(sb, gdp),
EXT4_SB(sb)->s_itb_per_group)) {
ext4_error(sb, "Freeing blocks in system zone - "
"Block = %llu, count = %lu", block, count);
/* err = 0. ext4_std_error should be a no op */
goto error_return;
}
BUFFER_TRACE(bitmap_bh, "getting write access");
err = ext4_journal_get_write_access(handle, bitmap_bh);
if (err)
goto error_return;
/*
* We are about to modify some metadata. Call the journal APIs
* to unshare ->b_data if a currently-committing transaction is
* using it
*/
BUFFER_TRACE(gd_bh, "get_write_access");
err = ext4_journal_get_write_access(handle, gd_bh);
if (err)
goto error_return;
#ifdef AGGRESSIVE_CHECK
{
int i;
for (i = 0; i < count_clusters; i++)
BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
}
#endif
trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
err = ext4_mb_load_buddy(sb, block_group, &e4b);
if (err)
goto error_return;
if ((flags & EXT4_FREE_BLOCKS_METADATA) && ext4_handle_valid(handle)) {
struct ext4_free_data *new_entry;
/*
* blocks being freed are metadata. these blocks shouldn't
* be used until this transaction is committed
*/
new_entry = kmem_cache_alloc(ext4_free_data_cachep, GFP_NOFS);
if (!new_entry) {
err = -ENOMEM;
goto error_return;
}
new_entry->efd_start_cluster = bit;
new_entry->efd_group = block_group;
new_entry->efd_count = count_clusters;
new_entry->efd_tid = handle->h_transaction->t_tid;
ext4_lock_group(sb, block_group);
mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
ext4_mb_free_metadata(handle, &e4b, new_entry);
} else {
/* need to update group_info->bb_free and bitmap
* with group lock held. generate_buddy look at
* them with group lock_held
*/
ext4_lock_group(sb, block_group);
mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
mb_free_blocks(inode, &e4b, bit, count_clusters);
}
ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
ext4_free_group_clusters_set(sb, gdp, ret);
gdp->bg_checksum = ext4_group_desc_csum(sbi, block_group, gdp);
ext4_unlock_group(sb, block_group);
percpu_counter_add(&sbi->s_freeclusters_counter, count_clusters);
if (sbi->s_log_groups_per_flex) {
ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
atomic_add(count_clusters,
&sbi->s_flex_groups[flex_group].free_clusters);
}
ext4_mb_unload_buddy(&e4b);
freed += count;
if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
/* We dirtied the bitmap block */
BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
/* And the group descriptor block */
BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
if (!err)
err = ret;
if (overflow && !err) {
block += count;
count = overflow;
put_bh(bitmap_bh);
goto do_more;
}
ext4_mark_super_dirty(sb);
error_return:
brelse(bitmap_bh);
ext4_std_error(sb, err);
return;
}
/**
* ext4_group_add_blocks() -- Add given blocks to an existing group
* @handle: handle to this transaction
* @sb: super block
* @block: start physcial block to add to the block group
* @count: number of blocks to free
*
* This marks the blocks as free in the bitmap and buddy.
*/
int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
ext4_fsblk_t block, unsigned long count)
{
struct buffer_head *bitmap_bh = NULL;
struct buffer_head *gd_bh;
ext4_group_t block_group;
ext4_grpblk_t bit;
unsigned int i;
struct ext4_group_desc *desc;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_buddy e4b;
int err = 0, ret, blk_free_count;
ext4_grpblk_t blocks_freed;
ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
if (count == 0)
return 0;
ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
/*
* Check to see if we are freeing blocks across a group
* boundary.
*/
if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
ext4_warning(sb, "too much blocks added to group %u\n",
block_group);
err = -EINVAL;
goto error_return;
}
bitmap_bh = ext4_read_block_bitmap(sb, block_group);
if (!bitmap_bh) {
err = -EIO;
goto error_return;
}
desc = ext4_get_group_desc(sb, block_group, &gd_bh);
if (!desc) {
err = -EIO;
goto error_return;
}
if (in_range(ext4_block_bitmap(sb, desc), block, count) ||
in_range(ext4_inode_bitmap(sb, desc), block, count) ||
in_range(block, ext4_inode_table(sb, desc), sbi->s_itb_per_group) ||
in_range(block + count - 1, ext4_inode_table(sb, desc),
sbi->s_itb_per_group)) {
ext4_error(sb, "Adding blocks in system zones - "
"Block = %llu, count = %lu",
block, count);
err = -EINVAL;
goto error_return;
}
BUFFER_TRACE(bitmap_bh, "getting write access");
err = ext4_journal_get_write_access(handle, bitmap_bh);
if (err)
goto error_return;
/*
* We are about to modify some metadata. Call the journal APIs
* to unshare ->b_data if a currently-committing transaction is
* using it
*/
BUFFER_TRACE(gd_bh, "get_write_access");
err = ext4_journal_get_write_access(handle, gd_bh);
if (err)
goto error_return;
for (i = 0, blocks_freed = 0; i < count; i++) {
BUFFER_TRACE(bitmap_bh, "clear bit");
if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
ext4_error(sb, "bit already cleared for block %llu",
(ext4_fsblk_t)(block + i));
BUFFER_TRACE(bitmap_bh, "bit already cleared");
} else {
blocks_freed++;
}
}
err = ext4_mb_load_buddy(sb, block_group, &e4b);
if (err)
goto error_return;
/*
* need to update group_info->bb_free and bitmap
* with group lock held. generate_buddy look at
* them with group lock_held
*/
ext4_lock_group(sb, block_group);
mb_clear_bits(bitmap_bh->b_data, bit, count);
mb_free_blocks(NULL, &e4b, bit, count);
blk_free_count = blocks_freed + ext4_free_group_clusters(sb, desc);
ext4_free_group_clusters_set(sb, desc, blk_free_count);
desc->bg_checksum = ext4_group_desc_csum(sbi, block_group, desc);
ext4_unlock_group(sb, block_group);
percpu_counter_add(&sbi->s_freeclusters_counter,
EXT4_B2C(sbi, blocks_freed));
if (sbi->s_log_groups_per_flex) {
ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
atomic_add(EXT4_B2C(sbi, blocks_freed),
&sbi->s_flex_groups[flex_group].free_clusters);
}
ext4_mb_unload_buddy(&e4b);
/* We dirtied the bitmap block */
BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
/* And the group descriptor block */
BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
if (!err)
err = ret;
error_return:
brelse(bitmap_bh);
ext4_std_error(sb, err);
return err;
}
/**
* ext4_trim_extent -- function to TRIM one single free extent in the group
* @sb: super block for the file system
* @start: starting block of the free extent in the alloc. group
* @count: number of blocks to TRIM
* @group: alloc. group we are working with
* @e4b: ext4 buddy for the group
*
* Trim "count" blocks starting at "start" in the "group". To assure that no
* one will allocate those blocks, mark it as used in buddy bitmap. This must
* be called with under the group lock.
*/
static void ext4_trim_extent(struct super_block *sb, int start, int count,
ext4_group_t group, struct ext4_buddy *e4b)
{
struct ext4_free_extent ex;
trace_ext4_trim_extent(sb, group, start, count);
assert_spin_locked(ext4_group_lock_ptr(sb, group));
ex.fe_start = start;
ex.fe_group = group;
ex.fe_len = count;
/*
* Mark blocks used, so no one can reuse them while
* being trimmed.
*/
mb_mark_used(e4b, &ex);
ext4_unlock_group(sb, group);
ext4_issue_discard(sb, group, start, count);
ext4_lock_group(sb, group);
mb_free_blocks(NULL, e4b, start, ex.fe_len);
}
/**
* ext4_trim_all_free -- function to trim all free space in alloc. group
* @sb: super block for file system
* @group: group to be trimmed
* @start: first group block to examine
* @max: last group block to examine
* @minblocks: minimum extent block count
*
* ext4_trim_all_free walks through group's buddy bitmap searching for free
* extents. When the free block is found, ext4_trim_extent is called to TRIM
* the extent.
*
*
* ext4_trim_all_free walks through group's block bitmap searching for free
* extents. When the free extent is found, mark it as used in group buddy
* bitmap. Then issue a TRIM command on this extent and free the extent in
* the group buddy bitmap. This is done until whole group is scanned.
*/
static ext4_grpblk_t
ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
ext4_grpblk_t start, ext4_grpblk_t max,
ext4_grpblk_t minblocks)
{
void *bitmap;
ext4_grpblk_t next, count = 0, free_count = 0;
struct ext4_buddy e4b;
int ret;
trace_ext4_trim_all_free(sb, group, start, max);
ret = ext4_mb_load_buddy(sb, group, &e4b);
if (ret) {
ext4_error(sb, "Error in loading buddy "
"information for %u", group);
return ret;
}
bitmap = e4b.bd_bitmap;
ext4_lock_group(sb, group);
if (EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) &&
minblocks >= atomic_read(&EXT4_SB(sb)->s_last_trim_minblks))
goto out;
start = (e4b.bd_info->bb_first_free > start) ?
e4b.bd_info->bb_first_free : start;
while (start <= max) {
start = mb_find_next_zero_bit(bitmap, max + 1, start);
if (start > max)
break;
next = mb_find_next_bit(bitmap, max + 1, start);
if ((next - start) >= minblocks) {
ext4_trim_extent(sb, start,
next - start, group, &e4b);
count += next - start;
}
free_count += next - start;
start = next + 1;
if (fatal_signal_pending(current)) {
count = -ERESTARTSYS;
break;
}
if (need_resched()) {
ext4_unlock_group(sb, group);
cond_resched();
ext4_lock_group(sb, group);
}
if ((e4b.bd_info->bb_free - free_count) < minblocks)
break;
}
if (!ret)
EXT4_MB_GRP_SET_TRIMMED(e4b.bd_info);
out:
ext4_unlock_group(sb, group);
ext4_mb_unload_buddy(&e4b);
ext4_debug("trimmed %d blocks in the group %d\n",
count, group);
return count;
}
/**
* ext4_trim_fs() -- trim ioctl handle function
* @sb: superblock for filesystem
* @range: fstrim_range structure
*
* start: First Byte to trim
* len: number of Bytes to trim from start
* minlen: minimum extent length in Bytes
* ext4_trim_fs goes through all allocation groups containing Bytes from
* start to start+len. For each such a group ext4_trim_all_free function
* is invoked to trim all free space.
*/
int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
{
struct ext4_group_info *grp;
ext4_group_t group, first_group, last_group;
ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
uint64_t start, end, minlen, trimmed = 0;
ext4_fsblk_t first_data_blk =
le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
int ret = 0;
start = range->start >> sb->s_blocksize_bits;
end = start + (range->len >> sb->s_blocksize_bits) - 1;
minlen = range->minlen >> sb->s_blocksize_bits;
if (unlikely(minlen > EXT4_CLUSTERS_PER_GROUP(sb)) ||
unlikely(start >= max_blks))
return -EINVAL;
if (end >= max_blks)
end = max_blks - 1;
if (end <= first_data_blk)
goto out;
if (start < first_data_blk)
start = first_data_blk;
/* Determine first and last group to examine based on start and end */
ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
&first_group, &first_cluster);
ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
&last_group, &last_cluster);
/* end now represents the last cluster to discard in this group */
end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
for (group = first_group; group <= last_group; group++) {
grp = ext4_get_group_info(sb, group);
/* We only do this if the grp has never been initialized */
if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
ret = ext4_mb_init_group(sb, group);
if (ret)
break;
}
/*
* For all the groups except the last one, last cluster will
* always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
* change it for the last group, note that last_cluster is
* already computed earlier by ext4_get_group_no_and_offset()
*/
if (group == last_group)
end = last_cluster;
if (grp->bb_free >= minlen) {
cnt = ext4_trim_all_free(sb, group, first_cluster,
end, minlen);
if (cnt < 0) {
ret = cnt;
break;
}
trimmed += cnt;
}
/*
* For every group except the first one, we are sure
* that the first cluster to discard will be cluster #0.
*/
first_cluster = 0;
}
if (!ret)
atomic_set(&EXT4_SB(sb)->s_last_trim_minblks, minlen);
out:
range->len = trimmed * sb->s_blocksize;
return ret;
}
| gpl-2.0 |
jznomoney/htc-sense-froyo-kernel | drivers/serial/68360serial.c | 1514 | 76262 | /*
* UART driver for 68360 CPM SCC or SMC
* Copyright (c) 2000 D. Jeff Dionne <jeff@uclinux.org>,
* Copyright (c) 2000 Michael Leslie <mleslie@lineo.ca>
* Copyright (c) 1997 Dan Malek <dmalek@jlc.net>
*
* I used the serial.c driver as the framework for this driver.
* Give credit to those guys.
* The original code was written for the MBX860 board. I tried to make
* it generic, but there may be some assumptions in the structures that
* have to be fixed later.
* To save porting time, I did not bother to change any object names
* that are not accessed outside of this file.
* It still needs lots of work........When it was easy, I included code
* to support the SCCs, but this has never been tested, nor is it complete.
* Only the SCCs support modem control, so that is not complete either.
*
* This module exports the following rs232 io functions:
*
* int rs_360_init(void);
*/
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/timer.h>
#include <linux/interrupt.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/serial.h>
#include <linux/serialP.h>
#include <linux/major.h>
#include <linux/string.h>
#include <linux/fcntl.h>
#include <linux/ptrace.h>
#include <linux/mm.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <asm/irq.h>
#include <asm/m68360.h>
#include <asm/commproc.h>
#ifdef CONFIG_KGDB
extern void breakpoint(void);
extern void set_debug_traps(void);
extern int kgdb_output_string (const char* s, unsigned int count);
#endif
/* #ifdef CONFIG_SERIAL_CONSOLE */ /* This seems to be a post 2.0 thing - mles */
#include <linux/console.h>
#include <linux/jiffies.h>
/* this defines the index into rs_table for the port to use
*/
#ifndef CONFIG_SERIAL_CONSOLE_PORT
#define CONFIG_SERIAL_CONSOLE_PORT 1 /* ie SMC2 - note USE_SMC2 must be defined */
#endif
/* #endif */
#if 0
/* SCC2 for console
*/
#undef CONFIG_SERIAL_CONSOLE_PORT
#define CONFIG_SERIAL_CONSOLE_PORT 2
#endif
#define TX_WAKEUP ASYNC_SHARE_IRQ
static char *serial_name = "CPM UART driver";
static char *serial_version = "0.03";
static struct tty_driver *serial_driver;
int serial_console_setup(struct console *co, char *options);
/*
* Serial driver configuration section. Here are the various options:
*/
#define SERIAL_PARANOIA_CHECK
#define CONFIG_SERIAL_NOPAUSE_IO
#define SERIAL_DO_RESTART
/* Set of debugging defines */
#undef SERIAL_DEBUG_INTR
#undef SERIAL_DEBUG_OPEN
#undef SERIAL_DEBUG_FLOW
#undef SERIAL_DEBUG_RS_WAIT_UNTIL_SENT
#define _INLINE_ inline
#define DBG_CNT(s)
/* We overload some of the items in the data structure to meet our
* needs. For example, the port address is the CPM parameter ram
* offset for the SCC or SMC. The maximum number of ports is 4 SCCs and
* 2 SMCs. The "hub6" field is used to indicate the channel number, with
* a flag indicating SCC or SMC, and the number is used as an index into
* the CPM parameter area for this device.
* The "type" field is currently set to 0, for PORT_UNKNOWN. It is
* not currently used. I should probably use it to indicate the port
* type of SMC or SCC.
* The SMCs do not support any modem control signals.
*/
#define smc_scc_num hub6
#define NUM_IS_SCC ((int)0x00010000)
#define PORT_NUM(P) ((P) & 0x0000ffff)
#if defined (CONFIG_UCQUICC)
volatile extern void *_periph_base;
/* sipex transceiver
* mode bits for are on pins
*
* SCC2 d16..19
* SCC3 d20..23
* SCC4 d24..27
*/
#define SIPEX_MODE(n,m) ((m & 0x0f)<<(16+4*(n-1)))
static uint sipex_mode_bits = 0x00000000;
#endif
/* There is no `serial_state' defined back here in 2.0.
* Try to get by with serial_struct
*/
/* #define serial_state serial_struct */
/* 2.4 -> 2.0 portability problem: async_icount in 2.4 has a few
* extras: */
#if 0
struct async_icount_24 {
__u32 cts, dsr, rng, dcd, tx, rx;
__u32 frame, parity, overrun, brk;
__u32 buf_overrun;
} icount;
#endif
#if 0
struct serial_state {
int magic;
int baud_base;
unsigned long port;
int irq;
int flags;
int hub6;
int type;
int line;
int revision; /* Chip revision (950) */
int xmit_fifo_size;
int custom_divisor;
int count;
u8 *iomem_base;
u16 iomem_reg_shift;
unsigned short close_delay;
unsigned short closing_wait; /* time to wait before closing */
struct async_icount_24 icount;
int io_type;
struct async_struct *info;
};
#endif
#define SSTATE_MAGIC 0x5302
/* SMC2 is sometimes used for low performance TDM interfaces. Define
* this as 1 if you want SMC2 as a serial port UART managed by this driver.
* Define this as 0 if you wish to use SMC2 for something else.
*/
#define USE_SMC2 1
#if 0
/* Define SCC to ttySx mapping. */
#define SCC_NUM_BASE (USE_SMC2 + 1) /* SCC base tty "number" */
/* Define which SCC is the first one to use for a serial port. These
* are 0-based numbers, i.e. this assumes the first SCC (SCC1) is used
* for Ethernet, and the first available SCC for serial UART is SCC2.
* NOTE: IF YOU CHANGE THIS, you have to change the PROFF_xxx and
* interrupt vectors in the table below to match.
*/
#define SCC_IDX_BASE 1 /* table index */
#endif
/* Processors other than the 860 only get SMCs configured by default.
* Either they don't have SCCs or they are allocated somewhere else.
* Of course, there are now 860s without some SCCs, so we will need to
* address that someday.
* The Embedded Planet Multimedia I/O cards use TDM interfaces to the
* stereo codec parts, and we use SMC2 to help support that.
*/
static struct serial_state rs_table[] = {
/* type line PORT IRQ FLAGS smc_scc_num (F.K.A. hub6) */
{ 0, 0, PRSLOT_SMC1, CPMVEC_SMC1, 0, 0 } /* SMC1 ttyS0 */
#if USE_SMC2
,{ 0, 0, PRSLOT_SMC2, CPMVEC_SMC2, 0, 1 } /* SMC2 ttyS1 */
#endif
#if defined(CONFIG_SERIAL_68360_SCC)
,{ 0, 0, PRSLOT_SCC2, CPMVEC_SCC2, 0, (NUM_IS_SCC | 1) } /* SCC2 ttyS2 */
,{ 0, 0, PRSLOT_SCC3, CPMVEC_SCC3, 0, (NUM_IS_SCC | 2) } /* SCC3 ttyS3 */
,{ 0, 0, PRSLOT_SCC4, CPMVEC_SCC4, 0, (NUM_IS_SCC | 3) } /* SCC4 ttyS4 */
#endif
};
#define NR_PORTS (sizeof(rs_table)/sizeof(struct serial_state))
/* The number of buffer descriptors and their sizes.
*/
#define RX_NUM_FIFO 4
#define RX_BUF_SIZE 32
#define TX_NUM_FIFO 4
#define TX_BUF_SIZE 32
#define CONSOLE_NUM_FIFO 2
#define CONSOLE_BUF_SIZE 4
char *console_fifos[CONSOLE_NUM_FIFO * CONSOLE_BUF_SIZE];
/* The async_struct in serial.h does not really give us what we
* need, so define our own here.
*/
typedef struct serial_info {
int magic;
int flags;
struct serial_state *state;
/* struct serial_struct *state; */
/* struct async_struct *state; */
struct tty_struct *tty;
int read_status_mask;
int ignore_status_mask;
int timeout;
int line;
int x_char; /* xon/xoff character */
int close_delay;
unsigned short closing_wait;
unsigned short closing_wait2;
unsigned long event;
unsigned long last_active;
int blocked_open; /* # of blocked opens */
struct work_struct tqueue;
struct work_struct tqueue_hangup;
wait_queue_head_t open_wait;
wait_queue_head_t close_wait;
/* CPM Buffer Descriptor pointers.
*/
QUICC_BD *rx_bd_base;
QUICC_BD *rx_cur;
QUICC_BD *tx_bd_base;
QUICC_BD *tx_cur;
} ser_info_t;
/* since kmalloc_init() does not get called until much after this initialization: */
static ser_info_t quicc_ser_info[NR_PORTS];
static char rx_buf_pool[NR_PORTS * RX_NUM_FIFO * RX_BUF_SIZE];
static char tx_buf_pool[NR_PORTS * TX_NUM_FIFO * TX_BUF_SIZE];
static void change_speed(ser_info_t *info);
static void rs_360_wait_until_sent(struct tty_struct *tty, int timeout);
static inline int serial_paranoia_check(ser_info_t *info,
char *name, const char *routine)
{
#ifdef SERIAL_PARANOIA_CHECK
static const char *badmagic =
"Warning: bad magic number for serial struct (%s) in %s\n";
static const char *badinfo =
"Warning: null async_struct for (%s) in %s\n";
if (!info) {
printk(badinfo, name, routine);
return 1;
}
if (info->magic != SERIAL_MAGIC) {
printk(badmagic, name, routine);
return 1;
}
#endif
return 0;
}
/*
* This is used to figure out the divisor speeds and the timeouts,
* indexed by the termio value. The generic CPM functions are responsible
* for setting and assigning baud rate generators for us.
*/
static int baud_table[] = {
0, 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
9600, 19200, 38400, 57600, 115200, 230400, 460800, 0 };
/* This sucks. There is a better way: */
#if defined(CONFIG_CONSOLE_9600)
#define CONSOLE_BAUDRATE 9600
#elif defined(CONFIG_CONSOLE_19200)
#define CONSOLE_BAUDRATE 19200
#elif defined(CONFIG_CONSOLE_115200)
#define CONSOLE_BAUDRATE 115200
#else
#warning "console baud rate undefined"
#define CONSOLE_BAUDRATE 9600
#endif
/*
* ------------------------------------------------------------
* rs_stop() and rs_start()
*
* This routines are called before setting or resetting tty->stopped.
* They enable or disable transmitter interrupts, as necessary.
* ------------------------------------------------------------
*/
static void rs_360_stop(struct tty_struct *tty)
{
ser_info_t *info = (ser_info_t *)tty->driver_data;
int idx;
unsigned long flags;
volatile struct scc_regs *sccp;
volatile struct smc_regs *smcp;
if (serial_paranoia_check(info, tty->name, "rs_stop"))
return;
local_irq_save(flags);
idx = PORT_NUM(info->state->smc_scc_num);
if (info->state->smc_scc_num & NUM_IS_SCC) {
sccp = &pquicc->scc_regs[idx];
sccp->scc_sccm &= ~UART_SCCM_TX;
} else {
/* smcp = &cpmp->cp_smc[idx]; */
smcp = &pquicc->smc_regs[idx];
smcp->smc_smcm &= ~SMCM_TX;
}
local_irq_restore(flags);
}
static void rs_360_start(struct tty_struct *tty)
{
ser_info_t *info = (ser_info_t *)tty->driver_data;
int idx;
unsigned long flags;
volatile struct scc_regs *sccp;
volatile struct smc_regs *smcp;
if (serial_paranoia_check(info, tty->name, "rs_stop"))
return;
local_irq_save(flags);
idx = PORT_NUM(info->state->smc_scc_num);
if (info->state->smc_scc_num & NUM_IS_SCC) {
sccp = &pquicc->scc_regs[idx];
sccp->scc_sccm |= UART_SCCM_TX;
} else {
smcp = &pquicc->smc_regs[idx];
smcp->smc_smcm |= SMCM_TX;
}
local_irq_restore(flags);
}
/*
* ----------------------------------------------------------------------
*
* Here starts the interrupt handling routines. All of the following
* subroutines are declared as inline and are folded into
* rs_interrupt(). They were separated out for readability's sake.
*
* Note: rs_interrupt() is a "fast" interrupt, which means that it
* runs with interrupts turned off. People who may want to modify
* rs_interrupt() should try to keep the interrupt handler as fast as
* possible. After you are done making modifications, it is not a bad
* idea to do:
*
* gcc -S -DKERNEL -Wall -Wstrict-prototypes -O6 -fomit-frame-pointer serial.c
*
* and look at the resulting assemble code in serial.s.
*
* - Ted Ts'o (tytso@mit.edu), 7-Mar-93
* -----------------------------------------------------------------------
*/
static _INLINE_ void receive_chars(ser_info_t *info)
{
struct tty_struct *tty = info->port.tty;
unsigned char ch, flag, *cp;
/*int ignored = 0;*/
int i;
ushort status;
struct async_icount *icount;
/* struct async_icount_24 *icount; */
volatile QUICC_BD *bdp;
icount = &info->state->icount;
/* Just loop through the closed BDs and copy the characters into
* the buffer.
*/
bdp = info->rx_cur;
for (;;) {
if (bdp->status & BD_SC_EMPTY) /* If this one is empty */
break; /* we are all done */
/* The read status mask tell us what we should do with
* incoming characters, especially if errors occur.
* One special case is the use of BD_SC_EMPTY. If
* this is not set, we are supposed to be ignoring
* inputs. In this case, just mark the buffer empty and
* continue.
*/
if (!(info->read_status_mask & BD_SC_EMPTY)) {
bdp->status |= BD_SC_EMPTY;
bdp->status &=
~(BD_SC_BR | BD_SC_FR | BD_SC_PR | BD_SC_OV);
if (bdp->status & BD_SC_WRAP)
bdp = info->rx_bd_base;
else
bdp++;
continue;
}
/* Get the number of characters and the buffer pointer.
*/
i = bdp->length;
/* cp = (unsigned char *)__va(bdp->buf); */
cp = (char *)bdp->buf;
status = bdp->status;
while (i-- > 0) {
ch = *cp++;
icount->rx++;
#ifdef SERIAL_DEBUG_INTR
printk("DR%02x:%02x...", ch, status);
#endif
flag = TTY_NORMAL;
if (status & (BD_SC_BR | BD_SC_FR |
BD_SC_PR | BD_SC_OV)) {
/*
* For statistics only
*/
if (status & BD_SC_BR)
icount->brk++;
else if (status & BD_SC_PR)
icount->parity++;
else if (status & BD_SC_FR)
icount->frame++;
if (status & BD_SC_OV)
icount->overrun++;
/*
* Now check to see if character should be
* ignored, and mask off conditions which
* should be ignored.
if (status & info->ignore_status_mask) {
if (++ignored > 100)
break;
continue;
}
*/
status &= info->read_status_mask;
if (status & (BD_SC_BR)) {
#ifdef SERIAL_DEBUG_INTR
printk("handling break....");
#endif
*tty->flip.flag_buf_ptr = TTY_BREAK;
if (info->flags & ASYNC_SAK)
do_SAK(tty);
} else if (status & BD_SC_PR)
flag = TTY_PARITY;
else if (status & BD_SC_FR)
flag = TTY_FRAME;
}
tty_insert_flip_char(tty, ch, flag);
if (status & BD_SC_OV)
/*
* Overrun is special, since it's
* reported immediately, and doesn't
* affect the current character
*/
tty_insert_flip_char(tty, 0, TTY_OVERRUN);
}
/* This BD is ready to be used again. Clear status.
* Get next BD.
*/
bdp->status |= BD_SC_EMPTY;
bdp->status &= ~(BD_SC_BR | BD_SC_FR | BD_SC_PR | BD_SC_OV);
if (bdp->status & BD_SC_WRAP)
bdp = info->rx_bd_base;
else
bdp++;
}
info->rx_cur = (QUICC_BD *)bdp;
tty_schedule_flip(tty);
}
static _INLINE_ void receive_break(ser_info_t *info)
{
struct tty_struct *tty = info->port.tty;
info->state->icount.brk++;
/* Check to see if there is room in the tty buffer for
* the break. If not, we exit now, losing the break. FIXME
*/
tty_insert_flip_char(tty, 0, TTY_BREAK);
tty_schedule_flip(tty);
}
static _INLINE_ void transmit_chars(ser_info_t *info)
{
if ((info->flags & TX_WAKEUP) ||
(info->port.tty->flags & (1 << TTY_DO_WRITE_WAKEUP))) {
schedule_work(&info->tqueue);
}
#ifdef SERIAL_DEBUG_INTR
printk("THRE...");
#endif
}
#ifdef notdef
/* I need to do this for the SCCs, so it is left as a reminder.
*/
static _INLINE_ void check_modem_status(struct async_struct *info)
{
int status;
/* struct async_icount *icount; */
struct async_icount_24 *icount;
status = serial_in(info, UART_MSR);
if (status & UART_MSR_ANY_DELTA) {
icount = &info->state->icount;
/* update input line counters */
if (status & UART_MSR_TERI)
icount->rng++;
if (status & UART_MSR_DDSR)
icount->dsr++;
if (status & UART_MSR_DDCD) {
icount->dcd++;
#ifdef CONFIG_HARD_PPS
if ((info->flags & ASYNC_HARDPPS_CD) &&
(status & UART_MSR_DCD))
hardpps();
#endif
}
if (status & UART_MSR_DCTS)
icount->cts++;
wake_up_interruptible(&info->delta_msr_wait);
}
if ((info->flags & ASYNC_CHECK_CD) && (status & UART_MSR_DDCD)) {
#if (defined(SERIAL_DEBUG_OPEN) || defined(SERIAL_DEBUG_INTR))
printk("ttys%d CD now %s...", info->line,
(status & UART_MSR_DCD) ? "on" : "off");
#endif
if (status & UART_MSR_DCD)
wake_up_interruptible(&info->open_wait);
else {
#ifdef SERIAL_DEBUG_OPEN
printk("scheduling hangup...");
#endif
queue_task(&info->tqueue_hangup,
&tq_scheduler);
}
}
if (info->flags & ASYNC_CTS_FLOW) {
if (info->port.tty->hw_stopped) {
if (status & UART_MSR_CTS) {
#if (defined(SERIAL_DEBUG_INTR) || defined(SERIAL_DEBUG_FLOW))
printk("CTS tx start...");
#endif
info->port.tty->hw_stopped = 0;
info->IER |= UART_IER_THRI;
serial_out(info, UART_IER, info->IER);
rs_sched_event(info, RS_EVENT_WRITE_WAKEUP);
return;
}
} else {
if (!(status & UART_MSR_CTS)) {
#if (defined(SERIAL_DEBUG_INTR) || defined(SERIAL_DEBUG_FLOW))
printk("CTS tx stop...");
#endif
info->port.tty->hw_stopped = 1;
info->IER &= ~UART_IER_THRI;
serial_out(info, UART_IER, info->IER);
}
}
}
}
#endif
/*
* This is the serial driver's interrupt routine for a single port
*/
/* static void rs_360_interrupt(void *dev_id) */ /* until and if we start servicing irqs here */
static void rs_360_interrupt(int vec, void *dev_id)
{
u_char events;
int idx;
ser_info_t *info;
volatile struct smc_regs *smcp;
volatile struct scc_regs *sccp;
info = dev_id;
idx = PORT_NUM(info->state->smc_scc_num);
if (info->state->smc_scc_num & NUM_IS_SCC) {
sccp = &pquicc->scc_regs[idx];
events = sccp->scc_scce;
if (events & SCCM_RX)
receive_chars(info);
if (events & SCCM_TX)
transmit_chars(info);
sccp->scc_scce = events;
} else {
smcp = &pquicc->smc_regs[idx];
events = smcp->smc_smce;
if (events & SMCM_BRKE)
receive_break(info);
if (events & SMCM_RX)
receive_chars(info);
if (events & SMCM_TX)
transmit_chars(info);
smcp->smc_smce = events;
}
#ifdef SERIAL_DEBUG_INTR
printk("rs_interrupt_single(%d, %x)...",
info->state->smc_scc_num, events);
#endif
#ifdef modem_control
check_modem_status(info);
#endif
info->last_active = jiffies;
#ifdef SERIAL_DEBUG_INTR
printk("end.\n");
#endif
}
/*
* -------------------------------------------------------------------
* Here ends the serial interrupt routines.
* -------------------------------------------------------------------
*/
static void do_softint(void *private_)
{
ser_info_t *info = (ser_info_t *) private_;
struct tty_struct *tty;
tty = info->port.tty;
if (!tty)
return;
if (test_and_clear_bit(RS_EVENT_WRITE_WAKEUP, &info->event))
tty_wakeup(tty);
}
/*
* This routine is called from the scheduler tqueue when the interrupt
* routine has signalled that a hangup has occurred. The path of
* hangup processing is:
*
* serial interrupt routine -> (scheduler tqueue) ->
* do_serial_hangup() -> tty->hangup() -> rs_hangup()
*
*/
static void do_serial_hangup(void *private_)
{
struct async_struct *info = (struct async_struct *) private_;
struct tty_struct *tty;
tty = info->port.tty;
if (!tty)
return;
tty_hangup(tty);
}
static int startup(ser_info_t *info)
{
unsigned long flags;
int retval=0;
int idx;
/*struct serial_state *state = info->state;*/
volatile struct smc_regs *smcp;
volatile struct scc_regs *sccp;
volatile struct smc_uart_pram *up;
volatile struct uart_pram *scup;
local_irq_save(flags);
if (info->flags & ASYNC_INITIALIZED) {
goto errout;
}
#ifdef maybe
if (!state->port || !state->type) {
if (info->port.tty)
set_bit(TTY_IO_ERROR, &info->port.tty->flags);
goto errout;
}
#endif
#ifdef SERIAL_DEBUG_OPEN
printk("starting up ttys%d (irq %d)...", info->line, state->irq);
#endif
#ifdef modem_control
info->MCR = 0;
if (info->port.tty->termios->c_cflag & CBAUD)
info->MCR = UART_MCR_DTR | UART_MCR_RTS;
#endif
if (info->port.tty)
clear_bit(TTY_IO_ERROR, &info->port.tty->flags);
/*
* and set the speed of the serial port
*/
change_speed(info);
idx = PORT_NUM(info->state->smc_scc_num);
if (info->state->smc_scc_num & NUM_IS_SCC) {
sccp = &pquicc->scc_regs[idx];
scup = &pquicc->pram[info->state->port].scc.pscc.u;
scup->mrblr = RX_BUF_SIZE;
scup->max_idl = RX_BUF_SIZE;
sccp->scc_sccm |= (UART_SCCM_TX | UART_SCCM_RX);
sccp->scc_gsmr.w.low |= (SCC_GSMRL_ENR | SCC_GSMRL_ENT);
} else {
smcp = &pquicc->smc_regs[idx];
/* Enable interrupts and I/O.
*/
smcp->smc_smcm |= (SMCM_RX | SMCM_TX);
smcp->smc_smcmr |= (SMCMR_REN | SMCMR_TEN);
/* We can tune the buffer length and idle characters
* to take advantage of the entire incoming buffer size.
* If mrblr is something other than 1, maxidl has to be
* non-zero or we never get an interrupt. The maxidl
* is the number of character times we wait after reception
* of the last character before we decide no more characters
* are coming.
*/
/* up = (smc_uart_t *)&pquicc->cp_dparam[state->port]; */
/* holy unionized structures, Batman: */
up = &pquicc->pram[info->state->port].scc.pothers.idma_smc.psmc.u;
up->mrblr = RX_BUF_SIZE;
up->max_idl = RX_BUF_SIZE;
up->brkcr = 1; /* number of break chars */
}
info->flags |= ASYNC_INITIALIZED;
local_irq_restore(flags);
return 0;
errout:
local_irq_restore(flags);
return retval;
}
/*
* This routine will shutdown a serial port; interrupts are disabled, and
* DTR is dropped if the hangup on close termio flag is on.
*/
static void shutdown(ser_info_t *info)
{
unsigned long flags;
struct serial_state *state;
int idx;
volatile struct smc_regs *smcp;
volatile struct scc_regs *sccp;
if (!(info->flags & ASYNC_INITIALIZED))
return;
state = info->state;
#ifdef SERIAL_DEBUG_OPEN
printk("Shutting down serial port %d (irq %d)....", info->line,
state->irq);
#endif
local_irq_save(flags);
idx = PORT_NUM(state->smc_scc_num);
if (state->smc_scc_num & NUM_IS_SCC) {
sccp = &pquicc->scc_regs[idx];
sccp->scc_gsmr.w.low &= ~(SCC_GSMRL_ENR | SCC_GSMRL_ENT);
#ifdef CONFIG_SERIAL_CONSOLE
/* We can't disable the transmitter if this is the
* system console.
*/
if ((state - rs_table) != CONFIG_SERIAL_CONSOLE_PORT)
#endif
sccp->scc_sccm &= ~(UART_SCCM_TX | UART_SCCM_RX);
} else {
smcp = &pquicc->smc_regs[idx];
/* Disable interrupts and I/O.
*/
smcp->smc_smcm &= ~(SMCM_RX | SMCM_TX);
#ifdef CONFIG_SERIAL_CONSOLE
/* We can't disable the transmitter if this is the
* system console.
*/
if ((state - rs_table) != CONFIG_SERIAL_CONSOLE_PORT)
#endif
smcp->smc_smcmr &= ~(SMCMR_REN | SMCMR_TEN);
}
if (info->port.tty)
set_bit(TTY_IO_ERROR, &info->port.tty->flags);
info->flags &= ~ASYNC_INITIALIZED;
local_irq_restore(flags);
}
/*
* This routine is called to set the UART divisor registers to match
* the specified baud rate for a serial port.
*/
static void change_speed(ser_info_t *info)
{
int baud_rate;
unsigned cflag, cval, scval, prev_mode;
int i, bits, sbits, idx;
unsigned long flags;
struct serial_state *state;
volatile struct smc_regs *smcp;
volatile struct scc_regs *sccp;
if (!info->port.tty || !info->port.tty->termios)
return;
cflag = info->port.tty->termios->c_cflag;
state = info->state;
/* Character length programmed into the mode register is the
* sum of: 1 start bit, number of data bits, 0 or 1 parity bit,
* 1 or 2 stop bits, minus 1.
* The value 'bits' counts this for us.
*/
cval = 0;
scval = 0;
/* byte size and parity */
switch (cflag & CSIZE) {
case CS5: bits = 5; break;
case CS6: bits = 6; break;
case CS7: bits = 7; break;
case CS8: bits = 8; break;
/* Never happens, but GCC is too dumb to figure it out */
default: bits = 8; break;
}
sbits = bits - 5;
if (cflag & CSTOPB) {
cval |= SMCMR_SL; /* Two stops */
scval |= SCU_PMSR_SL;
bits++;
}
if (cflag & PARENB) {
cval |= SMCMR_PEN;
scval |= SCU_PMSR_PEN;
bits++;
}
if (!(cflag & PARODD)) {
cval |= SMCMR_PM_EVEN;
scval |= (SCU_PMSR_REVP | SCU_PMSR_TEVP);
}
/* Determine divisor based on baud rate */
i = cflag & CBAUD;
if (i >= (sizeof(baud_table)/sizeof(int)))
baud_rate = 9600;
else
baud_rate = baud_table[i];
info->timeout = (TX_BUF_SIZE*HZ*bits);
info->timeout += HZ/50; /* Add .02 seconds of slop */
#ifdef modem_control
/* CTS flow control flag and modem status interrupts */
info->IER &= ~UART_IER_MSI;
if (info->flags & ASYNC_HARDPPS_CD)
info->IER |= UART_IER_MSI;
if (cflag & CRTSCTS) {
info->flags |= ASYNC_CTS_FLOW;
info->IER |= UART_IER_MSI;
} else
info->flags &= ~ASYNC_CTS_FLOW;
if (cflag & CLOCAL)
info->flags &= ~ASYNC_CHECK_CD;
else {
info->flags |= ASYNC_CHECK_CD;
info->IER |= UART_IER_MSI;
}
serial_out(info, UART_IER, info->IER);
#endif
/*
* Set up parity check flag
*/
info->read_status_mask = (BD_SC_EMPTY | BD_SC_OV);
if (I_INPCK(info->port.tty))
info->read_status_mask |= BD_SC_FR | BD_SC_PR;
if (I_BRKINT(info->port.tty) || I_PARMRK(info->port.tty))
info->read_status_mask |= BD_SC_BR;
/*
* Characters to ignore
*/
info->ignore_status_mask = 0;
if (I_IGNPAR(info->port.tty))
info->ignore_status_mask |= BD_SC_PR | BD_SC_FR;
if (I_IGNBRK(info->port.tty)) {
info->ignore_status_mask |= BD_SC_BR;
/*
* If we're ignore parity and break indicators, ignore
* overruns too. (For real raw support).
*/
if (I_IGNPAR(info->port.tty))
info->ignore_status_mask |= BD_SC_OV;
}
/*
* !!! ignore all characters if CREAD is not set
*/
if ((cflag & CREAD) == 0)
info->read_status_mask &= ~BD_SC_EMPTY;
local_irq_save(flags);
/* Start bit has not been added (so don't, because we would just
* subtract it later), and we need to add one for the number of
* stops bits (there is always at least one).
*/
bits++;
idx = PORT_NUM(state->smc_scc_num);
if (state->smc_scc_num & NUM_IS_SCC) {
sccp = &pquicc->scc_regs[idx];
sccp->scc_psmr = (sbits << 12) | scval;
} else {
smcp = &pquicc->smc_regs[idx];
/* Set the mode register. We want to keep a copy of the
* enables, because we want to put them back if they were
* present.
*/
prev_mode = smcp->smc_smcmr;
smcp->smc_smcmr = smcr_mk_clen(bits) | cval | SMCMR_SM_UART;
smcp->smc_smcmr |= (prev_mode & (SMCMR_REN | SMCMR_TEN));
}
m360_cpm_setbrg((state - rs_table), baud_rate);
local_irq_restore(flags);
}
static void rs_360_put_char(struct tty_struct *tty, unsigned char ch)
{
ser_info_t *info = (ser_info_t *)tty->driver_data;
volatile QUICC_BD *bdp;
if (serial_paranoia_check(info, tty->name, "rs_put_char"))
return 0;
if (!tty)
return 0;
bdp = info->tx_cur;
while (bdp->status & BD_SC_READY);
/* *((char *)__va(bdp->buf)) = ch; */
*((char *)bdp->buf) = ch;
bdp->length = 1;
bdp->status |= BD_SC_READY;
/* Get next BD.
*/
if (bdp->status & BD_SC_WRAP)
bdp = info->tx_bd_base;
else
bdp++;
info->tx_cur = (QUICC_BD *)bdp;
return 1;
}
static int rs_360_write(struct tty_struct * tty,
const unsigned char *buf, int count)
{
int c, ret = 0;
ser_info_t *info = (ser_info_t *)tty->driver_data;
volatile QUICC_BD *bdp;
#ifdef CONFIG_KGDB
/* Try to let stub handle output. Returns true if it did. */
if (kgdb_output_string(buf, count))
return ret;
#endif
if (serial_paranoia_check(info, tty->name, "rs_write"))
return 0;
if (!tty)
return 0;
bdp = info->tx_cur;
while (1) {
c = min(count, TX_BUF_SIZE);
if (c <= 0)
break;
if (bdp->status & BD_SC_READY) {
info->flags |= TX_WAKEUP;
break;
}
/* memcpy(__va(bdp->buf), buf, c); */
memcpy((void *)bdp->buf, buf, c);
bdp->length = c;
bdp->status |= BD_SC_READY;
buf += c;
count -= c;
ret += c;
/* Get next BD.
*/
if (bdp->status & BD_SC_WRAP)
bdp = info->tx_bd_base;
else
bdp++;
info->tx_cur = (QUICC_BD *)bdp;
}
return ret;
}
static int rs_360_write_room(struct tty_struct *tty)
{
ser_info_t *info = (ser_info_t *)tty->driver_data;
int ret;
if (serial_paranoia_check(info, tty->name, "rs_write_room"))
return 0;
if ((info->tx_cur->status & BD_SC_READY) == 0) {
info->flags &= ~TX_WAKEUP;
ret = TX_BUF_SIZE;
}
else {
info->flags |= TX_WAKEUP;
ret = 0;
}
return ret;
}
/* I could track this with transmit counters....maybe later.
*/
static int rs_360_chars_in_buffer(struct tty_struct *tty)
{
ser_info_t *info = (ser_info_t *)tty->driver_data;
if (serial_paranoia_check(info, tty->name, "rs_chars_in_buffer"))
return 0;
return 0;
}
static void rs_360_flush_buffer(struct tty_struct *tty)
{
ser_info_t *info = (ser_info_t *)tty->driver_data;
if (serial_paranoia_check(info, tty->name, "rs_flush_buffer"))
return;
/* There is nothing to "flush", whatever we gave the CPM
* is on its way out.
*/
tty_wakeup(tty);
info->flags &= ~TX_WAKEUP;
}
/*
* This function is used to send a high-priority XON/XOFF character to
* the device
*/
static void rs_360_send_xchar(struct tty_struct *tty, char ch)
{
volatile QUICC_BD *bdp;
ser_info_t *info = (ser_info_t *)tty->driver_data;
if (serial_paranoia_check(info, tty->name, "rs_send_char"))
return;
bdp = info->tx_cur;
while (bdp->status & BD_SC_READY);
/* *((char *)__va(bdp->buf)) = ch; */
*((char *)bdp->buf) = ch;
bdp->length = 1;
bdp->status |= BD_SC_READY;
/* Get next BD.
*/
if (bdp->status & BD_SC_WRAP)
bdp = info->tx_bd_base;
else
bdp++;
info->tx_cur = (QUICC_BD *)bdp;
}
/*
* ------------------------------------------------------------
* rs_throttle()
*
* This routine is called by the upper-layer tty layer to signal that
* incoming characters should be throttled.
* ------------------------------------------------------------
*/
static void rs_360_throttle(struct tty_struct * tty)
{
ser_info_t *info = (ser_info_t *)tty->driver_data;
#ifdef SERIAL_DEBUG_THROTTLE
char buf[64];
printk("throttle %s: %d....\n", _tty_name(tty, buf),
tty->ldisc.chars_in_buffer(tty));
#endif
if (serial_paranoia_check(info, tty->name, "rs_throttle"))
return;
if (I_IXOFF(tty))
rs_360_send_xchar(tty, STOP_CHAR(tty));
#ifdef modem_control
if (tty->termios->c_cflag & CRTSCTS)
info->MCR &= ~UART_MCR_RTS;
local_irq_disable();
serial_out(info, UART_MCR, info->MCR);
local_irq_enable();
#endif
}
static void rs_360_unthrottle(struct tty_struct * tty)
{
ser_info_t *info = (ser_info_t *)tty->driver_data;
#ifdef SERIAL_DEBUG_THROTTLE
char buf[64];
printk("unthrottle %s: %d....\n", _tty_name(tty, buf),
tty->ldisc.chars_in_buffer(tty));
#endif
if (serial_paranoia_check(info, tty->name, "rs_unthrottle"))
return;
if (I_IXOFF(tty)) {
if (info->x_char)
info->x_char = 0;
else
rs_360_send_xchar(tty, START_CHAR(tty));
}
#ifdef modem_control
if (tty->termios->c_cflag & CRTSCTS)
info->MCR |= UART_MCR_RTS;
local_irq_disable();
serial_out(info, UART_MCR, info->MCR);
local_irq_enable();
#endif
}
/*
* ------------------------------------------------------------
* rs_ioctl() and friends
* ------------------------------------------------------------
*/
#ifdef maybe
/*
* get_lsr_info - get line status register info
*
* Purpose: Let user call ioctl() to get info when the UART physically
* is emptied. On bus types like RS485, the transmitter must
* release the bus after transmitting. This must be done when
* the transmit shift register is empty, not be done when the
* transmit holding register is empty. This functionality
* allows an RS485 driver to be written in user space.
*/
static int get_lsr_info(struct async_struct * info, unsigned int *value)
{
unsigned char status;
unsigned int result;
local_irq_disable();
status = serial_in(info, UART_LSR);
local_irq_enable();
result = ((status & UART_LSR_TEMT) ? TIOCSER_TEMT : 0);
return put_user(result,value);
}
#endif
static int rs_360_tiocmget(struct tty_struct *tty, struct file *file)
{
ser_info_t *info = (ser_info_t *)tty->driver_data;
unsigned int result = 0;
#ifdef modem_control
unsigned char control, status;
if (serial_paranoia_check(info, tty->name, __func__))
return -ENODEV;
if (tty->flags & (1 << TTY_IO_ERROR))
return -EIO;
control = info->MCR;
local_irq_disable();
status = serial_in(info, UART_MSR);
local_irq_enable();
result = ((control & UART_MCR_RTS) ? TIOCM_RTS : 0)
| ((control & UART_MCR_DTR) ? TIOCM_DTR : 0)
#ifdef TIOCM_OUT1
| ((control & UART_MCR_OUT1) ? TIOCM_OUT1 : 0)
| ((control & UART_MCR_OUT2) ? TIOCM_OUT2 : 0)
#endif
| ((status & UART_MSR_DCD) ? TIOCM_CAR : 0)
| ((status & UART_MSR_RI) ? TIOCM_RNG : 0)
| ((status & UART_MSR_DSR) ? TIOCM_DSR : 0)
| ((status & UART_MSR_CTS) ? TIOCM_CTS : 0);
#endif
return result;
}
static int rs_360_tiocmset(struct tty_struct *tty, struct file *file,
unsigned int set, unsigned int clear)
{
#ifdef modem_control
ser_info_t *info = (ser_info_t *)tty->driver_data;
unsigned int arg;
if (serial_paranoia_check(info, tty->name, __func__))
return -ENODEV;
if (tty->flags & (1 << TTY_IO_ERROR))
return -EIO;
/* FIXME: locking on info->mcr */
if (set & TIOCM_RTS)
info->mcr |= UART_MCR_RTS;
if (set & TIOCM_DTR)
info->mcr |= UART_MCR_DTR;
if (clear & TIOCM_RTS)
info->MCR &= ~UART_MCR_RTS;
if (clear & TIOCM_DTR)
info->MCR &= ~UART_MCR_DTR;
#ifdef TIOCM_OUT1
if (set & TIOCM_OUT1)
info->MCR |= UART_MCR_OUT1;
if (set & TIOCM_OUT2)
info->MCR |= UART_MCR_OUT2;
if (clear & TIOCM_OUT1)
info->MCR &= ~UART_MCR_OUT1;
if (clear & TIOCM_OUT2)
info->MCR &= ~UART_MCR_OUT2;
#endif
local_irq_disable();
serial_out(info, UART_MCR, info->MCR);
local_irq_enable();
#endif
return 0;
}
/* Sending a break is a two step process on the SMC/SCC. It is accomplished
* by sending a STOP TRANSMIT command followed by a RESTART TRANSMIT
* command. We take advantage of the begin/end functions to make this
* happen.
*/
static ushort smc_chan_map[] = {
CPM_CR_CH_SMC1,
CPM_CR_CH_SMC2
};
static ushort scc_chan_map[] = {
CPM_CR_CH_SCC1,
CPM_CR_CH_SCC2,
CPM_CR_CH_SCC3,
CPM_CR_CH_SCC4
};
static void begin_break(ser_info_t *info)
{
volatile QUICC *cp;
ushort chan;
int idx;
cp = pquicc;
idx = PORT_NUM(info->state->smc_scc_num);
if (info->state->smc_scc_num & NUM_IS_SCC)
chan = scc_chan_map[idx];
else
chan = smc_chan_map[idx];
cp->cp_cr = mk_cr_cmd(chan, CPM_CR_STOP_TX) | CPM_CR_FLG;
while (cp->cp_cr & CPM_CR_FLG);
}
static void end_break(ser_info_t *info)
{
volatile QUICC *cp;
ushort chan;
int idx;
cp = pquicc;
idx = PORT_NUM(info->state->smc_scc_num);
if (info->state->smc_scc_num & NUM_IS_SCC)
chan = scc_chan_map[idx];
else
chan = smc_chan_map[idx];
cp->cp_cr = mk_cr_cmd(chan, CPM_CR_RESTART_TX) | CPM_CR_FLG;
while (cp->cp_cr & CPM_CR_FLG);
}
/*
* This routine sends a break character out the serial port.
*/
static void send_break(ser_info_t *info, unsigned int duration)
{
#ifdef SERIAL_DEBUG_SEND_BREAK
printk("rs_send_break(%d) jiff=%lu...", duration, jiffies);
#endif
begin_break(info);
msleep_interruptible(duration);
end_break(info);
#ifdef SERIAL_DEBUG_SEND_BREAK
printk("done jiffies=%lu\n", jiffies);
#endif
}
static int rs_360_ioctl(struct tty_struct *tty, struct file * file,
unsigned int cmd, unsigned long arg)
{
int error;
ser_info_t *info = (ser_info_t *)tty->driver_data;
int retval;
struct async_icount cnow;
/* struct async_icount_24 cnow;*/ /* kernel counter temps */
struct serial_icounter_struct *p_cuser; /* user space */
if (serial_paranoia_check(info, tty->name, "rs_ioctl"))
return -ENODEV;
if ((cmd != TIOCMIWAIT) && (cmd != TIOCGICOUNT)) {
if (tty->flags & (1 << TTY_IO_ERROR))
return -EIO;
}
switch (cmd) {
case TCSBRK: /* SVID version: non-zero arg --> no break */
retval = tty_check_change(tty);
if (retval)
return retval;
tty_wait_until_sent(tty, 0);
if (signal_pending(current))
return -EINTR;
if (!arg) {
send_break(info, 250); /* 1/4 second */
if (signal_pending(current))
return -EINTR;
}
return 0;
case TCSBRKP: /* support for POSIX tcsendbreak() */
retval = tty_check_change(tty);
if (retval)
return retval;
tty_wait_until_sent(tty, 0);
if (signal_pending(current))
return -EINTR;
send_break(info, arg ? arg*100 : 250);
if (signal_pending(current))
return -EINTR;
return 0;
case TIOCSBRK:
retval = tty_check_change(tty);
if (retval)
return retval;
tty_wait_until_sent(tty, 0);
begin_break(info);
return 0;
case TIOCCBRK:
retval = tty_check_change(tty);
if (retval)
return retval;
end_break(info);
return 0;
#ifdef maybe
case TIOCSERGETLSR: /* Get line status register */
return get_lsr_info(info, (unsigned int *) arg);
#endif
/*
* Wait for any of the 4 modem inputs (DCD,RI,DSR,CTS) to change
* - mask passed in arg for lines of interest
* (use |'ed TIOCM_RNG/DSR/CD/CTS for masking)
* Caller should use TIOCGICOUNT to see which one it was
*/
case TIOCMIWAIT:
#ifdef modem_control
local_irq_disable();
/* note the counters on entry */
cprev = info->state->icount;
local_irq_enable();
while (1) {
interruptible_sleep_on(&info->delta_msr_wait);
/* see if a signal did it */
if (signal_pending(current))
return -ERESTARTSYS;
local_irq_disable();
cnow = info->state->icount; /* atomic copy */
local_irq_enable();
if (cnow.rng == cprev.rng && cnow.dsr == cprev.dsr &&
cnow.dcd == cprev.dcd && cnow.cts == cprev.cts)
return -EIO; /* no change => error */
if ( ((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) ||
((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) ||
((arg & TIOCM_CD) && (cnow.dcd != cprev.dcd)) ||
((arg & TIOCM_CTS) && (cnow.cts != cprev.cts)) ) {
return 0;
}
cprev = cnow;
}
/* NOTREACHED */
#else
return 0;
#endif
/*
* Get counter of input serial line interrupts (DCD,RI,DSR,CTS)
* Return: write counters to the user passed counter struct
* NB: both 1->0 and 0->1 transitions are counted except for
* RI where only 0->1 is counted.
*/
case TIOCGICOUNT:
local_irq_disable();
cnow = info->state->icount;
local_irq_enable();
p_cuser = (struct serial_icounter_struct *) arg;
/* error = put_user(cnow.cts, &p_cuser->cts); */
/* if (error) return error; */
/* error = put_user(cnow.dsr, &p_cuser->dsr); */
/* if (error) return error; */
/* error = put_user(cnow.rng, &p_cuser->rng); */
/* if (error) return error; */
/* error = put_user(cnow.dcd, &p_cuser->dcd); */
/* if (error) return error; */
put_user(cnow.cts, &p_cuser->cts);
put_user(cnow.dsr, &p_cuser->dsr);
put_user(cnow.rng, &p_cuser->rng);
put_user(cnow.dcd, &p_cuser->dcd);
return 0;
default:
return -ENOIOCTLCMD;
}
return 0;
}
/* FIX UP modem control here someday......
*/
static void rs_360_set_termios(struct tty_struct *tty, struct ktermios *old_termios)
{
ser_info_t *info = (ser_info_t *)tty->driver_data;
change_speed(info);
#ifdef modem_control
/* Handle transition to B0 status */
if ((old_termios->c_cflag & CBAUD) &&
!(tty->termios->c_cflag & CBAUD)) {
info->MCR &= ~(UART_MCR_DTR|UART_MCR_RTS);
local_irq_disable();
serial_out(info, UART_MCR, info->MCR);
local_irq_enable();
}
/* Handle transition away from B0 status */
if (!(old_termios->c_cflag & CBAUD) &&
(tty->termios->c_cflag & CBAUD)) {
info->MCR |= UART_MCR_DTR;
if (!tty->hw_stopped ||
!(tty->termios->c_cflag & CRTSCTS)) {
info->MCR |= UART_MCR_RTS;
}
local_irq_disable();
serial_out(info, UART_MCR, info->MCR);
local_irq_enable();
}
/* Handle turning off CRTSCTS */
if ((old_termios->c_cflag & CRTSCTS) &&
!(tty->termios->c_cflag & CRTSCTS)) {
tty->hw_stopped = 0;
rs_360_start(tty);
}
#endif
#if 0
/*
* No need to wake up processes in open wait, since they
* sample the CLOCAL flag once, and don't recheck it.
* XXX It's not clear whether the current behavior is correct
* or not. Hence, this may change.....
*/
if (!(old_termios->c_cflag & CLOCAL) &&
(tty->termios->c_cflag & CLOCAL))
wake_up_interruptible(&info->open_wait);
#endif
}
/*
* ------------------------------------------------------------
* rs_close()
*
* This routine is called when the serial port gets closed. First, we
* wait for the last remaining data to be sent. Then, we unlink its
* async structure from the interrupt chain if necessary, and we free
* that IRQ if nothing is left in the chain.
* ------------------------------------------------------------
*/
static void rs_360_close(struct tty_struct *tty, struct file * filp)
{
ser_info_t *info = (ser_info_t *)tty->driver_data;
/* struct async_state *state; */
struct serial_state *state;
unsigned long flags;
int idx;
volatile struct smc_regs *smcp;
volatile struct scc_regs *sccp;
if (!info || serial_paranoia_check(info, tty->name, "rs_close"))
return;
state = info->state;
local_irq_save(flags);
if (tty_hung_up_p(filp)) {
DBG_CNT("before DEC-hung");
local_irq_restore(flags);
return;
}
#ifdef SERIAL_DEBUG_OPEN
printk("rs_close ttys%d, count = %d\n", info->line, state->count);
#endif
if ((tty->count == 1) && (state->count != 1)) {
/*
* Uh, oh. tty->count is 1, which means that the tty
* structure will be freed. state->count should always
* be one in these conditions. If it's greater than
* one, we've got real problems, since it means the
* serial port won't be shutdown.
*/
printk("rs_close: bad serial port count; tty->count is 1, "
"state->count is %d\n", state->count);
state->count = 1;
}
if (--state->count < 0) {
printk("rs_close: bad serial port count for ttys%d: %d\n",
info->line, state->count);
state->count = 0;
}
if (state->count) {
DBG_CNT("before DEC-2");
local_irq_restore(flags);
return;
}
info->flags |= ASYNC_CLOSING;
/*
* Now we wait for the transmit buffer to clear; and we notify
* the line discipline to only process XON/XOFF characters.
*/
tty->closing = 1;
if (info->closing_wait != ASYNC_CLOSING_WAIT_NONE)
tty_wait_until_sent(tty, info->closing_wait);
/*
* At this point we stop accepting input. To do this, we
* disable the receive line status interrupts, and tell the
* interrupt driver to stop checking the data ready bit in the
* line status register.
*/
info->read_status_mask &= ~BD_SC_EMPTY;
if (info->flags & ASYNC_INITIALIZED) {
idx = PORT_NUM(info->state->smc_scc_num);
if (info->state->smc_scc_num & NUM_IS_SCC) {
sccp = &pquicc->scc_regs[idx];
sccp->scc_sccm &= ~UART_SCCM_RX;
sccp->scc_gsmr.w.low &= ~SCC_GSMRL_ENR;
} else {
smcp = &pquicc->smc_regs[idx];
smcp->smc_smcm &= ~SMCM_RX;
smcp->smc_smcmr &= ~SMCMR_REN;
}
/*
* Before we drop DTR, make sure the UART transmitter
* has completely drained; this is especially
* important if there is a transmit FIFO!
*/
rs_360_wait_until_sent(tty, info->timeout);
}
shutdown(info);
rs_360_flush_buffer(tty);
tty_ldisc_flush(tty);
tty->closing = 0;
info->event = 0;
info->port.tty = NULL;
if (info->blocked_open) {
if (info->close_delay) {
msleep_interruptible(jiffies_to_msecs(info->close_delay));
}
wake_up_interruptible(&info->open_wait);
}
info->flags &= ~(ASYNC_NORMAL_ACTIVE|ASYNC_CLOSING);
wake_up_interruptible(&info->close_wait);
local_irq_restore(flags);
}
/*
* rs_wait_until_sent() --- wait until the transmitter is empty
*/
static void rs_360_wait_until_sent(struct tty_struct *tty, int timeout)
{
ser_info_t *info = (ser_info_t *)tty->driver_data;
unsigned long orig_jiffies, char_time;
/*int lsr;*/
volatile QUICC_BD *bdp;
if (serial_paranoia_check(info, tty->name, "rs_wait_until_sent"))
return;
#ifdef maybe
if (info->state->type == PORT_UNKNOWN)
return;
#endif
orig_jiffies = jiffies;
/*
* Set the check interval to be 1/5 of the estimated time to
* send a single character, and make it at least 1. The check
* interval should also be less than the timeout.
*
* Note: we have to use pretty tight timings here to satisfy
* the NIST-PCTS.
*/
char_time = 1;
if (timeout)
char_time = min(char_time, (unsigned long)timeout);
#ifdef SERIAL_DEBUG_RS_WAIT_UNTIL_SENT
printk("In rs_wait_until_sent(%d) check=%lu...", timeout, char_time);
printk("jiff=%lu...", jiffies);
#endif
lock_kernel();
/* We go through the loop at least once because we can't tell
* exactly when the last character exits the shifter. There can
* be at least two characters waiting to be sent after the buffers
* are empty.
*/
do {
#ifdef SERIAL_DEBUG_RS_WAIT_UNTIL_SENT
printk("lsr = %d (jiff=%lu)...", lsr, jiffies);
#endif
/* current->counter = 0; make us low-priority */
msleep_interruptible(jiffies_to_msecs(char_time));
if (signal_pending(current))
break;
if (timeout && (time_after(jiffies, orig_jiffies + timeout)))
break;
/* The 'tx_cur' is really the next buffer to send. We
* have to back up to the previous BD and wait for it
* to go. This isn't perfect, because all this indicates
* is the buffer is available. There are still characters
* in the CPM FIFO.
*/
bdp = info->tx_cur;
if (bdp == info->tx_bd_base)
bdp += (TX_NUM_FIFO-1);
else
bdp--;
} while (bdp->status & BD_SC_READY);
current->state = TASK_RUNNING;
unlock_kernel();
#ifdef SERIAL_DEBUG_RS_WAIT_UNTIL_SENT
printk("lsr = %d (jiff=%lu)...done\n", lsr, jiffies);
#endif
}
/*
* rs_hangup() --- called by tty_hangup() when a hangup is signaled.
*/
static void rs_360_hangup(struct tty_struct *tty)
{
ser_info_t *info = (ser_info_t *)tty->driver_data;
struct serial_state *state = info->state;
if (serial_paranoia_check(info, tty->name, "rs_hangup"))
return;
state = info->state;
rs_360_flush_buffer(tty);
shutdown(info);
info->event = 0;
state->count = 0;
info->flags &= ~ASYNC_NORMAL_ACTIVE;
info->port.tty = NULL;
wake_up_interruptible(&info->open_wait);
}
/*
* ------------------------------------------------------------
* rs_open() and friends
* ------------------------------------------------------------
*/
static int block_til_ready(struct tty_struct *tty, struct file * filp,
ser_info_t *info)
{
#ifdef DO_THIS_LATER
DECLARE_WAITQUEUE(wait, current);
#endif
struct serial_state *state = info->state;
int retval;
int do_clocal = 0;
/*
* If the device is in the middle of being closed, then block
* until it's done, and then try again.
*/
if (tty_hung_up_p(filp) ||
(info->flags & ASYNC_CLOSING)) {
if (info->flags & ASYNC_CLOSING)
interruptible_sleep_on(&info->close_wait);
#ifdef SERIAL_DO_RESTART
if (info->flags & ASYNC_HUP_NOTIFY)
return -EAGAIN;
else
return -ERESTARTSYS;
#else
return -EAGAIN;
#endif
}
/*
* If non-blocking mode is set, or the port is not enabled,
* then make the check up front and then exit.
* If this is an SMC port, we don't have modem control to wait
* for, so just get out here.
*/
if ((filp->f_flags & O_NONBLOCK) ||
(tty->flags & (1 << TTY_IO_ERROR)) ||
!(info->state->smc_scc_num & NUM_IS_SCC)) {
info->flags |= ASYNC_NORMAL_ACTIVE;
return 0;
}
if (tty->termios->c_cflag & CLOCAL)
do_clocal = 1;
/*
* Block waiting for the carrier detect and the line to become
* free (i.e., not in use by the callout). While we are in
* this loop, state->count is dropped by one, so that
* rs_close() knows when to free things. We restore it upon
* exit, either normal or abnormal.
*/
retval = 0;
#ifdef DO_THIS_LATER
add_wait_queue(&info->open_wait, &wait);
#ifdef SERIAL_DEBUG_OPEN
printk("block_til_ready before block: ttys%d, count = %d\n",
state->line, state->count);
#endif
local_irq_disable();
if (!tty_hung_up_p(filp))
state->count--;
local_irq_enable();
info->blocked_open++;
while (1) {
local_irq_disable();
if (tty->termios->c_cflag & CBAUD)
serial_out(info, UART_MCR,
serial_inp(info, UART_MCR) |
(UART_MCR_DTR | UART_MCR_RTS));
local_irq_enable();
set_current_state(TASK_INTERRUPTIBLE);
if (tty_hung_up_p(filp) ||
!(info->flags & ASYNC_INITIALIZED)) {
#ifdef SERIAL_DO_RESTART
if (info->flags & ASYNC_HUP_NOTIFY)
retval = -EAGAIN;
else
retval = -ERESTARTSYS;
#else
retval = -EAGAIN;
#endif
break;
}
if (!(info->flags & ASYNC_CLOSING) &&
(do_clocal || (serial_in(info, UART_MSR) &
UART_MSR_DCD)))
break;
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
#ifdef SERIAL_DEBUG_OPEN
printk("block_til_ready blocking: ttys%d, count = %d\n",
info->line, state->count);
#endif
schedule();
}
current->state = TASK_RUNNING;
remove_wait_queue(&info->open_wait, &wait);
if (!tty_hung_up_p(filp))
state->count++;
info->blocked_open--;
#ifdef SERIAL_DEBUG_OPEN
printk("block_til_ready after blocking: ttys%d, count = %d\n",
info->line, state->count);
#endif
#endif /* DO_THIS_LATER */
if (retval)
return retval;
info->flags |= ASYNC_NORMAL_ACTIVE;
return 0;
}
static int get_async_struct(int line, ser_info_t **ret_info)
{
struct serial_state *sstate;
sstate = rs_table + line;
if (sstate->info) {
sstate->count++;
*ret_info = (ser_info_t *)sstate->info;
return 0;
}
else {
return -ENOMEM;
}
}
/*
* This routine is called whenever a serial port is opened. It
* enables interrupts for a serial port, linking in its async structure into
* the IRQ chain. It also performs the serial-specific
* initialization for the tty structure.
*/
static int rs_360_open(struct tty_struct *tty, struct file * filp)
{
ser_info_t *info;
int retval, line;
line = tty->index;
if ((line < 0) || (line >= NR_PORTS))
return -ENODEV;
retval = get_async_struct(line, &info);
if (retval)
return retval;
if (serial_paranoia_check(info, tty->name, "rs_open"))
return -ENODEV;
#ifdef SERIAL_DEBUG_OPEN
printk("rs_open %s, count = %d\n", tty->name, info->state->count);
#endif
tty->driver_data = info;
info->port.tty = tty;
/*
* Start up serial port
*/
retval = startup(info);
if (retval)
return retval;
retval = block_til_ready(tty, filp, info);
if (retval) {
#ifdef SERIAL_DEBUG_OPEN
printk("rs_open returning after block_til_ready with %d\n",
retval);
#endif
return retval;
}
#ifdef SERIAL_DEBUG_OPEN
printk("rs_open %s successful...", tty->name);
#endif
return 0;
}
/*
* /proc fs routines....
*/
static inline int line_info(char *buf, struct serial_state *state)
{
#ifdef notdef
struct async_struct *info = state->info, scr_info;
char stat_buf[30], control, status;
#endif
int ret;
ret = sprintf(buf, "%d: uart:%s port:%X irq:%d",
state->line,
(state->smc_scc_num & NUM_IS_SCC) ? "SCC" : "SMC",
(unsigned int)(state->port), state->irq);
if (!state->port || (state->type == PORT_UNKNOWN)) {
ret += sprintf(buf+ret, "\n");
return ret;
}
#ifdef notdef
/*
* Figure out the current RS-232 lines
*/
if (!info) {
info = &scr_info; /* This is just for serial_{in,out} */
info->magic = SERIAL_MAGIC;
info->port = state->port;
info->flags = state->flags;
info->quot = 0;
info->port.tty = NULL;
}
local_irq_disable();
status = serial_in(info, UART_MSR);
control = info ? info->MCR : serial_in(info, UART_MCR);
local_irq_enable();
stat_buf[0] = 0;
stat_buf[1] = 0;
if (control & UART_MCR_RTS)
strcat(stat_buf, "|RTS");
if (status & UART_MSR_CTS)
strcat(stat_buf, "|CTS");
if (control & UART_MCR_DTR)
strcat(stat_buf, "|DTR");
if (status & UART_MSR_DSR)
strcat(stat_buf, "|DSR");
if (status & UART_MSR_DCD)
strcat(stat_buf, "|CD");
if (status & UART_MSR_RI)
strcat(stat_buf, "|RI");
if (info->quot) {
ret += sprintf(buf+ret, " baud:%d",
state->baud_base / info->quot);
}
ret += sprintf(buf+ret, " tx:%d rx:%d",
state->icount.tx, state->icount.rx);
if (state->icount.frame)
ret += sprintf(buf+ret, " fe:%d", state->icount.frame);
if (state->icount.parity)
ret += sprintf(buf+ret, " pe:%d", state->icount.parity);
if (state->icount.brk)
ret += sprintf(buf+ret, " brk:%d", state->icount.brk);
if (state->icount.overrun)
ret += sprintf(buf+ret, " oe:%d", state->icount.overrun);
/*
* Last thing is the RS-232 status lines
*/
ret += sprintf(buf+ret, " %s\n", stat_buf+1);
#endif
return ret;
}
int rs_360_read_proc(char *page, char **start, off_t off, int count,
int *eof, void *data)
{
int i, len = 0;
off_t begin = 0;
len += sprintf(page, "serinfo:1.0 driver:%s\n", serial_version);
for (i = 0; i < NR_PORTS && len < 4000; i++) {
len += line_info(page + len, &rs_table[i]);
if (len+begin > off+count)
goto done;
if (len+begin < off) {
begin += len;
len = 0;
}
}
*eof = 1;
done:
if (off >= len+begin)
return 0;
*start = page + (begin-off);
return ((count < begin+len-off) ? count : begin+len-off);
}
/*
* ---------------------------------------------------------------------
* rs_init() and friends
*
* rs_init() is called at boot-time to initialize the serial driver.
* ---------------------------------------------------------------------
*/
/*
* This routine prints out the appropriate serial driver version
* number, and identifies which options were configured into this
* driver.
*/
static _INLINE_ void show_serial_version(void)
{
printk(KERN_INFO "%s version %s\n", serial_name, serial_version);
}
/*
* The serial console driver used during boot. Note that these names
* clash with those found in "serial.c", so we currently can't support
* the 16xxx uarts and these at the same time. I will fix this to become
* an indirect function call from tty_io.c (or something).
*/
#ifdef CONFIG_SERIAL_CONSOLE
/*
* Print a string to the serial port trying not to disturb any possible
* real use of the port...
*/
static void my_console_write(int idx, const char *s,
unsigned count)
{
struct serial_state *ser;
ser_info_t *info;
unsigned i;
QUICC_BD *bdp, *bdbase;
volatile struct smc_uart_pram *up;
volatile u_char *cp;
ser = rs_table + idx;
/* If the port has been initialized for general use, we have
* to use the buffer descriptors allocated there. Otherwise,
* we simply use the single buffer allocated.
*/
if ((info = (ser_info_t *)ser->info) != NULL) {
bdp = info->tx_cur;
bdbase = info->tx_bd_base;
}
else {
/* Pointer to UART in parameter ram.
*/
/* up = (smc_uart_t *)&cpmp->cp_dparam[ser->port]; */
up = &pquicc->pram[ser->port].scc.pothers.idma_smc.psmc.u;
/* Get the address of the host memory buffer.
*/
bdp = bdbase = (QUICC_BD *)((uint)pquicc + (uint)up->tbase);
}
/*
* We need to gracefully shut down the transmitter, disable
* interrupts, then send our bytes out.
*/
/*
* Now, do each character. This is not as bad as it looks
* since this is a holding FIFO and not a transmitting FIFO.
* We could add the complexity of filling the entire transmit
* buffer, but we would just wait longer between accesses......
*/
for (i = 0; i < count; i++, s++) {
/* Wait for transmitter fifo to empty.
* Ready indicates output is ready, and xmt is doing
* that, not that it is ready for us to send.
*/
while (bdp->status & BD_SC_READY);
/* Send the character out.
*/
cp = bdp->buf;
*cp = *s;
bdp->length = 1;
bdp->status |= BD_SC_READY;
if (bdp->status & BD_SC_WRAP)
bdp = bdbase;
else
bdp++;
/* if a LF, also do CR... */
if (*s == 10) {
while (bdp->status & BD_SC_READY);
/* cp = __va(bdp->buf); */
cp = bdp->buf;
*cp = 13;
bdp->length = 1;
bdp->status |= BD_SC_READY;
if (bdp->status & BD_SC_WRAP) {
bdp = bdbase;
}
else {
bdp++;
}
}
}
/*
* Finally, Wait for transmitter & holding register to empty
* and restore the IER
*/
while (bdp->status & BD_SC_READY);
if (info)
info->tx_cur = (QUICC_BD *)bdp;
}
static void serial_console_write(struct console *c, const char *s,
unsigned count)
{
#ifdef CONFIG_KGDB
/* Try to let stub handle output. Returns true if it did. */
if (kgdb_output_string(s, count))
return;
#endif
my_console_write(c->index, s, count);
}
/*void console_print_68360(const char *p)
{
const char *cp = p;
int i;
for (i=0;cp[i]!=0;i++);
serial_console_write (p, i);
//Comment this if you want to have a strict interrupt-driven output
//rs_fair_output();
return;
}*/
#ifdef CONFIG_XMON
int
xmon_360_write(const char *s, unsigned count)
{
my_console_write(0, s, count);
return(count);
}
#endif
#ifdef CONFIG_KGDB
void
putDebugChar(char ch)
{
my_console_write(0, &ch, 1);
}
#endif
/*
* Receive character from the serial port. This only works well
* before the port is initialized for real use.
*/
static int my_console_wait_key(int idx, int xmon, char *obuf)
{
struct serial_state *ser;
u_char c, *cp;
ser_info_t *info;
QUICC_BD *bdp;
volatile struct smc_uart_pram *up;
int i;
ser = rs_table + idx;
/* Get the address of the host memory buffer.
* If the port has been initialized for general use, we must
* use information from the port structure.
*/
if ((info = (ser_info_t *)ser->info))
bdp = info->rx_cur;
else
/* bdp = (QUICC_BD *)&cpmp->cp_dpmem[up->smc_rbase]; */
bdp = (QUICC_BD *)((uint)pquicc + (uint)up->tbase);
/* Pointer to UART in parameter ram.
*/
/* up = (smc_uart_t *)&cpmp->cp_dparam[ser->port]; */
up = &pquicc->pram[info->state->port].scc.pothers.idma_smc.psmc.u;
/*
* We need to gracefully shut down the receiver, disable
* interrupts, then read the input.
* XMON just wants a poll. If no character, return -1, else
* return the character.
*/
if (!xmon) {
while (bdp->status & BD_SC_EMPTY);
}
else {
if (bdp->status & BD_SC_EMPTY)
return -1;
}
cp = (char *)bdp->buf;
if (obuf) {
i = c = bdp->length;
while (i-- > 0)
*obuf++ = *cp++;
}
else {
c = *cp;
}
bdp->status |= BD_SC_EMPTY;
if (info) {
if (bdp->status & BD_SC_WRAP) {
bdp = info->rx_bd_base;
}
else {
bdp++;
}
info->rx_cur = (QUICC_BD *)bdp;
}
return((int)c);
}
static int serial_console_wait_key(struct console *co)
{
return(my_console_wait_key(co->index, 0, NULL));
}
#ifdef CONFIG_XMON
int
xmon_360_read_poll(void)
{
return(my_console_wait_key(0, 1, NULL));
}
int
xmon_360_read_char(void)
{
return(my_console_wait_key(0, 0, NULL));
}
#endif
#ifdef CONFIG_KGDB
static char kgdb_buf[RX_BUF_SIZE], *kgdp;
static int kgdb_chars;
unsigned char
getDebugChar(void)
{
if (kgdb_chars <= 0) {
kgdb_chars = my_console_wait_key(0, 0, kgdb_buf);
kgdp = kgdb_buf;
}
kgdb_chars--;
return(*kgdp++);
}
void kgdb_interruptible(int state)
{
}
void kgdb_map_scc(void)
{
struct serial_state *ser;
uint mem_addr;
volatile QUICC_BD *bdp;
volatile smc_uart_t *up;
cpmp = (cpm360_t *)&(((immap_t *)IMAP_ADDR)->im_cpm);
/* To avoid data cache CPM DMA coherency problems, allocate a
* buffer in the CPM DPRAM. This will work until the CPM and
* serial ports are initialized. At that time a memory buffer
* will be allocated.
* The port is already initialized from the boot procedure, all
* we do here is give it a different buffer and make it a FIFO.
*/
ser = rs_table;
/* Right now, assume we are using SMCs.
*/
up = (smc_uart_t *)&cpmp->cp_dparam[ser->port];
/* Allocate space for an input FIFO, plus a few bytes for output.
* Allocate bytes to maintain word alignment.
*/
mem_addr = (uint)(&cpmp->cp_dpmem[0x1000]);
/* Set the physical address of the host memory buffers in
* the buffer descriptors.
*/
bdp = (QUICC_BD *)&cpmp->cp_dpmem[up->smc_rbase];
bdp->buf = mem_addr;
bdp = (QUICC_BD *)&cpmp->cp_dpmem[up->smc_tbase];
bdp->buf = mem_addr+RX_BUF_SIZE;
up->smc_mrblr = RX_BUF_SIZE; /* receive buffer length */
up->smc_maxidl = RX_BUF_SIZE;
}
#endif
static struct tty_struct *serial_console_device(struct console *c, int *index)
{
*index = c->index;
return serial_driver;
}
struct console sercons = {
.name = "ttyS",
.write = serial_console_write,
.device = serial_console_device,
.wait_key = serial_console_wait_key,
.setup = serial_console_setup,
.flags = CON_PRINTBUFFER,
.index = CONFIG_SERIAL_CONSOLE_PORT,
};
/*
* Register console.
*/
long console_360_init(long kmem_start, long kmem_end)
{
register_console(&sercons);
/*register_console (console_print_68360); - 2.0.38 only required a write
function pointer. */
return kmem_start;
}
#endif
/* Index in baud rate table of the default console baud rate.
*/
static int baud_idx;
static const struct tty_operations rs_360_ops = {
.owner = THIS_MODULE,
.open = rs_360_open,
.close = rs_360_close,
.write = rs_360_write,
.put_char = rs_360_put_char,
.write_room = rs_360_write_room,
.chars_in_buffer = rs_360_chars_in_buffer,
.flush_buffer = rs_360_flush_buffer,
.ioctl = rs_360_ioctl,
.throttle = rs_360_throttle,
.unthrottle = rs_360_unthrottle,
/* .send_xchar = rs_360_send_xchar, */
.set_termios = rs_360_set_termios,
.stop = rs_360_stop,
.start = rs_360_start,
.hangup = rs_360_hangup,
/* .wait_until_sent = rs_360_wait_until_sent, */
/* .read_proc = rs_360_read_proc, */
.tiocmget = rs_360_tiocmget,
.tiocmset = rs_360_tiocmset,
};
static int __init rs_360_init(void)
{
struct serial_state * state;
ser_info_t *info;
void *mem_addr;
uint dp_addr, iobits;
int i, j, idx;
ushort chan;
QUICC_BD *bdp;
volatile QUICC *cp;
volatile struct smc_regs *sp;
volatile struct smc_uart_pram *up;
volatile struct scc_regs *scp;
volatile struct uart_pram *sup;
/* volatile immap_t *immap; */
serial_driver = alloc_tty_driver(NR_PORTS);
if (!serial_driver)
return -1;
show_serial_version();
serial_driver->name = "ttyS";
serial_driver->major = TTY_MAJOR;
serial_driver->minor_start = 64;
serial_driver->type = TTY_DRIVER_TYPE_SERIAL;
serial_driver->subtype = SERIAL_TYPE_NORMAL;
serial_driver->init_termios = tty_std_termios;
serial_driver->init_termios.c_cflag =
baud_idx | CS8 | CREAD | HUPCL | CLOCAL;
serial_driver->flags = TTY_DRIVER_REAL_RAW;
tty_set_operations(serial_driver, &rs_360_ops);
if (tty_register_driver(serial_driver))
panic("Couldn't register serial driver\n");
cp = pquicc; /* Get pointer to Communication Processor */
/* immap = (immap_t *)IMAP_ADDR; */ /* and to internal registers */
/* Configure SCC2, SCC3, and SCC4 instead of port A parallel I/O.
*/
/* The "standard" configuration through the 860.
*/
/* immap->im_ioport.iop_papar |= 0x00fc; */
/* immap->im_ioport.iop_padir &= ~0x00fc; */
/* immap->im_ioport.iop_paodr &= ~0x00fc; */
cp->pio_papar |= 0x00fc;
cp->pio_padir &= ~0x00fc;
/* cp->pio_paodr &= ~0x00fc; */
/* Since we don't yet do modem control, connect the port C pins
* as general purpose I/O. This will assert CTS and CD for the
* SCC ports.
*/
/* FIXME: see 360um p.7-365 and 860um p.34-12
* I can't make sense of these bits - mleslie*/
/* immap->im_ioport.iop_pcdir |= 0x03c6; */
/* immap->im_ioport.iop_pcpar &= ~0x03c6; */
/* cp->pio_pcdir |= 0x03c6; */
/* cp->pio_pcpar &= ~0x03c6; */
/* Connect SCC2 and SCC3 to NMSI. Connect BRG3 to SCC2 and
* BRG4 to SCC3.
*/
cp->si_sicr &= ~0x00ffff00;
cp->si_sicr |= 0x001b1200;
#ifdef CONFIG_PP04
/* Frequentis PP04 forced to RS-232 until we know better.
* Port C 12 and 13 low enables RS-232 on SCC3 and SCC4.
*/
immap->im_ioport.iop_pcdir |= 0x000c;
immap->im_ioport.iop_pcpar &= ~0x000c;
immap->im_ioport.iop_pcdat &= ~0x000c;
/* This enables the TX driver.
*/
cp->cp_pbpar &= ~0x6000;
cp->cp_pbdat &= ~0x6000;
#endif
for (i = 0, state = rs_table; i < NR_PORTS; i++,state++) {
state->magic = SSTATE_MAGIC;
state->line = i;
state->type = PORT_UNKNOWN;
state->custom_divisor = 0;
state->close_delay = 5*HZ/10;
state->closing_wait = 30*HZ;
state->icount.cts = state->icount.dsr =
state->icount.rng = state->icount.dcd = 0;
state->icount.rx = state->icount.tx = 0;
state->icount.frame = state->icount.parity = 0;
state->icount.overrun = state->icount.brk = 0;
printk(KERN_INFO "ttyS%d at irq 0x%02x is an %s\n",
i, (unsigned int)(state->irq),
(state->smc_scc_num & NUM_IS_SCC) ? "SCC" : "SMC");
#ifdef CONFIG_SERIAL_CONSOLE
/* If we just printed the message on the console port, and
* we are about to initialize it for general use, we have
* to wait a couple of character times for the CR/NL to
* make it out of the transmit buffer.
*/
if (i == CONFIG_SERIAL_CONSOLE_PORT)
mdelay(8);
/* idx = PORT_NUM(info->state->smc_scc_num); */
/* if (info->state->smc_scc_num & NUM_IS_SCC) */
/* chan = scc_chan_map[idx]; */
/* else */
/* chan = smc_chan_map[idx]; */
/* cp->cp_cr = mk_cr_cmd(chan, CPM_CR_STOP_TX) | CPM_CR_FLG; */
/* while (cp->cp_cr & CPM_CR_FLG); */
#endif
/* info = kmalloc(sizeof(ser_info_t), GFP_KERNEL); */
info = &quicc_ser_info[i];
if (info) {
memset (info, 0, sizeof(ser_info_t));
info->magic = SERIAL_MAGIC;
info->line = i;
info->flags = state->flags;
INIT_WORK(&info->tqueue, do_softint, info);
INIT_WORK(&info->tqueue_hangup, do_serial_hangup, info);
init_waitqueue_head(&info->open_wait);
init_waitqueue_head(&info->close_wait);
info->state = state;
state->info = (struct async_struct *)info;
/* We need to allocate a transmit and receive buffer
* descriptors from dual port ram, and a character
* buffer area from host mem.
*/
dp_addr = m360_cpm_dpalloc(sizeof(QUICC_BD) * RX_NUM_FIFO);
/* Allocate space for FIFOs in the host memory.
* (for now this is from a static array of buffers :(
*/
/* mem_addr = m360_cpm_hostalloc(RX_NUM_FIFO * RX_BUF_SIZE); */
/* mem_addr = kmalloc (RX_NUM_FIFO * RX_BUF_SIZE, GFP_BUFFER); */
mem_addr = &rx_buf_pool[i * RX_NUM_FIFO * RX_BUF_SIZE];
/* Set the physical address of the host memory
* buffers in the buffer descriptors, and the
* virtual address for us to work with.
*/
bdp = (QUICC_BD *)((uint)pquicc + dp_addr);
info->rx_cur = info->rx_bd_base = bdp;
/* initialize rx buffer descriptors */
for (j=0; j<(RX_NUM_FIFO-1); j++) {
bdp->buf = &rx_buf_pool[(i * RX_NUM_FIFO + j ) * RX_BUF_SIZE];
bdp->status = BD_SC_EMPTY | BD_SC_INTRPT;
mem_addr += RX_BUF_SIZE;
bdp++;
}
bdp->buf = &rx_buf_pool[(i * RX_NUM_FIFO + j ) * RX_BUF_SIZE];
bdp->status = BD_SC_WRAP | BD_SC_EMPTY | BD_SC_INTRPT;
idx = PORT_NUM(info->state->smc_scc_num);
if (info->state->smc_scc_num & NUM_IS_SCC) {
#if defined (CONFIG_UCQUICC) && 1
/* set the transceiver mode to RS232 */
sipex_mode_bits &= ~(uint)SIPEX_MODE(idx,0x0f); /* clear current mode */
sipex_mode_bits |= (uint)SIPEX_MODE(idx,0x02);
*(uint *)_periph_base = sipex_mode_bits;
/* printk ("sipex bits = 0x%08x\n", sipex_mode_bits); */
#endif
}
dp_addr = m360_cpm_dpalloc(sizeof(QUICC_BD) * TX_NUM_FIFO);
/* Allocate space for FIFOs in the host memory.
*/
/* mem_addr = m360_cpm_hostalloc(TX_NUM_FIFO * TX_BUF_SIZE); */
/* mem_addr = kmalloc (TX_NUM_FIFO * TX_BUF_SIZE, GFP_BUFFER); */
mem_addr = &tx_buf_pool[i * TX_NUM_FIFO * TX_BUF_SIZE];
/* Set the physical address of the host memory
* buffers in the buffer descriptors, and the
* virtual address for us to work with.
*/
/* bdp = (QUICC_BD *)&cp->cp_dpmem[dp_addr]; */
bdp = (QUICC_BD *)((uint)pquicc + dp_addr);
info->tx_cur = info->tx_bd_base = (QUICC_BD *)bdp;
/* initialize tx buffer descriptors */
for (j=0; j<(TX_NUM_FIFO-1); j++) {
bdp->buf = &tx_buf_pool[(i * TX_NUM_FIFO + j ) * TX_BUF_SIZE];
bdp->status = BD_SC_INTRPT;
mem_addr += TX_BUF_SIZE;
bdp++;
}
bdp->buf = &tx_buf_pool[(i * TX_NUM_FIFO + j ) * TX_BUF_SIZE];
bdp->status = (BD_SC_WRAP | BD_SC_INTRPT);
if (info->state->smc_scc_num & NUM_IS_SCC) {
scp = &pquicc->scc_regs[idx];
sup = &pquicc->pram[info->state->port].scc.pscc.u;
sup->rbase = dp_addr;
sup->tbase = dp_addr;
/* Set up the uart parameters in the
* parameter ram.
*/
sup->rfcr = SMC_EB;
sup->tfcr = SMC_EB;
/* Set this to 1 for now, so we get single
* character interrupts. Using idle charater
* time requires some additional tuning.
*/
sup->mrblr = 1;
sup->max_idl = 0;
sup->brkcr = 1;
sup->parec = 0;
sup->frmer = 0;
sup->nosec = 0;
sup->brkec = 0;
sup->uaddr1 = 0;
sup->uaddr2 = 0;
sup->toseq = 0;
{
int i;
for (i=0;i<8;i++)
sup->cc[i] = 0x8000;
}
sup->rccm = 0xc0ff;
/* Send the CPM an initialize command.
*/
chan = scc_chan_map[idx];
/* execute the INIT RX & TX PARAMS command for this channel. */
cp->cp_cr = mk_cr_cmd(chan, CPM_CR_INIT_TRX) | CPM_CR_FLG;
while (cp->cp_cr & CPM_CR_FLG);
/* Set UART mode, 8 bit, no parity, one stop.
* Enable receive and transmit.
*/
scp->scc_gsmr.w.high = 0;
scp->scc_gsmr.w.low =
(SCC_GSMRL_MODE_UART | SCC_GSMRL_TDCR_16 | SCC_GSMRL_RDCR_16);
/* Disable all interrupts and clear all pending
* events.
*/
scp->scc_sccm = 0;
scp->scc_scce = 0xffff;
scp->scc_dsr = 0x7e7e;
scp->scc_psmr = 0x3000;
/* If the port is the console, enable Rx and Tx.
*/
#ifdef CONFIG_SERIAL_CONSOLE
if (i == CONFIG_SERIAL_CONSOLE_PORT)
scp->scc_gsmr.w.low |= (SCC_GSMRL_ENR | SCC_GSMRL_ENT);
#endif
}
else {
/* Configure SMCs Tx/Rx instead of port B
* parallel I/O.
*/
up = &pquicc->pram[info->state->port].scc.pothers.idma_smc.psmc.u;
up->rbase = dp_addr;
iobits = 0xc0 << (idx * 4);
cp->pip_pbpar |= iobits;
cp->pip_pbdir &= ~iobits;
cp->pip_pbodr &= ~iobits;
/* Connect the baud rate generator to the
* SMC based upon index in rs_table. Also
* make sure it is connected to NMSI.
*/
cp->si_simode &= ~(0xffff << (idx * 16));
cp->si_simode |= (i << ((idx * 16) + 12));
up->tbase = dp_addr;
/* Set up the uart parameters in the
* parameter ram.
*/
up->rfcr = SMC_EB;
up->tfcr = SMC_EB;
/* Set this to 1 for now, so we get single
* character interrupts. Using idle charater
* time requires some additional tuning.
*/
up->mrblr = 1;
up->max_idl = 0;
up->brkcr = 1;
/* Send the CPM an initialize command.
*/
chan = smc_chan_map[idx];
cp->cp_cr = mk_cr_cmd(chan,
CPM_CR_INIT_TRX) | CPM_CR_FLG;
#ifdef CONFIG_SERIAL_CONSOLE
if (i == CONFIG_SERIAL_CONSOLE_PORT)
printk("");
#endif
while (cp->cp_cr & CPM_CR_FLG);
/* Set UART mode, 8 bit, no parity, one stop.
* Enable receive and transmit.
*/
sp = &cp->smc_regs[idx];
sp->smc_smcmr = smcr_mk_clen(9) | SMCMR_SM_UART;
/* Disable all interrupts and clear all pending
* events.
*/
sp->smc_smcm = 0;
sp->smc_smce = 0xff;
/* If the port is the console, enable Rx and Tx.
*/
#ifdef CONFIG_SERIAL_CONSOLE
if (i == CONFIG_SERIAL_CONSOLE_PORT)
sp->smc_smcmr |= SMCMR_REN | SMCMR_TEN;
#endif
}
/* Install interrupt handler.
*/
/* cpm_install_handler(IRQ_MACHSPEC | state->irq, rs_360_interrupt, info); */
/*request_irq(IRQ_MACHSPEC | state->irq, rs_360_interrupt, */
request_irq(state->irq, rs_360_interrupt,
IRQ_FLG_LOCK, "ttyS", (void *)info);
/* Set up the baud rate generator.
*/
m360_cpm_setbrg(i, baud_table[baud_idx]);
}
}
return 0;
}
module_init(rs_360_init);
/* This must always be called before the rs_360_init() function, otherwise
* it blows away the port control information.
*/
//static int __init serial_console_setup( struct console *co, char *options)
int serial_console_setup( struct console *co, char *options)
{
struct serial_state *ser;
uint mem_addr, dp_addr, bidx, idx, iobits;
ushort chan;
QUICC_BD *bdp;
volatile QUICC *cp;
volatile struct smc_regs *sp;
volatile struct scc_regs *scp;
volatile struct smc_uart_pram *up;
volatile struct uart_pram *sup;
/* mleslie TODO:
* add something to the 68k bootloader to store a desired initial console baud rate */
/* bd_t *bd; */ /* a board info struct used by EPPC-bug */
/* bd = (bd_t *)__res; */
for (bidx = 0; bidx < (sizeof(baud_table) / sizeof(int)); bidx++)
/* if (bd->bi_baudrate == baud_table[bidx]) */
if (CONSOLE_BAUDRATE == baud_table[bidx])
break;
/* co->cflag = CREAD|CLOCAL|bidx|CS8; */
baud_idx = bidx;
ser = rs_table + CONFIG_SERIAL_CONSOLE_PORT;
cp = pquicc; /* Get pointer to Communication Processor */
idx = PORT_NUM(ser->smc_scc_num);
if (ser->smc_scc_num & NUM_IS_SCC) {
/* TODO: need to set up SCC pin assignment etc. here */
}
else {
iobits = 0xc0 << (idx * 4);
cp->pip_pbpar |= iobits;
cp->pip_pbdir &= ~iobits;
cp->pip_pbodr &= ~iobits;
/* Connect the baud rate generator to the
* SMC based upon index in rs_table. Also
* make sure it is connected to NMSI.
*/
cp->si_simode &= ~(0xffff << (idx * 16));
cp->si_simode |= (idx << ((idx * 16) + 12));
}
/* When we get here, the CPM has been reset, so we need
* to configure the port.
* We need to allocate a transmit and receive buffer descriptor
* from dual port ram, and a character buffer area from host mem.
*/
/* Allocate space for two buffer descriptors in the DP ram.
*/
dp_addr = m360_cpm_dpalloc(sizeof(QUICC_BD) * CONSOLE_NUM_FIFO);
/* Allocate space for two 2 byte FIFOs in the host memory.
*/
/* mem_addr = m360_cpm_hostalloc(8); */
mem_addr = (uint)console_fifos;
/* Set the physical address of the host memory buffers in
* the buffer descriptors.
*/
/* bdp = (QUICC_BD *)&cp->cp_dpmem[dp_addr]; */
bdp = (QUICC_BD *)((uint)pquicc + dp_addr);
bdp->buf = (char *)mem_addr;
(bdp+1)->buf = (char *)(mem_addr+4);
/* For the receive, set empty and wrap.
* For transmit, set wrap.
*/
bdp->status = BD_SC_EMPTY | BD_SC_WRAP;
(bdp+1)->status = BD_SC_WRAP;
/* Set up the uart parameters in the parameter ram.
*/
if (ser->smc_scc_num & NUM_IS_SCC) {
scp = &cp->scc_regs[idx];
/* sup = (scc_uart_t *)&cp->cp_dparam[ser->port]; */
sup = &pquicc->pram[ser->port].scc.pscc.u;
sup->rbase = dp_addr;
sup->tbase = dp_addr + sizeof(QUICC_BD);
/* Set up the uart parameters in the
* parameter ram.
*/
sup->rfcr = SMC_EB;
sup->tfcr = SMC_EB;
/* Set this to 1 for now, so we get single
* character interrupts. Using idle charater
* time requires some additional tuning.
*/
sup->mrblr = 1;
sup->max_idl = 0;
sup->brkcr = 1;
sup->parec = 0;
sup->frmer = 0;
sup->nosec = 0;
sup->brkec = 0;
sup->uaddr1 = 0;
sup->uaddr2 = 0;
sup->toseq = 0;
{
int i;
for (i=0;i<8;i++)
sup->cc[i] = 0x8000;
}
sup->rccm = 0xc0ff;
/* Send the CPM an initialize command.
*/
chan = scc_chan_map[idx];
cp->cp_cr = mk_cr_cmd(chan, CPM_CR_INIT_TRX) | CPM_CR_FLG;
while (cp->cp_cr & CPM_CR_FLG);
/* Set UART mode, 8 bit, no parity, one stop.
* Enable receive and transmit.
*/
scp->scc_gsmr.w.high = 0;
scp->scc_gsmr.w.low =
(SCC_GSMRL_MODE_UART | SCC_GSMRL_TDCR_16 | SCC_GSMRL_RDCR_16);
/* Disable all interrupts and clear all pending
* events.
*/
scp->scc_sccm = 0;
scp->scc_scce = 0xffff;
scp->scc_dsr = 0x7e7e;
scp->scc_psmr = 0x3000;
scp->scc_gsmr.w.low |= (SCC_GSMRL_ENR | SCC_GSMRL_ENT);
}
else {
/* up = (smc_uart_t *)&cp->cp_dparam[ser->port]; */
up = &pquicc->pram[ser->port].scc.pothers.idma_smc.psmc.u;
up->rbase = dp_addr; /* Base of receive buffer desc. */
up->tbase = dp_addr+sizeof(QUICC_BD); /* Base of xmt buffer desc. */
up->rfcr = SMC_EB;
up->tfcr = SMC_EB;
/* Set this to 1 for now, so we get single character interrupts.
*/
up->mrblr = 1; /* receive buffer length */
up->max_idl = 0; /* wait forever for next char */
/* Send the CPM an initialize command.
*/
chan = smc_chan_map[idx];
cp->cp_cr = mk_cr_cmd(chan, CPM_CR_INIT_TRX) | CPM_CR_FLG;
while (cp->cp_cr & CPM_CR_FLG);
/* Set UART mode, 8 bit, no parity, one stop.
* Enable receive and transmit.
*/
sp = &cp->smc_regs[idx];
sp->smc_smcmr = smcr_mk_clen(9) | SMCMR_SM_UART;
/* And finally, enable Rx and Tx.
*/
sp->smc_smcmr |= SMCMR_REN | SMCMR_TEN;
}
/* Set up the baud rate generator.
*/
/* m360_cpm_setbrg((ser - rs_table), bd->bi_baudrate); */
m360_cpm_setbrg((ser - rs_table), CONSOLE_BAUDRATE);
return 0;
}
/*
* Local variables:
* c-indent-level: 4
* c-basic-offset: 4
* tab-width: 4
* End:
*/
| gpl-2.0 |
GeyerA/kernel_hammerhead | fs/binfmt_elf.c | 2538 | 55934 | /*
* linux/fs/binfmt_elf.c
*
* These are the functions used to load ELF format executables as used
* on SVr4 machines. Information on the format may be found in the book
* "UNIX SYSTEM V RELEASE 4 Programmers Guide: Ansi C and Programming Support
* Tools".
*
* Copyright 1993, 1994: Eric Youngdale (ericy@cais.com).
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/mman.h>
#include <linux/errno.h>
#include <linux/signal.h>
#include <linux/binfmts.h>
#include <linux/string.h>
#include <linux/file.h>
#include <linux/slab.h>
#include <linux/personality.h>
#include <linux/elfcore.h>
#include <linux/init.h>
#include <linux/highuid.h>
#include <linux/compiler.h>
#include <linux/highmem.h>
#include <linux/pagemap.h>
#include <linux/security.h>
#include <linux/random.h>
#include <linux/elf.h>
#include <linux/utsname.h>
#include <linux/coredump.h>
#include <asm/uaccess.h>
#include <asm/param.h>
#include <asm/page.h>
#include <asm/exec.h>
static int load_elf_binary(struct linux_binprm *bprm, struct pt_regs *regs);
static int load_elf_library(struct file *);
static unsigned long elf_map(struct file *, unsigned long, struct elf_phdr *,
int, int, unsigned long);
/*
* If we don't support core dumping, then supply a NULL so we
* don't even try.
*/
#ifdef CONFIG_ELF_CORE
static int elf_core_dump(struct coredump_params *cprm);
#else
#define elf_core_dump NULL
#endif
#if ELF_EXEC_PAGESIZE > PAGE_SIZE
#define ELF_MIN_ALIGN ELF_EXEC_PAGESIZE
#else
#define ELF_MIN_ALIGN PAGE_SIZE
#endif
#ifndef ELF_CORE_EFLAGS
#define ELF_CORE_EFLAGS 0
#endif
#define ELF_PAGESTART(_v) ((_v) & ~(unsigned long)(ELF_MIN_ALIGN-1))
#define ELF_PAGEOFFSET(_v) ((_v) & (ELF_MIN_ALIGN-1))
#define ELF_PAGEALIGN(_v) (((_v) + ELF_MIN_ALIGN - 1) & ~(ELF_MIN_ALIGN - 1))
static struct linux_binfmt elf_format = {
.module = THIS_MODULE,
.load_binary = load_elf_binary,
.load_shlib = load_elf_library,
.core_dump = elf_core_dump,
.min_coredump = ELF_EXEC_PAGESIZE,
};
#define BAD_ADDR(x) ((unsigned long)(x) >= TASK_SIZE)
static int set_brk(unsigned long start, unsigned long end)
{
start = ELF_PAGEALIGN(start);
end = ELF_PAGEALIGN(end);
if (end > start) {
unsigned long addr;
addr = vm_brk(start, end - start);
if (BAD_ADDR(addr))
return addr;
}
current->mm->start_brk = current->mm->brk = end;
return 0;
}
/* We need to explicitly zero any fractional pages
after the data section (i.e. bss). This would
contain the junk from the file that should not
be in memory
*/
static int padzero(unsigned long elf_bss)
{
unsigned long nbyte;
nbyte = ELF_PAGEOFFSET(elf_bss);
if (nbyte) {
nbyte = ELF_MIN_ALIGN - nbyte;
if (clear_user((void __user *) elf_bss, nbyte))
return -EFAULT;
}
return 0;
}
/* Let's use some macros to make this stack manipulation a little clearer */
#ifdef CONFIG_STACK_GROWSUP
#define STACK_ADD(sp, items) ((elf_addr_t __user *)(sp) + (items))
#define STACK_ROUND(sp, items) \
((15 + (unsigned long) ((sp) + (items))) &~ 15UL)
#define STACK_ALLOC(sp, len) ({ \
elf_addr_t __user *old_sp = (elf_addr_t __user *)sp; sp += len; \
old_sp; })
#else
#define STACK_ADD(sp, items) ((elf_addr_t __user *)(sp) - (items))
#define STACK_ROUND(sp, items) \
(((unsigned long) (sp - items)) &~ 15UL)
#define STACK_ALLOC(sp, len) ({ sp -= len ; sp; })
#endif
#ifndef ELF_BASE_PLATFORM
/*
* AT_BASE_PLATFORM indicates the "real" hardware/microarchitecture.
* If the arch defines ELF_BASE_PLATFORM (in asm/elf.h), the value
* will be copied to the user stack in the same manner as AT_PLATFORM.
*/
#define ELF_BASE_PLATFORM NULL
#endif
static int
create_elf_tables(struct linux_binprm *bprm, struct elfhdr *exec,
unsigned long load_addr, unsigned long interp_load_addr)
{
unsigned long p = bprm->p;
int argc = bprm->argc;
int envc = bprm->envc;
elf_addr_t __user *argv;
elf_addr_t __user *envp;
elf_addr_t __user *sp;
elf_addr_t __user *u_platform;
elf_addr_t __user *u_base_platform;
elf_addr_t __user *u_rand_bytes;
const char *k_platform = ELF_PLATFORM;
const char *k_base_platform = ELF_BASE_PLATFORM;
unsigned char k_rand_bytes[16];
int items;
elf_addr_t *elf_info;
int ei_index = 0;
const struct cred *cred = current_cred();
struct vm_area_struct *vma;
/*
* In some cases (e.g. Hyper-Threading), we want to avoid L1
* evictions by the processes running on the same package. One
* thing we can do is to shuffle the initial stack for them.
*/
p = arch_align_stack(p);
/*
* If this architecture has a platform capability string, copy it
* to userspace. In some cases (Sparc), this info is impossible
* for userspace to get any other way, in others (i386) it is
* merely difficult.
*/
u_platform = NULL;
if (k_platform) {
size_t len = strlen(k_platform) + 1;
u_platform = (elf_addr_t __user *)STACK_ALLOC(p, len);
if (__copy_to_user(u_platform, k_platform, len))
return -EFAULT;
}
/*
* If this architecture has a "base" platform capability
* string, copy it to userspace.
*/
u_base_platform = NULL;
if (k_base_platform) {
size_t len = strlen(k_base_platform) + 1;
u_base_platform = (elf_addr_t __user *)STACK_ALLOC(p, len);
if (__copy_to_user(u_base_platform, k_base_platform, len))
return -EFAULT;
}
/*
* Generate 16 random bytes for userspace PRNG seeding.
*/
get_random_bytes(k_rand_bytes, sizeof(k_rand_bytes));
u_rand_bytes = (elf_addr_t __user *)
STACK_ALLOC(p, sizeof(k_rand_bytes));
if (__copy_to_user(u_rand_bytes, k_rand_bytes, sizeof(k_rand_bytes)))
return -EFAULT;
/* Create the ELF interpreter info */
elf_info = (elf_addr_t *)current->mm->saved_auxv;
/* update AT_VECTOR_SIZE_BASE if the number of NEW_AUX_ENT() changes */
#define NEW_AUX_ENT(id, val) \
do { \
elf_info[ei_index++] = id; \
elf_info[ei_index++] = val; \
} while (0)
#ifdef ARCH_DLINFO
/*
* ARCH_DLINFO must come first so PPC can do its special alignment of
* AUXV.
* update AT_VECTOR_SIZE_ARCH if the number of NEW_AUX_ENT() in
* ARCH_DLINFO changes
*/
ARCH_DLINFO;
#endif
NEW_AUX_ENT(AT_HWCAP, ELF_HWCAP);
NEW_AUX_ENT(AT_PAGESZ, ELF_EXEC_PAGESIZE);
NEW_AUX_ENT(AT_CLKTCK, CLOCKS_PER_SEC);
NEW_AUX_ENT(AT_PHDR, load_addr + exec->e_phoff);
NEW_AUX_ENT(AT_PHENT, sizeof(struct elf_phdr));
NEW_AUX_ENT(AT_PHNUM, exec->e_phnum);
NEW_AUX_ENT(AT_BASE, interp_load_addr);
NEW_AUX_ENT(AT_FLAGS, 0);
NEW_AUX_ENT(AT_ENTRY, exec->e_entry);
NEW_AUX_ENT(AT_UID, cred->uid);
NEW_AUX_ENT(AT_EUID, cred->euid);
NEW_AUX_ENT(AT_GID, cred->gid);
NEW_AUX_ENT(AT_EGID, cred->egid);
NEW_AUX_ENT(AT_SECURE, security_bprm_secureexec(bprm));
NEW_AUX_ENT(AT_RANDOM, (elf_addr_t)(unsigned long)u_rand_bytes);
NEW_AUX_ENT(AT_EXECFN, bprm->exec);
if (k_platform) {
NEW_AUX_ENT(AT_PLATFORM,
(elf_addr_t)(unsigned long)u_platform);
}
if (k_base_platform) {
NEW_AUX_ENT(AT_BASE_PLATFORM,
(elf_addr_t)(unsigned long)u_base_platform);
}
if (bprm->interp_flags & BINPRM_FLAGS_EXECFD) {
NEW_AUX_ENT(AT_EXECFD, bprm->interp_data);
}
#undef NEW_AUX_ENT
/* AT_NULL is zero; clear the rest too */
memset(&elf_info[ei_index], 0,
sizeof current->mm->saved_auxv - ei_index * sizeof elf_info[0]);
/* And advance past the AT_NULL entry. */
ei_index += 2;
sp = STACK_ADD(p, ei_index);
items = (argc + 1) + (envc + 1) + 1;
bprm->p = STACK_ROUND(sp, items);
/* Point sp at the lowest address on the stack */
#ifdef CONFIG_STACK_GROWSUP
sp = (elf_addr_t __user *)bprm->p - items - ei_index;
bprm->exec = (unsigned long)sp; /* XXX: PARISC HACK */
#else
sp = (elf_addr_t __user *)bprm->p;
#endif
/*
* Grow the stack manually; some architectures have a limit on how
* far ahead a user-space access may be in order to grow the stack.
*/
vma = find_extend_vma(current->mm, bprm->p);
if (!vma)
return -EFAULT;
/* Now, let's put argc (and argv, envp if appropriate) on the stack */
if (__put_user(argc, sp++))
return -EFAULT;
argv = sp;
envp = argv + argc + 1;
/* Populate argv and envp */
p = current->mm->arg_end = current->mm->arg_start;
while (argc-- > 0) {
size_t len;
if (__put_user((elf_addr_t)p, argv++))
return -EFAULT;
len = strnlen_user((void __user *)p, MAX_ARG_STRLEN);
if (!len || len > MAX_ARG_STRLEN)
return -EINVAL;
p += len;
}
if (__put_user(0, argv))
return -EFAULT;
current->mm->arg_end = current->mm->env_start = p;
while (envc-- > 0) {
size_t len;
if (__put_user((elf_addr_t)p, envp++))
return -EFAULT;
len = strnlen_user((void __user *)p, MAX_ARG_STRLEN);
if (!len || len > MAX_ARG_STRLEN)
return -EINVAL;
p += len;
}
if (__put_user(0, envp))
return -EFAULT;
current->mm->env_end = p;
/* Put the elf_info on the stack in the right place. */
sp = (elf_addr_t __user *)envp + 1;
if (copy_to_user(sp, elf_info, ei_index * sizeof(elf_addr_t)))
return -EFAULT;
return 0;
}
static unsigned long elf_map(struct file *filep, unsigned long addr,
struct elf_phdr *eppnt, int prot, int type,
unsigned long total_size)
{
unsigned long map_addr;
unsigned long size = eppnt->p_filesz + ELF_PAGEOFFSET(eppnt->p_vaddr);
unsigned long off = eppnt->p_offset - ELF_PAGEOFFSET(eppnt->p_vaddr);
addr = ELF_PAGESTART(addr);
size = ELF_PAGEALIGN(size);
/* mmap() will return -EINVAL if given a zero size, but a
* segment with zero filesize is perfectly valid */
if (!size)
return addr;
down_write(¤t->mm->mmap_sem);
/*
* total_size is the size of the ELF (interpreter) image.
* The _first_ mmap needs to know the full size, otherwise
* randomization might put this image into an overlapping
* position with the ELF binary image. (since size < total_size)
* So we first map the 'big' image - and unmap the remainder at
* the end. (which unmap is needed for ELF images with holes.)
*/
if (total_size) {
total_size = ELF_PAGEALIGN(total_size);
map_addr = do_mmap(filep, addr, total_size, prot, type, off);
if (!BAD_ADDR(map_addr))
do_munmap(current->mm, map_addr+size, total_size-size);
} else
map_addr = do_mmap(filep, addr, size, prot, type, off);
up_write(¤t->mm->mmap_sem);
return(map_addr);
}
static unsigned long total_mapping_size(struct elf_phdr *cmds, int nr)
{
int i, first_idx = -1, last_idx = -1;
for (i = 0; i < nr; i++) {
if (cmds[i].p_type == PT_LOAD) {
last_idx = i;
if (first_idx == -1)
first_idx = i;
}
}
if (first_idx == -1)
return 0;
return cmds[last_idx].p_vaddr + cmds[last_idx].p_memsz -
ELF_PAGESTART(cmds[first_idx].p_vaddr);
}
/* This is much more generalized than the library routine read function,
so we keep this separate. Technically the library read function
is only provided so that we can read a.out libraries that have
an ELF header */
static unsigned long load_elf_interp(struct elfhdr *interp_elf_ex,
struct file *interpreter, unsigned long *interp_map_addr,
unsigned long no_base)
{
struct elf_phdr *elf_phdata;
struct elf_phdr *eppnt;
unsigned long load_addr = 0;
int load_addr_set = 0;
unsigned long last_bss = 0, elf_bss = 0;
unsigned long error = ~0UL;
unsigned long total_size;
int retval, i, size;
/* First of all, some simple consistency checks */
if (interp_elf_ex->e_type != ET_EXEC &&
interp_elf_ex->e_type != ET_DYN)
goto out;
if (!elf_check_arch(interp_elf_ex))
goto out;
if (!interpreter->f_op || !interpreter->f_op->mmap)
goto out;
/*
* If the size of this structure has changed, then punt, since
* we will be doing the wrong thing.
*/
if (interp_elf_ex->e_phentsize != sizeof(struct elf_phdr))
goto out;
if (interp_elf_ex->e_phnum < 1 ||
interp_elf_ex->e_phnum > 65536U / sizeof(struct elf_phdr))
goto out;
/* Now read in all of the header information */
size = sizeof(struct elf_phdr) * interp_elf_ex->e_phnum;
if (size > ELF_MIN_ALIGN)
goto out;
elf_phdata = kmalloc(size, GFP_KERNEL);
if (!elf_phdata)
goto out;
retval = kernel_read(interpreter, interp_elf_ex->e_phoff,
(char *)elf_phdata, size);
error = -EIO;
if (retval != size) {
if (retval < 0)
error = retval;
goto out_close;
}
total_size = total_mapping_size(elf_phdata, interp_elf_ex->e_phnum);
if (!total_size) {
error = -EINVAL;
goto out_close;
}
eppnt = elf_phdata;
for (i = 0; i < interp_elf_ex->e_phnum; i++, eppnt++) {
if (eppnt->p_type == PT_LOAD) {
int elf_type = MAP_PRIVATE | MAP_DENYWRITE;
int elf_prot = 0;
unsigned long vaddr = 0;
unsigned long k, map_addr;
if (eppnt->p_flags & PF_R)
elf_prot = PROT_READ;
if (eppnt->p_flags & PF_W)
elf_prot |= PROT_WRITE;
if (eppnt->p_flags & PF_X)
elf_prot |= PROT_EXEC;
vaddr = eppnt->p_vaddr;
if (interp_elf_ex->e_type == ET_EXEC || load_addr_set)
elf_type |= MAP_FIXED;
else if (no_base && interp_elf_ex->e_type == ET_DYN)
load_addr = -vaddr;
map_addr = elf_map(interpreter, load_addr + vaddr,
eppnt, elf_prot, elf_type, total_size);
total_size = 0;
if (!*interp_map_addr)
*interp_map_addr = map_addr;
error = map_addr;
if (BAD_ADDR(map_addr))
goto out_close;
if (!load_addr_set &&
interp_elf_ex->e_type == ET_DYN) {
load_addr = map_addr - ELF_PAGESTART(vaddr);
load_addr_set = 1;
}
/*
* Check to see if the section's size will overflow the
* allowed task size. Note that p_filesz must always be
* <= p_memsize so it's only necessary to check p_memsz.
*/
k = load_addr + eppnt->p_vaddr;
if (BAD_ADDR(k) ||
eppnt->p_filesz > eppnt->p_memsz ||
eppnt->p_memsz > TASK_SIZE ||
TASK_SIZE - eppnt->p_memsz < k) {
error = -ENOMEM;
goto out_close;
}
/*
* Find the end of the file mapping for this phdr, and
* keep track of the largest address we see for this.
*/
k = load_addr + eppnt->p_vaddr + eppnt->p_filesz;
if (k > elf_bss)
elf_bss = k;
/*
* Do the same thing for the memory mapping - between
* elf_bss and last_bss is the bss section.
*/
k = load_addr + eppnt->p_memsz + eppnt->p_vaddr;
if (k > last_bss)
last_bss = k;
}
}
if (last_bss > elf_bss) {
/*
* Now fill out the bss section. First pad the last page up
* to the page boundary, and then perform a mmap to make sure
* that there are zero-mapped pages up to and including the
* last bss page.
*/
if (padzero(elf_bss)) {
error = -EFAULT;
goto out_close;
}
/* What we have mapped so far */
elf_bss = ELF_PAGESTART(elf_bss + ELF_MIN_ALIGN - 1);
/* Map the last of the bss segment */
error = vm_brk(elf_bss, last_bss - elf_bss);
if (BAD_ADDR(error))
goto out_close;
}
error = load_addr;
out_close:
kfree(elf_phdata);
out:
return error;
}
/*
* These are the functions used to load ELF style executables and shared
* libraries. There is no binary dependent code anywhere else.
*/
#define INTERPRETER_NONE 0
#define INTERPRETER_ELF 2
#ifndef STACK_RND_MASK
#define STACK_RND_MASK (0x7ff >> (PAGE_SHIFT - 12)) /* 8MB of VA */
#endif
static unsigned long randomize_stack_top(unsigned long stack_top)
{
unsigned int random_variable = 0;
if ((current->flags & PF_RANDOMIZE) &&
!(current->personality & ADDR_NO_RANDOMIZE)) {
random_variable = get_random_int() & STACK_RND_MASK;
random_variable <<= PAGE_SHIFT;
}
#ifdef CONFIG_STACK_GROWSUP
return PAGE_ALIGN(stack_top) + random_variable;
#else
return PAGE_ALIGN(stack_top) - random_variable;
#endif
}
static int load_elf_binary(struct linux_binprm *bprm, struct pt_regs *regs)
{
struct file *interpreter = NULL; /* to shut gcc up */
unsigned long load_addr = 0, load_bias = 0;
int load_addr_set = 0;
char * elf_interpreter = NULL;
unsigned long error;
struct elf_phdr *elf_ppnt, *elf_phdata;
unsigned long elf_bss, elf_brk;
int retval, i;
unsigned int size;
unsigned long elf_entry;
unsigned long interp_load_addr = 0;
unsigned long start_code, end_code, start_data, end_data;
unsigned long reloc_func_desc __maybe_unused = 0;
int executable_stack = EXSTACK_DEFAULT;
unsigned long def_flags = 0;
struct {
struct elfhdr elf_ex;
struct elfhdr interp_elf_ex;
} *loc;
loc = kmalloc(sizeof(*loc), GFP_KERNEL);
if (!loc) {
retval = -ENOMEM;
goto out_ret;
}
/* Get the exec-header */
loc->elf_ex = *((struct elfhdr *)bprm->buf);
retval = -ENOEXEC;
/* First of all, some simple consistency checks */
if (memcmp(loc->elf_ex.e_ident, ELFMAG, SELFMAG) != 0)
goto out;
if (loc->elf_ex.e_type != ET_EXEC && loc->elf_ex.e_type != ET_DYN)
goto out;
if (!elf_check_arch(&loc->elf_ex))
goto out;
if (!bprm->file->f_op || !bprm->file->f_op->mmap)
goto out;
/* Now read in all of the header information */
if (loc->elf_ex.e_phentsize != sizeof(struct elf_phdr))
goto out;
if (loc->elf_ex.e_phnum < 1 ||
loc->elf_ex.e_phnum > 65536U / sizeof(struct elf_phdr))
goto out;
size = loc->elf_ex.e_phnum * sizeof(struct elf_phdr);
retval = -ENOMEM;
elf_phdata = kmalloc(size, GFP_KERNEL);
if (!elf_phdata)
goto out;
retval = kernel_read(bprm->file, loc->elf_ex.e_phoff,
(char *)elf_phdata, size);
if (retval != size) {
if (retval >= 0)
retval = -EIO;
goto out_free_ph;
}
elf_ppnt = elf_phdata;
elf_bss = 0;
elf_brk = 0;
start_code = ~0UL;
end_code = 0;
start_data = 0;
end_data = 0;
for (i = 0; i < loc->elf_ex.e_phnum; i++) {
if (elf_ppnt->p_type == PT_INTERP) {
/* This is the program interpreter used for
* shared libraries - for now assume that this
* is an a.out format binary
*/
retval = -ENOEXEC;
if (elf_ppnt->p_filesz > PATH_MAX ||
elf_ppnt->p_filesz < 2)
goto out_free_ph;
retval = -ENOMEM;
elf_interpreter = kmalloc(elf_ppnt->p_filesz,
GFP_KERNEL);
if (!elf_interpreter)
goto out_free_ph;
retval = kernel_read(bprm->file, elf_ppnt->p_offset,
elf_interpreter,
elf_ppnt->p_filesz);
if (retval != elf_ppnt->p_filesz) {
if (retval >= 0)
retval = -EIO;
goto out_free_interp;
}
/* make sure path is NULL terminated */
retval = -ENOEXEC;
if (elf_interpreter[elf_ppnt->p_filesz - 1] != '\0')
goto out_free_interp;
interpreter = open_exec(elf_interpreter);
retval = PTR_ERR(interpreter);
if (IS_ERR(interpreter))
goto out_free_interp;
/*
* If the binary is not readable then enforce
* mm->dumpable = 0 regardless of the interpreter's
* permissions.
*/
would_dump(bprm, interpreter);
retval = kernel_read(interpreter, 0, bprm->buf,
BINPRM_BUF_SIZE);
if (retval != BINPRM_BUF_SIZE) {
if (retval >= 0)
retval = -EIO;
goto out_free_dentry;
}
/* Get the exec headers */
loc->interp_elf_ex = *((struct elfhdr *)bprm->buf);
break;
}
elf_ppnt++;
}
elf_ppnt = elf_phdata;
for (i = 0; i < loc->elf_ex.e_phnum; i++, elf_ppnt++)
if (elf_ppnt->p_type == PT_GNU_STACK) {
if (elf_ppnt->p_flags & PF_X)
executable_stack = EXSTACK_ENABLE_X;
else
executable_stack = EXSTACK_DISABLE_X;
break;
}
/* Some simple consistency checks for the interpreter */
if (elf_interpreter) {
retval = -ELIBBAD;
/* Not an ELF interpreter */
if (memcmp(loc->interp_elf_ex.e_ident, ELFMAG, SELFMAG) != 0)
goto out_free_dentry;
/* Verify the interpreter has a valid arch */
if (!elf_check_arch(&loc->interp_elf_ex))
goto out_free_dentry;
}
/* Flush all traces of the currently running executable */
retval = flush_old_exec(bprm);
if (retval)
goto out_free_dentry;
/* OK, This is the point of no return */
current->mm->def_flags = def_flags;
/* Do this immediately, since STACK_TOP as used in setup_arg_pages
may depend on the personality. */
SET_PERSONALITY(loc->elf_ex);
if (elf_read_implies_exec(loc->elf_ex, executable_stack))
current->personality |= READ_IMPLIES_EXEC;
if (!(current->personality & ADDR_NO_RANDOMIZE) && randomize_va_space)
current->flags |= PF_RANDOMIZE;
setup_new_exec(bprm);
/* Do this so that we can load the interpreter, if need be. We will
change some of these later */
current->mm->free_area_cache = current->mm->mmap_base;
current->mm->cached_hole_size = 0;
retval = setup_arg_pages(bprm, randomize_stack_top(STACK_TOP),
executable_stack);
if (retval < 0) {
send_sig(SIGKILL, current, 0);
goto out_free_dentry;
}
current->mm->start_stack = bprm->p;
/* Now we do a little grungy work by mmapping the ELF image into
the correct location in memory. */
for(i = 0, elf_ppnt = elf_phdata;
i < loc->elf_ex.e_phnum; i++, elf_ppnt++) {
int elf_prot = 0, elf_flags;
unsigned long k, vaddr;
if (elf_ppnt->p_type != PT_LOAD)
continue;
if (unlikely (elf_brk > elf_bss)) {
unsigned long nbyte;
/* There was a PT_LOAD segment with p_memsz > p_filesz
before this one. Map anonymous pages, if needed,
and clear the area. */
retval = set_brk(elf_bss + load_bias,
elf_brk + load_bias);
if (retval) {
send_sig(SIGKILL, current, 0);
goto out_free_dentry;
}
nbyte = ELF_PAGEOFFSET(elf_bss);
if (nbyte) {
nbyte = ELF_MIN_ALIGN - nbyte;
if (nbyte > elf_brk - elf_bss)
nbyte = elf_brk - elf_bss;
if (clear_user((void __user *)elf_bss +
load_bias, nbyte)) {
/*
* This bss-zeroing can fail if the ELF
* file specifies odd protections. So
* we don't check the return value
*/
}
}
}
if (elf_ppnt->p_flags & PF_R)
elf_prot |= PROT_READ;
if (elf_ppnt->p_flags & PF_W)
elf_prot |= PROT_WRITE;
if (elf_ppnt->p_flags & PF_X)
elf_prot |= PROT_EXEC;
elf_flags = MAP_PRIVATE | MAP_DENYWRITE | MAP_EXECUTABLE;
vaddr = elf_ppnt->p_vaddr;
if (loc->elf_ex.e_type == ET_EXEC || load_addr_set) {
elf_flags |= MAP_FIXED;
} else if (loc->elf_ex.e_type == ET_DYN) {
/* Try and get dynamic programs out of the way of the
* default mmap base, as well as whatever program they
* might try to exec. This is because the brk will
* follow the loader, and is not movable. */
#ifdef CONFIG_ARCH_BINFMT_ELF_RANDOMIZE_PIE
/* Memory randomization might have been switched off
* in runtime via sysctl.
* If that is the case, retain the original non-zero
* load_bias value in order to establish proper
* non-randomized mappings.
*/
if (current->flags & PF_RANDOMIZE)
load_bias = 0;
else
load_bias = ELF_PAGESTART(ELF_ET_DYN_BASE - vaddr);
#else
load_bias = ELF_PAGESTART(ELF_ET_DYN_BASE - vaddr);
#endif
}
error = elf_map(bprm->file, load_bias + vaddr, elf_ppnt,
elf_prot, elf_flags, 0);
if (BAD_ADDR(error)) {
send_sig(SIGKILL, current, 0);
retval = IS_ERR((void *)error) ?
PTR_ERR((void*)error) : -EINVAL;
goto out_free_dentry;
}
if (!load_addr_set) {
load_addr_set = 1;
load_addr = (elf_ppnt->p_vaddr - elf_ppnt->p_offset);
if (loc->elf_ex.e_type == ET_DYN) {
load_bias += error -
ELF_PAGESTART(load_bias + vaddr);
load_addr += load_bias;
reloc_func_desc = load_bias;
}
}
k = elf_ppnt->p_vaddr;
if (k < start_code)
start_code = k;
if (start_data < k)
start_data = k;
/*
* Check to see if the section's size will overflow the
* allowed task size. Note that p_filesz must always be
* <= p_memsz so it is only necessary to check p_memsz.
*/
if (BAD_ADDR(k) || elf_ppnt->p_filesz > elf_ppnt->p_memsz ||
elf_ppnt->p_memsz > TASK_SIZE ||
TASK_SIZE - elf_ppnt->p_memsz < k) {
/* set_brk can never work. Avoid overflows. */
send_sig(SIGKILL, current, 0);
retval = -EINVAL;
goto out_free_dentry;
}
k = elf_ppnt->p_vaddr + elf_ppnt->p_filesz;
if (k > elf_bss)
elf_bss = k;
if ((elf_ppnt->p_flags & PF_X) && end_code < k)
end_code = k;
if (end_data < k)
end_data = k;
k = elf_ppnt->p_vaddr + elf_ppnt->p_memsz;
if (k > elf_brk)
elf_brk = k;
}
loc->elf_ex.e_entry += load_bias;
elf_bss += load_bias;
elf_brk += load_bias;
start_code += load_bias;
end_code += load_bias;
start_data += load_bias;
end_data += load_bias;
/* Calling set_brk effectively mmaps the pages that we need
* for the bss and break sections. We must do this before
* mapping in the interpreter, to make sure it doesn't wind
* up getting placed where the bss needs to go.
*/
retval = set_brk(elf_bss, elf_brk);
if (retval) {
send_sig(SIGKILL, current, 0);
goto out_free_dentry;
}
if (likely(elf_bss != elf_brk) && unlikely(padzero(elf_bss))) {
send_sig(SIGSEGV, current, 0);
retval = -EFAULT; /* Nobody gets to see this, but.. */
goto out_free_dentry;
}
if (elf_interpreter) {
unsigned long uninitialized_var(interp_map_addr);
elf_entry = load_elf_interp(&loc->interp_elf_ex,
interpreter,
&interp_map_addr,
load_bias);
if (!IS_ERR((void *)elf_entry)) {
/*
* load_elf_interp() returns relocation
* adjustment
*/
interp_load_addr = elf_entry;
elf_entry += loc->interp_elf_ex.e_entry;
}
if (BAD_ADDR(elf_entry)) {
force_sig(SIGSEGV, current);
retval = IS_ERR((void *)elf_entry) ?
(int)elf_entry : -EINVAL;
goto out_free_dentry;
}
reloc_func_desc = interp_load_addr;
allow_write_access(interpreter);
fput(interpreter);
kfree(elf_interpreter);
} else {
elf_entry = loc->elf_ex.e_entry;
if (BAD_ADDR(elf_entry)) {
force_sig(SIGSEGV, current);
retval = -EINVAL;
goto out_free_dentry;
}
}
kfree(elf_phdata);
set_binfmt(&elf_format);
#ifdef ARCH_HAS_SETUP_ADDITIONAL_PAGES
retval = arch_setup_additional_pages(bprm, !!elf_interpreter);
if (retval < 0) {
send_sig(SIGKILL, current, 0);
goto out;
}
#endif /* ARCH_HAS_SETUP_ADDITIONAL_PAGES */
install_exec_creds(bprm);
retval = create_elf_tables(bprm, &loc->elf_ex,
load_addr, interp_load_addr);
if (retval < 0) {
send_sig(SIGKILL, current, 0);
goto out;
}
/* N.B. passed_fileno might not be initialized? */
current->mm->end_code = end_code;
current->mm->start_code = start_code;
current->mm->start_data = start_data;
current->mm->end_data = end_data;
current->mm->start_stack = bprm->p;
#ifdef arch_randomize_brk
if ((current->flags & PF_RANDOMIZE) && (randomize_va_space > 1)) {
current->mm->brk = current->mm->start_brk =
arch_randomize_brk(current->mm);
#ifdef CONFIG_COMPAT_BRK
current->brk_randomized = 1;
#endif
}
#endif
if (current->personality & MMAP_PAGE_ZERO) {
/* Why this, you ask??? Well SVr4 maps page 0 as read-only,
and some applications "depend" upon this behavior.
Since we do not have the power to recompile these, we
emulate the SVr4 behavior. Sigh. */
error = vm_mmap(NULL, 0, PAGE_SIZE, PROT_READ | PROT_EXEC,
MAP_FIXED | MAP_PRIVATE, 0);
}
#ifdef ELF_PLAT_INIT
/*
* The ABI may specify that certain registers be set up in special
* ways (on i386 %edx is the address of a DT_FINI function, for
* example. In addition, it may also specify (eg, PowerPC64 ELF)
* that the e_entry field is the address of the function descriptor
* for the startup routine, rather than the address of the startup
* routine itself. This macro performs whatever initialization to
* the regs structure is required as well as any relocations to the
* function descriptor entries when executing dynamically links apps.
*/
ELF_PLAT_INIT(regs, reloc_func_desc);
#endif
start_thread(regs, elf_entry, bprm->p);
retval = 0;
out:
kfree(loc);
out_ret:
return retval;
/* error cleanup */
out_free_dentry:
allow_write_access(interpreter);
if (interpreter)
fput(interpreter);
out_free_interp:
kfree(elf_interpreter);
out_free_ph:
kfree(elf_phdata);
goto out;
}
/* This is really simpleminded and specialized - we are loading an
a.out library that is given an ELF header. */
static int load_elf_library(struct file *file)
{
struct elf_phdr *elf_phdata;
struct elf_phdr *eppnt;
unsigned long elf_bss, bss, len;
int retval, error, i, j;
struct elfhdr elf_ex;
error = -ENOEXEC;
retval = kernel_read(file, 0, (char *)&elf_ex, sizeof(elf_ex));
if (retval != sizeof(elf_ex))
goto out;
if (memcmp(elf_ex.e_ident, ELFMAG, SELFMAG) != 0)
goto out;
/* First of all, some simple consistency checks */
if (elf_ex.e_type != ET_EXEC || elf_ex.e_phnum > 2 ||
!elf_check_arch(&elf_ex) || !file->f_op || !file->f_op->mmap)
goto out;
/* Now read in all of the header information */
j = sizeof(struct elf_phdr) * elf_ex.e_phnum;
/* j < ELF_MIN_ALIGN because elf_ex.e_phnum <= 2 */
error = -ENOMEM;
elf_phdata = kmalloc(j, GFP_KERNEL);
if (!elf_phdata)
goto out;
eppnt = elf_phdata;
error = -ENOEXEC;
retval = kernel_read(file, elf_ex.e_phoff, (char *)eppnt, j);
if (retval != j)
goto out_free_ph;
for (j = 0, i = 0; i<elf_ex.e_phnum; i++)
if ((eppnt + i)->p_type == PT_LOAD)
j++;
if (j != 1)
goto out_free_ph;
while (eppnt->p_type != PT_LOAD)
eppnt++;
/* Now use mmap to map the library into memory. */
error = vm_mmap(file,
ELF_PAGESTART(eppnt->p_vaddr),
(eppnt->p_filesz +
ELF_PAGEOFFSET(eppnt->p_vaddr)),
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_FIXED | MAP_PRIVATE | MAP_DENYWRITE,
(eppnt->p_offset -
ELF_PAGEOFFSET(eppnt->p_vaddr)));
if (error != ELF_PAGESTART(eppnt->p_vaddr))
goto out_free_ph;
elf_bss = eppnt->p_vaddr + eppnt->p_filesz;
if (padzero(elf_bss)) {
error = -EFAULT;
goto out_free_ph;
}
len = ELF_PAGESTART(eppnt->p_filesz + eppnt->p_vaddr +
ELF_MIN_ALIGN - 1);
bss = eppnt->p_memsz + eppnt->p_vaddr;
if (bss > len)
vm_brk(len, bss - len);
error = 0;
out_free_ph:
kfree(elf_phdata);
out:
return error;
}
#ifdef CONFIG_ELF_CORE
/*
* ELF core dumper
*
* Modelled on fs/exec.c:aout_core_dump()
* Jeremy Fitzhardinge <jeremy@sw.oz.au>
*/
/*
* The purpose of always_dump_vma() is to make sure that special kernel mappings
* that are useful for post-mortem analysis are included in every core dump.
* In that way we ensure that the core dump is fully interpretable later
* without matching up the same kernel and hardware config to see what PC values
* meant. These special mappings include - vDSO, vsyscall, and other
* architecture specific mappings
*/
static bool always_dump_vma(struct vm_area_struct *vma)
{
/* Any vsyscall mappings? */
if (vma == get_gate_vma(vma->vm_mm))
return true;
/*
* arch_vma_name() returns non-NULL for special architecture mappings,
* such as vDSO sections.
*/
if (arch_vma_name(vma))
return true;
return false;
}
/*
* Decide what to dump of a segment, part, all or none.
*/
static unsigned long vma_dump_size(struct vm_area_struct *vma,
unsigned long mm_flags)
{
#define FILTER(type) (mm_flags & (1UL << MMF_DUMP_##type))
/* always dump the vdso and vsyscall sections */
if (always_dump_vma(vma))
goto whole;
if (vma->vm_flags & VM_NODUMP)
return 0;
/* Hugetlb memory check */
if (vma->vm_flags & VM_HUGETLB) {
if ((vma->vm_flags & VM_SHARED) && FILTER(HUGETLB_SHARED))
goto whole;
if (!(vma->vm_flags & VM_SHARED) && FILTER(HUGETLB_PRIVATE))
goto whole;
}
/* Do not dump I/O mapped devices or special mappings */
if (vma->vm_flags & (VM_IO | VM_RESERVED))
return 0;
/* By default, dump shared memory if mapped from an anonymous file. */
if (vma->vm_flags & VM_SHARED) {
if (vma->vm_file->f_path.dentry->d_inode->i_nlink == 0 ?
FILTER(ANON_SHARED) : FILTER(MAPPED_SHARED))
goto whole;
return 0;
}
/* Dump segments that have been written to. */
if (vma->anon_vma && FILTER(ANON_PRIVATE))
goto whole;
if (vma->vm_file == NULL)
return 0;
if (FILTER(MAPPED_PRIVATE))
goto whole;
/*
* If this looks like the beginning of a DSO or executable mapping,
* check for an ELF header. If we find one, dump the first page to
* aid in determining what was mapped here.
*/
if (FILTER(ELF_HEADERS) &&
vma->vm_pgoff == 0 && (vma->vm_flags & VM_READ)) {
u32 __user *header = (u32 __user *) vma->vm_start;
u32 word;
mm_segment_t fs = get_fs();
/*
* Doing it this way gets the constant folded by GCC.
*/
union {
u32 cmp;
char elfmag[SELFMAG];
} magic;
BUILD_BUG_ON(SELFMAG != sizeof word);
magic.elfmag[EI_MAG0] = ELFMAG0;
magic.elfmag[EI_MAG1] = ELFMAG1;
magic.elfmag[EI_MAG2] = ELFMAG2;
magic.elfmag[EI_MAG3] = ELFMAG3;
/*
* Switch to the user "segment" for get_user(),
* then put back what elf_core_dump() had in place.
*/
set_fs(USER_DS);
if (unlikely(get_user(word, header)))
word = 0;
set_fs(fs);
if (word == magic.cmp)
return PAGE_SIZE;
}
#undef FILTER
return 0;
whole:
return vma->vm_end - vma->vm_start;
}
/* An ELF note in memory */
struct memelfnote
{
const char *name;
int type;
unsigned int datasz;
void *data;
};
static int notesize(struct memelfnote *en)
{
int sz;
sz = sizeof(struct elf_note);
sz += roundup(strlen(en->name) + 1, 4);
sz += roundup(en->datasz, 4);
return sz;
}
#define DUMP_WRITE(addr, nr, foffset) \
do { if (!dump_write(file, (addr), (nr))) return 0; *foffset += (nr); } while(0)
static int alignfile(struct file *file, loff_t *foffset)
{
static const char buf[4] = { 0, };
DUMP_WRITE(buf, roundup(*foffset, 4) - *foffset, foffset);
return 1;
}
static int writenote(struct memelfnote *men, struct file *file,
loff_t *foffset)
{
struct elf_note en;
en.n_namesz = strlen(men->name) + 1;
en.n_descsz = men->datasz;
en.n_type = men->type;
DUMP_WRITE(&en, sizeof(en), foffset);
DUMP_WRITE(men->name, en.n_namesz, foffset);
if (!alignfile(file, foffset))
return 0;
DUMP_WRITE(men->data, men->datasz, foffset);
if (!alignfile(file, foffset))
return 0;
return 1;
}
#undef DUMP_WRITE
static void fill_elf_header(struct elfhdr *elf, int segs,
u16 machine, u32 flags, u8 osabi)
{
memset(elf, 0, sizeof(*elf));
memcpy(elf->e_ident, ELFMAG, SELFMAG);
elf->e_ident[EI_CLASS] = ELF_CLASS;
elf->e_ident[EI_DATA] = ELF_DATA;
elf->e_ident[EI_VERSION] = EV_CURRENT;
elf->e_ident[EI_OSABI] = ELF_OSABI;
elf->e_type = ET_CORE;
elf->e_machine = machine;
elf->e_version = EV_CURRENT;
elf->e_phoff = sizeof(struct elfhdr);
elf->e_flags = flags;
elf->e_ehsize = sizeof(struct elfhdr);
elf->e_phentsize = sizeof(struct elf_phdr);
elf->e_phnum = segs;
return;
}
static void fill_elf_note_phdr(struct elf_phdr *phdr, int sz, loff_t offset)
{
phdr->p_type = PT_NOTE;
phdr->p_offset = offset;
phdr->p_vaddr = 0;
phdr->p_paddr = 0;
phdr->p_filesz = sz;
phdr->p_memsz = 0;
phdr->p_flags = 0;
phdr->p_align = 0;
return;
}
static void fill_note(struct memelfnote *note, const char *name, int type,
unsigned int sz, void *data)
{
note->name = name;
note->type = type;
note->datasz = sz;
note->data = data;
return;
}
/*
* fill up all the fields in prstatus from the given task struct, except
* registers which need to be filled up separately.
*/
static void fill_prstatus(struct elf_prstatus *prstatus,
struct task_struct *p, long signr)
{
prstatus->pr_info.si_signo = prstatus->pr_cursig = signr;
prstatus->pr_sigpend = p->pending.signal.sig[0];
prstatus->pr_sighold = p->blocked.sig[0];
rcu_read_lock();
prstatus->pr_ppid = task_pid_vnr(rcu_dereference(p->real_parent));
rcu_read_unlock();
prstatus->pr_pid = task_pid_vnr(p);
prstatus->pr_pgrp = task_pgrp_vnr(p);
prstatus->pr_sid = task_session_vnr(p);
if (thread_group_leader(p)) {
struct task_cputime cputime;
/*
* This is the record for the group leader. It shows the
* group-wide total, not its individual thread total.
*/
thread_group_cputime(p, &cputime);
cputime_to_timeval(cputime.utime, &prstatus->pr_utime);
cputime_to_timeval(cputime.stime, &prstatus->pr_stime);
} else {
cputime_to_timeval(p->utime, &prstatus->pr_utime);
cputime_to_timeval(p->stime, &prstatus->pr_stime);
}
cputime_to_timeval(p->signal->cutime, &prstatus->pr_cutime);
cputime_to_timeval(p->signal->cstime, &prstatus->pr_cstime);
}
static int fill_psinfo(struct elf_prpsinfo *psinfo, struct task_struct *p,
struct mm_struct *mm)
{
const struct cred *cred;
unsigned int i, len;
/* first copy the parameters from user space */
memset(psinfo, 0, sizeof(struct elf_prpsinfo));
len = mm->arg_end - mm->arg_start;
if (len >= ELF_PRARGSZ)
len = ELF_PRARGSZ-1;
if (copy_from_user(&psinfo->pr_psargs,
(const char __user *)mm->arg_start, len))
return -EFAULT;
for(i = 0; i < len; i++)
if (psinfo->pr_psargs[i] == 0)
psinfo->pr_psargs[i] = ' ';
psinfo->pr_psargs[len] = 0;
rcu_read_lock();
psinfo->pr_ppid = task_pid_vnr(rcu_dereference(p->real_parent));
rcu_read_unlock();
psinfo->pr_pid = task_pid_vnr(p);
psinfo->pr_pgrp = task_pgrp_vnr(p);
psinfo->pr_sid = task_session_vnr(p);
i = p->state ? ffz(~p->state) + 1 : 0;
psinfo->pr_state = i;
psinfo->pr_sname = (i > 5) ? '.' : "RSDTZW"[i];
psinfo->pr_zomb = psinfo->pr_sname == 'Z';
psinfo->pr_nice = task_nice(p);
psinfo->pr_flag = p->flags;
rcu_read_lock();
cred = __task_cred(p);
SET_UID(psinfo->pr_uid, cred->uid);
SET_GID(psinfo->pr_gid, cred->gid);
rcu_read_unlock();
strncpy(psinfo->pr_fname, p->comm, sizeof(psinfo->pr_fname));
return 0;
}
static void fill_auxv_note(struct memelfnote *note, struct mm_struct *mm)
{
elf_addr_t *auxv = (elf_addr_t *) mm->saved_auxv;
int i = 0;
do
i += 2;
while (auxv[i - 2] != AT_NULL);
fill_note(note, "CORE", NT_AUXV, i * sizeof(elf_addr_t), auxv);
}
#ifdef CORE_DUMP_USE_REGSET
#include <linux/regset.h>
struct elf_thread_core_info {
struct elf_thread_core_info *next;
struct task_struct *task;
struct elf_prstatus prstatus;
struct memelfnote notes[0];
};
struct elf_note_info {
struct elf_thread_core_info *thread;
struct memelfnote psinfo;
struct memelfnote auxv;
size_t size;
int thread_notes;
};
/*
* When a regset has a writeback hook, we call it on each thread before
* dumping user memory. On register window machines, this makes sure the
* user memory backing the register data is up to date before we read it.
*/
static void do_thread_regset_writeback(struct task_struct *task,
const struct user_regset *regset)
{
if (regset->writeback)
regset->writeback(task, regset, 1);
}
#ifndef PR_REG_SIZE
#define PR_REG_SIZE(S) sizeof(S)
#endif
#ifndef PRSTATUS_SIZE
#define PRSTATUS_SIZE(S) sizeof(S)
#endif
#ifndef PR_REG_PTR
#define PR_REG_PTR(S) (&((S)->pr_reg))
#endif
#ifndef SET_PR_FPVALID
#define SET_PR_FPVALID(S, V) ((S)->pr_fpvalid = (V))
#endif
static int fill_thread_core_info(struct elf_thread_core_info *t,
const struct user_regset_view *view,
long signr, size_t *total)
{
unsigned int i;
/*
* NT_PRSTATUS is the one special case, because the regset data
* goes into the pr_reg field inside the note contents, rather
* than being the whole note contents. We fill the reset in here.
* We assume that regset 0 is NT_PRSTATUS.
*/
fill_prstatus(&t->prstatus, t->task, signr);
(void) view->regsets[0].get(t->task, &view->regsets[0],
0, PR_REG_SIZE(t->prstatus.pr_reg),
PR_REG_PTR(&t->prstatus), NULL);
fill_note(&t->notes[0], "CORE", NT_PRSTATUS,
PRSTATUS_SIZE(t->prstatus), &t->prstatus);
*total += notesize(&t->notes[0]);
do_thread_regset_writeback(t->task, &view->regsets[0]);
/*
* Each other regset might generate a note too. For each regset
* that has no core_note_type or is inactive, we leave t->notes[i]
* all zero and we'll know to skip writing it later.
*/
for (i = 1; i < view->n; ++i) {
const struct user_regset *regset = &view->regsets[i];
do_thread_regset_writeback(t->task, regset);
if (regset->core_note_type && regset->get &&
(!regset->active || regset->active(t->task, regset))) {
int ret;
size_t size = regset->n * regset->size;
void *data = kmalloc(size, GFP_KERNEL);
if (unlikely(!data))
return 0;
ret = regset->get(t->task, regset,
0, size, data, NULL);
if (unlikely(ret))
kfree(data);
else {
if (regset->core_note_type != NT_PRFPREG)
fill_note(&t->notes[i], "LINUX",
regset->core_note_type,
size, data);
else {
SET_PR_FPVALID(&t->prstatus, 1);
fill_note(&t->notes[i], "CORE",
NT_PRFPREG, size, data);
}
*total += notesize(&t->notes[i]);
}
}
}
return 1;
}
static int fill_note_info(struct elfhdr *elf, int phdrs,
struct elf_note_info *info,
long signr, struct pt_regs *regs)
{
struct task_struct *dump_task = current;
const struct user_regset_view *view = task_user_regset_view(dump_task);
struct elf_thread_core_info *t;
struct elf_prpsinfo *psinfo;
struct core_thread *ct;
unsigned int i;
info->size = 0;
info->thread = NULL;
psinfo = kmalloc(sizeof(*psinfo), GFP_KERNEL);
if (psinfo == NULL)
return 0;
fill_note(&info->psinfo, "CORE", NT_PRPSINFO, sizeof(*psinfo), psinfo);
/*
* Figure out how many notes we're going to need for each thread.
*/
info->thread_notes = 0;
for (i = 0; i < view->n; ++i)
if (view->regsets[i].core_note_type != 0)
++info->thread_notes;
/*
* Sanity check. We rely on regset 0 being in NT_PRSTATUS,
* since it is our one special case.
*/
if (unlikely(info->thread_notes == 0) ||
unlikely(view->regsets[0].core_note_type != NT_PRSTATUS)) {
WARN_ON(1);
return 0;
}
/*
* Initialize the ELF file header.
*/
fill_elf_header(elf, phdrs,
view->e_machine, view->e_flags, view->ei_osabi);
/*
* Allocate a structure for each thread.
*/
for (ct = &dump_task->mm->core_state->dumper; ct; ct = ct->next) {
t = kzalloc(offsetof(struct elf_thread_core_info,
notes[info->thread_notes]),
GFP_KERNEL);
if (unlikely(!t))
return 0;
t->task = ct->task;
if (ct->task == dump_task || !info->thread) {
t->next = info->thread;
info->thread = t;
} else {
/*
* Make sure to keep the original task at
* the head of the list.
*/
t->next = info->thread->next;
info->thread->next = t;
}
}
/*
* Now fill in each thread's information.
*/
for (t = info->thread; t != NULL; t = t->next)
if (!fill_thread_core_info(t, view, signr, &info->size))
return 0;
/*
* Fill in the two process-wide notes.
*/
fill_psinfo(psinfo, dump_task->group_leader, dump_task->mm);
info->size += notesize(&info->psinfo);
fill_auxv_note(&info->auxv, current->mm);
info->size += notesize(&info->auxv);
return 1;
}
static size_t get_note_info_size(struct elf_note_info *info)
{
return info->size;
}
/*
* Write all the notes for each thread. When writing the first thread, the
* process-wide notes are interleaved after the first thread-specific note.
*/
static int write_note_info(struct elf_note_info *info,
struct file *file, loff_t *foffset)
{
bool first = 1;
struct elf_thread_core_info *t = info->thread;
do {
int i;
if (!writenote(&t->notes[0], file, foffset))
return 0;
if (first && !writenote(&info->psinfo, file, foffset))
return 0;
if (first && !writenote(&info->auxv, file, foffset))
return 0;
for (i = 1; i < info->thread_notes; ++i)
if (t->notes[i].data &&
!writenote(&t->notes[i], file, foffset))
return 0;
first = 0;
t = t->next;
} while (t);
return 1;
}
static void free_note_info(struct elf_note_info *info)
{
struct elf_thread_core_info *threads = info->thread;
while (threads) {
unsigned int i;
struct elf_thread_core_info *t = threads;
threads = t->next;
WARN_ON(t->notes[0].data && t->notes[0].data != &t->prstatus);
for (i = 1; i < info->thread_notes; ++i)
kfree(t->notes[i].data);
kfree(t);
}
kfree(info->psinfo.data);
}
#else
/* Here is the structure in which status of each thread is captured. */
struct elf_thread_status
{
struct list_head list;
struct elf_prstatus prstatus; /* NT_PRSTATUS */
elf_fpregset_t fpu; /* NT_PRFPREG */
struct task_struct *thread;
#ifdef ELF_CORE_COPY_XFPREGS
elf_fpxregset_t xfpu; /* ELF_CORE_XFPREG_TYPE */
#endif
struct memelfnote notes[3];
int num_notes;
};
/*
* In order to add the specific thread information for the elf file format,
* we need to keep a linked list of every threads pr_status and then create
* a single section for them in the final core file.
*/
static int elf_dump_thread_status(long signr, struct elf_thread_status *t)
{
int sz = 0;
struct task_struct *p = t->thread;
t->num_notes = 0;
fill_prstatus(&t->prstatus, p, signr);
elf_core_copy_task_regs(p, &t->prstatus.pr_reg);
fill_note(&t->notes[0], "CORE", NT_PRSTATUS, sizeof(t->prstatus),
&(t->prstatus));
t->num_notes++;
sz += notesize(&t->notes[0]);
if ((t->prstatus.pr_fpvalid = elf_core_copy_task_fpregs(p, NULL,
&t->fpu))) {
fill_note(&t->notes[1], "CORE", NT_PRFPREG, sizeof(t->fpu),
&(t->fpu));
t->num_notes++;
sz += notesize(&t->notes[1]);
}
#ifdef ELF_CORE_COPY_XFPREGS
if (elf_core_copy_task_xfpregs(p, &t->xfpu)) {
fill_note(&t->notes[2], "LINUX", ELF_CORE_XFPREG_TYPE,
sizeof(t->xfpu), &t->xfpu);
t->num_notes++;
sz += notesize(&t->notes[2]);
}
#endif
return sz;
}
struct elf_note_info {
struct memelfnote *notes;
struct elf_prstatus *prstatus; /* NT_PRSTATUS */
struct elf_prpsinfo *psinfo; /* NT_PRPSINFO */
struct list_head thread_list;
elf_fpregset_t *fpu;
#ifdef ELF_CORE_COPY_XFPREGS
elf_fpxregset_t *xfpu;
#endif
int thread_status_size;
int numnote;
};
static int elf_note_info_init(struct elf_note_info *info)
{
memset(info, 0, sizeof(*info));
INIT_LIST_HEAD(&info->thread_list);
/* Allocate space for six ELF notes */
info->notes = kmalloc(6 * sizeof(struct memelfnote), GFP_KERNEL);
if (!info->notes)
return 0;
info->psinfo = kmalloc(sizeof(*info->psinfo), GFP_KERNEL);
if (!info->psinfo)
goto notes_free;
info->prstatus = kmalloc(sizeof(*info->prstatus), GFP_KERNEL);
if (!info->prstatus)
goto psinfo_free;
info->fpu = kmalloc(sizeof(*info->fpu), GFP_KERNEL);
if (!info->fpu)
goto prstatus_free;
#ifdef ELF_CORE_COPY_XFPREGS
info->xfpu = kmalloc(sizeof(*info->xfpu), GFP_KERNEL);
if (!info->xfpu)
goto fpu_free;
#endif
return 1;
#ifdef ELF_CORE_COPY_XFPREGS
fpu_free:
kfree(info->fpu);
#endif
prstatus_free:
kfree(info->prstatus);
psinfo_free:
kfree(info->psinfo);
notes_free:
kfree(info->notes);
return 0;
}
static int fill_note_info(struct elfhdr *elf, int phdrs,
struct elf_note_info *info,
long signr, struct pt_regs *regs)
{
struct list_head *t;
if (!elf_note_info_init(info))
return 0;
if (signr) {
struct core_thread *ct;
struct elf_thread_status *ets;
for (ct = current->mm->core_state->dumper.next;
ct; ct = ct->next) {
ets = kzalloc(sizeof(*ets), GFP_KERNEL);
if (!ets)
return 0;
ets->thread = ct->task;
list_add(&ets->list, &info->thread_list);
}
list_for_each(t, &info->thread_list) {
int sz;
ets = list_entry(t, struct elf_thread_status, list);
sz = elf_dump_thread_status(signr, ets);
info->thread_status_size += sz;
}
}
/* now collect the dump for the current */
memset(info->prstatus, 0, sizeof(*info->prstatus));
fill_prstatus(info->prstatus, current, signr);
elf_core_copy_regs(&info->prstatus->pr_reg, regs);
/* Set up header */
fill_elf_header(elf, phdrs, ELF_ARCH, ELF_CORE_EFLAGS, ELF_OSABI);
/*
* Set up the notes in similar form to SVR4 core dumps made
* with info from their /proc.
*/
fill_note(info->notes + 0, "CORE", NT_PRSTATUS,
sizeof(*info->prstatus), info->prstatus);
fill_psinfo(info->psinfo, current->group_leader, current->mm);
fill_note(info->notes + 1, "CORE", NT_PRPSINFO,
sizeof(*info->psinfo), info->psinfo);
info->numnote = 2;
fill_auxv_note(&info->notes[info->numnote++], current->mm);
/* Try to dump the FPU. */
info->prstatus->pr_fpvalid = elf_core_copy_task_fpregs(current, regs,
info->fpu);
if (info->prstatus->pr_fpvalid)
fill_note(info->notes + info->numnote++,
"CORE", NT_PRFPREG, sizeof(*info->fpu), info->fpu);
#ifdef ELF_CORE_COPY_XFPREGS
if (elf_core_copy_task_xfpregs(current, info->xfpu))
fill_note(info->notes + info->numnote++,
"LINUX", ELF_CORE_XFPREG_TYPE,
sizeof(*info->xfpu), info->xfpu);
#endif
return 1;
}
static size_t get_note_info_size(struct elf_note_info *info)
{
int sz = 0;
int i;
for (i = 0; i < info->numnote; i++)
sz += notesize(info->notes + i);
sz += info->thread_status_size;
return sz;
}
static int write_note_info(struct elf_note_info *info,
struct file *file, loff_t *foffset)
{
int i;
struct list_head *t;
for (i = 0; i < info->numnote; i++)
if (!writenote(info->notes + i, file, foffset))
return 0;
/* write out the thread status notes section */
list_for_each(t, &info->thread_list) {
struct elf_thread_status *tmp =
list_entry(t, struct elf_thread_status, list);
for (i = 0; i < tmp->num_notes; i++)
if (!writenote(&tmp->notes[i], file, foffset))
return 0;
}
return 1;
}
static void free_note_info(struct elf_note_info *info)
{
while (!list_empty(&info->thread_list)) {
struct list_head *tmp = info->thread_list.next;
list_del(tmp);
kfree(list_entry(tmp, struct elf_thread_status, list));
}
kfree(info->prstatus);
kfree(info->psinfo);
kfree(info->notes);
kfree(info->fpu);
#ifdef ELF_CORE_COPY_XFPREGS
kfree(info->xfpu);
#endif
}
#endif
static struct vm_area_struct *first_vma(struct task_struct *tsk,
struct vm_area_struct *gate_vma)
{
struct vm_area_struct *ret = tsk->mm->mmap;
if (ret)
return ret;
return gate_vma;
}
/*
* Helper function for iterating across a vma list. It ensures that the caller
* will visit `gate_vma' prior to terminating the search.
*/
static struct vm_area_struct *next_vma(struct vm_area_struct *this_vma,
struct vm_area_struct *gate_vma)
{
struct vm_area_struct *ret;
ret = this_vma->vm_next;
if (ret)
return ret;
if (this_vma == gate_vma)
return NULL;
return gate_vma;
}
static void fill_extnum_info(struct elfhdr *elf, struct elf_shdr *shdr4extnum,
elf_addr_t e_shoff, int segs)
{
elf->e_shoff = e_shoff;
elf->e_shentsize = sizeof(*shdr4extnum);
elf->e_shnum = 1;
elf->e_shstrndx = SHN_UNDEF;
memset(shdr4extnum, 0, sizeof(*shdr4extnum));
shdr4extnum->sh_type = SHT_NULL;
shdr4extnum->sh_size = elf->e_shnum;
shdr4extnum->sh_link = elf->e_shstrndx;
shdr4extnum->sh_info = segs;
}
static size_t elf_core_vma_data_size(struct vm_area_struct *gate_vma,
unsigned long mm_flags)
{
struct vm_area_struct *vma;
size_t size = 0;
for (vma = first_vma(current, gate_vma); vma != NULL;
vma = next_vma(vma, gate_vma))
size += vma_dump_size(vma, mm_flags);
return size;
}
/*
* Actual dumper
*
* This is a two-pass process; first we find the offsets of the bits,
* and then they are actually written out. If we run out of core limit
* we just truncate.
*/
static int elf_core_dump(struct coredump_params *cprm)
{
int has_dumped = 0;
mm_segment_t fs;
int segs;
size_t size = 0;
struct vm_area_struct *vma, *gate_vma;
struct elfhdr *elf = NULL;
loff_t offset = 0, dataoff, foffset;
struct elf_note_info info;
struct elf_phdr *phdr4note = NULL;
struct elf_shdr *shdr4extnum = NULL;
Elf_Half e_phnum;
elf_addr_t e_shoff;
/*
* We no longer stop all VM operations.
*
* This is because those proceses that could possibly change map_count
* or the mmap / vma pages are now blocked in do_exit on current
* finishing this core dump.
*
* Only ptrace can touch these memory addresses, but it doesn't change
* the map_count or the pages allocated. So no possibility of crashing
* exists while dumping the mm->vm_next areas to the core file.
*/
/* alloc memory for large data structures: too large to be on stack */
elf = kmalloc(sizeof(*elf), GFP_KERNEL);
if (!elf)
goto out;
/*
* The number of segs are recored into ELF header as 16bit value.
* Please check DEFAULT_MAX_MAP_COUNT definition when you modify here.
*/
segs = current->mm->map_count;
segs += elf_core_extra_phdrs();
gate_vma = get_gate_vma(current->mm);
if (gate_vma != NULL)
segs++;
/* for notes section */
segs++;
/* If segs > PN_XNUM(0xffff), then e_phnum overflows. To avoid
* this, kernel supports extended numbering. Have a look at
* include/linux/elf.h for further information. */
e_phnum = segs > PN_XNUM ? PN_XNUM : segs;
/*
* Collect all the non-memory information about the process for the
* notes. This also sets up the file header.
*/
if (!fill_note_info(elf, e_phnum, &info, cprm->signr, cprm->regs))
goto cleanup;
has_dumped = 1;
current->flags |= PF_DUMPCORE;
fs = get_fs();
set_fs(KERNEL_DS);
offset += sizeof(*elf); /* Elf header */
offset += segs * sizeof(struct elf_phdr); /* Program headers */
foffset = offset;
/* Write notes phdr entry */
{
size_t sz = get_note_info_size(&info);
sz += elf_coredump_extra_notes_size();
phdr4note = kmalloc(sizeof(*phdr4note), GFP_KERNEL);
if (!phdr4note)
goto end_coredump;
fill_elf_note_phdr(phdr4note, sz, offset);
offset += sz;
}
dataoff = offset = roundup(offset, ELF_EXEC_PAGESIZE);
offset += elf_core_vma_data_size(gate_vma, cprm->mm_flags);
offset += elf_core_extra_data_size();
e_shoff = offset;
if (e_phnum == PN_XNUM) {
shdr4extnum = kmalloc(sizeof(*shdr4extnum), GFP_KERNEL);
if (!shdr4extnum)
goto end_coredump;
fill_extnum_info(elf, shdr4extnum, e_shoff, segs);
}
offset = dataoff;
size += sizeof(*elf);
if (size > cprm->limit || !dump_write(cprm->file, elf, sizeof(*elf)))
goto end_coredump;
size += sizeof(*phdr4note);
if (size > cprm->limit
|| !dump_write(cprm->file, phdr4note, sizeof(*phdr4note)))
goto end_coredump;
/* Write program headers for segments dump */
for (vma = first_vma(current, gate_vma); vma != NULL;
vma = next_vma(vma, gate_vma)) {
struct elf_phdr phdr;
phdr.p_type = PT_LOAD;
phdr.p_offset = offset;
phdr.p_vaddr = vma->vm_start;
phdr.p_paddr = 0;
phdr.p_filesz = vma_dump_size(vma, cprm->mm_flags);
phdr.p_memsz = vma->vm_end - vma->vm_start;
offset += phdr.p_filesz;
phdr.p_flags = vma->vm_flags & VM_READ ? PF_R : 0;
if (vma->vm_flags & VM_WRITE)
phdr.p_flags |= PF_W;
if (vma->vm_flags & VM_EXEC)
phdr.p_flags |= PF_X;
phdr.p_align = ELF_EXEC_PAGESIZE;
size += sizeof(phdr);
if (size > cprm->limit
|| !dump_write(cprm->file, &phdr, sizeof(phdr)))
goto end_coredump;
}
if (!elf_core_write_extra_phdrs(cprm->file, offset, &size, cprm->limit))
goto end_coredump;
/* write out the notes section */
if (!write_note_info(&info, cprm->file, &foffset))
goto end_coredump;
if (elf_coredump_extra_notes_write(cprm->file, &foffset))
goto end_coredump;
/* Align to page */
if (!dump_seek(cprm->file, dataoff - foffset))
goto end_coredump;
for (vma = first_vma(current, gate_vma); vma != NULL;
vma = next_vma(vma, gate_vma)) {
unsigned long addr;
unsigned long end;
end = vma->vm_start + vma_dump_size(vma, cprm->mm_flags);
for (addr = vma->vm_start; addr < end; addr += PAGE_SIZE) {
struct page *page;
int stop;
page = get_dump_page(addr);
if (page) {
void *kaddr = kmap(page);
stop = ((size += PAGE_SIZE) > cprm->limit) ||
!dump_write(cprm->file, kaddr,
PAGE_SIZE);
kunmap(page);
page_cache_release(page);
} else
stop = !dump_seek(cprm->file, PAGE_SIZE);
if (stop)
goto end_coredump;
}
}
if (!elf_core_write_extra_data(cprm->file, &size, cprm->limit))
goto end_coredump;
if (e_phnum == PN_XNUM) {
size += sizeof(*shdr4extnum);
if (size > cprm->limit
|| !dump_write(cprm->file, shdr4extnum,
sizeof(*shdr4extnum)))
goto end_coredump;
}
end_coredump:
set_fs(fs);
cleanup:
free_note_info(&info);
kfree(shdr4extnum);
kfree(phdr4note);
kfree(elf);
out:
return has_dumped;
}
#endif /* CONFIG_ELF_CORE */
static int __init init_elf_binfmt(void)
{
register_binfmt(&elf_format);
return 0;
}
static void __exit exit_elf_binfmt(void)
{
/* Remove the COFF and ELF loaders. */
unregister_binfmt(&elf_format);
}
core_initcall(init_elf_binfmt);
module_exit(exit_elf_binfmt);
MODULE_LICENSE("GPL");
| gpl-2.0 |
YUPlayGod/android_kernel_yu_msm8916 | block/partitions/mac.c | 2538 | 3444 | /*
* fs/partitions/mac.c
*
* Code extracted from drivers/block/genhd.c
* Copyright (C) 1991-1998 Linus Torvalds
* Re-organised Feb 1998 Russell King
*/
#include <linux/ctype.h>
#include "check.h"
#include "mac.h"
#ifdef CONFIG_PPC_PMAC
#include <asm/machdep.h>
extern void note_bootable_part(dev_t dev, int part, int goodness);
#endif
/*
* Code to understand MacOS partition tables.
*/
static inline void mac_fix_string(char *stg, int len)
{
int i;
for (i = len - 1; i >= 0 && stg[i] == ' '; i--)
stg[i] = 0;
}
int mac_partition(struct parsed_partitions *state)
{
Sector sect;
unsigned char *data;
int slot, blocks_in_map;
unsigned secsize;
#ifdef CONFIG_PPC_PMAC
int found_root = 0;
int found_root_goodness = 0;
#endif
struct mac_partition *part;
struct mac_driver_desc *md;
/* Get 0th block and look at the first partition map entry. */
md = read_part_sector(state, 0, §);
if (!md)
return -1;
if (be16_to_cpu(md->signature) != MAC_DRIVER_MAGIC) {
put_dev_sector(sect);
return 0;
}
secsize = be16_to_cpu(md->block_size);
put_dev_sector(sect);
data = read_part_sector(state, secsize/512, §);
if (!data)
return -1;
part = (struct mac_partition *) (data + secsize%512);
if (be16_to_cpu(part->signature) != MAC_PARTITION_MAGIC) {
put_dev_sector(sect);
return 0; /* not a MacOS disk */
}
blocks_in_map = be32_to_cpu(part->map_count);
if (blocks_in_map < 0 || blocks_in_map >= DISK_MAX_PARTS) {
put_dev_sector(sect);
return 0;
}
if (blocks_in_map >= state->limit)
blocks_in_map = state->limit - 1;
strlcat(state->pp_buf, " [mac]", PAGE_SIZE);
for (slot = 1; slot <= blocks_in_map; ++slot) {
int pos = slot * secsize;
put_dev_sector(sect);
data = read_part_sector(state, pos/512, §);
if (!data)
return -1;
part = (struct mac_partition *) (data + pos%512);
if (be16_to_cpu(part->signature) != MAC_PARTITION_MAGIC)
break;
put_partition(state, slot,
be32_to_cpu(part->start_block) * (secsize/512),
be32_to_cpu(part->block_count) * (secsize/512));
if (!strnicmp(part->type, "Linux_RAID", 10))
state->parts[slot].flags = ADDPART_FLAG_RAID;
#ifdef CONFIG_PPC_PMAC
/*
* If this is the first bootable partition, tell the
* setup code, in case it wants to make this the root.
*/
if (machine_is(powermac)) {
int goodness = 0;
mac_fix_string(part->processor, 16);
mac_fix_string(part->name, 32);
mac_fix_string(part->type, 32);
if ((be32_to_cpu(part->status) & MAC_STATUS_BOOTABLE)
&& strcasecmp(part->processor, "powerpc") == 0)
goodness++;
if (strcasecmp(part->type, "Apple_UNIX_SVR2") == 0
|| (strnicmp(part->type, "Linux", 5) == 0
&& strcasecmp(part->type, "Linux_swap") != 0)) {
int i, l;
goodness++;
l = strlen(part->name);
if (strcmp(part->name, "/") == 0)
goodness++;
for (i = 0; i <= l - 4; ++i) {
if (strnicmp(part->name + i, "root",
4) == 0) {
goodness += 2;
break;
}
}
if (strnicmp(part->name, "swap", 4) == 0)
goodness--;
}
if (goodness > found_root_goodness) {
found_root = slot;
found_root_goodness = goodness;
}
}
#endif /* CONFIG_PPC_PMAC */
}
#ifdef CONFIG_PPC_PMAC
if (found_root_goodness)
note_bootable_part(state->bdev->bd_dev, found_root,
found_root_goodness);
#endif
put_dev_sector(sect);
strlcat(state->pp_buf, "\n", PAGE_SIZE);
return 1;
}
| gpl-2.0 |
htc-msm8660/android_kernel_htc_msm8660 | arch/arm/kernel/unwind.c | 3050 | 11437 | /*
* arch/arm/kernel/unwind.c
*
* Copyright (C) 2008 ARM Limited
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
* Stack unwinding support for ARM
*
* An ARM EABI version of gcc is required to generate the unwind
* tables. For information about the structure of the unwind tables,
* see "Exception Handling ABI for the ARM Architecture" at:
*
* http://infocenter.arm.com/help/topic/com.arm.doc.subset.swdev.abi/index.html
*/
#ifndef __CHECKER__
#if !defined (__ARM_EABI__)
#warning Your compiler does not have EABI support.
#warning ARM unwind is known to compile only with EABI compilers.
#warning Change compiler or disable ARM_UNWIND option.
#elif (__GNUC__ == 4 && __GNUC_MINOR__ <= 2)
#warning Your compiler is too buggy; it is known to not compile ARM unwind support.
#warning Change compiler or disable ARM_UNWIND option.
#endif
#endif /* __CHECKER__ */
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/list.h>
#include <asm/stacktrace.h>
#include <asm/traps.h>
#include <asm/unwind.h>
/* Dummy functions to avoid linker complaints */
void __aeabi_unwind_cpp_pr0(void)
{
};
EXPORT_SYMBOL(__aeabi_unwind_cpp_pr0);
void __aeabi_unwind_cpp_pr1(void)
{
};
EXPORT_SYMBOL(__aeabi_unwind_cpp_pr1);
void __aeabi_unwind_cpp_pr2(void)
{
};
EXPORT_SYMBOL(__aeabi_unwind_cpp_pr2);
struct unwind_ctrl_block {
unsigned long vrs[16]; /* virtual register set */
unsigned long *insn; /* pointer to the current instructions word */
int entries; /* number of entries left to interpret */
int byte; /* current byte number in the instructions word */
};
enum regs {
#ifdef CONFIG_THUMB2_KERNEL
FP = 7,
#else
FP = 11,
#endif
SP = 13,
LR = 14,
PC = 15
};
extern struct unwind_idx __start_unwind_idx[];
extern struct unwind_idx __stop_unwind_idx[];
static DEFINE_SPINLOCK(unwind_lock);
static LIST_HEAD(unwind_tables);
/* Convert a prel31 symbol to an absolute address */
#define prel31_to_addr(ptr) \
({ \
/* sign-extend to 32 bits */ \
long offset = (((long)*(ptr)) << 1) >> 1; \
(unsigned long)(ptr) + offset; \
})
/*
* Binary search in the unwind index. The entries entries are
* guaranteed to be sorted in ascending order by the linker.
*/
static struct unwind_idx *search_index(unsigned long addr,
struct unwind_idx *first,
struct unwind_idx *last)
{
pr_debug("%s(%08lx, %p, %p)\n", __func__, addr, first, last);
if (addr < first->addr) {
pr_warning("unwind: Unknown symbol address %08lx\n", addr);
return NULL;
} else if (addr >= last->addr)
return last;
while (first < last - 1) {
struct unwind_idx *mid = first + ((last - first + 1) >> 1);
if (addr < mid->addr)
last = mid;
else
first = mid;
}
return first;
}
static struct unwind_idx *unwind_find_idx(unsigned long addr)
{
struct unwind_idx *idx = NULL;
unsigned long flags;
pr_debug("%s(%08lx)\n", __func__, addr);
if (core_kernel_text(addr))
/* main unwind table */
idx = search_index(addr, __start_unwind_idx,
__stop_unwind_idx - 1);
else {
/* module unwind tables */
struct unwind_table *table;
spin_lock_irqsave(&unwind_lock, flags);
list_for_each_entry(table, &unwind_tables, list) {
if (addr >= table->begin_addr &&
addr < table->end_addr) {
idx = search_index(addr, table->start,
table->stop - 1);
/* Move-to-front to exploit common traces */
list_move(&table->list, &unwind_tables);
break;
}
}
spin_unlock_irqrestore(&unwind_lock, flags);
}
pr_debug("%s: idx = %p\n", __func__, idx);
return idx;
}
static unsigned long unwind_get_byte(struct unwind_ctrl_block *ctrl)
{
unsigned long ret;
if (ctrl->entries <= 0) {
pr_warning("unwind: Corrupt unwind table\n");
return 0;
}
ret = (*ctrl->insn >> (ctrl->byte * 8)) & 0xff;
if (ctrl->byte == 0) {
ctrl->insn++;
ctrl->entries--;
ctrl->byte = 3;
} else
ctrl->byte--;
return ret;
}
/*
* Execute the current unwind instruction.
*/
static int unwind_exec_insn(struct unwind_ctrl_block *ctrl)
{
unsigned long insn = unwind_get_byte(ctrl);
pr_debug("%s: insn = %08lx\n", __func__, insn);
if ((insn & 0xc0) == 0x00)
ctrl->vrs[SP] += ((insn & 0x3f) << 2) + 4;
else if ((insn & 0xc0) == 0x40)
ctrl->vrs[SP] -= ((insn & 0x3f) << 2) + 4;
else if ((insn & 0xf0) == 0x80) {
unsigned long mask;
unsigned long *vsp = (unsigned long *)ctrl->vrs[SP];
int load_sp, reg = 4;
insn = (insn << 8) | unwind_get_byte(ctrl);
mask = insn & 0x0fff;
if (mask == 0) {
pr_warning("unwind: 'Refuse to unwind' instruction %04lx\n",
insn);
return -URC_FAILURE;
}
/* pop R4-R15 according to mask */
load_sp = mask & (1 << (13 - 4));
while (mask) {
if (mask & 1)
ctrl->vrs[reg] = *vsp++;
mask >>= 1;
reg++;
}
if (!load_sp)
ctrl->vrs[SP] = (unsigned long)vsp;
} else if ((insn & 0xf0) == 0x90 &&
(insn & 0x0d) != 0x0d)
ctrl->vrs[SP] = ctrl->vrs[insn & 0x0f];
else if ((insn & 0xf0) == 0xa0) {
unsigned long *vsp = (unsigned long *)ctrl->vrs[SP];
int reg;
/* pop R4-R[4+bbb] */
for (reg = 4; reg <= 4 + (insn & 7); reg++)
ctrl->vrs[reg] = *vsp++;
if (insn & 0x80)
ctrl->vrs[14] = *vsp++;
ctrl->vrs[SP] = (unsigned long)vsp;
} else if (insn == 0xb0) {
if (ctrl->vrs[PC] == 0)
ctrl->vrs[PC] = ctrl->vrs[LR];
/* no further processing */
ctrl->entries = 0;
} else if (insn == 0xb1) {
unsigned long mask = unwind_get_byte(ctrl);
unsigned long *vsp = (unsigned long *)ctrl->vrs[SP];
int reg = 0;
if (mask == 0 || mask & 0xf0) {
pr_warning("unwind: Spare encoding %04lx\n",
(insn << 8) | mask);
return -URC_FAILURE;
}
/* pop R0-R3 according to mask */
while (mask) {
if (mask & 1)
ctrl->vrs[reg] = *vsp++;
mask >>= 1;
reg++;
}
ctrl->vrs[SP] = (unsigned long)vsp;
} else if (insn == 0xb2) {
unsigned long uleb128 = unwind_get_byte(ctrl);
ctrl->vrs[SP] += 0x204 + (uleb128 << 2);
} else {
pr_warning("unwind: Unhandled instruction %02lx\n", insn);
return -URC_FAILURE;
}
pr_debug("%s: fp = %08lx sp = %08lx lr = %08lx pc = %08lx\n", __func__,
ctrl->vrs[FP], ctrl->vrs[SP], ctrl->vrs[LR], ctrl->vrs[PC]);
return URC_OK;
}
/*
* Unwind a single frame starting with *sp for the symbol at *pc. It
* updates the *pc and *sp with the new values.
*/
int unwind_frame(struct stackframe *frame)
{
unsigned long high, low;
struct unwind_idx *idx;
struct unwind_ctrl_block ctrl;
/* only go to a higher address on the stack */
low = frame->sp;
high = ALIGN(low, THREAD_SIZE);
pr_debug("%s(pc = %08lx lr = %08lx sp = %08lx)\n", __func__,
frame->pc, frame->lr, frame->sp);
if (!kernel_text_address(frame->pc))
return -URC_FAILURE;
idx = unwind_find_idx(frame->pc);
if (!idx) {
pr_warning("unwind: Index not found %08lx\n", frame->pc);
return -URC_FAILURE;
}
ctrl.vrs[FP] = frame->fp;
ctrl.vrs[SP] = frame->sp;
ctrl.vrs[LR] = frame->lr;
ctrl.vrs[PC] = 0;
if (idx->insn == 1)
/* can't unwind */
return -URC_FAILURE;
else if ((idx->insn & 0x80000000) == 0)
/* prel31 to the unwind table */
ctrl.insn = (unsigned long *)prel31_to_addr(&idx->insn);
else if ((idx->insn & 0xff000000) == 0x80000000)
/* only personality routine 0 supported in the index */
ctrl.insn = &idx->insn;
else {
pr_warning("unwind: Unsupported personality routine %08lx in the index at %p\n",
idx->insn, idx);
return -URC_FAILURE;
}
/* check the personality routine */
if ((*ctrl.insn & 0xff000000) == 0x80000000) {
ctrl.byte = 2;
ctrl.entries = 1;
} else if ((*ctrl.insn & 0xff000000) == 0x81000000) {
ctrl.byte = 1;
ctrl.entries = 1 + ((*ctrl.insn & 0x00ff0000) >> 16);
} else {
pr_warning("unwind: Unsupported personality routine %08lx at %p\n",
*ctrl.insn, ctrl.insn);
return -URC_FAILURE;
}
while (ctrl.entries > 0) {
int urc = unwind_exec_insn(&ctrl);
if (urc < 0)
return urc;
if (ctrl.vrs[SP] < low || ctrl.vrs[SP] >= high)
return -URC_FAILURE;
}
if (ctrl.vrs[PC] == 0)
ctrl.vrs[PC] = ctrl.vrs[LR];
/* check for infinite loop */
if (frame->pc == ctrl.vrs[PC])
return -URC_FAILURE;
frame->fp = ctrl.vrs[FP];
frame->sp = ctrl.vrs[SP];
frame->lr = ctrl.vrs[LR];
frame->pc = ctrl.vrs[PC];
return URC_OK;
}
void unwind_backtrace(struct pt_regs *regs, struct task_struct *tsk)
{
struct stackframe frame;
register unsigned long current_sp asm ("sp");
pr_debug("%s(regs = %p tsk = %p)\n", __func__, regs, tsk);
if (!tsk)
tsk = current;
if (regs) {
frame.fp = regs->ARM_fp;
frame.sp = regs->ARM_sp;
frame.lr = regs->ARM_lr;
/* PC might be corrupted, use LR in that case. */
frame.pc = kernel_text_address(regs->ARM_pc)
? regs->ARM_pc : regs->ARM_lr;
} else if (tsk == current) {
frame.fp = (unsigned long)__builtin_frame_address(0);
frame.sp = current_sp;
frame.lr = (unsigned long)__builtin_return_address(0);
frame.pc = (unsigned long)unwind_backtrace;
} else {
/* task blocked in __switch_to */
frame.fp = thread_saved_fp(tsk);
frame.sp = thread_saved_sp(tsk);
/*
* The function calling __switch_to cannot be a leaf function
* so LR is recovered from the stack.
*/
frame.lr = 0;
frame.pc = thread_saved_pc(tsk);
}
while (1) {
int urc;
unsigned long where = frame.pc;
urc = unwind_frame(&frame);
if (urc < 0)
break;
dump_backtrace_entry(where, frame.pc, frame.sp - 4);
}
}
struct unwind_table *unwind_table_add(unsigned long start, unsigned long size,
unsigned long text_addr,
unsigned long text_size)
{
unsigned long flags;
struct unwind_idx *idx;
struct unwind_table *tab = kmalloc(sizeof(*tab), GFP_KERNEL);
pr_debug("%s(%08lx, %08lx, %08lx, %08lx)\n", __func__, start, size,
text_addr, text_size);
if (!tab)
return tab;
tab->start = (struct unwind_idx *)start;
tab->stop = (struct unwind_idx *)(start + size);
tab->begin_addr = text_addr;
tab->end_addr = text_addr + text_size;
/* Convert the symbol addresses to absolute values */
for (idx = tab->start; idx < tab->stop; idx++)
idx->addr = prel31_to_addr(&idx->addr);
spin_lock_irqsave(&unwind_lock, flags);
list_add_tail(&tab->list, &unwind_tables);
spin_unlock_irqrestore(&unwind_lock, flags);
return tab;
}
void unwind_table_del(struct unwind_table *tab)
{
unsigned long flags;
if (!tab)
return;
spin_lock_irqsave(&unwind_lock, flags);
list_del(&tab->list);
spin_unlock_irqrestore(&unwind_lock, flags);
kfree(tab);
}
int __init unwind_init(void)
{
struct unwind_idx *idx;
/* Convert the symbol addresses to absolute values */
for (idx = __start_unwind_idx; idx < __stop_unwind_idx; idx++)
idx->addr = prel31_to_addr(&idx->addr);
pr_debug("unwind: ARM stack unwinding initialised\n");
return 0;
}
| gpl-2.0 |
CaptainThrowback/android_kernel_htc_a32e | arch/xtensa/platforms/iss/console.c | 3562 | 6429 | /*
* arch/xtensa/platforms/iss/console.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.
*
* Copyright (C) 2001-2005 Tensilica Inc.
* Authors Christian Zankel, Joe Taylor
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/console.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/major.h>
#include <linux/param.h>
#include <linux/seq_file.h>
#include <linux/serial.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <platform/simcall.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#ifdef SERIAL_INLINE
#define _INLINE_ inline
#endif
#define SERIAL_MAX_NUM_LINES 1
#define SERIAL_TIMER_VALUE (HZ / 10)
static struct tty_driver *serial_driver;
static struct tty_port serial_port;
static struct timer_list serial_timer;
static DEFINE_SPINLOCK(timer_lock);
static char *serial_version = "0.1";
static char *serial_name = "ISS serial driver";
/*
* This routine is called whenever a serial port is opened. It
* enables interrupts for a serial port, linking in its async structure into
* the IRQ chain. It also performs the serial-specific
* initialization for the tty structure.
*/
static void rs_poll(unsigned long);
static int rs_open(struct tty_struct *tty, struct file * filp)
{
tty->port = &serial_port;
spin_lock_bh(&timer_lock);
if (tty->count == 1) {
setup_timer(&serial_timer, rs_poll,
(unsigned long)&serial_port);
mod_timer(&serial_timer, jiffies + SERIAL_TIMER_VALUE);
}
spin_unlock_bh(&timer_lock);
return 0;
}
/*
* ------------------------------------------------------------
* iss_serial_close()
*
* This routine is called when the serial port gets closed. First, we
* wait for the last remaining data to be sent. Then, we unlink its
* async structure from the interrupt chain if necessary, and we free
* that IRQ if nothing is left in the chain.
* ------------------------------------------------------------
*/
static void rs_close(struct tty_struct *tty, struct file * filp)
{
spin_lock_bh(&timer_lock);
if (tty->count == 1)
del_timer_sync(&serial_timer);
spin_unlock_bh(&timer_lock);
}
static int rs_write(struct tty_struct * tty,
const unsigned char *buf, int count)
{
/* see drivers/char/serialX.c to reference original version */
simc_write(1, buf, count);
return count;
}
static void rs_poll(unsigned long priv)
{
struct tty_port *port = (struct tty_port *)priv;
int i = 0;
unsigned char c;
spin_lock(&timer_lock);
while (simc_poll(0)) {
simc_read(0, &c, 1);
tty_insert_flip_char(port, c, TTY_NORMAL);
i++;
}
if (i)
tty_flip_buffer_push(port);
mod_timer(&serial_timer, jiffies + SERIAL_TIMER_VALUE);
spin_unlock(&timer_lock);
}
static int rs_put_char(struct tty_struct *tty, unsigned char ch)
{
return rs_write(tty, &ch, 1);
}
static void rs_flush_chars(struct tty_struct *tty)
{
}
static int rs_write_room(struct tty_struct *tty)
{
/* Let's say iss can always accept 2K characters.. */
return 2 * 1024;
}
static int rs_chars_in_buffer(struct tty_struct *tty)
{
/* the iss doesn't buffer characters */
return 0;
}
static void rs_hangup(struct tty_struct *tty)
{
/* Stub, once again.. */
}
static void rs_wait_until_sent(struct tty_struct *tty, int timeout)
{
/* Stub, once again.. */
}
static int rs_proc_show(struct seq_file *m, void *v)
{
seq_printf(m, "serinfo:1.0 driver:%s\n", serial_version);
return 0;
}
static int rs_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, rs_proc_show, NULL);
}
static const struct file_operations rs_proc_fops = {
.owner = THIS_MODULE,
.open = rs_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static const struct tty_operations serial_ops = {
.open = rs_open,
.close = rs_close,
.write = rs_write,
.put_char = rs_put_char,
.flush_chars = rs_flush_chars,
.write_room = rs_write_room,
.chars_in_buffer = rs_chars_in_buffer,
.hangup = rs_hangup,
.wait_until_sent = rs_wait_until_sent,
.proc_fops = &rs_proc_fops,
};
int __init rs_init(void)
{
tty_port_init(&serial_port);
serial_driver = alloc_tty_driver(SERIAL_MAX_NUM_LINES);
printk ("%s %s\n", serial_name, serial_version);
/* Initialize the tty_driver structure */
serial_driver->driver_name = "iss_serial";
serial_driver->name = "ttyS";
serial_driver->major = TTY_MAJOR;
serial_driver->minor_start = 64;
serial_driver->type = TTY_DRIVER_TYPE_SERIAL;
serial_driver->subtype = SERIAL_TYPE_NORMAL;
serial_driver->init_termios = tty_std_termios;
serial_driver->init_termios.c_cflag =
B9600 | CS8 | CREAD | HUPCL | CLOCAL;
serial_driver->flags = TTY_DRIVER_REAL_RAW;
tty_set_operations(serial_driver, &serial_ops);
tty_port_link_device(&serial_port, serial_driver, 0);
if (tty_register_driver(serial_driver))
panic("Couldn't register serial driver\n");
return 0;
}
static __exit void rs_exit(void)
{
int error;
if ((error = tty_unregister_driver(serial_driver)))
printk("ISS_SERIAL: failed to unregister serial driver (%d)\n",
error);
put_tty_driver(serial_driver);
tty_port_destroy(&serial_port);
}
/* We use `late_initcall' instead of just `__initcall' as a workaround for
* the fact that (1) simcons_tty_init can't be called before tty_init,
* (2) tty_init is called via `module_init', (3) if statically linked,
* module_init == device_init, and (4) there's no ordering of init lists.
* We can do this easily because simcons is always statically linked, but
* other tty drivers that depend on tty_init and which must use
* `module_init' to declare their init routines are likely to be broken.
*/
late_initcall(rs_init);
#ifdef CONFIG_SERIAL_CONSOLE
static void iss_console_write(struct console *co, const char *s, unsigned count)
{
int len = strlen(s);
if (s != 0 && *s != 0)
simc_write(1, s, count < len ? count : len);
}
static struct tty_driver* iss_console_device(struct console *c, int *index)
{
*index = c->index;
return serial_driver;
}
static struct console sercons = {
.name = "ttyS",
.write = iss_console_write,
.device = iss_console_device,
.flags = CON_PRINTBUFFER,
.index = -1
};
static int __init iss_console_init(void)
{
register_console(&sercons);
return 0;
}
console_initcall(iss_console_init);
#endif /* CONFIG_SERIAL_CONSOLE */
| gpl-2.0 |
RadiumBot/Radium_jflte | drivers/mtd/mtdsuper.c | 5098 | 5583 | /* MTD-based superblock management
*
* Copyright © 2001-2007 Red Hat, Inc. All Rights Reserved.
* Copyright © 2001-2010 David Woodhouse <dwmw2@infradead.org>
*
* Written by: David Howells <dhowells@redhat.com>
* David Woodhouse <dwmw2@infradead.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/mtd/super.h>
#include <linux/namei.h>
#include <linux/export.h>
#include <linux/ctype.h>
#include <linux/slab.h>
/*
* compare superblocks to see if they're equivalent
* - they are if the underlying MTD device is the same
*/
static int get_sb_mtd_compare(struct super_block *sb, void *_mtd)
{
struct mtd_info *mtd = _mtd;
if (sb->s_mtd == mtd) {
pr_debug("MTDSB: Match on device %d (\"%s\")\n",
mtd->index, mtd->name);
return 1;
}
pr_debug("MTDSB: No match, device %d (\"%s\"), device %d (\"%s\")\n",
sb->s_mtd->index, sb->s_mtd->name, mtd->index, mtd->name);
return 0;
}
/*
* mark the superblock by the MTD device it is using
* - set the device number to be the correct MTD block device for pesuperstence
* of NFS exports
*/
static int get_sb_mtd_set(struct super_block *sb, void *_mtd)
{
struct mtd_info *mtd = _mtd;
sb->s_mtd = mtd;
sb->s_dev = MKDEV(MTD_BLOCK_MAJOR, mtd->index);
sb->s_bdi = mtd->backing_dev_info;
return 0;
}
/*
* get a superblock on an MTD-backed filesystem
*/
static struct dentry *mount_mtd_aux(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data,
struct mtd_info *mtd,
int (*fill_super)(struct super_block *, void *, int))
{
struct super_block *sb;
int ret;
sb = sget(fs_type, get_sb_mtd_compare, get_sb_mtd_set, mtd);
if (IS_ERR(sb))
goto out_error;
if (sb->s_root)
goto already_mounted;
/* fresh new superblock */
pr_debug("MTDSB: New superblock for device %d (\"%s\")\n",
mtd->index, mtd->name);
sb->s_flags = flags;
ret = fill_super(sb, data, flags & MS_SILENT ? 1 : 0);
if (ret < 0) {
deactivate_locked_super(sb);
return ERR_PTR(ret);
}
/* go */
sb->s_flags |= MS_ACTIVE;
return dget(sb->s_root);
/* new mountpoint for an already mounted superblock */
already_mounted:
pr_debug("MTDSB: Device %d (\"%s\") is already mounted\n",
mtd->index, mtd->name);
put_mtd_device(mtd);
return dget(sb->s_root);
out_error:
put_mtd_device(mtd);
return ERR_CAST(sb);
}
/*
* get a superblock on an MTD-backed filesystem by MTD device number
*/
static struct dentry *mount_mtd_nr(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data, int mtdnr,
int (*fill_super)(struct super_block *, void *, int))
{
struct mtd_info *mtd;
mtd = get_mtd_device(NULL, mtdnr);
if (IS_ERR(mtd)) {
pr_debug("MTDSB: Device #%u doesn't appear to exist\n", mtdnr);
return ERR_CAST(mtd);
}
return mount_mtd_aux(fs_type, flags, dev_name, data, mtd, fill_super);
}
/*
* set up an MTD-based superblock
*/
struct dentry *mount_mtd(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data,
int (*fill_super)(struct super_block *, void *, int))
{
#ifdef CONFIG_BLOCK
struct block_device *bdev;
int ret, major;
#endif
int mtdnr;
if (!dev_name)
return ERR_PTR(-EINVAL);
pr_debug("MTDSB: dev_name \"%s\"\n", dev_name);
/* the preferred way of mounting in future; especially when
* CONFIG_BLOCK=n - we specify the underlying MTD device by number or
* by name, so that we don't require block device support to be present
* in the kernel. */
if (dev_name[0] == 'm' && dev_name[1] == 't' && dev_name[2] == 'd') {
if (dev_name[3] == ':') {
struct mtd_info *mtd;
/* mount by MTD device name */
pr_debug("MTDSB: mtd:%%s, name \"%s\"\n",
dev_name + 4);
mtd = get_mtd_device_nm(dev_name + 4);
if (!IS_ERR(mtd))
return mount_mtd_aux(
fs_type, flags,
dev_name, data, mtd,
fill_super);
printk(KERN_NOTICE "MTD:"
" MTD device with name \"%s\" not found.\n",
dev_name + 4);
} else if (isdigit(dev_name[3])) {
/* mount by MTD device number name */
char *endptr;
mtdnr = simple_strtoul(dev_name + 3, &endptr, 0);
if (!*endptr) {
/* It was a valid number */
pr_debug("MTDSB: mtd%%d, mtdnr %d\n",
mtdnr);
return mount_mtd_nr(fs_type, flags,
dev_name, data,
mtdnr, fill_super);
}
}
}
#ifdef CONFIG_BLOCK
/* try the old way - the hack where we allowed users to mount
* /dev/mtdblock$(n) but didn't actually _use_ the blockdev
*/
bdev = lookup_bdev(dev_name);
if (IS_ERR(bdev)) {
ret = PTR_ERR(bdev);
pr_debug("MTDSB: lookup_bdev() returned %d\n", ret);
return ERR_PTR(ret);
}
pr_debug("MTDSB: lookup_bdev() returned 0\n");
ret = -EINVAL;
major = MAJOR(bdev->bd_dev);
mtdnr = MINOR(bdev->bd_dev);
bdput(bdev);
if (major != MTD_BLOCK_MAJOR)
goto not_an_MTD_device;
return mount_mtd_nr(fs_type, flags, dev_name, data, mtdnr, fill_super);
not_an_MTD_device:
#endif /* CONFIG_BLOCK */
if (!(flags & MS_SILENT))
printk(KERN_NOTICE
"MTD: Attempt to mount non-MTD device \"%s\"\n",
dev_name);
return ERR_PTR(-EINVAL);
}
EXPORT_SYMBOL_GPL(mount_mtd);
/*
* destroy an MTD-based superblock
*/
void kill_mtd_super(struct super_block *sb)
{
generic_shutdown_super(sb);
put_mtd_device(sb->s_mtd);
sb->s_mtd = NULL;
}
EXPORT_SYMBOL_GPL(kill_mtd_super);
| gpl-2.0 |
flar2/m7-GPE-4.4.3 | drivers/oprofile/timer_int.c | 7146 | 2604 | /**
* @file timer_int.c
*
* @remark Copyright 2002 OProfile authors
* @remark Read the file COPYING
*
* @author John Levon <levon@movementarian.org>
*/
#include <linux/kernel.h>
#include <linux/notifier.h>
#include <linux/smp.h>
#include <linux/oprofile.h>
#include <linux/profile.h>
#include <linux/init.h>
#include <linux/cpu.h>
#include <linux/hrtimer.h>
#include <asm/irq_regs.h>
#include <asm/ptrace.h>
#include "oprof.h"
static DEFINE_PER_CPU(struct hrtimer, oprofile_hrtimer);
static int ctr_running;
static enum hrtimer_restart oprofile_hrtimer_notify(struct hrtimer *hrtimer)
{
oprofile_add_sample(get_irq_regs(), 0);
hrtimer_forward_now(hrtimer, ns_to_ktime(TICK_NSEC));
return HRTIMER_RESTART;
}
static void __oprofile_hrtimer_start(void *unused)
{
struct hrtimer *hrtimer = &__get_cpu_var(oprofile_hrtimer);
if (!ctr_running)
return;
hrtimer_init(hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
hrtimer->function = oprofile_hrtimer_notify;
hrtimer_start(hrtimer, ns_to_ktime(TICK_NSEC),
HRTIMER_MODE_REL_PINNED);
}
static int oprofile_hrtimer_start(void)
{
get_online_cpus();
ctr_running = 1;
on_each_cpu(__oprofile_hrtimer_start, NULL, 1);
put_online_cpus();
return 0;
}
static void __oprofile_hrtimer_stop(int cpu)
{
struct hrtimer *hrtimer = &per_cpu(oprofile_hrtimer, cpu);
if (!ctr_running)
return;
hrtimer_cancel(hrtimer);
}
static void oprofile_hrtimer_stop(void)
{
int cpu;
get_online_cpus();
for_each_online_cpu(cpu)
__oprofile_hrtimer_stop(cpu);
ctr_running = 0;
put_online_cpus();
}
static int __cpuinit oprofile_cpu_notify(struct notifier_block *self,
unsigned long action, void *hcpu)
{
long cpu = (long) hcpu;
switch (action) {
case CPU_ONLINE:
case CPU_ONLINE_FROZEN:
smp_call_function_single(cpu, __oprofile_hrtimer_start,
NULL, 1);
break;
case CPU_DEAD:
case CPU_DEAD_FROZEN:
__oprofile_hrtimer_stop(cpu);
break;
}
return NOTIFY_OK;
}
static struct notifier_block __refdata oprofile_cpu_notifier = {
.notifier_call = oprofile_cpu_notify,
};
static int oprofile_hrtimer_setup(void)
{
return register_hotcpu_notifier(&oprofile_cpu_notifier);
}
static void oprofile_hrtimer_shutdown(void)
{
unregister_hotcpu_notifier(&oprofile_cpu_notifier);
}
int oprofile_timer_init(struct oprofile_operations *ops)
{
ops->create_files = NULL;
ops->setup = oprofile_hrtimer_setup;
ops->shutdown = oprofile_hrtimer_shutdown;
ops->start = oprofile_hrtimer_start;
ops->stop = oprofile_hrtimer_stop;
ops->cpu_type = "timer";
printk(KERN_INFO "oprofile: using timer interrupt.\n");
return 0;
}
| gpl-2.0 |
46890580/rk3188-kernel-3.0 | drivers/mtk_wcn_combo/drv_wlan/mt6620/wlan/mgmt/swcr.c | 235 | 45723 | /*
** $Id: //Department/DaVinci/BRANCHES/MT6620_WIFI_DRIVER_V2_3/mgmt/swcr.c#1 $
*/
/*! \file "swcr.c"
\brief
*/
/*
** $Log: swcr.c $
*
* 06 04 2012 tsaiyuan.hsu
* [WCXRP00001249] [ALPS.ICS] Daily build warning on "wlan/mgmt/swcr.c#1"
* resolve build waring for "WNM_UNIT_TEST not defined".
*
* 03 02 2012 terry.wu
* NULL
* Sync CFG80211 modification from branch 2,2.
*
* 01 05 2012 tsaiyuan.hsu
* [WCXRP00001157] [MT6620 Wi-Fi][FW][DRV] add timing measurement support for 802.11v
* add timing measurement support for 802.11v.
*
* 11 22 2011 tsaiyuan.hsu
* [WCXRP00001083] [MT6620 Wi-Fi][DRV]] dump debug counter or frames when debugging is triggered
* keep debug counter setting after wake up.
*
* 11 15 2011 cm.chang
* NULL
* Fix compiling warning
*
* 11 11 2011 tsaiyuan.hsu
* [WCXRP00001083] [MT6620 Wi-Fi][DRV]] dump debug counter or frames when debugging is triggered
* fix debug counters of rx in driver.
*
* 11 11 2011 tsaiyuan.hsu
* [WCXRP00001083] [MT6620 Wi-Fi][DRV]] dump debug counter or frames when debugging is triggered
* add debug counters of bb and ar for xlog.
*
* 11 10 2011 eddie.chen
* [WCXRP00001096] [MT6620 Wi-Fi][Driver/FW] Enhance the log function (xlog)
* Modify the QM xlog level and remove LOG_FUNC.
*
* 11 08 2011 tsaiyuan.hsu
* [WCXRP00001083] [MT6620 Wi-Fi][DRV]] dump debug counter or frames when debugging is triggered
* add debug counters, eCurPsProf, for PS.
*
* 11 07 2011 tsaiyuan.hsu
* [WCXRP00001083] [MT6620 Wi-Fi][DRV]] dump debug counter or frames when debugging is triggered
* add debug counters and periodically dump counters for debugging.
*
* 11 03 2011 wh.su
* [WCXRP00001078] [MT6620 Wi-Fi][Driver] Adding the mediatek log improment support : XLOG
* change the DBGLOG for "\n" and "\r\n". LABEL to LOUD for XLOG
*
* 08 31 2011 tsaiyuan.hsu
* [WCXRP00000931] [MT5931 Wi-Fi][DRV/FW] add swcr to disable roaming from driver
* remove obsolete code.
*
* 08 15 2011 tsaiyuan.hsu
* [WCXRP00000931] [MT5931 Wi-Fi][DRV/FW] add swcr to disable roaming from driver
* add swcr in driver reg, 0x9fxx0000, to disable roaming .
*
* 05 11 2011 eddie.chen
* [WCXRP00000709] [MT6620 Wi-Fi][Driver] Check free number before copying broadcast packet
* Fix dest type when GO packet copying.
*
* 05 09 2011 eddie.chen
* [WCXRP00000709] [MT6620 Wi-Fi][Driver] Check free number before copying broadcast packet
* Check free number before copying broadcast packet.
*
* 04 14 2011 eddie.chen
* [WCXRP00000603] [MT6620 Wi-Fi][DRV] Fix Klocwork warning
* Check the SW RFB free. Fix the compile warning..
*
* 04 12 2011 eddie.chen
* [WCXRP00000617] [MT6620 Wi-Fi][DRV/FW] Fix for sigma
* Fix the sta index in processing security frame
* Simple flow control for TC4 to avoid mgt frames for PS STA to occupy the TC4
* Add debug message.
*
* 03 28 2011 eddie.chen
* [WCXRP00000603] [MT6620 Wi-Fi][DRV] Fix Klocwork warning
* Fix Klockwork warning.
*
* 03 15 2011 eddie.chen
* [WCXRP00000554] [MT6620 Wi-Fi][DRV] Add sw control debug counter
* Add sw debug counter for QM.
*
* 01 11 2011 eddie.chen
* [WCXRP00000322] Add WMM IE in beacon,
Add per station flow control when STA is in PS
* Add swcr for test.
*
*
*/
/*******************************************************************************
* C O M P I L E R F L A G S
********************************************************************************
*/
/*******************************************************************************
* E X T E R N A L R E F E R E N C E S
********************************************************************************
*/
#include "precomp.h"
#if CFG_SUPPORT_SWCR
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wformat"
#endif
/*******************************************************************************
* D A T A T Y P E S
********************************************************************************
*/
/*******************************************************************************
* P U B L I C D A T A
********************************************************************************
*/
#if 0
extern SWCR_MAP_ENTRY_T g_arRlmArSwCrMap[];
SWCR_MOD_MAP_ENTRY_T g_arSwCrAllMaps[] = {
{ SWCR_MAP_NUM(g_arRlmArSwCrMap), g_arRlmArSwCrMap}, /* 0x00nn */
{0,NULL}
};
#endif
VOID swCtrlCmdCategory0(P_ADAPTER_T prAdapter, UINT_8 ucCate, UINT_8 ucAction, UINT_8 ucOpt0,UINT_8 ucOpt1);
VOID swCtrlCmdCategory1(P_ADAPTER_T prAdapter, UINT_8 ucCate, UINT_8 ucAction, UINT_8 ucOpt0,UINT_8 ucOpt1);
VOID testPsCmdCategory0(P_ADAPTER_T prAdapter, UINT_8 ucCate, UINT_8 ucAction, UINT_8 ucOpt0,UINT_8 ucOpt1);
VOID testPsCmdCategory1(P_ADAPTER_T prAdapter, UINT_8 ucCate, UINT_8 ucAction, UINT_8 ucOpt0,UINT_8 ucOpt1);
void testWNMCmdCategory0(P_ADAPTER_T prAdapter, UINT_8 ucCate, UINT_8 ucAction, UINT_8 ucOpt0,UINT_8 ucOpt1);
VOID swCtrlSwCr(P_ADAPTER_T prAdapter, UINT_8 ucRead, UINT_16 u2Addr, UINT_32 *pu4Data);
/* Support Debug */
VOID swCrDebugCheck(P_ADAPTER_T prAdapter, P_CMD_SW_DBG_CTRL_T prCmdSwCtrl);
VOID swCrDebugCheckTimeout(
IN P_ADAPTER_T prAdapter,
UINT_32 u4Param);
VOID swCrDebugQuery(
IN P_ADAPTER_T prAdapter,
IN P_CMD_INFO_T prCmdInfo,
IN PUINT_8 pucEventBuf
);
VOID swCrDebugQueryTimeout(
IN P_ADAPTER_T prAdapter,
IN P_CMD_INFO_T prCmdInfo);
UINT_32 g_au4SwCr[SWCR_CR_NUM]; /*: 0: command other: data */
/* JB mDNS Filter*/
UINT_32 g_u4mDNSRXFilter = 0; /* [31] 0: stop 1: start, [3] IPv6 [2] IPv4*/
static TIMER_T g_rSwcrDebugTimer;
static BOOLEAN g_fgSwcrDebugTimer = FALSE;
static UINT_32 g_u4SwcrDebugCheckTimeout = 0;
static ENUM_SWCR_DBG_TYPE_T g_ucSwcrDebugCheckType = 0;
static UINT_32 g_u4SwcrDebugFrameDumpType = 0;
/*******************************************************************************
* P R I V A T E D A T A
********************************************************************************
*/
#define TEST_PS 1
const static PFN_CMD_RW_T g_arSwCtrlCmd[] ={
swCtrlCmdCategory0,
swCtrlCmdCategory1
#if TEST_PS
, testPsCmdCategory0
, testPsCmdCategory1
#endif
#if CFG_SUPPORT_802_11V
#if (CFG_SUPPORT_802_11V_TIMING_MEASUREMENT ==1) && (WNM_UNIT_TEST ==1)
, testWNMCmdCategory0
#endif
#endif
};
const PFN_SWCR_RW_T g_arSwCrModHandle[] = {
swCtrlSwCr,
NULL
};
/*******************************************************************************
* M A C R O S
********************************************************************************
*/
enum {
SWCTRL_MAGIC,
SWCTRL_DEBUG,
SWCTRL_WIFI_VAR,
SWCTRL_ENABLE_INT,
SWCTRL_DISABLE_INT,
SWCTRL_TXM_INFO,
SWCTRL_RXM_INFO,
SWCTRL_DUMP_BSS,
SWCTRL_QM_INFO,
SWCTRL_DUMP_ALL_QUEUE_LEN,
SWCTRL_DUMP_MEM,
SWCTRL_TX_CTRL_INFO,
SWCTRL_DUMP_QUEUE,
SWCTRL_DUMP_QM_DBG_CNT,
SWCTRL_QM_DBG_CNT,
SWCTRL_RX_PKTS_DUMP,
SWCTRL_RX_MDNS_FILTER,
SWCTRL_CATA0_INDEX_NUM
};
enum {
SWCTRL_STA_INFO,
SWCTRL_DUMP_STA,
SWCTRL_STA_QUE_INFO,
SWCTRL_CATA1_INDEX_NUM
};
/* JB mDNS Filter*/
#define RX_MDNS_FILTER_START (1<<31)
#define RX_MDNS_FILTER_IPV4 (1<<2)
#define RX_MDNS_FILTER_IPV6 (1<<3)
typedef enum _ENUM_SWCR_RX_MDNS_FILTER_CMD_T {
SWCR_RX_MDNS_FILTER_CMD_STOP = 0,
SWCR_RX_MDNS_FILTER_CMD_START,
SWCR_RX_MDNS_FILTER_CMD_ADD,
SWCR_RX_MDNS_FILTER_CMD_REMOVE,
SWCR_RX_MDNS_FILTER_NUM
} ENUM_SWCR_RX_MDNS_FILTER_CMD_T;
#if TEST_PS
enum {
TEST_PS_MAGIC,
TEST_PS_SETUP_BSS,
TEST_PS_ENABLE_BEACON,
TEST_PS_TRIGGER_BMC,
TEST_PS_SEND_NULL,
TEST_PS_BUFFER_BMC,
TEST_PS_UPDATE_BEACON,
TEST_PS_CATA0_INDEX_NUM
};
enum {
TEST_PS_STA_PS,
TEST_PS_STA_ENTER_PS,
TEST_PS_STA_EXIT_PS,
TEST_PS_STA_TRIGGER_PSPOLL,
TEST_PS_STA_TRIGGER_FRAME,
TEST_PS_CATA1_INDEX_NUM
};
#endif
#if CFG_SUPPORT_802_11V
#if WNM_UNIT_TEST
enum {
TEST_WNM_TIMING_MEAS,
TEST_WNM_CATA0_INDEX_NUM
};
#endif
#endif
#define _SWCTRL_MAGIC 0x66201642
/*******************************************************************************
* F U N C T I O N D E C L A R A T I O N S
********************************************************************************
*/
/*******************************************************************************
* F U N C T I O N S
********************************************************************************
*/
void dumpQueue(P_ADAPTER_T prAdapter)
{
P_TX_CTRL_T prTxCtrl;
P_QUE_MGT_T prQM;
P_GLUE_INFO_T prGlueInfo;
UINT_32 i;
UINT_32 j;
DEBUGFUNC("dumpQueue");
prTxCtrl = &prAdapter->rTxCtrl;
prQM = &prAdapter->rQM;
prGlueInfo = prAdapter->prGlueInfo;
for(i = TC0_INDEX; i<=TC5_INDEX; i++) {
DBGLOG(SW4, INFO,( "TC %u\n",i));
DBGLOG(SW4, INFO,( "Max %u Free %u\n",
prTxCtrl->rTc.aucMaxNumOfBuffer[i], prTxCtrl->rTc.aucFreeBufferCount[i]));
DBGLOG(SW4, INFO,("Average %u minReserved %u CurrentTcResource %u GuaranteedTcResource %u\n",
QM_GET_TX_QUEUE_LEN(prAdapter, i),
prQM->au4MinReservedTcResource[i],
prQM->au4CurrentTcResource[i],
prQM->au4GuaranteedTcResource[i]));
}
for(i = 0; i<NUM_OF_PER_STA_TX_QUEUES; i++) {
DBGLOG(SW4, INFO,( "TC %u HeadStaIdx %u ForwardCount %u\n",i, prQM->au4HeadStaRecIndex[i],prQM->au4ForwardCount[i]));
}
DBGLOG(SW4, INFO,( "BMC or unknown TxQueue Len %u\n",prQM->arTxQueue[0].u4NumElem));
DBGLOG(SW4, INFO,( "Pending %d\n",prGlueInfo->i4TxPendingFrameNum));
DBGLOG(SW4, INFO,( "Pending Security %d\n",prGlueInfo->i4TxPendingSecurityFrameNum));
#if defined(LINUX)
for(i=0;i<4;i++){
for(j=0;j<CFG_MAX_TXQ_NUM;j++){
DBGLOG(SW4, INFO,( "Pending Q[%u][%u] %d\n",i,j,prGlueInfo->ai4TxPendingFrameNumPerQueue[i][j]));
}
}
#endif
DBGLOG(SW4, INFO,( " rFreeSwRfbList %u\n", prAdapter->rRxCtrl.rFreeSwRfbList.u4NumElem));
DBGLOG(SW4, INFO,( " rReceivedRfbList %u\n", prAdapter->rRxCtrl.rReceivedRfbList.u4NumElem));
DBGLOG(SW4, INFO,( " rIndicatedRfbList %u\n", prAdapter->rRxCtrl.rIndicatedRfbList.u4NumElem));
DBGLOG(SW4, INFO,( " ucNumIndPacket %u\n", prAdapter->rRxCtrl.ucNumIndPacket));
DBGLOG(SW4, INFO,( " ucNumRetainedPacket %u\n", prAdapter->rRxCtrl.ucNumRetainedPacket));
}
void dumpSTA(P_ADAPTER_T prAdapter, P_STA_RECORD_T prStaRec)
{
UINT_8 ucWTEntry;
UINT_32 i;
P_BSS_INFO_T prBssInfo;
DEBUGFUNC("dumpSTA");
ASSERT(prStaRec);
ucWTEntry = prStaRec->ucWTEntry;
prBssInfo = &prAdapter->rWifiVar.arBssInfo[prStaRec->ucNetTypeIndex];
ASSERT(prBssInfo);
DBGLOG(SW4, INFO,("Mac address: " MACSTR " Rcpi %u" "\n", MAC2STR(prStaRec->aucMacAddr),prStaRec->ucRCPI));
DBGLOG(SW4, INFO,("Idx %u Wtbl %u Used %u State %u Bss Phy 0x%x Sta DesiredPhy 0x%x\n",
prStaRec->ucIndex, ucWTEntry,
prStaRec->fgIsInUse,prStaRec->ucStaState,
prBssInfo->ucPhyTypeSet,
prStaRec->ucDesiredPhyTypeSet));
DBGLOG(SW4, INFO,("Sta Operation 0x%x DesiredNontHtRateSet 0x%x Mcs 0x%x u2HtCapInfo 0x%x\n",
prStaRec->u2OperationalRateSet,prStaRec->u2DesiredNonHTRateSet,prStaRec->ucMcsSet, prStaRec->u2HtCapInfo));
for(i = 0; i<NUM_OF_PER_STA_TX_QUEUES; i++) {
DBGLOG(SW4, INFO,( "TC %u Queue Len %u\n",i,prStaRec->arTxQueue[i].u4NumElem));
}
DBGLOG(SW4, INFO, ("BmpDeliveryAC %x\n",prStaRec->ucBmpDeliveryAC));
DBGLOG(SW4, INFO, ("BmpTriggerAC %x\n",prStaRec->ucBmpTriggerAC));
DBGLOG(SW4, INFO, ("UapsdSpSupproted %u\n",prStaRec->fgIsUapsdSupported));
DBGLOG(SW4, INFO, ("IsQoS %u\n",prStaRec->fgIsQoS));
DBGLOG(SW4, INFO, ("AssocId %u\n",prStaRec->u2AssocId));
DBGLOG(SW4, INFO, ("fgIsInPS %u\n",prStaRec->fgIsInPS));
DBGLOG(SW4, INFO, ("ucFreeQuota %u\n",prStaRec->ucFreeQuota));
DBGLOG(SW4, INFO, ("ucFreeQuotaForDelivery %u\n",prStaRec->ucFreeQuotaForDelivery));
DBGLOG(SW4, INFO, ("ucFreeQuotaForNonDelivery %u\n",prStaRec->ucFreeQuotaForNonDelivery));
#if 0
DBGLOG(SW4, INFO, ("IsQmmSup %u\n",prStaRec->fgIsWmmSupported));
DBGLOG(SW4, INFO, ("IsUapsdSup %u\n",prStaRec->fgIsUapsdSupported));
DBGLOG(SW4, INFO, ("AvailabaleDeliverPkts %u\n",prStaRec->ucAvailableDeliverPkts));
DBGLOG(SW4, INFO, ("BmpDeliverPktsAC %u\n",prStaRec->u4BmpDeliverPktsAC));
DBGLOG(SW4, INFO, ("BmpBufferAC %u\n",prStaRec->u4BmpBufferAC));
DBGLOG(SW4, INFO, ("BmpNonDeliverPktsAC %u\n",prStaRec->u4BmpNonDeliverPktsAC));
#endif
for(i=0;i<CFG_RX_MAX_BA_TID_NUM;i++) {
if(prStaRec->aprRxReorderParamRefTbl[i]){
DBGLOG(SW4, INFO,("RxReorder fgIsValid: %u\n",prStaRec->aprRxReorderParamRefTbl[i]->fgIsValid));
DBGLOG(SW4, INFO,("RxReorder Tid: %u\n",prStaRec->aprRxReorderParamRefTbl[i]->ucTid));
DBGLOG(SW4, INFO,("RxReorder rReOrderQue Len: %u\n", prStaRec->aprRxReorderParamRefTbl[i]->rReOrderQue.u4NumElem));
DBGLOG(SW4, INFO,("RxReorder WinStart: %u\n", prStaRec->aprRxReorderParamRefTbl[i]->u2WinStart));
DBGLOG(SW4, INFO,("RxReorder WinEnd: %u\n", prStaRec->aprRxReorderParamRefTbl[i]->u2WinEnd));
DBGLOG(SW4, INFO,("RxReorder WinSize: %u\n", prStaRec->aprRxReorderParamRefTbl[i]->u2WinSize));
}
}
}
VOID dumpBss(P_ADAPTER_T prAdapter, P_BSS_INFO_T prBssInfo)
{
DBGLOG(SW4, INFO, ("SSID %s\n",prBssInfo->aucSSID));
DBGLOG(SW4, INFO, ("OWN " MACSTR"\n",MAC2STR(prBssInfo->aucOwnMacAddr)));
DBGLOG(SW4, INFO, ("BSSID " MACSTR"\n",MAC2STR(prBssInfo->aucBSSID)));
DBGLOG(SW4, INFO, ("ucNetTypeIndex %u\n",prBssInfo->ucNetTypeIndex));
DBGLOG(SW4, INFO, ("eConnectionState %u\n",prBssInfo->eConnectionState));
DBGLOG(SW4, INFO, ("eCurrentOPMode %u\n",prBssInfo->eCurrentOPMode));
DBGLOG(SW4, INFO, ("fgIsQBSS %u\n",prBssInfo->fgIsQBSS));
DBGLOG(SW4, INFO, ("fgIsShortPreambleAllowed %u\n",prBssInfo->fgIsShortPreambleAllowed));
DBGLOG(SW4, INFO, ("fgUseShortPreamble %u\n",prBssInfo->fgUseShortPreamble));
DBGLOG(SW4, INFO, ("fgUseShortSlotTime %u\n",prBssInfo->fgUseShortSlotTime));
DBGLOG(SW4, INFO, ("ucNonHTBasicPhyType %x\n",prBssInfo->ucNonHTBasicPhyType));
DBGLOG(SW4, INFO, ("u2OperationalRateSet %x\n",prBssInfo->u2OperationalRateSet));
DBGLOG(SW4, INFO, ("u2BSSBasicRateSet %x\n",prBssInfo->u2BSSBasicRateSet));
DBGLOG(SW4, INFO, ("ucPhyTypeSet %x\n",prBssInfo->ucPhyTypeSet));
DBGLOG(SW4, INFO, ("rStaRecOfClientList %d\n",prBssInfo->rStaRecOfClientList.u4NumElem));
DBGLOG(SW4, INFO, ("u2CapInfo %x\n",prBssInfo->u2CapInfo));
DBGLOG(SW4, INFO, ("u2ATIMWindow %x\n",prBssInfo->u2ATIMWindow));
DBGLOG(SW4, INFO, ("u2AssocId %x\n",prBssInfo->u2AssocId));
DBGLOG(SW4, INFO, ("ucDTIMPeriod %x\n",prBssInfo->ucDTIMPeriod));
DBGLOG(SW4, INFO, ("ucDTIMCount %x\n",prBssInfo->ucDTIMCount));
DBGLOG(SW4, INFO, ("fgIsNetAbsent %x\n", prBssInfo->fgIsNetAbsent));
DBGLOG(SW4, INFO, ("eBand %d\n", prBssInfo->eBand));
DBGLOG(SW4, INFO, ("ucPrimaryChannel %d\n", prBssInfo->ucPrimaryChannel));
DBGLOG(SW4, INFO, ("ucHtOpInfo1 %d\n", prBssInfo->ucHtOpInfo1));
DBGLOG(SW4, INFO, ("ucHtOpInfo2 %d\n", prBssInfo->u2HtOpInfo2));
DBGLOG(SW4, INFO, ("ucHtOpInfo3 %d\n", prBssInfo->u2HtOpInfo3));
DBGLOG(SW4, INFO, ("fgErpProtectMode %d\n", prBssInfo->fgErpProtectMode));
DBGLOG(SW4, INFO, ("eHtProtectMode %d\n", prBssInfo->eHtProtectMode));
DBGLOG(SW4, INFO, ("eGfOperationMode %d\n", prBssInfo->eGfOperationMode));
DBGLOG(SW4, INFO, ("eRifsOperationMode %d\n", prBssInfo->eRifsOperationMode));
DBGLOG(SW4, INFO, ("fgObssErpProtectMode %d\n", prBssInfo->fgObssErpProtectMode));
DBGLOG(SW4, INFO, ("eObssHtProtectMode %d\n", prBssInfo->eObssHtProtectMode));
DBGLOG(SW4, INFO, ("eObssGfProtectMode %d\n", prBssInfo->eObssGfOperationMode));
DBGLOG(SW4, INFO, ("fgObssRifsOperationMode %d\n", prBssInfo->fgObssRifsOperationMode));
DBGLOG(SW4, INFO, ("fgAssoc40mBwAllowed %d\n", prBssInfo->fgAssoc40mBwAllowed));
DBGLOG(SW4, INFO, ("fg40mBwAllowed %d\n", prBssInfo->fg40mBwAllowed));
DBGLOG(SW4, INFO, ("eBssSCO %d\n", prBssInfo->eBssSCO));
}
VOID swCtrlCmdCategory0(P_ADAPTER_T prAdapter, UINT_8 ucCate, UINT_8 ucAction, UINT_8 ucOpt0,UINT_8 ucOpt1)
{
UINT_8 ucIndex,ucRead;
UINT_32 i;
DEBUGFUNC("swCtrlCmdCategory0");
SWCR_GET_RW_INDEX(ucAction,ucRead,ucIndex);
i=0;
if(ucIndex>=SWCTRL_CATA0_INDEX_NUM) return;
if(ucRead == SWCR_WRITE) {
switch(ucIndex) {
case SWCTRL_DEBUG:
#if DBG
aucDebugModule[ucOpt0] = (UINT_8)g_au4SwCr[1];
#endif
break;
case SWCTRL_WIFI_VAR:
break;
#if QM_DEBUG_COUNTER
case SWCTRL_DUMP_QM_DBG_CNT:
for(i=0;i<QM_DBG_CNT_NUM;i++) {
prAdapter->rQM.au4QmDebugCounters[i] = 0;
}
break;
case SWCTRL_QM_DBG_CNT:
prAdapter->rQM.au4QmDebugCounters[ucOpt0] = g_au4SwCr[1];
break;
#endif
#if CFG_RX_PKTS_DUMP
case SWCTRL_RX_PKTS_DUMP:
//DBGLOG(SW4, INFO,("SWCTRL_RX_PKTS_DUMP: mask %x\n", g_au4SwCr[1]));
prAdapter->rRxCtrl.u4RxPktsDumpTypeMask = g_au4SwCr[1];
break;
#endif
case SWCTRL_RX_MDNS_FILTER:
{
UINT_32 u4rxfilter;
BOOLEAN fgUpdate = FALSE;
WLAN_STATUS rStatus = WLAN_STATUS_SUCCESS;
if (ucOpt0 == SWCR_RX_MDNS_FILTER_CMD_STOP) {
g_u4mDNSRXFilter &= ~(RX_MDNS_FILTER_START);
u4rxfilter = prAdapter->u4OsPacketFilter;
fgUpdate = TRUE;
}
else if (ucOpt0 == SWCR_RX_MDNS_FILTER_CMD_START) {
g_u4mDNSRXFilter |= (RX_MDNS_FILTER_START);
u4rxfilter = prAdapter->u4OsPacketFilter;
if ((g_u4mDNSRXFilter & RX_MDNS_FILTER_IPV4) &&
(g_u4mDNSRXFilter & RX_MDNS_FILTER_IPV6)) {
u4rxfilter &= ~(PARAM_PACKET_FILTER_ALL_MULTICAST|
PARAM_PACKET_FILTER_MULTICAST);
}
else {
u4rxfilter |= PARAM_PACKET_FILTER_ALL_MULTICAST;
}
fgUpdate = TRUE;
}
else if (ucOpt0 == SWCR_RX_MDNS_FILTER_CMD_ADD) {
if (ucOpt1 < 31) {
g_u4mDNSRXFilter |= (1<<ucOpt1);
}
}
else if (ucOpt0 == SWCR_RX_MDNS_FILTER_CMD_REMOVE) {
if (ucOpt1 < 31) {
g_u4mDNSRXFilter &= ~(1<<ucOpt1);
}
}
if (fgUpdate == TRUE) {
rStatus = wlanSendSetQueryCmd (
prAdapter, /* prAdapter */
CMD_ID_SET_RX_FILTER, /* ucCID */
TRUE, /* fgSetQuery */
FALSE, /* fgNeedResp */
FALSE, /* fgIsOid */
NULL, /* pfCmdDoneHandler */
NULL, /* pfCmdTimeoutHandler */
sizeof(UINT_32), /* u4SetQueryInfoLen */
(PUINT_8) &u4rxfilter, /* pucInfoBuffer */
NULL, /* pvSetQueryBuffer */
0 /* un4SetQueryBufferLen */
);
}
//DBGLOG(SW4, INFO,("SWCTRL_RX_MDNS_FILTER: g_u4mDNSRXFilter %x ucOpt0 %x ucOpt1 %x fgUpdate %x u4rxfilter %x, rStatus %x\n",
// g_u4mDNSRXFilter, ucOpt0, ucOpt1, fgUpdate, u4rxfilter, rStatus));
}
break;
default:
break;
}
}
else {
switch(ucIndex) {
case SWCTRL_DEBUG:
#if DBG
g_au4SwCr[1] = aucDebugModule[ucOpt0] ;
#endif
break;
case SWCTRL_MAGIC:
g_au4SwCr[1] = _SWCTRL_MAGIC ;
DBGLOG(SW4, INFO,("BUILD TIME: %s %s\n", __DATE__, __TIME__));
break;
case SWCTRL_QM_INFO:
{
P_QUE_MGT_T prQM = &prAdapter->rQM;
switch(ucOpt0) {
case 0:
g_au4SwCr[1] = (QM_GET_TX_QUEUE_LEN(prAdapter, ucOpt1)) ;
g_au4SwCr[2] = prQM->au4MinReservedTcResource[ucOpt1] ;
g_au4SwCr[3] = prQM->au4CurrentTcResource[ucOpt1];
g_au4SwCr[4] = prQM->au4GuaranteedTcResource[ucOpt1];
break;
case 1:
g_au4SwCr[1] = prQM->au4ForwardCount[ucOpt1];
g_au4SwCr[2] = prQM->au4HeadStaRecIndex[ucOpt1];
break;
case 2:
g_au4SwCr[1] = prQM->arTxQueue[ucOpt1].u4NumElem; /* only one */
break;
}
}
case SWCTRL_TX_CTRL_INFO:
{
P_TX_CTRL_T prTxCtrl;
prTxCtrl = &prAdapter->rTxCtrl;
switch(ucOpt0) {
case 0:
g_au4SwCr[1] = prAdapter->rTxCtrl.rTc.aucFreeBufferCount[ucOpt1];
g_au4SwCr[2] = prAdapter->rTxCtrl.rTc.aucMaxNumOfBuffer[ucOpt1];
break;
}
}
break;
case SWCTRL_DUMP_QUEUE:
dumpQueue(prAdapter);
break;
#if QM_DEBUG_COUNTER
case SWCTRL_DUMP_QM_DBG_CNT:
for(i=0;i<QM_DBG_CNT_NUM;i++) {
DBGLOG(SW4, INFO,("QM:DBG %u %u\n",i , prAdapter->rQM.au4QmDebugCounters[i]));
}
break;
case SWCTRL_QM_DBG_CNT:
g_au4SwCr[1] = prAdapter->rQM.au4QmDebugCounters[ucOpt0];
break;
#endif
case SWCTRL_DUMP_BSS:
{
dumpBss(prAdapter, &(prAdapter->rWifiVar.arBssInfo[ucOpt0])) ;
}
break;
default:
break;
}
}
}
VOID swCtrlCmdCategory1(P_ADAPTER_T prAdapter, UINT_8 ucCate, UINT_8 ucAction, UINT_8 ucOpt0,UINT_8 ucOpt1)
{
UINT_8 ucIndex,ucRead;
UINT_8 ucWTEntry;
P_STA_RECORD_T prStaRec;
DEBUGFUNC("swCtrlCmdCategory1");
SWCR_GET_RW_INDEX(ucAction,ucRead,ucIndex);
if(ucOpt0>=CFG_STA_REC_NUM) return;
//prStaRec = cnmGetStaRecByIndex (prAdapter, ucOpt0);
prStaRec = &prAdapter->arStaRec[ucOpt0];
ucWTEntry = prStaRec->ucWTEntry;
if(ucRead == SWCR_WRITE) {
}
else {
/* Read */
switch(ucIndex) {
case SWCTRL_STA_QUE_INFO:
{
g_au4SwCr[1] = prStaRec->arTxQueue[ucOpt1].u4NumElem;
}
break;
case SWCTRL_STA_INFO:
switch(ucOpt1) {
case 0:
g_au4SwCr[1] = prStaRec->fgIsInPS;
break;
}
break;
case SWCTRL_DUMP_STA:
{
dumpSTA(prAdapter, prStaRec);
}
break;
default:
break;
}
}
}
#if TEST_PS
VOID
testPsSendQoSNullFrame (
IN P_ADAPTER_T prAdapter,
IN P_STA_RECORD_T prStaRec,
IN UINT_8 ucUP,
IN UINT_8 ucNetTypeIndex,
IN BOOLEAN fgBMC,
IN BOOLEAN fgIsBurstEnd,
IN BOOLEAN ucPacketType,
IN BOOLEAN ucPsSessionID,
IN BOOLEAN fgSetEOSP
)
{
P_MSDU_INFO_T prMsduInfo;
UINT_16 u2EstimatedFrameLen;
P_WLAN_MAC_HEADER_QOS_T prQoSNullFrame;
DEBUGFUNC("testPsSendQoSNullFrame");
DBGLOG(SW4, LOUD, ("\n"));
//4 <1> Allocate a PKT_INFO_T for Null Frame
/* Init with MGMT Header Length */
u2EstimatedFrameLen = MAC_TX_RESERVED_FIELD + \
WLAN_MAC_HEADER_QOS_LEN;
/* Allocate a MSDU_INFO_T */
if ( (prMsduInfo = cnmMgtPktAlloc(prAdapter, u2EstimatedFrameLen)) == NULL) {
DBGLOG(SW4, WARN, ("No PKT_INFO_T for sending Null Frame.\n"));
return ;
}
//4 <2> Compose Null frame in MSDU_INfO_T.
bssComposeQoSNullFrame(prAdapter,
(PUINT_8)((UINT_32)(prMsduInfo->prPacket) + MAC_TX_RESERVED_FIELD),
prStaRec,
ucUP,
fgSetEOSP);
prMsduInfo->eSrc = TX_PACKET_MGMT;
//prMsduInfo->ucPacketType = HIF_TX_PACKET_TYPE_DATA;
prMsduInfo->ucPacketType = ucPacketType;
prMsduInfo->ucStaRecIndex = prStaRec->ucIndex;
prMsduInfo->ucNetworkType = ucNetTypeIndex;
prMsduInfo->ucMacHeaderLength = WLAN_MAC_HEADER_QOS_LEN;
prMsduInfo->fgIs802_1x = FALSE;
prMsduInfo->fgIs802_11 = TRUE;
prMsduInfo->u2FrameLength = WLAN_MAC_HEADER_QOS_LEN;
prMsduInfo->ucTxSeqNum = nicIncreaseTxSeqNum(prAdapter);
prMsduInfo->pfTxDoneHandler = NULL;
prMsduInfo->fgIsBasicRate = TRUE;
prMsduInfo->fgIsBurstEnd = fgIsBurstEnd;
prMsduInfo->ucUserPriority = ucUP;
prMsduInfo->ucPsSessionID = ucPsSessionID /* 0~7 Test 7 means NOACK*/;
prQoSNullFrame = (P_WLAN_MAC_HEADER_QOS_T)( (PUINT_8)((UINT_32)(prMsduInfo->prPacket) + MAC_TX_RESERVED_FIELD) );
if(fgBMC) {
prQoSNullFrame->aucAddr1[0] = 0xfd;
}
else {
prQoSNullFrame->aucAddr1[5] = 0xdd;
}
//4 <4> Inform TXM to send this Null frame.
nicTxEnqueueMsdu(prAdapter, prMsduInfo);
}
VOID
testPsSetupBss(
IN P_ADAPTER_T prAdapter,
IN UINT_8 ucNetworkTypeIndex
)
{
P_BSS_INFO_T prBssInfo;
UINT_8 _aucZeroMacAddr[] = NULL_MAC_ADDR;
DEBUGFUNC("testPsSetupBss()");
DBGLOG(SW4, INFO, ("index %d\n", ucNetworkTypeIndex));
prBssInfo = &(prAdapter->rWifiVar.arBssInfo[ucNetworkTypeIndex]);
//4 <1.2> Initiate PWR STATE
//SET_NET_PWR_STATE_IDLE(prAdapter, ucNetworkTypeIndex);
//4 <2> Initiate BSS_INFO_T - common part
BSS_INFO_INIT(prAdapter, ucNetworkTypeIndex);
prBssInfo->eConnectionState = PARAM_MEDIA_STATE_DISCONNECTED;
prBssInfo->eConnectionStateIndicated = PARAM_MEDIA_STATE_DISCONNECTED;
prBssInfo->eCurrentOPMode = OP_MODE_ACCESS_POINT;
prBssInfo->fgIsNetActive = TRUE;
prBssInfo->ucNetTypeIndex = (ucNetworkTypeIndex);
prBssInfo->ucReasonOfDisconnect = DISCONNECT_REASON_CODE_RESERVED;
prBssInfo->ucPhyTypeSet = PHY_TYPE_SET_802_11BG; /* Depend on eBand */
prBssInfo->ucConfigAdHocAPMode = AP_MODE_MIXED_11BG; /* Depend on eCurrentOPMode and ucPhyTypeSet */
prBssInfo->u2BSSBasicRateSet = RATE_SET_ERP;
prBssInfo->u2OperationalRateSet = RATE_SET_OFDM;
prBssInfo->fgErpProtectMode = FALSE;
prBssInfo->fgIsQBSS = TRUE;
//4 <1.5> Setup MIB for current BSS
prBssInfo->u2BeaconInterval = 100;
prBssInfo->ucDTIMPeriod = DOT11_DTIM_PERIOD_DEFAULT;
prBssInfo->u2ATIMWindow = 0;
prBssInfo->ucBeaconTimeoutCount = 0;
bssInitForAP (prAdapter,prBssInfo, TRUE);
COPY_MAC_ADDR(prBssInfo->aucBSSID, _aucZeroMacAddr);
LINK_INITIALIZE(&prBssInfo->rStaRecOfClientList);
prBssInfo->fgIsBeaconActivated = TRUE;
prBssInfo->ucHwDefaultFixedRateCode = RATE_CCK_1M_LONG;
COPY_MAC_ADDR(prBssInfo->aucOwnMacAddr, prAdapter->rWifiVar.aucMacAddress);
//4 <3> Initiate BSS_INFO_T - private part
/* TODO */
prBssInfo->eBand = BAND_2G4;
prBssInfo->ucPrimaryChannel = 1;
prBssInfo->prStaRecOfAP = (P_STA_RECORD_T)NULL;
//prBssInfo->fgErpProtectMode = eErpProectMode;
//prBssInfo->eHtProtectMode = eHtProtectMode;
//prBssInfo->eGfOperationMode = eGfOperationMode;
//4 <4> Allocate MSDU_INFO_T for Beacon
prBssInfo->prBeacon = cnmMgtPktAlloc(prAdapter,
OFFSET_OF(WLAN_BEACON_FRAME_T, aucInfoElem[0]) + MAX_IE_LENGTH);
if (prBssInfo->prBeacon) {
prBssInfo->prBeacon->eSrc = TX_PACKET_MGMT;
prBssInfo->prBeacon->ucNetworkType = ucNetworkTypeIndex;
}
else {
DBGLOG(SW4, INFO, ("prBeacon allocation fail\n"));
}
#if 0
prBssInfo->rPmProfSetupInfo.ucBmpDeliveryAC = PM_UAPSD_ALL;
prBssInfo->rPmProfSetupInfo.ucBmpTriggerAC = PM_UAPSD_ALL;
prBssInfo->rPmProfSetupInfo.ucUapsdSp = WMM_MAX_SP_LENGTH_2;
#else
prBssInfo->rPmProfSetupInfo.ucBmpDeliveryAC = (UINT_8)prAdapter->u4UapsdAcBmp;
prBssInfo->rPmProfSetupInfo.ucBmpTriggerAC =(UINT_8) prAdapter->u4UapsdAcBmp;
prBssInfo->rPmProfSetupInfo.ucUapsdSp = (UINT_8)prAdapter->u4MaxSpLen;
#endif
#if 0
for(eAci = 0; eAci < WMM_AC_INDEX_NUM; eAci++){
prBssInfo->arACQueParms[eAci].fgIsACMSet = FALSE;
prBssInfo->arACQueParms[eAci].u2Aifsn = (UINT_16) eAci;
prBssInfo->arACQueParms[eAci].u2CWmin = 7;
prBssInfo->arACQueParms[eAci].u2CWmax = 31;
prBssInfo->arACQueParms[eAci].u2TxopLimit = eAci+1;
DBGLOG(SW4, INFO, ("MQM: eAci = %d, ACM = %d, Aifsn = %d, CWmin = %d, CWmax = %d, TxopLimit = %d\n",
eAci,prBssInfo->arACQueParms[eAci].fgIsACMSet ,
prBssInfo->arACQueParms[eAci].u2Aifsn,
prBssInfo->arACQueParms[eAci].u2CWmin,
prBssInfo->arACQueParms[eAci].u2CWmax,
prBssInfo->arACQueParms[eAci].u2TxopLimit));
}
#endif
DBGLOG(SW4, INFO, ("[2] ucBmpDeliveryAC:0x%x, ucBmpTriggerAC:0x%x, ucUapsdSp:0x%x",
prBssInfo->rPmProfSetupInfo.ucBmpDeliveryAC,
prBssInfo->rPmProfSetupInfo.ucBmpTriggerAC,
prBssInfo->rPmProfSetupInfo.ucUapsdSp));
return;
}
VOID testPsCmdCategory0(P_ADAPTER_T prAdapter, UINT_8 ucCate, UINT_8 ucAction, UINT_8 ucOpt0,UINT_8 ucOpt1)
{
UINT_8 ucIndex,ucRead;
P_STA_RECORD_T prStaRec;
DEBUGFUNC("testPsCmdCategory0");
SWCR_GET_RW_INDEX(ucAction,ucRead,ucIndex);
DBGLOG(SW4, LOUD, ("Read %u Index %u\n",ucRead,ucIndex));
prStaRec = cnmGetStaRecByIndex (prAdapter, 0);
if(ucIndex>=TEST_PS_CATA0_INDEX_NUM) return;
if(ucRead == SWCR_WRITE) {
switch(ucIndex) {
case TEST_PS_SETUP_BSS:
testPsSetupBss(prAdapter, ucOpt0) ;
break;
case TEST_PS_ENABLE_BEACON:
break;
case TEST_PS_TRIGGER_BMC:
//txmForwardQueuedBmcPkts (ucOpt0);
break;
case TEST_PS_SEND_NULL:
{
testPsSendQoSNullFrame (prAdapter,prStaRec,
(UINT_8)(g_au4SwCr[1] & 0xFF), /* UP */
ucOpt0,
(BOOLEAN)((g_au4SwCr[1] >>8)& 0xFF), /* BMC*/
(BOOLEAN)((g_au4SwCr[1] >>16)& 0xFF), /* BurstEnd*/
(BOOLEAN)((g_au4SwCr[1] >>24)& 0xFF), /* Packet type*/
(UINT_8)((g_au4SwCr[2] )& 0xFF), /* PS sesson ID 7: NOACK */
FALSE /* EOSP */
);
}
break;
case TEST_PS_BUFFER_BMC:
//g_aprBssInfo[ucOpt0]->fgApToBufferBMC = (g_au4SwCr[1] & 0xFF);
break;
case TEST_PS_UPDATE_BEACON:
bssUpdateBeaconContent(prAdapter, ucOpt0 /*networktype*/ );
break;
default:
break;
}
}
else {
switch(ucIndex) {
case TEST_PS_MAGIC:
g_au4SwCr[1] = 0x88660011 ;
break;
}
}
}
#endif //TEST_PS
#if TEST_PS
VOID testPsCmdCategory1(P_ADAPTER_T prAdapter, UINT_8 ucCate, UINT_8 ucAction, UINT_8 ucOpt0,UINT_8 ucOpt1)
{
UINT_8 ucIndex,ucRead;
UINT_8 ucWTEntry;
P_STA_RECORD_T prStaRec;
DEBUGFUNC("testPsCmdCategory1");
SWCR_GET_RW_INDEX(ucAction,ucRead,ucIndex);
if(ucOpt0>=CFG_STA_REC_NUM) return;
prStaRec = cnmGetStaRecByIndex (prAdapter, ucOpt0);
ucWTEntry = prStaRec->ucWTEntry;
if(ucRead == SWCR_WRITE) {
switch(ucIndex) {
case TEST_PS_STA_PS:
prStaRec->fgIsInPS = (BOOLEAN) (g_au4SwCr[1] & 0x1);
prStaRec->fgIsQoS = (BOOLEAN) (g_au4SwCr[1] >>8 & 0xFF);
prStaRec->fgIsUapsdSupported = (BOOLEAN) (g_au4SwCr[1] >>16 & 0xFF);
prStaRec->ucBmpDeliveryAC = (BOOLEAN) (g_au4SwCr[1] >>24 & 0xFF);
break;
}
}
else {
/* Read */
switch(ucIndex) {
default:
break;
}
}
}
#endif //TEST_PS
#if CFG_SUPPORT_802_11V
#if (CFG_SUPPORT_802_11V_TIMING_MEASUREMENT ==1) && (WNM_UNIT_TEST ==1)
VOID testWNMCmdCategory0(P_ADAPTER_T prAdapter, UINT_8 ucCate, UINT_8 ucAction, UINT_8 ucOpt0,UINT_8 ucOpt1)
{
UINT_8 ucIndex,ucRead;
P_STA_RECORD_T prStaRec;
DEBUGFUNC("testWNMCmdCategory0");
SWCR_GET_RW_INDEX(ucAction,ucRead,ucIndex);
DBGLOG(SW4, INFO, ("Read %u Index %u\n",ucRead,ucIndex));
if(ucIndex>=TEST_WNM_CATA0_INDEX_NUM) return;
if(ucRead == SWCR_WRITE) {
switch(ucIndex) {
case TEST_WNM_TIMING_MEAS:
wnmTimingMeasUnitTest1(prAdapter, ucOpt0) ;
break;
default:
break;
}
}
}
#endif //TEST_WNM
#endif //CFG_SUPPORT_802_11V
VOID swCtrlSwCr(P_ADAPTER_T prAdapter, UINT_8 ucRead, UINT_16 u2Addr, UINT_32 *pu4Data)
{
/* According other register STAIDX */
UINT_8 ucOffset;
ucOffset = (u2Addr>>2) & 0x3F;
if(ucOffset>= SWCR_CR_NUM) return;
if(ucRead==SWCR_WRITE) {
g_au4SwCr[ucOffset] = *pu4Data;
if(ucOffset==0x0) {
/* Commmand [31:24]: Category */
/* Commmand [23:23]: 1(W) 0(R) */
/* Commmand [22:16]: Index */
/* Commmand [15:08]: Option0 */
/* Commmand [07:00]: Option1 */
UINT_8 ucCate;
UINT_32 u4Cmd;
u4Cmd = g_au4SwCr[0];
ucCate = (UINT_8)(u4Cmd >> 24) ;
if(ucCate < sizeof(g_arSwCtrlCmd)/sizeof(g_arSwCtrlCmd[0])) {
if(g_arSwCtrlCmd[ucCate]!=NULL) {
g_arSwCtrlCmd[ucCate](prAdapter, ucCate, (UINT_8)(u4Cmd>>16 & 0xFF),(UINT_8)((u4Cmd>>8) & 0xFF), (UINT_8)(u4Cmd&0xFF));
}
}
}
}
else {
*pu4Data = g_au4SwCr[ucOffset];
}
}
VOID swCrReadWriteCmd(P_ADAPTER_T prAdapter, UINT_8 ucRead, UINT_16 u2Addr, UINT_32 *pu4Data)
{
UINT_8 ucMod;
ucMod = u2Addr >>8;
/* Address [15:8] MOD ID */
/* Address [7:0] OFFSET */
DEBUGFUNC("swCrReadWriteCmd");
DBGLOG(SW4, INFO, ("%u addr 0x%x data 0x%x\n",ucRead,u2Addr,*pu4Data));
if(ucMod < (sizeof(g_arSwCrModHandle)/sizeof(g_arSwCrModHandle[0])) ) {
if(g_arSwCrModHandle[ucMod]!=NULL) {
g_arSwCrModHandle[ucMod](prAdapter, ucRead, u2Addr, pu4Data);
}
} /* ucMod */
}
/* Debug Support */
VOID swCrFrameCheckEnable(P_ADAPTER_T prAdapter, UINT_32 u4DumpType)
{
g_u4SwcrDebugFrameDumpType = u4DumpType;
prAdapter->rRxCtrl.u4RxPktsDumpTypeMask = u4DumpType;
}
VOID swCrDebugInit(P_ADAPTER_T prAdapter)
{
// frame dump
if (g_u4SwcrDebugFrameDumpType) {
swCrFrameCheckEnable(prAdapter, g_u4SwcrDebugFrameDumpType);
}
// debug counter
g_fgSwcrDebugTimer = FALSE;
cnmTimerInitTimer(prAdapter,
&g_rSwcrDebugTimer,
(PFN_MGMT_TIMEOUT_FUNC)swCrDebugCheckTimeout,
(UINT_32) NULL);
if (g_u4SwcrDebugCheckTimeout) {
swCrDebugCheckEnable(prAdapter, TRUE, g_ucSwcrDebugCheckType, g_u4SwcrDebugCheckTimeout);
}
}
VOID swCrDebugUninit(P_ADAPTER_T prAdapter)
{
cnmTimerStopTimer(prAdapter, &g_rSwcrDebugTimer);
g_fgSwcrDebugTimer = FALSE;
}
VOID swCrDebugCheckEnable(P_ADAPTER_T prAdapter, BOOLEAN fgIsEnable, UINT_8 ucType, UINT_32 u4Timeout)
{
if (fgIsEnable) {
g_ucSwcrDebugCheckType = ucType;
g_u4SwcrDebugCheckTimeout = u4Timeout;
if (g_fgSwcrDebugTimer == FALSE) {
swCrDebugCheckTimeout(prAdapter, 0);
}
}
else {
cnmTimerStopTimer(prAdapter, &g_rSwcrDebugTimer);
g_u4SwcrDebugCheckTimeout = 0;
}
g_fgSwcrDebugTimer = fgIsEnable;
}
VOID swCrDebugCheck(P_ADAPTER_T prAdapter, P_CMD_SW_DBG_CTRL_T prCmdSwCtrl)
{
P_RX_CTRL_T prRxCtrl;
P_TX_CTRL_T prTxCtrl;
ASSERT(prAdapter);
prTxCtrl = &prAdapter->rTxCtrl;
prRxCtrl = &prAdapter->rRxCtrl;
// dump counters
if (prCmdSwCtrl) {
if (prCmdSwCtrl->u4Data == SWCR_DBG_TYPE_ALL) {
// TX Counter from fw
DBGLOG(SW4, INFO, ("TX0\n" \
"%08x %08x %08x %08x\n" \
"%08x %08x %08x %08x\n",
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_TX_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_TX_BCN_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_TX_FAILED_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_TX_RETRY_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_TX_AGING_TIMEOUT_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_TX_PS_OVERFLOW_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_TX_MGNT_DROP_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_TX_ERROR_CNT]));
#if 1
// TX Counter from drv
DBGLOG(SW4, INFO, ("TX1\n" \
"%08x %08x %08x %08x\n",
(UINT_32)TX_GET_CNT(prTxCtrl, TX_INACTIVE_BSS_DROP),
(UINT_32)TX_GET_CNT(prTxCtrl, TX_INACTIVE_STA_DROP),
(UINT_32)TX_GET_CNT(prTxCtrl, TX_FORWARD_OVERFLOW_DROP),
(UINT_32)TX_GET_CNT(prTxCtrl, TX_AP_BORADCAST_DROP)));
#endif
// RX Counter
DBGLOG(SW4, INFO, ("RX0\n" \
"%08x %08x %08x %08x\n" \
"%08x %08x %08x %08x\n" \
"%08x %08x %08x %08x\n" \
"%08x %08x %08x %08x\n",
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_RX_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_RX_DROP_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_RX_DUP_DROP_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_RX_TYPE_ERROR_DROP_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_RX_CLASS_ERROR_DROP_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_RX_AMPDU_ERROR_DROP_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_RX_STATUS_ERROR_DROP_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_RX_FORMAT_ERROR_DROP_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_RX_ICV_ERROR_DROP_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_RX_KEY_ERROR_DROP_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_RX_TKIP_ERROR_DROP_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_RX_MIC_ERROR_DROP_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_RX_BIP_ERROR_DROP_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_RX_FCSERR_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_RX_FIFOFULL_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_RX_PFDROP_CNT]));
DBGLOG(SW4, INFO, ("RX1\n" \
"%08x %08x %08x %08x\n" \
"%08x %08x %08x %08x\n",
(UINT_32)RX_GET_CNT(prRxCtrl, RX_MPDU_TOTAL_COUNT),
(UINT_32)RX_GET_CNT(prRxCtrl, RX_DATA_INDICATION_COUNT),
(UINT_32)RX_GET_CNT(prRxCtrl, RX_DATA_RETURNED_COUNT),
(UINT_32)RX_GET_CNT(prRxCtrl, RX_DATA_RETAINED_COUNT),
(UINT_32)RX_GET_CNT(prRxCtrl, RX_DROP_TOTAL_COUNT),
(UINT_32)RX_GET_CNT(prRxCtrl, RX_TYPE_ERR_DROP_COUNT),
(UINT_32)RX_GET_CNT(prRxCtrl, RX_CLASS_ERR_DROP_COUNT),
(UINT_32)RX_GET_CNT(prRxCtrl, RX_DST_NULL_DROP_COUNT)));
DBGLOG(SW4, INFO, ("PWR\n" \
"%08x %08x %08x %08x\n" \
"%08x %08x %08x %08x\n",
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_PWR_PS_POLL_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_PWR_TRIGGER_NULL_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_PWR_BCN_IND_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_PWR_BCN_TIMEOUT_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_PWR_PM_STATE0],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_PWR_PM_STATE1],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_PWR_CUR_PS_PROF0],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_PWR_CUR_PS_PROF1]));
DBGLOG(SW4, INFO, ("ARM\n" \
"%08x %08x %08x %08x\n" \
"%08x %08x\n",
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_AR_STA0_RATE],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_AR_STA0_BWGI],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_AR_STA0_RX_RATE_RCPI],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_ROAMING_ENABLE],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_ROAMING_ROAM_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_ROAMING_INT_CNT]));
DBGLOG(SW4, INFO, ("BB\n" \
"%08x %08x %08x %08x\n" \
"%08x %08x %08x %08x\n",
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_BB_RX_MDRDY_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_BB_RX_FCSERR_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_BB_CCK_PD_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_BB_OFDM_PD_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_BB_CCK_SFDERR_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_BB_CCK_SIGERR_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_BB_OFDM_TAGERR_CNT],
prCmdSwCtrl->u4DebugCnt[SWCR_DBG_ALL_BB_OFDM_SIGERR_CNT]));
}
}
// start the next check
if (g_u4SwcrDebugCheckTimeout) {
cnmTimerStartTimer(prAdapter, &g_rSwcrDebugTimer, g_u4SwcrDebugCheckTimeout * MSEC_PER_SEC);
}
}
VOID swCrDebugCheckTimeout(
IN P_ADAPTER_T prAdapter,
UINT_32 u4Param)
{
CMD_SW_DBG_CTRL_T rCmdSwCtrl;
WLAN_STATUS rStatus;
rCmdSwCtrl.u4Id = (0xb000<<16) + g_ucSwcrDebugCheckType;
rCmdSwCtrl.u4Data = 0;
rStatus = wlanSendSetQueryCmd (
prAdapter, /* prAdapter */
CMD_ID_SW_DBG_CTRL, /* ucCID */
FALSE, /* fgSetQuery */
TRUE, /* fgNeedResp */
FALSE, /* fgIsOid */
swCrDebugQuery, /* pfCmdDoneHandler */
swCrDebugQueryTimeout, /* pfCmdTimeoutHandler */
sizeof(CMD_SW_DBG_CTRL_T), /* u4SetQueryInfoLen */
(PUINT_8)&rCmdSwCtrl, /* pucInfoBuffer */
NULL, /* pvSetQueryBuffer */
0 /* u4SetQueryBufferLen */
);
ASSERT(rStatus == WLAN_STATUS_PENDING);
return;
}
VOID swCrDebugQuery(
IN P_ADAPTER_T prAdapter,
IN P_CMD_INFO_T prCmdInfo,
IN PUINT_8 pucEventBuf
)
{
ASSERT(prAdapter);
swCrDebugCheck(prAdapter, (P_CMD_SW_DBG_CTRL_T)(pucEventBuf));
}
VOID swCrDebugQueryTimeout(
IN P_ADAPTER_T prAdapter,
IN P_CMD_INFO_T prCmdInfo)
{
ASSERT(prAdapter);
swCrDebugCheck(prAdapter, NULL);
}
#endif /* CFG_SUPPORT_SWCR */
| gpl-2.0 |
farindk/linux-sunxi | lib/show_mem.c | 491 | 1189 | /*
* Generic show_mem() implementation
*
* Copyright (C) 2008 Johannes Weiner <hannes@saeurebad.de>
* All code subject to the GPL version 2.
*/
#include <linux/mm.h>
#include <linux/nmi.h>
#include <linux/quicklist.h>
void show_mem(unsigned int filter)
{
pg_data_t *pgdat;
unsigned long total = 0, reserved = 0, highmem = 0;
printk("Mem-Info:\n");
show_free_areas(filter);
for_each_online_pgdat(pgdat) {
unsigned long flags;
int zoneid;
pgdat_resize_lock(pgdat, &flags);
for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
struct zone *zone = &pgdat->node_zones[zoneid];
if (!populated_zone(zone))
continue;
total += zone->present_pages;
reserved = zone->present_pages - zone->managed_pages;
if (is_highmem_idx(zoneid))
highmem += zone->present_pages;
}
pgdat_resize_unlock(pgdat, &flags);
}
printk("%lu pages RAM\n", total);
printk("%lu pages HighMem/MovableOnly\n", highmem);
printk("%lu pages reserved\n", reserved);
#ifdef CONFIG_QUICKLIST
printk("%lu pages in pagetable cache\n",
quicklist_total_size());
#endif
#ifdef CONFIG_MEMORY_FAILURE
printk("%lu pages hwpoisoned\n", atomic_long_read(&num_poisoned_pages));
#endif
}
| gpl-2.0 |
liuzhengcn/kernel-smb | net/xfrm/xfrm_policy.c | 491 | 68145 | /*
* xfrm_policy.c
*
* Changes:
* Mitsuru KANDA @USAGI
* Kazunori MIYAZAWA @USAGI
* Kunihiro Ishiguro <kunihiro@ipinfusion.com>
* IPv6 support
* Kazunori MIYAZAWA @USAGI
* YOSHIFUJI Hideaki
* Split up af-specific portion
* Derek Atkins <derek@ihtfp.com> Add the post_input processor
*
*/
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/kmod.h>
#include <linux/list.h>
#include <linux/spinlock.h>
#include <linux/workqueue.h>
#include <linux/notifier.h>
#include <linux/netdevice.h>
#include <linux/netfilter.h>
#include <linux/module.h>
#include <linux/cache.h>
#include <linux/audit.h>
#include <net/dst.h>
#include <net/xfrm.h>
#include <net/ip.h>
#ifdef CONFIG_XFRM_STATISTICS
#include <net/snmp.h>
#endif
#include "xfrm_hash.h"
DEFINE_MUTEX(xfrm_cfg_mutex);
EXPORT_SYMBOL(xfrm_cfg_mutex);
static DEFINE_RWLOCK(xfrm_policy_lock);
static DEFINE_RWLOCK(xfrm_policy_afinfo_lock);
static struct xfrm_policy_afinfo *xfrm_policy_afinfo[NPROTO];
static struct kmem_cache *xfrm_dst_cache __read_mostly;
static HLIST_HEAD(xfrm_policy_gc_list);
static DEFINE_SPINLOCK(xfrm_policy_gc_lock);
static struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family);
static void xfrm_policy_put_afinfo(struct xfrm_policy_afinfo *afinfo);
static void xfrm_init_pmtu(struct dst_entry *dst);
static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
int dir);
static inline int
__xfrm4_selector_match(struct xfrm_selector *sel, struct flowi *fl)
{
return addr_match(&fl->fl4_dst, &sel->daddr, sel->prefixlen_d) &&
addr_match(&fl->fl4_src, &sel->saddr, sel->prefixlen_s) &&
!((xfrm_flowi_dport(fl) ^ sel->dport) & sel->dport_mask) &&
!((xfrm_flowi_sport(fl) ^ sel->sport) & sel->sport_mask) &&
(fl->proto == sel->proto || !sel->proto) &&
(fl->oif == sel->ifindex || !sel->ifindex);
}
static inline int
__xfrm6_selector_match(struct xfrm_selector *sel, struct flowi *fl)
{
return addr_match(&fl->fl6_dst, &sel->daddr, sel->prefixlen_d) &&
addr_match(&fl->fl6_src, &sel->saddr, sel->prefixlen_s) &&
!((xfrm_flowi_dport(fl) ^ sel->dport) & sel->dport_mask) &&
!((xfrm_flowi_sport(fl) ^ sel->sport) & sel->sport_mask) &&
(fl->proto == sel->proto || !sel->proto) &&
(fl->oif == sel->ifindex || !sel->ifindex);
}
int xfrm_selector_match(struct xfrm_selector *sel, struct flowi *fl,
unsigned short family)
{
switch (family) {
case AF_INET:
return __xfrm4_selector_match(sel, fl);
case AF_INET6:
return __xfrm6_selector_match(sel, fl);
}
return 0;
}
static inline struct dst_entry *__xfrm_dst_lookup(struct net *net, int tos,
xfrm_address_t *saddr,
xfrm_address_t *daddr,
int family)
{
struct xfrm_policy_afinfo *afinfo;
struct dst_entry *dst;
afinfo = xfrm_policy_get_afinfo(family);
if (unlikely(afinfo == NULL))
return ERR_PTR(-EAFNOSUPPORT);
dst = afinfo->dst_lookup(net, tos, saddr, daddr);
xfrm_policy_put_afinfo(afinfo);
return dst;
}
static inline struct dst_entry *xfrm_dst_lookup(struct xfrm_state *x, int tos,
xfrm_address_t *prev_saddr,
xfrm_address_t *prev_daddr,
int family)
{
struct net *net = xs_net(x);
xfrm_address_t *saddr = &x->props.saddr;
xfrm_address_t *daddr = &x->id.daddr;
struct dst_entry *dst;
if (x->type->flags & XFRM_TYPE_LOCAL_COADDR) {
saddr = x->coaddr;
daddr = prev_daddr;
}
if (x->type->flags & XFRM_TYPE_REMOTE_COADDR) {
saddr = prev_saddr;
daddr = x->coaddr;
}
dst = __xfrm_dst_lookup(net, tos, saddr, daddr, family);
if (!IS_ERR(dst)) {
if (prev_saddr != saddr)
memcpy(prev_saddr, saddr, sizeof(*prev_saddr));
if (prev_daddr != daddr)
memcpy(prev_daddr, daddr, sizeof(*prev_daddr));
}
return dst;
}
static inline unsigned long make_jiffies(long secs)
{
if (secs >= (MAX_SCHEDULE_TIMEOUT-1)/HZ)
return MAX_SCHEDULE_TIMEOUT-1;
else
return secs*HZ;
}
static void xfrm_policy_timer(unsigned long data)
{
struct xfrm_policy *xp = (struct xfrm_policy*)data;
unsigned long now = get_seconds();
long next = LONG_MAX;
int warn = 0;
int dir;
read_lock(&xp->lock);
if (xp->walk.dead)
goto out;
dir = xfrm_policy_id2dir(xp->index);
if (xp->lft.hard_add_expires_seconds) {
long tmo = xp->lft.hard_add_expires_seconds +
xp->curlft.add_time - now;
if (tmo <= 0)
goto expired;
if (tmo < next)
next = tmo;
}
if (xp->lft.hard_use_expires_seconds) {
long tmo = xp->lft.hard_use_expires_seconds +
(xp->curlft.use_time ? : xp->curlft.add_time) - now;
if (tmo <= 0)
goto expired;
if (tmo < next)
next = tmo;
}
if (xp->lft.soft_add_expires_seconds) {
long tmo = xp->lft.soft_add_expires_seconds +
xp->curlft.add_time - now;
if (tmo <= 0) {
warn = 1;
tmo = XFRM_KM_TIMEOUT;
}
if (tmo < next)
next = tmo;
}
if (xp->lft.soft_use_expires_seconds) {
long tmo = xp->lft.soft_use_expires_seconds +
(xp->curlft.use_time ? : xp->curlft.add_time) - now;
if (tmo <= 0) {
warn = 1;
tmo = XFRM_KM_TIMEOUT;
}
if (tmo < next)
next = tmo;
}
if (warn)
km_policy_expired(xp, dir, 0, 0);
if (next != LONG_MAX &&
!mod_timer(&xp->timer, jiffies + make_jiffies(next)))
xfrm_pol_hold(xp);
out:
read_unlock(&xp->lock);
xfrm_pol_put(xp);
return;
expired:
read_unlock(&xp->lock);
if (!xfrm_policy_delete(xp, dir))
km_policy_expired(xp, dir, 1, 0);
xfrm_pol_put(xp);
}
/* Allocate xfrm_policy. Not used here, it is supposed to be used by pfkeyv2
* SPD calls.
*/
struct xfrm_policy *xfrm_policy_alloc(struct net *net, gfp_t gfp)
{
struct xfrm_policy *policy;
policy = kzalloc(sizeof(struct xfrm_policy), gfp);
if (policy) {
write_pnet(&policy->xp_net, net);
INIT_LIST_HEAD(&policy->walk.all);
INIT_HLIST_NODE(&policy->bydst);
INIT_HLIST_NODE(&policy->byidx);
rwlock_init(&policy->lock);
atomic_set(&policy->refcnt, 1);
setup_timer(&policy->timer, xfrm_policy_timer,
(unsigned long)policy);
}
return policy;
}
EXPORT_SYMBOL(xfrm_policy_alloc);
/* Destroy xfrm_policy: descendant resources must be released to this moment. */
void xfrm_policy_destroy(struct xfrm_policy *policy)
{
BUG_ON(!policy->walk.dead);
BUG_ON(policy->bundles);
if (del_timer(&policy->timer))
BUG();
security_xfrm_policy_free(policy->security);
kfree(policy);
}
EXPORT_SYMBOL(xfrm_policy_destroy);
static void xfrm_policy_gc_kill(struct xfrm_policy *policy)
{
struct dst_entry *dst;
while ((dst = policy->bundles) != NULL) {
policy->bundles = dst->next;
dst_free(dst);
}
if (del_timer(&policy->timer))
atomic_dec(&policy->refcnt);
if (atomic_read(&policy->refcnt) > 1)
flow_cache_flush();
xfrm_pol_put(policy);
}
static void xfrm_policy_gc_task(struct work_struct *work)
{
struct xfrm_policy *policy;
struct hlist_node *entry, *tmp;
struct hlist_head gc_list;
spin_lock_bh(&xfrm_policy_gc_lock);
gc_list.first = xfrm_policy_gc_list.first;
INIT_HLIST_HEAD(&xfrm_policy_gc_list);
spin_unlock_bh(&xfrm_policy_gc_lock);
hlist_for_each_entry_safe(policy, entry, tmp, &gc_list, bydst)
xfrm_policy_gc_kill(policy);
}
static DECLARE_WORK(xfrm_policy_gc_work, xfrm_policy_gc_task);
/* Rule must be locked. Release descentant resources, announce
* entry dead. The rule must be unlinked from lists to the moment.
*/
static void xfrm_policy_kill(struct xfrm_policy *policy)
{
int dead;
write_lock_bh(&policy->lock);
dead = policy->walk.dead;
policy->walk.dead = 1;
write_unlock_bh(&policy->lock);
if (unlikely(dead)) {
WARN_ON(1);
return;
}
spin_lock_bh(&xfrm_policy_gc_lock);
hlist_add_head(&policy->bydst, &xfrm_policy_gc_list);
spin_unlock_bh(&xfrm_policy_gc_lock);
schedule_work(&xfrm_policy_gc_work);
}
static unsigned int xfrm_policy_hashmax __read_mostly = 1 * 1024 * 1024;
static inline unsigned int idx_hash(struct net *net, u32 index)
{
return __idx_hash(index, net->xfrm.policy_idx_hmask);
}
static struct hlist_head *policy_hash_bysel(struct net *net, struct xfrm_selector *sel, unsigned short family, int dir)
{
unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
unsigned int hash = __sel_hash(sel, family, hmask);
return (hash == hmask + 1 ?
&net->xfrm.policy_inexact[dir] :
net->xfrm.policy_bydst[dir].table + hash);
}
static struct hlist_head *policy_hash_direct(struct net *net, xfrm_address_t *daddr, xfrm_address_t *saddr, unsigned short family, int dir)
{
unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
unsigned int hash = __addr_hash(daddr, saddr, family, hmask);
return net->xfrm.policy_bydst[dir].table + hash;
}
static void xfrm_dst_hash_transfer(struct hlist_head *list,
struct hlist_head *ndsttable,
unsigned int nhashmask)
{
struct hlist_node *entry, *tmp, *entry0 = NULL;
struct xfrm_policy *pol;
unsigned int h0 = 0;
redo:
hlist_for_each_entry_safe(pol, entry, tmp, list, bydst) {
unsigned int h;
h = __addr_hash(&pol->selector.daddr, &pol->selector.saddr,
pol->family, nhashmask);
if (!entry0) {
hlist_del(entry);
hlist_add_head(&pol->bydst, ndsttable+h);
h0 = h;
} else {
if (h != h0)
continue;
hlist_del(entry);
hlist_add_after(entry0, &pol->bydst);
}
entry0 = entry;
}
if (!hlist_empty(list)) {
entry0 = NULL;
goto redo;
}
}
static void xfrm_idx_hash_transfer(struct hlist_head *list,
struct hlist_head *nidxtable,
unsigned int nhashmask)
{
struct hlist_node *entry, *tmp;
struct xfrm_policy *pol;
hlist_for_each_entry_safe(pol, entry, tmp, list, byidx) {
unsigned int h;
h = __idx_hash(pol->index, nhashmask);
hlist_add_head(&pol->byidx, nidxtable+h);
}
}
static unsigned long xfrm_new_hash_mask(unsigned int old_hmask)
{
return ((old_hmask + 1) << 1) - 1;
}
static void xfrm_bydst_resize(struct net *net, int dir)
{
unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
unsigned int nhashmask = xfrm_new_hash_mask(hmask);
unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
struct hlist_head *odst = net->xfrm.policy_bydst[dir].table;
struct hlist_head *ndst = xfrm_hash_alloc(nsize);
int i;
if (!ndst)
return;
write_lock_bh(&xfrm_policy_lock);
for (i = hmask; i >= 0; i--)
xfrm_dst_hash_transfer(odst + i, ndst, nhashmask);
net->xfrm.policy_bydst[dir].table = ndst;
net->xfrm.policy_bydst[dir].hmask = nhashmask;
write_unlock_bh(&xfrm_policy_lock);
xfrm_hash_free(odst, (hmask + 1) * sizeof(struct hlist_head));
}
static void xfrm_byidx_resize(struct net *net, int total)
{
unsigned int hmask = net->xfrm.policy_idx_hmask;
unsigned int nhashmask = xfrm_new_hash_mask(hmask);
unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
struct hlist_head *oidx = net->xfrm.policy_byidx;
struct hlist_head *nidx = xfrm_hash_alloc(nsize);
int i;
if (!nidx)
return;
write_lock_bh(&xfrm_policy_lock);
for (i = hmask; i >= 0; i--)
xfrm_idx_hash_transfer(oidx + i, nidx, nhashmask);
net->xfrm.policy_byidx = nidx;
net->xfrm.policy_idx_hmask = nhashmask;
write_unlock_bh(&xfrm_policy_lock);
xfrm_hash_free(oidx, (hmask + 1) * sizeof(struct hlist_head));
}
static inline int xfrm_bydst_should_resize(struct net *net, int dir, int *total)
{
unsigned int cnt = net->xfrm.policy_count[dir];
unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
if (total)
*total += cnt;
if ((hmask + 1) < xfrm_policy_hashmax &&
cnt > hmask)
return 1;
return 0;
}
static inline int xfrm_byidx_should_resize(struct net *net, int total)
{
unsigned int hmask = net->xfrm.policy_idx_hmask;
if ((hmask + 1) < xfrm_policy_hashmax &&
total > hmask)
return 1;
return 0;
}
void xfrm_spd_getinfo(struct xfrmk_spdinfo *si)
{
read_lock_bh(&xfrm_policy_lock);
si->incnt = init_net.xfrm.policy_count[XFRM_POLICY_IN];
si->outcnt = init_net.xfrm.policy_count[XFRM_POLICY_OUT];
si->fwdcnt = init_net.xfrm.policy_count[XFRM_POLICY_FWD];
si->inscnt = init_net.xfrm.policy_count[XFRM_POLICY_IN+XFRM_POLICY_MAX];
si->outscnt = init_net.xfrm.policy_count[XFRM_POLICY_OUT+XFRM_POLICY_MAX];
si->fwdscnt = init_net.xfrm.policy_count[XFRM_POLICY_FWD+XFRM_POLICY_MAX];
si->spdhcnt = init_net.xfrm.policy_idx_hmask;
si->spdhmcnt = xfrm_policy_hashmax;
read_unlock_bh(&xfrm_policy_lock);
}
EXPORT_SYMBOL(xfrm_spd_getinfo);
static DEFINE_MUTEX(hash_resize_mutex);
static void xfrm_hash_resize(struct work_struct *work)
{
struct net *net = container_of(work, struct net, xfrm.policy_hash_work);
int dir, total;
mutex_lock(&hash_resize_mutex);
total = 0;
for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
if (xfrm_bydst_should_resize(net, dir, &total))
xfrm_bydst_resize(net, dir);
}
if (xfrm_byidx_should_resize(net, total))
xfrm_byidx_resize(net, total);
mutex_unlock(&hash_resize_mutex);
}
/* Generate new index... KAME seems to generate them ordered by cost
* of an absolute inpredictability of ordering of rules. This will not pass. */
static u32 xfrm_gen_index(struct net *net, int dir)
{
static u32 idx_generator;
for (;;) {
struct hlist_node *entry;
struct hlist_head *list;
struct xfrm_policy *p;
u32 idx;
int found;
idx = (idx_generator | dir);
idx_generator += 8;
if (idx == 0)
idx = 8;
list = net->xfrm.policy_byidx + idx_hash(net, idx);
found = 0;
hlist_for_each_entry(p, entry, list, byidx) {
if (p->index == idx) {
found = 1;
break;
}
}
if (!found)
return idx;
}
}
static inline int selector_cmp(struct xfrm_selector *s1, struct xfrm_selector *s2)
{
u32 *p1 = (u32 *) s1;
u32 *p2 = (u32 *) s2;
int len = sizeof(struct xfrm_selector) / sizeof(u32);
int i;
for (i = 0; i < len; i++) {
if (p1[i] != p2[i])
return 1;
}
return 0;
}
int xfrm_policy_insert(int dir, struct xfrm_policy *policy, int excl)
{
struct net *net = xp_net(policy);
struct xfrm_policy *pol;
struct xfrm_policy *delpol;
struct hlist_head *chain;
struct hlist_node *entry, *newpos;
struct dst_entry *gc_list;
write_lock_bh(&xfrm_policy_lock);
chain = policy_hash_bysel(net, &policy->selector, policy->family, dir);
delpol = NULL;
newpos = NULL;
hlist_for_each_entry(pol, entry, chain, bydst) {
if (pol->type == policy->type &&
!selector_cmp(&pol->selector, &policy->selector) &&
xfrm_sec_ctx_match(pol->security, policy->security) &&
!WARN_ON(delpol)) {
if (excl) {
write_unlock_bh(&xfrm_policy_lock);
return -EEXIST;
}
delpol = pol;
if (policy->priority > pol->priority)
continue;
} else if (policy->priority >= pol->priority) {
newpos = &pol->bydst;
continue;
}
if (delpol)
break;
}
if (newpos)
hlist_add_after(newpos, &policy->bydst);
else
hlist_add_head(&policy->bydst, chain);
xfrm_pol_hold(policy);
net->xfrm.policy_count[dir]++;
atomic_inc(&flow_cache_genid);
if (delpol)
__xfrm_policy_unlink(delpol, dir);
policy->index = delpol ? delpol->index : xfrm_gen_index(net, dir);
hlist_add_head(&policy->byidx, net->xfrm.policy_byidx+idx_hash(net, policy->index));
policy->curlft.add_time = get_seconds();
policy->curlft.use_time = 0;
if (!mod_timer(&policy->timer, jiffies + HZ))
xfrm_pol_hold(policy);
list_add(&policy->walk.all, &net->xfrm.policy_all);
write_unlock_bh(&xfrm_policy_lock);
if (delpol)
xfrm_policy_kill(delpol);
else if (xfrm_bydst_should_resize(net, dir, NULL))
schedule_work(&net->xfrm.policy_hash_work);
read_lock_bh(&xfrm_policy_lock);
gc_list = NULL;
entry = &policy->bydst;
hlist_for_each_entry_continue(policy, entry, bydst) {
struct dst_entry *dst;
write_lock(&policy->lock);
dst = policy->bundles;
if (dst) {
struct dst_entry *tail = dst;
while (tail->next)
tail = tail->next;
tail->next = gc_list;
gc_list = dst;
policy->bundles = NULL;
}
write_unlock(&policy->lock);
}
read_unlock_bh(&xfrm_policy_lock);
while (gc_list) {
struct dst_entry *dst = gc_list;
gc_list = dst->next;
dst_free(dst);
}
return 0;
}
EXPORT_SYMBOL(xfrm_policy_insert);
struct xfrm_policy *xfrm_policy_bysel_ctx(struct net *net, u8 type, int dir,
struct xfrm_selector *sel,
struct xfrm_sec_ctx *ctx, int delete,
int *err)
{
struct xfrm_policy *pol, *ret;
struct hlist_head *chain;
struct hlist_node *entry;
*err = 0;
write_lock_bh(&xfrm_policy_lock);
chain = policy_hash_bysel(net, sel, sel->family, dir);
ret = NULL;
hlist_for_each_entry(pol, entry, chain, bydst) {
if (pol->type == type &&
!selector_cmp(sel, &pol->selector) &&
xfrm_sec_ctx_match(ctx, pol->security)) {
xfrm_pol_hold(pol);
if (delete) {
*err = security_xfrm_policy_delete(
pol->security);
if (*err) {
write_unlock_bh(&xfrm_policy_lock);
return pol;
}
__xfrm_policy_unlink(pol, dir);
}
ret = pol;
break;
}
}
write_unlock_bh(&xfrm_policy_lock);
if (ret && delete) {
atomic_inc(&flow_cache_genid);
xfrm_policy_kill(ret);
}
return ret;
}
EXPORT_SYMBOL(xfrm_policy_bysel_ctx);
struct xfrm_policy *xfrm_policy_byid(struct net *net, u8 type, int dir, u32 id,
int delete, int *err)
{
struct xfrm_policy *pol, *ret;
struct hlist_head *chain;
struct hlist_node *entry;
*err = -ENOENT;
if (xfrm_policy_id2dir(id) != dir)
return NULL;
*err = 0;
write_lock_bh(&xfrm_policy_lock);
chain = net->xfrm.policy_byidx + idx_hash(net, id);
ret = NULL;
hlist_for_each_entry(pol, entry, chain, byidx) {
if (pol->type == type && pol->index == id) {
xfrm_pol_hold(pol);
if (delete) {
*err = security_xfrm_policy_delete(
pol->security);
if (*err) {
write_unlock_bh(&xfrm_policy_lock);
return pol;
}
__xfrm_policy_unlink(pol, dir);
}
ret = pol;
break;
}
}
write_unlock_bh(&xfrm_policy_lock);
if (ret && delete) {
atomic_inc(&flow_cache_genid);
xfrm_policy_kill(ret);
}
return ret;
}
EXPORT_SYMBOL(xfrm_policy_byid);
#ifdef CONFIG_SECURITY_NETWORK_XFRM
static inline int
xfrm_policy_flush_secctx_check(struct net *net, u8 type, struct xfrm_audit *audit_info)
{
int dir, err = 0;
for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
struct xfrm_policy *pol;
struct hlist_node *entry;
int i;
hlist_for_each_entry(pol, entry,
&net->xfrm.policy_inexact[dir], bydst) {
if (pol->type != type)
continue;
err = security_xfrm_policy_delete(pol->security);
if (err) {
xfrm_audit_policy_delete(pol, 0,
audit_info->loginuid,
audit_info->sessionid,
audit_info->secid);
return err;
}
}
for (i = net->xfrm.policy_bydst[dir].hmask; i >= 0; i--) {
hlist_for_each_entry(pol, entry,
net->xfrm.policy_bydst[dir].table + i,
bydst) {
if (pol->type != type)
continue;
err = security_xfrm_policy_delete(
pol->security);
if (err) {
xfrm_audit_policy_delete(pol, 0,
audit_info->loginuid,
audit_info->sessionid,
audit_info->secid);
return err;
}
}
}
}
return err;
}
#else
static inline int
xfrm_policy_flush_secctx_check(struct net *net, u8 type, struct xfrm_audit *audit_info)
{
return 0;
}
#endif
int xfrm_policy_flush(struct net *net, u8 type, struct xfrm_audit *audit_info)
{
int dir, err = 0;
write_lock_bh(&xfrm_policy_lock);
err = xfrm_policy_flush_secctx_check(net, type, audit_info);
if (err)
goto out;
for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
struct xfrm_policy *pol;
struct hlist_node *entry;
int i;
again1:
hlist_for_each_entry(pol, entry,
&net->xfrm.policy_inexact[dir], bydst) {
if (pol->type != type)
continue;
__xfrm_policy_unlink(pol, dir);
write_unlock_bh(&xfrm_policy_lock);
xfrm_audit_policy_delete(pol, 1, audit_info->loginuid,
audit_info->sessionid,
audit_info->secid);
xfrm_policy_kill(pol);
write_lock_bh(&xfrm_policy_lock);
goto again1;
}
for (i = net->xfrm.policy_bydst[dir].hmask; i >= 0; i--) {
again2:
hlist_for_each_entry(pol, entry,
net->xfrm.policy_bydst[dir].table + i,
bydst) {
if (pol->type != type)
continue;
__xfrm_policy_unlink(pol, dir);
write_unlock_bh(&xfrm_policy_lock);
xfrm_audit_policy_delete(pol, 1,
audit_info->loginuid,
audit_info->sessionid,
audit_info->secid);
xfrm_policy_kill(pol);
write_lock_bh(&xfrm_policy_lock);
goto again2;
}
}
}
atomic_inc(&flow_cache_genid);
out:
write_unlock_bh(&xfrm_policy_lock);
return err;
}
EXPORT_SYMBOL(xfrm_policy_flush);
int xfrm_policy_walk(struct net *net, struct xfrm_policy_walk *walk,
int (*func)(struct xfrm_policy *, int, int, void*),
void *data)
{
struct xfrm_policy *pol;
struct xfrm_policy_walk_entry *x;
int error = 0;
if (walk->type >= XFRM_POLICY_TYPE_MAX &&
walk->type != XFRM_POLICY_TYPE_ANY)
return -EINVAL;
if (list_empty(&walk->walk.all) && walk->seq != 0)
return 0;
write_lock_bh(&xfrm_policy_lock);
if (list_empty(&walk->walk.all))
x = list_first_entry(&net->xfrm.policy_all, struct xfrm_policy_walk_entry, all);
else
x = list_entry(&walk->walk.all, struct xfrm_policy_walk_entry, all);
list_for_each_entry_from(x, &net->xfrm.policy_all, all) {
if (x->dead)
continue;
pol = container_of(x, struct xfrm_policy, walk);
if (walk->type != XFRM_POLICY_TYPE_ANY &&
walk->type != pol->type)
continue;
error = func(pol, xfrm_policy_id2dir(pol->index),
walk->seq, data);
if (error) {
list_move_tail(&walk->walk.all, &x->all);
goto out;
}
walk->seq++;
}
if (walk->seq == 0) {
error = -ENOENT;
goto out;
}
list_del_init(&walk->walk.all);
out:
write_unlock_bh(&xfrm_policy_lock);
return error;
}
EXPORT_SYMBOL(xfrm_policy_walk);
void xfrm_policy_walk_init(struct xfrm_policy_walk *walk, u8 type)
{
INIT_LIST_HEAD(&walk->walk.all);
walk->walk.dead = 1;
walk->type = type;
walk->seq = 0;
}
EXPORT_SYMBOL(xfrm_policy_walk_init);
void xfrm_policy_walk_done(struct xfrm_policy_walk *walk)
{
if (list_empty(&walk->walk.all))
return;
write_lock_bh(&xfrm_policy_lock);
list_del(&walk->walk.all);
write_unlock_bh(&xfrm_policy_lock);
}
EXPORT_SYMBOL(xfrm_policy_walk_done);
/*
* Find policy to apply to this flow.
*
* Returns 0 if policy found, else an -errno.
*/
static int xfrm_policy_match(struct xfrm_policy *pol, struct flowi *fl,
u8 type, u16 family, int dir)
{
struct xfrm_selector *sel = &pol->selector;
int match, ret = -ESRCH;
if (pol->family != family ||
pol->type != type)
return ret;
match = xfrm_selector_match(sel, fl, family);
if (match)
ret = security_xfrm_policy_lookup(pol->security, fl->secid,
dir);
return ret;
}
static struct xfrm_policy *xfrm_policy_lookup_bytype(struct net *net, u8 type,
struct flowi *fl,
u16 family, u8 dir)
{
int err;
struct xfrm_policy *pol, *ret;
xfrm_address_t *daddr, *saddr;
struct hlist_node *entry;
struct hlist_head *chain;
u32 priority = ~0U;
daddr = xfrm_flowi_daddr(fl, family);
saddr = xfrm_flowi_saddr(fl, family);
if (unlikely(!daddr || !saddr))
return NULL;
read_lock_bh(&xfrm_policy_lock);
chain = policy_hash_direct(net, daddr, saddr, family, dir);
ret = NULL;
hlist_for_each_entry(pol, entry, chain, bydst) {
err = xfrm_policy_match(pol, fl, type, family, dir);
if (err) {
if (err == -ESRCH)
continue;
else {
ret = ERR_PTR(err);
goto fail;
}
} else {
ret = pol;
priority = ret->priority;
break;
}
}
chain = &net->xfrm.policy_inexact[dir];
hlist_for_each_entry(pol, entry, chain, bydst) {
err = xfrm_policy_match(pol, fl, type, family, dir);
if (err) {
if (err == -ESRCH)
continue;
else {
ret = ERR_PTR(err);
goto fail;
}
} else if (pol->priority < priority) {
ret = pol;
break;
}
}
if (ret)
xfrm_pol_hold(ret);
fail:
read_unlock_bh(&xfrm_policy_lock);
return ret;
}
static int xfrm_policy_lookup(struct net *net, struct flowi *fl, u16 family,
u8 dir, void **objp, atomic_t **obj_refp)
{
struct xfrm_policy *pol;
int err = 0;
#ifdef CONFIG_XFRM_SUB_POLICY
pol = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_SUB, fl, family, dir);
if (IS_ERR(pol)) {
err = PTR_ERR(pol);
pol = NULL;
}
if (pol || err)
goto end;
#endif
pol = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN, fl, family, dir);
if (IS_ERR(pol)) {
err = PTR_ERR(pol);
pol = NULL;
}
#ifdef CONFIG_XFRM_SUB_POLICY
end:
#endif
if ((*objp = (void *) pol) != NULL)
*obj_refp = &pol->refcnt;
return err;
}
static inline int policy_to_flow_dir(int dir)
{
if (XFRM_POLICY_IN == FLOW_DIR_IN &&
XFRM_POLICY_OUT == FLOW_DIR_OUT &&
XFRM_POLICY_FWD == FLOW_DIR_FWD)
return dir;
switch (dir) {
default:
case XFRM_POLICY_IN:
return FLOW_DIR_IN;
case XFRM_POLICY_OUT:
return FLOW_DIR_OUT;
case XFRM_POLICY_FWD:
return FLOW_DIR_FWD;
}
}
static struct xfrm_policy *xfrm_sk_policy_lookup(struct sock *sk, int dir, struct flowi *fl)
{
struct xfrm_policy *pol;
read_lock_bh(&xfrm_policy_lock);
if ((pol = sk->sk_policy[dir]) != NULL) {
int match = xfrm_selector_match(&pol->selector, fl,
sk->sk_family);
int err = 0;
if (match) {
err = security_xfrm_policy_lookup(pol->security,
fl->secid,
policy_to_flow_dir(dir));
if (!err)
xfrm_pol_hold(pol);
else if (err == -ESRCH)
pol = NULL;
else
pol = ERR_PTR(err);
} else
pol = NULL;
}
read_unlock_bh(&xfrm_policy_lock);
return pol;
}
static void __xfrm_policy_link(struct xfrm_policy *pol, int dir)
{
struct net *net = xp_net(pol);
struct hlist_head *chain = policy_hash_bysel(net, &pol->selector,
pol->family, dir);
list_add(&pol->walk.all, &net->xfrm.policy_all);
hlist_add_head(&pol->bydst, chain);
hlist_add_head(&pol->byidx, net->xfrm.policy_byidx+idx_hash(net, pol->index));
net->xfrm.policy_count[dir]++;
xfrm_pol_hold(pol);
if (xfrm_bydst_should_resize(net, dir, NULL))
schedule_work(&net->xfrm.policy_hash_work);
}
static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
int dir)
{
struct net *net = xp_net(pol);
if (hlist_unhashed(&pol->bydst))
return NULL;
hlist_del(&pol->bydst);
hlist_del(&pol->byidx);
list_del(&pol->walk.all);
net->xfrm.policy_count[dir]--;
return pol;
}
int xfrm_policy_delete(struct xfrm_policy *pol, int dir)
{
write_lock_bh(&xfrm_policy_lock);
pol = __xfrm_policy_unlink(pol, dir);
write_unlock_bh(&xfrm_policy_lock);
if (pol) {
if (dir < XFRM_POLICY_MAX)
atomic_inc(&flow_cache_genid);
xfrm_policy_kill(pol);
return 0;
}
return -ENOENT;
}
EXPORT_SYMBOL(xfrm_policy_delete);
int xfrm_sk_policy_insert(struct sock *sk, int dir, struct xfrm_policy *pol)
{
struct net *net = xp_net(pol);
struct xfrm_policy *old_pol;
#ifdef CONFIG_XFRM_SUB_POLICY
if (pol && pol->type != XFRM_POLICY_TYPE_MAIN)
return -EINVAL;
#endif
write_lock_bh(&xfrm_policy_lock);
old_pol = sk->sk_policy[dir];
sk->sk_policy[dir] = pol;
if (pol) {
pol->curlft.add_time = get_seconds();
pol->index = xfrm_gen_index(net, XFRM_POLICY_MAX+dir);
__xfrm_policy_link(pol, XFRM_POLICY_MAX+dir);
}
if (old_pol)
__xfrm_policy_unlink(old_pol, XFRM_POLICY_MAX+dir);
write_unlock_bh(&xfrm_policy_lock);
if (old_pol) {
xfrm_policy_kill(old_pol);
}
return 0;
}
static struct xfrm_policy *clone_policy(struct xfrm_policy *old, int dir)
{
struct xfrm_policy *newp = xfrm_policy_alloc(xp_net(old), GFP_ATOMIC);
if (newp) {
newp->selector = old->selector;
if (security_xfrm_policy_clone(old->security,
&newp->security)) {
kfree(newp);
return NULL; /* ENOMEM */
}
newp->lft = old->lft;
newp->curlft = old->curlft;
newp->action = old->action;
newp->flags = old->flags;
newp->xfrm_nr = old->xfrm_nr;
newp->index = old->index;
newp->type = old->type;
memcpy(newp->xfrm_vec, old->xfrm_vec,
newp->xfrm_nr*sizeof(struct xfrm_tmpl));
write_lock_bh(&xfrm_policy_lock);
__xfrm_policy_link(newp, XFRM_POLICY_MAX+dir);
write_unlock_bh(&xfrm_policy_lock);
xfrm_pol_put(newp);
}
return newp;
}
int __xfrm_sk_clone_policy(struct sock *sk)
{
struct xfrm_policy *p0 = sk->sk_policy[0],
*p1 = sk->sk_policy[1];
sk->sk_policy[0] = sk->sk_policy[1] = NULL;
if (p0 && (sk->sk_policy[0] = clone_policy(p0, 0)) == NULL)
return -ENOMEM;
if (p1 && (sk->sk_policy[1] = clone_policy(p1, 1)) == NULL)
return -ENOMEM;
return 0;
}
static int
xfrm_get_saddr(struct net *net, xfrm_address_t *local, xfrm_address_t *remote,
unsigned short family)
{
int err;
struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
if (unlikely(afinfo == NULL))
return -EINVAL;
err = afinfo->get_saddr(net, local, remote);
xfrm_policy_put_afinfo(afinfo);
return err;
}
/* Resolve list of templates for the flow, given policy. */
static int
xfrm_tmpl_resolve_one(struct xfrm_policy *policy, struct flowi *fl,
struct xfrm_state **xfrm,
unsigned short family)
{
struct net *net = xp_net(policy);
int nx;
int i, error;
xfrm_address_t *daddr = xfrm_flowi_daddr(fl, family);
xfrm_address_t *saddr = xfrm_flowi_saddr(fl, family);
xfrm_address_t tmp;
for (nx=0, i = 0; i < policy->xfrm_nr; i++) {
struct xfrm_state *x;
xfrm_address_t *remote = daddr;
xfrm_address_t *local = saddr;
struct xfrm_tmpl *tmpl = &policy->xfrm_vec[i];
if (tmpl->mode == XFRM_MODE_TUNNEL ||
tmpl->mode == XFRM_MODE_BEET) {
remote = &tmpl->id.daddr;
local = &tmpl->saddr;
family = tmpl->encap_family;
if (xfrm_addr_any(local, family)) {
error = xfrm_get_saddr(net, &tmp, remote, family);
if (error)
goto fail;
local = &tmp;
}
}
x = xfrm_state_find(remote, local, fl, tmpl, policy, &error, family);
if (x && x->km.state == XFRM_STATE_VALID) {
xfrm[nx++] = x;
daddr = remote;
saddr = local;
continue;
}
if (x) {
error = (x->km.state == XFRM_STATE_ERROR ?
-EINVAL : -EAGAIN);
xfrm_state_put(x);
}
else if (error == -ESRCH)
error = -EAGAIN;
if (!tmpl->optional)
goto fail;
}
return nx;
fail:
for (nx--; nx>=0; nx--)
xfrm_state_put(xfrm[nx]);
return error;
}
static int
xfrm_tmpl_resolve(struct xfrm_policy **pols, int npols, struct flowi *fl,
struct xfrm_state **xfrm,
unsigned short family)
{
struct xfrm_state *tp[XFRM_MAX_DEPTH];
struct xfrm_state **tpp = (npols > 1) ? tp : xfrm;
int cnx = 0;
int error;
int ret;
int i;
for (i = 0; i < npols; i++) {
if (cnx + pols[i]->xfrm_nr >= XFRM_MAX_DEPTH) {
error = -ENOBUFS;
goto fail;
}
ret = xfrm_tmpl_resolve_one(pols[i], fl, &tpp[cnx], family);
if (ret < 0) {
error = ret;
goto fail;
} else
cnx += ret;
}
/* found states are sorted for outbound processing */
if (npols > 1)
xfrm_state_sort(xfrm, tpp, cnx, family);
return cnx;
fail:
for (cnx--; cnx>=0; cnx--)
xfrm_state_put(tpp[cnx]);
return error;
}
/* Check that the bundle accepts the flow and its components are
* still valid.
*/
static struct dst_entry *
xfrm_find_bundle(struct flowi *fl, struct xfrm_policy *policy, unsigned short family)
{
struct dst_entry *x;
struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
if (unlikely(afinfo == NULL))
return ERR_PTR(-EINVAL);
x = afinfo->find_bundle(fl, policy);
xfrm_policy_put_afinfo(afinfo);
return x;
}
static inline int xfrm_get_tos(struct flowi *fl, int family)
{
struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
int tos;
if (!afinfo)
return -EINVAL;
tos = afinfo->get_tos(fl);
xfrm_policy_put_afinfo(afinfo);
return tos;
}
static inline struct xfrm_dst *xfrm_alloc_dst(int family)
{
struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
struct xfrm_dst *xdst;
if (!afinfo)
return ERR_PTR(-EINVAL);
xdst = dst_alloc(afinfo->dst_ops) ?: ERR_PTR(-ENOBUFS);
xfrm_policy_put_afinfo(afinfo);
return xdst;
}
static inline int xfrm_init_path(struct xfrm_dst *path, struct dst_entry *dst,
int nfheader_len)
{
struct xfrm_policy_afinfo *afinfo =
xfrm_policy_get_afinfo(dst->ops->family);
int err;
if (!afinfo)
return -EINVAL;
err = afinfo->init_path(path, dst, nfheader_len);
xfrm_policy_put_afinfo(afinfo);
return err;
}
static inline int xfrm_fill_dst(struct xfrm_dst *xdst, struct net_device *dev)
{
struct xfrm_policy_afinfo *afinfo =
xfrm_policy_get_afinfo(xdst->u.dst.ops->family);
int err;
if (!afinfo)
return -EINVAL;
err = afinfo->fill_dst(xdst, dev);
xfrm_policy_put_afinfo(afinfo);
return err;
}
/* Allocate chain of dst_entry's, attach known xfrm's, calculate
* all the metrics... Shortly, bundle a bundle.
*/
static struct dst_entry *xfrm_bundle_create(struct xfrm_policy *policy,
struct xfrm_state **xfrm, int nx,
struct flowi *fl,
struct dst_entry *dst)
{
unsigned long now = jiffies;
struct net_device *dev;
struct dst_entry *dst_prev = NULL;
struct dst_entry *dst0 = NULL;
int i = 0;
int err;
int header_len = 0;
int nfheader_len = 0;
int trailer_len = 0;
int tos;
int family = policy->selector.family;
xfrm_address_t saddr, daddr;
xfrm_flowi_addr_get(fl, &saddr, &daddr, family);
tos = xfrm_get_tos(fl, family);
err = tos;
if (tos < 0)
goto put_states;
dst_hold(dst);
for (; i < nx; i++) {
struct xfrm_dst *xdst = xfrm_alloc_dst(family);
struct dst_entry *dst1 = &xdst->u.dst;
err = PTR_ERR(xdst);
if (IS_ERR(xdst)) {
dst_release(dst);
goto put_states;
}
if (!dst_prev)
dst0 = dst1;
else {
dst_prev->child = dst_clone(dst1);
dst1->flags |= DST_NOHASH;
}
xdst->route = dst;
memcpy(&dst1->metrics, &dst->metrics, sizeof(dst->metrics));
if (xfrm[i]->props.mode != XFRM_MODE_TRANSPORT) {
family = xfrm[i]->props.family;
dst = xfrm_dst_lookup(xfrm[i], tos, &saddr, &daddr,
family);
err = PTR_ERR(dst);
if (IS_ERR(dst))
goto put_states;
} else
dst_hold(dst);
dst1->xfrm = xfrm[i];
xdst->genid = xfrm[i]->genid;
dst1->obsolete = -1;
dst1->flags |= DST_HOST;
dst1->lastuse = now;
dst1->input = dst_discard;
dst1->output = xfrm[i]->outer_mode->afinfo->output;
dst1->next = dst_prev;
dst_prev = dst1;
header_len += xfrm[i]->props.header_len;
if (xfrm[i]->type->flags & XFRM_TYPE_NON_FRAGMENT)
nfheader_len += xfrm[i]->props.header_len;
trailer_len += xfrm[i]->props.trailer_len;
}
dst_prev->child = dst;
dst0->path = dst;
err = -ENODEV;
dev = dst->dev;
if (!dev)
goto free_dst;
/* Copy neighbout for reachability confirmation */
dst0->neighbour = neigh_clone(dst->neighbour);
xfrm_init_path((struct xfrm_dst *)dst0, dst, nfheader_len);
xfrm_init_pmtu(dst_prev);
for (dst_prev = dst0; dst_prev != dst; dst_prev = dst_prev->child) {
struct xfrm_dst *xdst = (struct xfrm_dst *)dst_prev;
err = xfrm_fill_dst(xdst, dev);
if (err)
goto free_dst;
dst_prev->header_len = header_len;
dst_prev->trailer_len = trailer_len;
header_len -= xdst->u.dst.xfrm->props.header_len;
trailer_len -= xdst->u.dst.xfrm->props.trailer_len;
}
out:
return dst0;
put_states:
for (; i < nx; i++)
xfrm_state_put(xfrm[i]);
free_dst:
if (dst0)
dst_free(dst0);
dst0 = ERR_PTR(err);
goto out;
}
static int inline
xfrm_dst_alloc_copy(void **target, void *src, int size)
{
if (!*target) {
*target = kmalloc(size, GFP_ATOMIC);
if (!*target)
return -ENOMEM;
}
memcpy(*target, src, size);
return 0;
}
static int inline
xfrm_dst_update_parent(struct dst_entry *dst, struct xfrm_selector *sel)
{
#ifdef CONFIG_XFRM_SUB_POLICY
struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
return xfrm_dst_alloc_copy((void **)&(xdst->partner),
sel, sizeof(*sel));
#else
return 0;
#endif
}
static int inline
xfrm_dst_update_origin(struct dst_entry *dst, struct flowi *fl)
{
#ifdef CONFIG_XFRM_SUB_POLICY
struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
return xfrm_dst_alloc_copy((void **)&(xdst->origin), fl, sizeof(*fl));
#else
return 0;
#endif
}
static int stale_bundle(struct dst_entry *dst);
/* Main function: finds/creates a bundle for given flow.
*
* At the moment we eat a raw IP route. Mostly to speed up lookups
* on interfaces with disabled IPsec.
*/
int __xfrm_lookup(struct net *net, struct dst_entry **dst_p, struct flowi *fl,
struct sock *sk, int flags)
{
struct xfrm_policy *policy;
struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
int npols;
int pol_dead;
int xfrm_nr;
int pi;
struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
struct dst_entry *dst, *dst_orig = *dst_p;
int nx = 0;
int err;
u32 genid;
u16 family;
u8 dir = policy_to_flow_dir(XFRM_POLICY_OUT);
restart:
genid = atomic_read(&flow_cache_genid);
policy = NULL;
for (pi = 0; pi < ARRAY_SIZE(pols); pi++)
pols[pi] = NULL;
npols = 0;
pol_dead = 0;
xfrm_nr = 0;
if (sk && sk->sk_policy[XFRM_POLICY_OUT]) {
policy = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl);
err = PTR_ERR(policy);
if (IS_ERR(policy)) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
goto dropdst;
}
}
if (!policy) {
/* To accelerate a bit... */
if ((dst_orig->flags & DST_NOXFRM) ||
!net->xfrm.policy_count[XFRM_POLICY_OUT])
goto nopol;
policy = flow_cache_lookup(net, fl, dst_orig->ops->family,
dir, xfrm_policy_lookup);
err = PTR_ERR(policy);
if (IS_ERR(policy)) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
goto dropdst;
}
}
if (!policy)
goto nopol;
family = dst_orig->ops->family;
pols[0] = policy;
npols ++;
xfrm_nr += pols[0]->xfrm_nr;
err = -ENOENT;
if ((flags & XFRM_LOOKUP_ICMP) && !(policy->flags & XFRM_POLICY_ICMP))
goto error;
policy->curlft.use_time = get_seconds();
switch (policy->action) {
default:
case XFRM_POLICY_BLOCK:
/* Prohibit the flow */
XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLBLOCK);
err = -EPERM;
goto error;
case XFRM_POLICY_ALLOW:
#ifndef CONFIG_XFRM_SUB_POLICY
if (policy->xfrm_nr == 0) {
/* Flow passes not transformed. */
xfrm_pol_put(policy);
return 0;
}
#endif
/* Try to find matching bundle.
*
* LATER: help from flow cache. It is optional, this
* is required only for output policy.
*/
dst = xfrm_find_bundle(fl, policy, family);
if (IS_ERR(dst)) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLECHECKERROR);
err = PTR_ERR(dst);
goto error;
}
if (dst)
break;
#ifdef CONFIG_XFRM_SUB_POLICY
if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
pols[1] = xfrm_policy_lookup_bytype(net,
XFRM_POLICY_TYPE_MAIN,
fl, family,
XFRM_POLICY_OUT);
if (pols[1]) {
if (IS_ERR(pols[1])) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
err = PTR_ERR(pols[1]);
goto error;
}
if (pols[1]->action == XFRM_POLICY_BLOCK) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLBLOCK);
err = -EPERM;
goto error;
}
npols ++;
xfrm_nr += pols[1]->xfrm_nr;
}
}
/*
* Because neither flowi nor bundle information knows about
* transformation template size. On more than one policy usage
* we can realize whether all of them is bypass or not after
* they are searched. See above not-transformed bypass
* is surrounded by non-sub policy configuration, too.
*/
if (xfrm_nr == 0) {
/* Flow passes not transformed. */
xfrm_pols_put(pols, npols);
return 0;
}
#endif
nx = xfrm_tmpl_resolve(pols, npols, fl, xfrm, family);
if (unlikely(nx<0)) {
err = nx;
if (err == -EAGAIN && net->xfrm.sysctl_larval_drop) {
/* EREMOTE tells the caller to generate
* a one-shot blackhole route.
*/
XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
xfrm_pol_put(policy);
return -EREMOTE;
}
if (err == -EAGAIN && (flags & XFRM_LOOKUP_WAIT)) {
DECLARE_WAITQUEUE(wait, current);
add_wait_queue(&net->xfrm.km_waitq, &wait);
set_current_state(TASK_INTERRUPTIBLE);
schedule();
set_current_state(TASK_RUNNING);
remove_wait_queue(&net->xfrm.km_waitq, &wait);
nx = xfrm_tmpl_resolve(pols, npols, fl, xfrm, family);
if (nx == -EAGAIN && signal_pending(current)) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
err = -ERESTART;
goto error;
}
if (nx == -EAGAIN ||
genid != atomic_read(&flow_cache_genid)) {
xfrm_pols_put(pols, npols);
goto restart;
}
err = nx;
}
if (err < 0) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
goto error;
}
}
if (nx == 0) {
/* Flow passes not transformed. */
xfrm_pols_put(pols, npols);
return 0;
}
dst = xfrm_bundle_create(policy, xfrm, nx, fl, dst_orig);
err = PTR_ERR(dst);
if (IS_ERR(dst)) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLEGENERROR);
goto error;
}
for (pi = 0; pi < npols; pi++) {
read_lock_bh(&pols[pi]->lock);
pol_dead |= pols[pi]->walk.dead;
read_unlock_bh(&pols[pi]->lock);
}
write_lock_bh(&policy->lock);
if (unlikely(pol_dead || stale_bundle(dst))) {
/* Wow! While we worked on resolving, this
* policy has gone. Retry. It is not paranoia,
* we just cannot enlist new bundle to dead object.
* We can't enlist stable bundles either.
*/
write_unlock_bh(&policy->lock);
dst_free(dst);
if (pol_dead)
XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLDEAD);
else
XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLECHECKERROR);
err = -EHOSTUNREACH;
goto error;
}
if (npols > 1)
err = xfrm_dst_update_parent(dst, &pols[1]->selector);
else
err = xfrm_dst_update_origin(dst, fl);
if (unlikely(err)) {
write_unlock_bh(&policy->lock);
dst_free(dst);
XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLECHECKERROR);
goto error;
}
dst->next = policy->bundles;
policy->bundles = dst;
dst_hold(dst);
write_unlock_bh(&policy->lock);
}
*dst_p = dst;
dst_release(dst_orig);
xfrm_pols_put(pols, npols);
return 0;
error:
xfrm_pols_put(pols, npols);
dropdst:
dst_release(dst_orig);
*dst_p = NULL;
return err;
nopol:
err = -ENOENT;
if (flags & XFRM_LOOKUP_ICMP)
goto dropdst;
return 0;
}
EXPORT_SYMBOL(__xfrm_lookup);
int xfrm_lookup(struct net *net, struct dst_entry **dst_p, struct flowi *fl,
struct sock *sk, int flags)
{
int err = __xfrm_lookup(net, dst_p, fl, sk, flags);
if (err == -EREMOTE) {
dst_release(*dst_p);
*dst_p = NULL;
err = -EAGAIN;
}
return err;
}
EXPORT_SYMBOL(xfrm_lookup);
static inline int
xfrm_secpath_reject(int idx, struct sk_buff *skb, struct flowi *fl)
{
struct xfrm_state *x;
if (!skb->sp || idx < 0 || idx >= skb->sp->len)
return 0;
x = skb->sp->xvec[idx];
if (!x->type->reject)
return 0;
return x->type->reject(x, skb, fl);
}
/* When skb is transformed back to its "native" form, we have to
* check policy restrictions. At the moment we make this in maximally
* stupid way. Shame on me. :-) Of course, connected sockets must
* have policy cached at them.
*/
static inline int
xfrm_state_ok(struct xfrm_tmpl *tmpl, struct xfrm_state *x,
unsigned short family)
{
if (xfrm_state_kern(x))
return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, tmpl->encap_family);
return x->id.proto == tmpl->id.proto &&
(x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
(x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
x->props.mode == tmpl->mode &&
(tmpl->allalgs || (tmpl->aalgos & (1<<x->props.aalgo)) ||
!(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
!(x->props.mode != XFRM_MODE_TRANSPORT &&
xfrm_state_addr_cmp(tmpl, x, family));
}
/*
* 0 or more than 0 is returned when validation is succeeded (either bypass
* because of optional transport mode, or next index of the mathced secpath
* state with the template.
* -1 is returned when no matching template is found.
* Otherwise "-2 - errored_index" is returned.
*/
static inline int
xfrm_policy_ok(struct xfrm_tmpl *tmpl, struct sec_path *sp, int start,
unsigned short family)
{
int idx = start;
if (tmpl->optional) {
if (tmpl->mode == XFRM_MODE_TRANSPORT)
return start;
} else
start = -1;
for (; idx < sp->len; idx++) {
if (xfrm_state_ok(tmpl, sp->xvec[idx], family))
return ++idx;
if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
if (start == -1)
start = -2-idx;
break;
}
}
return start;
}
int __xfrm_decode_session(struct sk_buff *skb, struct flowi *fl,
unsigned int family, int reverse)
{
struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
int err;
if (unlikely(afinfo == NULL))
return -EAFNOSUPPORT;
afinfo->decode_session(skb, fl, reverse);
err = security_xfrm_decode_session(skb, &fl->secid);
xfrm_policy_put_afinfo(afinfo);
return err;
}
EXPORT_SYMBOL(__xfrm_decode_session);
static inline int secpath_has_nontransport(struct sec_path *sp, int k, int *idxp)
{
for (; k < sp->len; k++) {
if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
*idxp = k;
return 1;
}
}
return 0;
}
int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb,
unsigned short family)
{
struct net *net = dev_net(skb->dev);
struct xfrm_policy *pol;
struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
int npols = 0;
int xfrm_nr;
int pi;
int reverse;
struct flowi fl;
u8 fl_dir;
int xerr_idx = -1;
reverse = dir & ~XFRM_POLICY_MASK;
dir &= XFRM_POLICY_MASK;
fl_dir = policy_to_flow_dir(dir);
if (__xfrm_decode_session(skb, &fl, family, reverse) < 0) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMINHDRERROR);
return 0;
}
nf_nat_decode_session(skb, &fl, family);
/* First, check used SA against their selectors. */
if (skb->sp) {
int i;
for (i=skb->sp->len-1; i>=0; i--) {
struct xfrm_state *x = skb->sp->xvec[i];
if (!xfrm_selector_match(&x->sel, &fl, family)) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMINSTATEMISMATCH);
return 0;
}
}
}
pol = NULL;
if (sk && sk->sk_policy[dir]) {
pol = xfrm_sk_policy_lookup(sk, dir, &fl);
if (IS_ERR(pol)) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
return 0;
}
}
if (!pol)
pol = flow_cache_lookup(net, &fl, family, fl_dir,
xfrm_policy_lookup);
if (IS_ERR(pol)) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
return 0;
}
if (!pol) {
if (skb->sp && secpath_has_nontransport(skb->sp, 0, &xerr_idx)) {
xfrm_secpath_reject(xerr_idx, skb, &fl);
XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
return 0;
}
return 1;
}
pol->curlft.use_time = get_seconds();
pols[0] = pol;
npols ++;
#ifdef CONFIG_XFRM_SUB_POLICY
if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
pols[1] = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN,
&fl, family,
XFRM_POLICY_IN);
if (pols[1]) {
if (IS_ERR(pols[1])) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
return 0;
}
pols[1]->curlft.use_time = get_seconds();
npols ++;
}
}
#endif
if (pol->action == XFRM_POLICY_ALLOW) {
struct sec_path *sp;
static struct sec_path dummy;
struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
struct xfrm_tmpl **tpp = tp;
int ti = 0;
int i, k;
if ((sp = skb->sp) == NULL)
sp = &dummy;
for (pi = 0; pi < npols; pi++) {
if (pols[pi] != pol &&
pols[pi]->action != XFRM_POLICY_ALLOW) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
goto reject;
}
if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
goto reject_error;
}
for (i = 0; i < pols[pi]->xfrm_nr; i++)
tpp[ti++] = &pols[pi]->xfrm_vec[i];
}
xfrm_nr = ti;
if (npols > 1) {
xfrm_tmpl_sort(stp, tpp, xfrm_nr, family);
tpp = stp;
}
/* For each tunnel xfrm, find the first matching tmpl.
* For each tmpl before that, find corresponding xfrm.
* Order is _important_. Later we will implement
* some barriers, but at the moment barriers
* are implied between each two transformations.
*/
for (i = xfrm_nr-1, k = 0; i >= 0; i--) {
k = xfrm_policy_ok(tpp[i], sp, k, family);
if (k < 0) {
if (k < -1)
/* "-2 - errored_index" returned */
xerr_idx = -(2+k);
XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
goto reject;
}
}
if (secpath_has_nontransport(sp, k, &xerr_idx)) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
goto reject;
}
xfrm_pols_put(pols, npols);
return 1;
}
XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
reject:
xfrm_secpath_reject(xerr_idx, skb, &fl);
reject_error:
xfrm_pols_put(pols, npols);
return 0;
}
EXPORT_SYMBOL(__xfrm_policy_check);
int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
{
struct net *net = dev_net(skb->dev);
struct flowi fl;
struct dst_entry *dst;
int res;
if (xfrm_decode_session(skb, &fl, family) < 0) {
/* XXX: we should have something like FWDHDRERROR here. */
XFRM_INC_STATS(net, LINUX_MIB_XFRMINHDRERROR);
return 0;
}
dst = skb_dst(skb);
res = xfrm_lookup(net, &dst, &fl, NULL, 0) == 0;
skb_dst_set(skb, dst);
return res;
}
EXPORT_SYMBOL(__xfrm_route_forward);
/* Optimize later using cookies and generation ids. */
static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
{
/* Code (such as __xfrm4_bundle_create()) sets dst->obsolete
* to "-1" to force all XFRM destinations to get validated by
* dst_ops->check on every use. We do this because when a
* normal route referenced by an XFRM dst is obsoleted we do
* not go looking around for all parent referencing XFRM dsts
* so that we can invalidate them. It is just too much work.
* Instead we make the checks here on every use. For example:
*
* XFRM dst A --> IPv4 dst X
*
* X is the "xdst->route" of A (X is also the "dst->path" of A
* in this example). If X is marked obsolete, "A" will not
* notice. That's what we are validating here via the
* stale_bundle() check.
*
* When a policy's bundle is pruned, we dst_free() the XFRM
* dst which causes it's ->obsolete field to be set to a
* positive non-zero integer. If an XFRM dst has been pruned
* like this, we want to force a new route lookup.
*/
if (dst->obsolete < 0 && !stale_bundle(dst))
return dst;
return NULL;
}
static int stale_bundle(struct dst_entry *dst)
{
return !xfrm_bundle_ok(NULL, (struct xfrm_dst *)dst, NULL, AF_UNSPEC, 0);
}
void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
{
while ((dst = dst->child) && dst->xfrm && dst->dev == dev) {
dst->dev = dev_net(dev)->loopback_dev;
dev_hold(dst->dev);
dev_put(dev);
}
}
EXPORT_SYMBOL(xfrm_dst_ifdown);
static void xfrm_link_failure(struct sk_buff *skb)
{
/* Impossible. Such dst must be popped before reaches point of failure. */
return;
}
static struct dst_entry *xfrm_negative_advice(struct dst_entry *dst)
{
if (dst) {
if (dst->obsolete) {
dst_release(dst);
dst = NULL;
}
}
return dst;
}
static void prune_one_bundle(struct xfrm_policy *pol, int (*func)(struct dst_entry *), struct dst_entry **gc_list_p)
{
struct dst_entry *dst, **dstp;
write_lock(&pol->lock);
dstp = &pol->bundles;
while ((dst=*dstp) != NULL) {
if (func(dst)) {
*dstp = dst->next;
dst->next = *gc_list_p;
*gc_list_p = dst;
} else {
dstp = &dst->next;
}
}
write_unlock(&pol->lock);
}
static void xfrm_prune_bundles(struct net *net, int (*func)(struct dst_entry *))
{
struct dst_entry *gc_list = NULL;
int dir;
read_lock_bh(&xfrm_policy_lock);
for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
struct xfrm_policy *pol;
struct hlist_node *entry;
struct hlist_head *table;
int i;
hlist_for_each_entry(pol, entry,
&net->xfrm.policy_inexact[dir], bydst)
prune_one_bundle(pol, func, &gc_list);
table = net->xfrm.policy_bydst[dir].table;
for (i = net->xfrm.policy_bydst[dir].hmask; i >= 0; i--) {
hlist_for_each_entry(pol, entry, table + i, bydst)
prune_one_bundle(pol, func, &gc_list);
}
}
read_unlock_bh(&xfrm_policy_lock);
while (gc_list) {
struct dst_entry *dst = gc_list;
gc_list = dst->next;
dst_free(dst);
}
}
static int unused_bundle(struct dst_entry *dst)
{
return !atomic_read(&dst->__refcnt);
}
static void __xfrm_garbage_collect(struct net *net)
{
xfrm_prune_bundles(net, unused_bundle);
}
static int xfrm_flush_bundles(struct net *net)
{
xfrm_prune_bundles(net, stale_bundle);
return 0;
}
static void xfrm_init_pmtu(struct dst_entry *dst)
{
do {
struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
u32 pmtu, route_mtu_cached;
pmtu = dst_mtu(dst->child);
xdst->child_mtu_cached = pmtu;
pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
route_mtu_cached = dst_mtu(xdst->route);
xdst->route_mtu_cached = route_mtu_cached;
if (pmtu > route_mtu_cached)
pmtu = route_mtu_cached;
dst->metrics[RTAX_MTU-1] = pmtu;
} while ((dst = dst->next));
}
/* Check that the bundle accepts the flow and its components are
* still valid.
*/
int xfrm_bundle_ok(struct xfrm_policy *pol, struct xfrm_dst *first,
struct flowi *fl, int family, int strict)
{
struct dst_entry *dst = &first->u.dst;
struct xfrm_dst *last;
u32 mtu;
if (!dst_check(dst->path, ((struct xfrm_dst *)dst)->path_cookie) ||
(dst->dev && !netif_running(dst->dev)))
return 0;
#ifdef CONFIG_XFRM_SUB_POLICY
if (fl) {
if (first->origin && !flow_cache_uli_match(first->origin, fl))
return 0;
if (first->partner &&
!xfrm_selector_match(first->partner, fl, family))
return 0;
}
#endif
last = NULL;
do {
struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
if (fl && !xfrm_selector_match(&dst->xfrm->sel, fl, family))
return 0;
if (fl && pol &&
!security_xfrm_state_pol_flow_match(dst->xfrm, pol, fl))
return 0;
if (dst->xfrm->km.state != XFRM_STATE_VALID)
return 0;
if (xdst->genid != dst->xfrm->genid)
return 0;
if (strict && fl &&
!(dst->xfrm->outer_mode->flags & XFRM_MODE_FLAG_TUNNEL) &&
!xfrm_state_addr_flow_check(dst->xfrm, fl, family))
return 0;
mtu = dst_mtu(dst->child);
if (xdst->child_mtu_cached != mtu) {
last = xdst;
xdst->child_mtu_cached = mtu;
}
if (!dst_check(xdst->route, xdst->route_cookie))
return 0;
mtu = dst_mtu(xdst->route);
if (xdst->route_mtu_cached != mtu) {
last = xdst;
xdst->route_mtu_cached = mtu;
}
dst = dst->child;
} while (dst->xfrm);
if (likely(!last))
return 1;
mtu = last->child_mtu_cached;
for (;;) {
dst = &last->u.dst;
mtu = xfrm_state_mtu(dst->xfrm, mtu);
if (mtu > last->route_mtu_cached)
mtu = last->route_mtu_cached;
dst->metrics[RTAX_MTU-1] = mtu;
if (last == first)
break;
last = (struct xfrm_dst *)last->u.dst.next;
last->child_mtu_cached = mtu;
}
return 1;
}
EXPORT_SYMBOL(xfrm_bundle_ok);
int xfrm_policy_register_afinfo(struct xfrm_policy_afinfo *afinfo)
{
int err = 0;
if (unlikely(afinfo == NULL))
return -EINVAL;
if (unlikely(afinfo->family >= NPROTO))
return -EAFNOSUPPORT;
write_lock_bh(&xfrm_policy_afinfo_lock);
if (unlikely(xfrm_policy_afinfo[afinfo->family] != NULL))
err = -ENOBUFS;
else {
struct dst_ops *dst_ops = afinfo->dst_ops;
if (likely(dst_ops->kmem_cachep == NULL))
dst_ops->kmem_cachep = xfrm_dst_cache;
if (likely(dst_ops->check == NULL))
dst_ops->check = xfrm_dst_check;
if (likely(dst_ops->negative_advice == NULL))
dst_ops->negative_advice = xfrm_negative_advice;
if (likely(dst_ops->link_failure == NULL))
dst_ops->link_failure = xfrm_link_failure;
if (likely(afinfo->garbage_collect == NULL))
afinfo->garbage_collect = __xfrm_garbage_collect;
xfrm_policy_afinfo[afinfo->family] = afinfo;
}
write_unlock_bh(&xfrm_policy_afinfo_lock);
return err;
}
EXPORT_SYMBOL(xfrm_policy_register_afinfo);
int xfrm_policy_unregister_afinfo(struct xfrm_policy_afinfo *afinfo)
{
int err = 0;
if (unlikely(afinfo == NULL))
return -EINVAL;
if (unlikely(afinfo->family >= NPROTO))
return -EAFNOSUPPORT;
write_lock_bh(&xfrm_policy_afinfo_lock);
if (likely(xfrm_policy_afinfo[afinfo->family] != NULL)) {
if (unlikely(xfrm_policy_afinfo[afinfo->family] != afinfo))
err = -EINVAL;
else {
struct dst_ops *dst_ops = afinfo->dst_ops;
xfrm_policy_afinfo[afinfo->family] = NULL;
dst_ops->kmem_cachep = NULL;
dst_ops->check = NULL;
dst_ops->negative_advice = NULL;
dst_ops->link_failure = NULL;
afinfo->garbage_collect = NULL;
}
}
write_unlock_bh(&xfrm_policy_afinfo_lock);
return err;
}
EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
static struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family)
{
struct xfrm_policy_afinfo *afinfo;
if (unlikely(family >= NPROTO))
return NULL;
read_lock(&xfrm_policy_afinfo_lock);
afinfo = xfrm_policy_afinfo[family];
if (unlikely(!afinfo))
read_unlock(&xfrm_policy_afinfo_lock);
return afinfo;
}
static void xfrm_policy_put_afinfo(struct xfrm_policy_afinfo *afinfo)
{
read_unlock(&xfrm_policy_afinfo_lock);
}
static int xfrm_dev_event(struct notifier_block *this, unsigned long event, void *ptr)
{
struct net_device *dev = ptr;
switch (event) {
case NETDEV_DOWN:
xfrm_flush_bundles(dev_net(dev));
}
return NOTIFY_DONE;
}
static struct notifier_block xfrm_dev_notifier = {
.notifier_call = xfrm_dev_event,
};
#ifdef CONFIG_XFRM_STATISTICS
static int __net_init xfrm_statistics_init(struct net *net)
{
int rv;
if (snmp_mib_init((void **)net->mib.xfrm_statistics,
sizeof(struct linux_xfrm_mib)) < 0)
return -ENOMEM;
rv = xfrm_proc_init(net);
if (rv < 0)
snmp_mib_free((void **)net->mib.xfrm_statistics);
return rv;
}
static void xfrm_statistics_fini(struct net *net)
{
xfrm_proc_fini(net);
snmp_mib_free((void **)net->mib.xfrm_statistics);
}
#else
static int __net_init xfrm_statistics_init(struct net *net)
{
return 0;
}
static void xfrm_statistics_fini(struct net *net)
{
}
#endif
static int __net_init xfrm_policy_init(struct net *net)
{
unsigned int hmask, sz;
int dir;
if (net_eq(net, &init_net))
xfrm_dst_cache = kmem_cache_create("xfrm_dst_cache",
sizeof(struct xfrm_dst),
0, SLAB_HWCACHE_ALIGN|SLAB_PANIC,
NULL);
hmask = 8 - 1;
sz = (hmask+1) * sizeof(struct hlist_head);
net->xfrm.policy_byidx = xfrm_hash_alloc(sz);
if (!net->xfrm.policy_byidx)
goto out_byidx;
net->xfrm.policy_idx_hmask = hmask;
for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
struct xfrm_policy_hash *htab;
net->xfrm.policy_count[dir] = 0;
INIT_HLIST_HEAD(&net->xfrm.policy_inexact[dir]);
htab = &net->xfrm.policy_bydst[dir];
htab->table = xfrm_hash_alloc(sz);
if (!htab->table)
goto out_bydst;
htab->hmask = hmask;
}
INIT_LIST_HEAD(&net->xfrm.policy_all);
INIT_WORK(&net->xfrm.policy_hash_work, xfrm_hash_resize);
if (net_eq(net, &init_net))
register_netdevice_notifier(&xfrm_dev_notifier);
return 0;
out_bydst:
for (dir--; dir >= 0; dir--) {
struct xfrm_policy_hash *htab;
htab = &net->xfrm.policy_bydst[dir];
xfrm_hash_free(htab->table, sz);
}
xfrm_hash_free(net->xfrm.policy_byidx, sz);
out_byidx:
return -ENOMEM;
}
static void xfrm_policy_fini(struct net *net)
{
struct xfrm_audit audit_info;
unsigned int sz;
int dir;
flush_work(&net->xfrm.policy_hash_work);
#ifdef CONFIG_XFRM_SUB_POLICY
audit_info.loginuid = -1;
audit_info.sessionid = -1;
audit_info.secid = 0;
xfrm_policy_flush(net, XFRM_POLICY_TYPE_SUB, &audit_info);
#endif
audit_info.loginuid = -1;
audit_info.sessionid = -1;
audit_info.secid = 0;
xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, &audit_info);
flush_work(&xfrm_policy_gc_work);
WARN_ON(!list_empty(&net->xfrm.policy_all));
for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
struct xfrm_policy_hash *htab;
WARN_ON(!hlist_empty(&net->xfrm.policy_inexact[dir]));
htab = &net->xfrm.policy_bydst[dir];
sz = (htab->hmask + 1);
WARN_ON(!hlist_empty(htab->table));
xfrm_hash_free(htab->table, sz);
}
sz = (net->xfrm.policy_idx_hmask + 1) * sizeof(struct hlist_head);
WARN_ON(!hlist_empty(net->xfrm.policy_byidx));
xfrm_hash_free(net->xfrm.policy_byidx, sz);
}
static int __net_init xfrm_net_init(struct net *net)
{
int rv;
rv = xfrm_statistics_init(net);
if (rv < 0)
goto out_statistics;
rv = xfrm_state_init(net);
if (rv < 0)
goto out_state;
rv = xfrm_policy_init(net);
if (rv < 0)
goto out_policy;
rv = xfrm_sysctl_init(net);
if (rv < 0)
goto out_sysctl;
return 0;
out_sysctl:
xfrm_policy_fini(net);
out_policy:
xfrm_state_fini(net);
out_state:
xfrm_statistics_fini(net);
out_statistics:
return rv;
}
static void __net_exit xfrm_net_exit(struct net *net)
{
xfrm_sysctl_fini(net);
xfrm_policy_fini(net);
xfrm_state_fini(net);
xfrm_statistics_fini(net);
}
static struct pernet_operations __net_initdata xfrm_net_ops = {
.init = xfrm_net_init,
.exit = xfrm_net_exit,
};
void __init xfrm_init(void)
{
register_pernet_subsys(&xfrm_net_ops);
xfrm_input_init();
}
#ifdef CONFIG_AUDITSYSCALL
static void xfrm_audit_common_policyinfo(struct xfrm_policy *xp,
struct audit_buffer *audit_buf)
{
struct xfrm_sec_ctx *ctx = xp->security;
struct xfrm_selector *sel = &xp->selector;
if (ctx)
audit_log_format(audit_buf, " sec_alg=%u sec_doi=%u sec_obj=%s",
ctx->ctx_alg, ctx->ctx_doi, ctx->ctx_str);
switch(sel->family) {
case AF_INET:
audit_log_format(audit_buf, " src=%pI4", &sel->saddr.a4);
if (sel->prefixlen_s != 32)
audit_log_format(audit_buf, " src_prefixlen=%d",
sel->prefixlen_s);
audit_log_format(audit_buf, " dst=%pI4", &sel->daddr.a4);
if (sel->prefixlen_d != 32)
audit_log_format(audit_buf, " dst_prefixlen=%d",
sel->prefixlen_d);
break;
case AF_INET6:
audit_log_format(audit_buf, " src=%pI6", sel->saddr.a6);
if (sel->prefixlen_s != 128)
audit_log_format(audit_buf, " src_prefixlen=%d",
sel->prefixlen_s);
audit_log_format(audit_buf, " dst=%pI6", sel->daddr.a6);
if (sel->prefixlen_d != 128)
audit_log_format(audit_buf, " dst_prefixlen=%d",
sel->prefixlen_d);
break;
}
}
void xfrm_audit_policy_add(struct xfrm_policy *xp, int result,
uid_t auid, u32 sessionid, u32 secid)
{
struct audit_buffer *audit_buf;
audit_buf = xfrm_audit_start("SPD-add");
if (audit_buf == NULL)
return;
xfrm_audit_helper_usrinfo(auid, sessionid, secid, audit_buf);
audit_log_format(audit_buf, " res=%u", result);
xfrm_audit_common_policyinfo(xp, audit_buf);
audit_log_end(audit_buf);
}
EXPORT_SYMBOL_GPL(xfrm_audit_policy_add);
void xfrm_audit_policy_delete(struct xfrm_policy *xp, int result,
uid_t auid, u32 sessionid, u32 secid)
{
struct audit_buffer *audit_buf;
audit_buf = xfrm_audit_start("SPD-delete");
if (audit_buf == NULL)
return;
xfrm_audit_helper_usrinfo(auid, sessionid, secid, audit_buf);
audit_log_format(audit_buf, " res=%u", result);
xfrm_audit_common_policyinfo(xp, audit_buf);
audit_log_end(audit_buf);
}
EXPORT_SYMBOL_GPL(xfrm_audit_policy_delete);
#endif
#ifdef CONFIG_XFRM_MIGRATE
static int xfrm_migrate_selector_match(struct xfrm_selector *sel_cmp,
struct xfrm_selector *sel_tgt)
{
if (sel_cmp->proto == IPSEC_ULPROTO_ANY) {
if (sel_tgt->family == sel_cmp->family &&
xfrm_addr_cmp(&sel_tgt->daddr, &sel_cmp->daddr,
sel_cmp->family) == 0 &&
xfrm_addr_cmp(&sel_tgt->saddr, &sel_cmp->saddr,
sel_cmp->family) == 0 &&
sel_tgt->prefixlen_d == sel_cmp->prefixlen_d &&
sel_tgt->prefixlen_s == sel_cmp->prefixlen_s) {
return 1;
}
} else {
if (memcmp(sel_tgt, sel_cmp, sizeof(*sel_tgt)) == 0) {
return 1;
}
}
return 0;
}
static struct xfrm_policy * xfrm_migrate_policy_find(struct xfrm_selector *sel,
u8 dir, u8 type)
{
struct xfrm_policy *pol, *ret = NULL;
struct hlist_node *entry;
struct hlist_head *chain;
u32 priority = ~0U;
read_lock_bh(&xfrm_policy_lock);
chain = policy_hash_direct(&init_net, &sel->daddr, &sel->saddr, sel->family, dir);
hlist_for_each_entry(pol, entry, chain, bydst) {
if (xfrm_migrate_selector_match(sel, &pol->selector) &&
pol->type == type) {
ret = pol;
priority = ret->priority;
break;
}
}
chain = &init_net.xfrm.policy_inexact[dir];
hlist_for_each_entry(pol, entry, chain, bydst) {
if (xfrm_migrate_selector_match(sel, &pol->selector) &&
pol->type == type &&
pol->priority < priority) {
ret = pol;
break;
}
}
if (ret)
xfrm_pol_hold(ret);
read_unlock_bh(&xfrm_policy_lock);
return ret;
}
static int migrate_tmpl_match(struct xfrm_migrate *m, struct xfrm_tmpl *t)
{
int match = 0;
if (t->mode == m->mode && t->id.proto == m->proto &&
(m->reqid == 0 || t->reqid == m->reqid)) {
switch (t->mode) {
case XFRM_MODE_TUNNEL:
case XFRM_MODE_BEET:
if (xfrm_addr_cmp(&t->id.daddr, &m->old_daddr,
m->old_family) == 0 &&
xfrm_addr_cmp(&t->saddr, &m->old_saddr,
m->old_family) == 0) {
match = 1;
}
break;
case XFRM_MODE_TRANSPORT:
/* in case of transport mode, template does not store
any IP addresses, hence we just compare mode and
protocol */
match = 1;
break;
default:
break;
}
}
return match;
}
/* update endpoint address(es) of template(s) */
static int xfrm_policy_migrate(struct xfrm_policy *pol,
struct xfrm_migrate *m, int num_migrate)
{
struct xfrm_migrate *mp;
struct dst_entry *dst;
int i, j, n = 0;
write_lock_bh(&pol->lock);
if (unlikely(pol->walk.dead)) {
/* target policy has been deleted */
write_unlock_bh(&pol->lock);
return -ENOENT;
}
for (i = 0; i < pol->xfrm_nr; i++) {
for (j = 0, mp = m; j < num_migrate; j++, mp++) {
if (!migrate_tmpl_match(mp, &pol->xfrm_vec[i]))
continue;
n++;
if (pol->xfrm_vec[i].mode != XFRM_MODE_TUNNEL &&
pol->xfrm_vec[i].mode != XFRM_MODE_BEET)
continue;
/* update endpoints */
memcpy(&pol->xfrm_vec[i].id.daddr, &mp->new_daddr,
sizeof(pol->xfrm_vec[i].id.daddr));
memcpy(&pol->xfrm_vec[i].saddr, &mp->new_saddr,
sizeof(pol->xfrm_vec[i].saddr));
pol->xfrm_vec[i].encap_family = mp->new_family;
/* flush bundles */
while ((dst = pol->bundles) != NULL) {
pol->bundles = dst->next;
dst_free(dst);
}
}
}
write_unlock_bh(&pol->lock);
if (!n)
return -ENODATA;
return 0;
}
static int xfrm_migrate_check(struct xfrm_migrate *m, int num_migrate)
{
int i, j;
if (num_migrate < 1 || num_migrate > XFRM_MAX_DEPTH)
return -EINVAL;
for (i = 0; i < num_migrate; i++) {
if ((xfrm_addr_cmp(&m[i].old_daddr, &m[i].new_daddr,
m[i].old_family) == 0) &&
(xfrm_addr_cmp(&m[i].old_saddr, &m[i].new_saddr,
m[i].old_family) == 0))
return -EINVAL;
if (xfrm_addr_any(&m[i].new_daddr, m[i].new_family) ||
xfrm_addr_any(&m[i].new_saddr, m[i].new_family))
return -EINVAL;
/* check if there is any duplicated entry */
for (j = i + 1; j < num_migrate; j++) {
if (!memcmp(&m[i].old_daddr, &m[j].old_daddr,
sizeof(m[i].old_daddr)) &&
!memcmp(&m[i].old_saddr, &m[j].old_saddr,
sizeof(m[i].old_saddr)) &&
m[i].proto == m[j].proto &&
m[i].mode == m[j].mode &&
m[i].reqid == m[j].reqid &&
m[i].old_family == m[j].old_family)
return -EINVAL;
}
}
return 0;
}
int xfrm_migrate(struct xfrm_selector *sel, u8 dir, u8 type,
struct xfrm_migrate *m, int num_migrate,
struct xfrm_kmaddress *k)
{
int i, err, nx_cur = 0, nx_new = 0;
struct xfrm_policy *pol = NULL;
struct xfrm_state *x, *xc;
struct xfrm_state *x_cur[XFRM_MAX_DEPTH];
struct xfrm_state *x_new[XFRM_MAX_DEPTH];
struct xfrm_migrate *mp;
if ((err = xfrm_migrate_check(m, num_migrate)) < 0)
goto out;
/* Stage 1 - find policy */
if ((pol = xfrm_migrate_policy_find(sel, dir, type)) == NULL) {
err = -ENOENT;
goto out;
}
/* Stage 2 - find and update state(s) */
for (i = 0, mp = m; i < num_migrate; i++, mp++) {
if ((x = xfrm_migrate_state_find(mp))) {
x_cur[nx_cur] = x;
nx_cur++;
if ((xc = xfrm_state_migrate(x, mp))) {
x_new[nx_new] = xc;
nx_new++;
} else {
err = -ENODATA;
goto restore_state;
}
}
}
/* Stage 3 - update policy */
if ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0)
goto restore_state;
/* Stage 4 - delete old state(s) */
if (nx_cur) {
xfrm_states_put(x_cur, nx_cur);
xfrm_states_delete(x_cur, nx_cur);
}
/* Stage 5 - announce */
km_migrate(sel, dir, type, m, num_migrate, k);
xfrm_pol_put(pol);
return 0;
out:
return err;
restore_state:
if (pol)
xfrm_pol_put(pol);
if (nx_cur)
xfrm_states_put(x_cur, nx_cur);
if (nx_new)
xfrm_states_delete(x_new, nx_new);
return err;
}
EXPORT_SYMBOL(xfrm_migrate);
#endif
| gpl-2.0 |
mathkid95/linux_samsung_gb | drivers/gpio/pl061.c | 747 | 8926 | /*
* linux/drivers/gpio/pl061.c
*
* Copyright (C) 2008, 2009 Provigent 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.
*
* Driver for the ARM PrimeCell(tm) General Purpose Input/Output (PL061)
*
* Data sheet: ARM DDI 0190B, September 2000
*/
#include <linux/spinlock.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/list.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/irq.h>
#include <linux/bitops.h>
#include <linux/workqueue.h>
#include <linux/gpio.h>
#include <linux/device.h>
#include <linux/amba/bus.h>
#include <linux/amba/pl061.h>
#include <linux/slab.h>
#define GPIODIR 0x400
#define GPIOIS 0x404
#define GPIOIBE 0x408
#define GPIOIEV 0x40C
#define GPIOIE 0x410
#define GPIORIS 0x414
#define GPIOMIS 0x418
#define GPIOIC 0x41C
#define PL061_GPIO_NR 8
struct pl061_gpio {
/* We use a list of pl061_gpio structs for each trigger IRQ in the main
* interrupts controller of the system. We need this to support systems
* in which more that one PL061s are connected to the same IRQ. The ISR
* interates through this list to find the source of the interrupt.
*/
struct list_head list;
/* Each of the two spinlocks protects a different set of hardware
* regiters and data structurs. This decouples the code of the IRQ from
* the GPIO code. This also makes the case of a GPIO routine call from
* the IRQ code simpler.
*/
spinlock_t lock; /* GPIO registers */
spinlock_t irq_lock; /* IRQ registers */
void __iomem *base;
unsigned irq_base;
struct gpio_chip gc;
};
static int pl061_direction_input(struct gpio_chip *gc, unsigned offset)
{
struct pl061_gpio *chip = container_of(gc, struct pl061_gpio, gc);
unsigned long flags;
unsigned char gpiodir;
if (offset >= gc->ngpio)
return -EINVAL;
spin_lock_irqsave(&chip->lock, flags);
gpiodir = readb(chip->base + GPIODIR);
gpiodir &= ~(1 << offset);
writeb(gpiodir, chip->base + GPIODIR);
spin_unlock_irqrestore(&chip->lock, flags);
return 0;
}
static int pl061_direction_output(struct gpio_chip *gc, unsigned offset,
int value)
{
struct pl061_gpio *chip = container_of(gc, struct pl061_gpio, gc);
unsigned long flags;
unsigned char gpiodir;
if (offset >= gc->ngpio)
return -EINVAL;
spin_lock_irqsave(&chip->lock, flags);
writeb(!!value << offset, chip->base + (1 << (offset + 2)));
gpiodir = readb(chip->base + GPIODIR);
gpiodir |= 1 << offset;
writeb(gpiodir, chip->base + GPIODIR);
/*
* gpio value is set again, because pl061 doesn't allow to set value of
* a gpio pin before configuring it in OUT mode.
*/
writeb(!!value << offset, chip->base + (1 << (offset + 2)));
spin_unlock_irqrestore(&chip->lock, flags);
return 0;
}
static int pl061_get_value(struct gpio_chip *gc, unsigned offset)
{
struct pl061_gpio *chip = container_of(gc, struct pl061_gpio, gc);
return !!readb(chip->base + (1 << (offset + 2)));
}
static void pl061_set_value(struct gpio_chip *gc, unsigned offset, int value)
{
struct pl061_gpio *chip = container_of(gc, struct pl061_gpio, gc);
writeb(!!value << offset, chip->base + (1 << (offset + 2)));
}
static int pl061_to_irq(struct gpio_chip *gc, unsigned offset)
{
struct pl061_gpio *chip = container_of(gc, struct pl061_gpio, gc);
if (chip->irq_base == (unsigned) -1)
return -EINVAL;
return chip->irq_base + offset;
}
/*
* PL061 GPIO IRQ
*/
static void pl061_irq_disable(unsigned irq)
{
struct pl061_gpio *chip = get_irq_chip_data(irq);
int offset = irq - chip->irq_base;
unsigned long flags;
u8 gpioie;
spin_lock_irqsave(&chip->irq_lock, flags);
gpioie = readb(chip->base + GPIOIE);
gpioie &= ~(1 << offset);
writeb(gpioie, chip->base + GPIOIE);
spin_unlock_irqrestore(&chip->irq_lock, flags);
}
static void pl061_irq_enable(unsigned irq)
{
struct pl061_gpio *chip = get_irq_chip_data(irq);
int offset = irq - chip->irq_base;
unsigned long flags;
u8 gpioie;
spin_lock_irqsave(&chip->irq_lock, flags);
gpioie = readb(chip->base + GPIOIE);
gpioie |= 1 << offset;
writeb(gpioie, chip->base + GPIOIE);
spin_unlock_irqrestore(&chip->irq_lock, flags);
}
static int pl061_irq_type(unsigned irq, unsigned trigger)
{
struct pl061_gpio *chip = get_irq_chip_data(irq);
int offset = irq - chip->irq_base;
unsigned long flags;
u8 gpiois, gpioibe, gpioiev;
if (offset < 0 || offset >= PL061_GPIO_NR)
return -EINVAL;
spin_lock_irqsave(&chip->irq_lock, flags);
gpioiev = readb(chip->base + GPIOIEV);
gpiois = readb(chip->base + GPIOIS);
if (trigger & (IRQ_TYPE_LEVEL_HIGH | IRQ_TYPE_LEVEL_LOW)) {
gpiois |= 1 << offset;
if (trigger & IRQ_TYPE_LEVEL_HIGH)
gpioiev |= 1 << offset;
else
gpioiev &= ~(1 << offset);
} else
gpiois &= ~(1 << offset);
writeb(gpiois, chip->base + GPIOIS);
gpioibe = readb(chip->base + GPIOIBE);
if ((trigger & IRQ_TYPE_EDGE_BOTH) == IRQ_TYPE_EDGE_BOTH)
gpioibe |= 1 << offset;
else {
gpioibe &= ~(1 << offset);
if (trigger & IRQ_TYPE_EDGE_RISING)
gpioiev |= 1 << offset;
else if (trigger & IRQ_TYPE_EDGE_FALLING)
gpioiev &= ~(1 << offset);
}
writeb(gpioibe, chip->base + GPIOIBE);
writeb(gpioiev, chip->base + GPIOIEV);
spin_unlock_irqrestore(&chip->irq_lock, flags);
return 0;
}
static struct irq_chip pl061_irqchip = {
.name = "GPIO",
.enable = pl061_irq_enable,
.disable = pl061_irq_disable,
.set_type = pl061_irq_type,
};
static void pl061_irq_handler(unsigned irq, struct irq_desc *desc)
{
struct list_head *chip_list = get_irq_data(irq);
struct list_head *ptr;
struct pl061_gpio *chip;
desc->chip->ack(irq);
list_for_each(ptr, chip_list) {
unsigned long pending;
int offset;
chip = list_entry(ptr, struct pl061_gpio, list);
pending = readb(chip->base + GPIOMIS);
writeb(pending, chip->base + GPIOIC);
if (pending == 0)
continue;
for_each_set_bit(offset, &pending, PL061_GPIO_NR)
generic_handle_irq(pl061_to_irq(&chip->gc, offset));
}
desc->chip->unmask(irq);
}
static int __init pl061_probe(struct amba_device *dev, struct amba_id *id)
{
struct pl061_platform_data *pdata;
struct pl061_gpio *chip;
struct list_head *chip_list;
int ret, irq, i;
static DECLARE_BITMAP(init_irq, NR_IRQS);
pdata = dev->dev.platform_data;
if (pdata == NULL)
return -ENODEV;
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (chip == NULL)
return -ENOMEM;
if (!request_mem_region(dev->res.start,
resource_size(&dev->res), "pl061")) {
ret = -EBUSY;
goto free_mem;
}
chip->base = ioremap(dev->res.start, resource_size(&dev->res));
if (chip->base == NULL) {
ret = -ENOMEM;
goto release_region;
}
spin_lock_init(&chip->lock);
spin_lock_init(&chip->irq_lock);
INIT_LIST_HEAD(&chip->list);
chip->gc.direction_input = pl061_direction_input;
chip->gc.direction_output = pl061_direction_output;
chip->gc.get = pl061_get_value;
chip->gc.set = pl061_set_value;
chip->gc.to_irq = pl061_to_irq;
chip->gc.base = pdata->gpio_base;
chip->gc.ngpio = PL061_GPIO_NR;
chip->gc.label = dev_name(&dev->dev);
chip->gc.dev = &dev->dev;
chip->gc.owner = THIS_MODULE;
chip->irq_base = pdata->irq_base;
ret = gpiochip_add(&chip->gc);
if (ret)
goto iounmap;
/*
* irq_chip support
*/
if (chip->irq_base == (unsigned) -1)
return 0;
writeb(0, chip->base + GPIOIE); /* disable irqs */
irq = dev->irq[0];
if (irq < 0) {
ret = -ENODEV;
goto iounmap;
}
set_irq_chained_handler(irq, pl061_irq_handler);
if (!test_and_set_bit(irq, init_irq)) { /* list initialized? */
chip_list = kmalloc(sizeof(*chip_list), GFP_KERNEL);
if (chip_list == NULL) {
clear_bit(irq, init_irq);
ret = -ENOMEM;
goto iounmap;
}
INIT_LIST_HEAD(chip_list);
set_irq_data(irq, chip_list);
} else
chip_list = get_irq_data(irq);
list_add(&chip->list, chip_list);
for (i = 0; i < PL061_GPIO_NR; i++) {
if (pdata->directions & (1 << i))
pl061_direction_output(&chip->gc, i,
pdata->values & (1 << i));
else
pl061_direction_input(&chip->gc, i);
set_irq_chip(i+chip->irq_base, &pl061_irqchip);
set_irq_handler(i+chip->irq_base, handle_simple_irq);
set_irq_flags(i+chip->irq_base, IRQF_VALID);
set_irq_chip_data(i+chip->irq_base, chip);
}
return 0;
iounmap:
iounmap(chip->base);
release_region:
release_mem_region(dev->res.start, resource_size(&dev->res));
free_mem:
kfree(chip);
return ret;
}
static struct amba_id pl061_ids[] __initdata = {
{
.id = 0x00041061,
.mask = 0x000fffff,
},
{ 0, 0 },
};
static struct amba_driver pl061_gpio_driver = {
.drv = {
.name = "pl061_gpio",
},
.id_table = pl061_ids,
.probe = pl061_probe,
};
static int __init pl061_gpio_init(void)
{
return amba_driver_register(&pl061_gpio_driver);
}
subsys_initcall(pl061_gpio_init);
MODULE_AUTHOR("Baruch Siach <baruch@tkos.co.il>");
MODULE_DESCRIPTION("PL061 GPIO driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
phenomx4/android_kernel_lge_fx3 | drivers/net/wireless/rt2x00/rt2x00queue.c | 2795 | 33809 | /*
Copyright (C) 2010 Willow Garage <http://www.willowgarage.com>
Copyright (C) 2004 - 2010 Ivo van Doorn <IvDoorn@gmail.com>
Copyright (C) 2004 - 2009 Gertjan van Wingerde <gwingerde@gmail.com>
<http://rt2x00.serialmonkey.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.
*/
/*
Module: rt2x00lib
Abstract: rt2x00 queue specific routines.
*/
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/dma-mapping.h>
#include "rt2x00.h"
#include "rt2x00lib.h"
struct sk_buff *rt2x00queue_alloc_rxskb(struct queue_entry *entry)
{
struct rt2x00_dev *rt2x00dev = entry->queue->rt2x00dev;
struct sk_buff *skb;
struct skb_frame_desc *skbdesc;
unsigned int frame_size;
unsigned int head_size = 0;
unsigned int tail_size = 0;
/*
* The frame size includes descriptor size, because the
* hardware directly receive the frame into the skbuffer.
*/
frame_size = entry->queue->data_size + entry->queue->desc_size;
/*
* The payload should be aligned to a 4-byte boundary,
* this means we need at least 3 bytes for moving the frame
* into the correct offset.
*/
head_size = 4;
/*
* For IV/EIV/ICV assembly we must make sure there is
* at least 8 bytes bytes available in headroom for IV/EIV
* and 8 bytes for ICV data as tailroon.
*/
if (test_bit(CAPABILITY_HW_CRYPTO, &rt2x00dev->cap_flags)) {
head_size += 8;
tail_size += 8;
}
/*
* Allocate skbuffer.
*/
skb = dev_alloc_skb(frame_size + head_size + tail_size);
if (!skb)
return NULL;
/*
* Make sure we not have a frame with the requested bytes
* available in the head and tail.
*/
skb_reserve(skb, head_size);
skb_put(skb, frame_size);
/*
* Populate skbdesc.
*/
skbdesc = get_skb_frame_desc(skb);
memset(skbdesc, 0, sizeof(*skbdesc));
skbdesc->entry = entry;
if (test_bit(REQUIRE_DMA, &rt2x00dev->cap_flags)) {
skbdesc->skb_dma = dma_map_single(rt2x00dev->dev,
skb->data,
skb->len,
DMA_FROM_DEVICE);
skbdesc->flags |= SKBDESC_DMA_MAPPED_RX;
}
return skb;
}
void rt2x00queue_map_txskb(struct queue_entry *entry)
{
struct device *dev = entry->queue->rt2x00dev->dev;
struct skb_frame_desc *skbdesc = get_skb_frame_desc(entry->skb);
skbdesc->skb_dma =
dma_map_single(dev, entry->skb->data, entry->skb->len, DMA_TO_DEVICE);
skbdesc->flags |= SKBDESC_DMA_MAPPED_TX;
}
EXPORT_SYMBOL_GPL(rt2x00queue_map_txskb);
void rt2x00queue_unmap_skb(struct queue_entry *entry)
{
struct device *dev = entry->queue->rt2x00dev->dev;
struct skb_frame_desc *skbdesc = get_skb_frame_desc(entry->skb);
if (skbdesc->flags & SKBDESC_DMA_MAPPED_RX) {
dma_unmap_single(dev, skbdesc->skb_dma, entry->skb->len,
DMA_FROM_DEVICE);
skbdesc->flags &= ~SKBDESC_DMA_MAPPED_RX;
} else if (skbdesc->flags & SKBDESC_DMA_MAPPED_TX) {
dma_unmap_single(dev, skbdesc->skb_dma, entry->skb->len,
DMA_TO_DEVICE);
skbdesc->flags &= ~SKBDESC_DMA_MAPPED_TX;
}
}
EXPORT_SYMBOL_GPL(rt2x00queue_unmap_skb);
void rt2x00queue_free_skb(struct queue_entry *entry)
{
if (!entry->skb)
return;
rt2x00queue_unmap_skb(entry);
dev_kfree_skb_any(entry->skb);
entry->skb = NULL;
}
void rt2x00queue_align_frame(struct sk_buff *skb)
{
unsigned int frame_length = skb->len;
unsigned int align = ALIGN_SIZE(skb, 0);
if (!align)
return;
skb_push(skb, align);
memmove(skb->data, skb->data + align, frame_length);
skb_trim(skb, frame_length);
}
void rt2x00queue_insert_l2pad(struct sk_buff *skb, unsigned int header_length)
{
unsigned int payload_length = skb->len - header_length;
unsigned int header_align = ALIGN_SIZE(skb, 0);
unsigned int payload_align = ALIGN_SIZE(skb, header_length);
unsigned int l2pad = payload_length ? L2PAD_SIZE(header_length) : 0;
/*
* Adjust the header alignment if the payload needs to be moved more
* than the header.
*/
if (payload_align > header_align)
header_align += 4;
/* There is nothing to do if no alignment is needed */
if (!header_align)
return;
/* Reserve the amount of space needed in front of the frame */
skb_push(skb, header_align);
/*
* Move the header.
*/
memmove(skb->data, skb->data + header_align, header_length);
/* Move the payload, if present and if required */
if (payload_length && payload_align)
memmove(skb->data + header_length + l2pad,
skb->data + header_length + l2pad + payload_align,
payload_length);
/* Trim the skb to the correct size */
skb_trim(skb, header_length + l2pad + payload_length);
}
void rt2x00queue_remove_l2pad(struct sk_buff *skb, unsigned int header_length)
{
/*
* L2 padding is only present if the skb contains more than just the
* IEEE 802.11 header.
*/
unsigned int l2pad = (skb->len > header_length) ?
L2PAD_SIZE(header_length) : 0;
if (!l2pad)
return;
memmove(skb->data + l2pad, skb->data, header_length);
skb_pull(skb, l2pad);
}
static void rt2x00queue_create_tx_descriptor_seq(struct rt2x00_dev *rt2x00dev,
struct sk_buff *skb,
struct txentry_desc *txdesc)
{
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
struct rt2x00_intf *intf = vif_to_intf(tx_info->control.vif);
if (!(tx_info->flags & IEEE80211_TX_CTL_ASSIGN_SEQ))
return;
__set_bit(ENTRY_TXD_GENERATE_SEQ, &txdesc->flags);
if (!test_bit(REQUIRE_SW_SEQNO, &rt2x00dev->cap_flags))
return;
/*
* The hardware is not able to insert a sequence number. Assign a
* software generated one here.
*
* This is wrong because beacons are not getting sequence
* numbers assigned properly.
*
* A secondary problem exists for drivers that cannot toggle
* sequence counting per-frame, since those will override the
* sequence counter given by mac80211.
*/
spin_lock(&intf->seqlock);
if (test_bit(ENTRY_TXD_FIRST_FRAGMENT, &txdesc->flags))
intf->seqno += 0x10;
hdr->seq_ctrl &= cpu_to_le16(IEEE80211_SCTL_FRAG);
hdr->seq_ctrl |= cpu_to_le16(intf->seqno);
spin_unlock(&intf->seqlock);
}
static void rt2x00queue_create_tx_descriptor_plcp(struct rt2x00_dev *rt2x00dev,
struct sk_buff *skb,
struct txentry_desc *txdesc,
const struct rt2x00_rate *hwrate)
{
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ieee80211_tx_rate *txrate = &tx_info->control.rates[0];
unsigned int data_length;
unsigned int duration;
unsigned int residual;
/*
* Determine with what IFS priority this frame should be send.
* Set ifs to IFS_SIFS when the this is not the first fragment,
* or this fragment came after RTS/CTS.
*/
if (test_bit(ENTRY_TXD_FIRST_FRAGMENT, &txdesc->flags))
txdesc->u.plcp.ifs = IFS_BACKOFF;
else
txdesc->u.plcp.ifs = IFS_SIFS;
/* Data length + CRC + Crypto overhead (IV/EIV/ICV/MIC) */
data_length = skb->len + 4;
data_length += rt2x00crypto_tx_overhead(rt2x00dev, skb);
/*
* PLCP setup
* Length calculation depends on OFDM/CCK rate.
*/
txdesc->u.plcp.signal = hwrate->plcp;
txdesc->u.plcp.service = 0x04;
if (hwrate->flags & DEV_RATE_OFDM) {
txdesc->u.plcp.length_high = (data_length >> 6) & 0x3f;
txdesc->u.plcp.length_low = data_length & 0x3f;
} else {
/*
* Convert length to microseconds.
*/
residual = GET_DURATION_RES(data_length, hwrate->bitrate);
duration = GET_DURATION(data_length, hwrate->bitrate);
if (residual != 0) {
duration++;
/*
* Check if we need to set the Length Extension
*/
if (hwrate->bitrate == 110 && residual <= 30)
txdesc->u.plcp.service |= 0x80;
}
txdesc->u.plcp.length_high = (duration >> 8) & 0xff;
txdesc->u.plcp.length_low = duration & 0xff;
/*
* When preamble is enabled we should set the
* preamble bit for the signal.
*/
if (txrate->flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE)
txdesc->u.plcp.signal |= 0x08;
}
}
static void rt2x00queue_create_tx_descriptor_ht(struct rt2x00_dev *rt2x00dev,
struct sk_buff *skb,
struct txentry_desc *txdesc,
const struct rt2x00_rate *hwrate)
{
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ieee80211_tx_rate *txrate = &tx_info->control.rates[0];
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
struct rt2x00_sta *sta_priv = NULL;
if (tx_info->control.sta) {
txdesc->u.ht.mpdu_density =
tx_info->control.sta->ht_cap.ampdu_density;
sta_priv = sta_to_rt2x00_sta(tx_info->control.sta);
txdesc->u.ht.wcid = sta_priv->wcid;
}
txdesc->u.ht.ba_size = 7; /* FIXME: What value is needed? */
/*
* Only one STBC stream is supported for now.
*/
if (tx_info->flags & IEEE80211_TX_CTL_STBC)
txdesc->u.ht.stbc = 1;
/*
* If IEEE80211_TX_RC_MCS is set txrate->idx just contains the
* mcs rate to be used
*/
if (txrate->flags & IEEE80211_TX_RC_MCS) {
txdesc->u.ht.mcs = txrate->idx;
/*
* MIMO PS should be set to 1 for STA's using dynamic SM PS
* when using more then one tx stream (>MCS7).
*/
if (tx_info->control.sta && txdesc->u.ht.mcs > 7 &&
((tx_info->control.sta->ht_cap.cap &
IEEE80211_HT_CAP_SM_PS) >>
IEEE80211_HT_CAP_SM_PS_SHIFT) ==
WLAN_HT_CAP_SM_PS_DYNAMIC)
__set_bit(ENTRY_TXD_HT_MIMO_PS, &txdesc->flags);
} else {
txdesc->u.ht.mcs = rt2x00_get_rate_mcs(hwrate->mcs);
if (txrate->flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE)
txdesc->u.ht.mcs |= 0x08;
}
/*
* This frame is eligible for an AMPDU, however, don't aggregate
* frames that are intended to probe a specific tx rate.
*/
if (tx_info->flags & IEEE80211_TX_CTL_AMPDU &&
!(tx_info->flags & IEEE80211_TX_CTL_RATE_CTRL_PROBE))
__set_bit(ENTRY_TXD_HT_AMPDU, &txdesc->flags);
/*
* Set 40Mhz mode if necessary (for legacy rates this will
* duplicate the frame to both channels).
*/
if (txrate->flags & IEEE80211_TX_RC_40_MHZ_WIDTH ||
txrate->flags & IEEE80211_TX_RC_DUP_DATA)
__set_bit(ENTRY_TXD_HT_BW_40, &txdesc->flags);
if (txrate->flags & IEEE80211_TX_RC_SHORT_GI)
__set_bit(ENTRY_TXD_HT_SHORT_GI, &txdesc->flags);
/*
* Determine IFS values
* - Use TXOP_BACKOFF for management frames except beacons
* - Use TXOP_SIFS for fragment bursts
* - Use TXOP_HTTXOP for everything else
*
* Note: rt2800 devices won't use CTS protection (if used)
* for frames not transmitted with TXOP_HTTXOP
*/
if (ieee80211_is_mgmt(hdr->frame_control) &&
!ieee80211_is_beacon(hdr->frame_control))
txdesc->u.ht.txop = TXOP_BACKOFF;
else if (!(tx_info->flags & IEEE80211_TX_CTL_FIRST_FRAGMENT))
txdesc->u.ht.txop = TXOP_SIFS;
else
txdesc->u.ht.txop = TXOP_HTTXOP;
}
static void rt2x00queue_create_tx_descriptor(struct rt2x00_dev *rt2x00dev,
struct sk_buff *skb,
struct txentry_desc *txdesc)
{
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
struct ieee80211_tx_rate *txrate = &tx_info->control.rates[0];
struct ieee80211_rate *rate;
const struct rt2x00_rate *hwrate = NULL;
memset(txdesc, 0, sizeof(*txdesc));
/*
* Header and frame information.
*/
txdesc->length = skb->len;
txdesc->header_length = ieee80211_get_hdrlen_from_skb(skb);
/*
* Check whether this frame is to be acked.
*/
if (!(tx_info->flags & IEEE80211_TX_CTL_NO_ACK))
__set_bit(ENTRY_TXD_ACK, &txdesc->flags);
/*
* Check if this is a RTS/CTS frame
*/
if (ieee80211_is_rts(hdr->frame_control) ||
ieee80211_is_cts(hdr->frame_control)) {
__set_bit(ENTRY_TXD_BURST, &txdesc->flags);
if (ieee80211_is_rts(hdr->frame_control))
__set_bit(ENTRY_TXD_RTS_FRAME, &txdesc->flags);
else
__set_bit(ENTRY_TXD_CTS_FRAME, &txdesc->flags);
if (tx_info->control.rts_cts_rate_idx >= 0)
rate =
ieee80211_get_rts_cts_rate(rt2x00dev->hw, tx_info);
}
/*
* Determine retry information.
*/
txdesc->retry_limit = tx_info->control.rates[0].count - 1;
if (txdesc->retry_limit >= rt2x00dev->long_retry)
__set_bit(ENTRY_TXD_RETRY_MODE, &txdesc->flags);
/*
* Check if more fragments are pending
*/
if (ieee80211_has_morefrags(hdr->frame_control)) {
__set_bit(ENTRY_TXD_BURST, &txdesc->flags);
__set_bit(ENTRY_TXD_MORE_FRAG, &txdesc->flags);
}
/*
* Check if more frames (!= fragments) are pending
*/
if (tx_info->flags & IEEE80211_TX_CTL_MORE_FRAMES)
__set_bit(ENTRY_TXD_BURST, &txdesc->flags);
/*
* Beacons and probe responses require the tsf timestamp
* to be inserted into the frame.
*/
if (ieee80211_is_beacon(hdr->frame_control) ||
ieee80211_is_probe_resp(hdr->frame_control))
__set_bit(ENTRY_TXD_REQ_TIMESTAMP, &txdesc->flags);
if ((tx_info->flags & IEEE80211_TX_CTL_FIRST_FRAGMENT) &&
!test_bit(ENTRY_TXD_RTS_FRAME, &txdesc->flags))
__set_bit(ENTRY_TXD_FIRST_FRAGMENT, &txdesc->flags);
/*
* Determine rate modulation.
*/
if (txrate->flags & IEEE80211_TX_RC_GREEN_FIELD)
txdesc->rate_mode = RATE_MODE_HT_GREENFIELD;
else if (txrate->flags & IEEE80211_TX_RC_MCS)
txdesc->rate_mode = RATE_MODE_HT_MIX;
else {
rate = ieee80211_get_tx_rate(rt2x00dev->hw, tx_info);
hwrate = rt2x00_get_rate(rate->hw_value);
if (hwrate->flags & DEV_RATE_OFDM)
txdesc->rate_mode = RATE_MODE_OFDM;
else
txdesc->rate_mode = RATE_MODE_CCK;
}
/*
* Apply TX descriptor handling by components
*/
rt2x00crypto_create_tx_descriptor(rt2x00dev, skb, txdesc);
rt2x00queue_create_tx_descriptor_seq(rt2x00dev, skb, txdesc);
if (test_bit(REQUIRE_HT_TX_DESC, &rt2x00dev->cap_flags))
rt2x00queue_create_tx_descriptor_ht(rt2x00dev, skb, txdesc,
hwrate);
else
rt2x00queue_create_tx_descriptor_plcp(rt2x00dev, skb, txdesc,
hwrate);
}
static int rt2x00queue_write_tx_data(struct queue_entry *entry,
struct txentry_desc *txdesc)
{
struct rt2x00_dev *rt2x00dev = entry->queue->rt2x00dev;
/*
* This should not happen, we already checked the entry
* was ours. When the hardware disagrees there has been
* a queue corruption!
*/
if (unlikely(rt2x00dev->ops->lib->get_entry_state &&
rt2x00dev->ops->lib->get_entry_state(entry))) {
ERROR(rt2x00dev,
"Corrupt queue %d, accessing entry which is not ours.\n"
"Please file bug report to %s.\n",
entry->queue->qid, DRV_PROJECT);
return -EINVAL;
}
/*
* Add the requested extra tx headroom in front of the skb.
*/
skb_push(entry->skb, rt2x00dev->ops->extra_tx_headroom);
memset(entry->skb->data, 0, rt2x00dev->ops->extra_tx_headroom);
/*
* Call the driver's write_tx_data function, if it exists.
*/
if (rt2x00dev->ops->lib->write_tx_data)
rt2x00dev->ops->lib->write_tx_data(entry, txdesc);
/*
* Map the skb to DMA.
*/
if (test_bit(REQUIRE_DMA, &rt2x00dev->cap_flags))
rt2x00queue_map_txskb(entry);
return 0;
}
static void rt2x00queue_write_tx_descriptor(struct queue_entry *entry,
struct txentry_desc *txdesc)
{
struct data_queue *queue = entry->queue;
queue->rt2x00dev->ops->lib->write_tx_desc(entry, txdesc);
/*
* All processing on the frame has been completed, this means
* it is now ready to be dumped to userspace through debugfs.
*/
rt2x00debug_dump_frame(queue->rt2x00dev, DUMP_FRAME_TX, entry->skb);
}
static void rt2x00queue_kick_tx_queue(struct data_queue *queue,
struct txentry_desc *txdesc)
{
/*
* Check if we need to kick the queue, there are however a few rules
* 1) Don't kick unless this is the last in frame in a burst.
* When the burst flag is set, this frame is always followed
* by another frame which in some way are related to eachother.
* This is true for fragments, RTS or CTS-to-self frames.
* 2) Rule 1 can be broken when the available entries
* in the queue are less then a certain threshold.
*/
if (rt2x00queue_threshold(queue) ||
!test_bit(ENTRY_TXD_BURST, &txdesc->flags))
queue->rt2x00dev->ops->lib->kick_queue(queue);
}
int rt2x00queue_write_tx_frame(struct data_queue *queue, struct sk_buff *skb,
bool local)
{
struct ieee80211_tx_info *tx_info;
struct queue_entry *entry;
struct txentry_desc txdesc;
struct skb_frame_desc *skbdesc;
u8 rate_idx, rate_flags;
int ret = 0;
/*
* Copy all TX descriptor information into txdesc,
* after that we are free to use the skb->cb array
* for our information.
*/
rt2x00queue_create_tx_descriptor(queue->rt2x00dev, skb, &txdesc);
/*
* All information is retrieved from the skb->cb array,
* now we should claim ownership of the driver part of that
* array, preserving the bitrate index and flags.
*/
tx_info = IEEE80211_SKB_CB(skb);
rate_idx = tx_info->control.rates[0].idx;
rate_flags = tx_info->control.rates[0].flags;
skbdesc = get_skb_frame_desc(skb);
memset(skbdesc, 0, sizeof(*skbdesc));
skbdesc->tx_rate_idx = rate_idx;
skbdesc->tx_rate_flags = rate_flags;
if (local)
skbdesc->flags |= SKBDESC_NOT_MAC80211;
/*
* When hardware encryption is supported, and this frame
* is to be encrypted, we should strip the IV/EIV data from
* the frame so we can provide it to the driver separately.
*/
if (test_bit(ENTRY_TXD_ENCRYPT, &txdesc.flags) &&
!test_bit(ENTRY_TXD_ENCRYPT_IV, &txdesc.flags)) {
if (test_bit(REQUIRE_COPY_IV, &queue->rt2x00dev->cap_flags))
rt2x00crypto_tx_copy_iv(skb, &txdesc);
else
rt2x00crypto_tx_remove_iv(skb, &txdesc);
}
/*
* When DMA allocation is required we should guarantee to the
* driver that the DMA is aligned to a 4-byte boundary.
* However some drivers require L2 padding to pad the payload
* rather then the header. This could be a requirement for
* PCI and USB devices, while header alignment only is valid
* for PCI devices.
*/
if (test_bit(REQUIRE_L2PAD, &queue->rt2x00dev->cap_flags))
rt2x00queue_insert_l2pad(skb, txdesc.header_length);
else if (test_bit(REQUIRE_DMA, &queue->rt2x00dev->cap_flags))
rt2x00queue_align_frame(skb);
/*
* That function must be called with bh disabled.
*/
spin_lock(&queue->tx_lock);
if (unlikely(rt2x00queue_full(queue))) {
ERROR(queue->rt2x00dev,
"Dropping frame due to full tx queue %d.\n", queue->qid);
ret = -ENOBUFS;
goto out;
}
entry = rt2x00queue_get_entry(queue, Q_INDEX);
if (unlikely(test_and_set_bit(ENTRY_OWNER_DEVICE_DATA,
&entry->flags))) {
ERROR(queue->rt2x00dev,
"Arrived at non-free entry in the non-full queue %d.\n"
"Please file bug report to %s.\n",
queue->qid, DRV_PROJECT);
ret = -EINVAL;
goto out;
}
skbdesc->entry = entry;
entry->skb = skb;
/*
* It could be possible that the queue was corrupted and this
* call failed. Since we always return NETDEV_TX_OK to mac80211,
* this frame will simply be dropped.
*/
if (unlikely(rt2x00queue_write_tx_data(entry, &txdesc))) {
clear_bit(ENTRY_OWNER_DEVICE_DATA, &entry->flags);
entry->skb = NULL;
ret = -EIO;
goto out;
}
set_bit(ENTRY_DATA_PENDING, &entry->flags);
rt2x00queue_index_inc(entry, Q_INDEX);
rt2x00queue_write_tx_descriptor(entry, &txdesc);
rt2x00queue_kick_tx_queue(queue, &txdesc);
out:
spin_unlock(&queue->tx_lock);
return ret;
}
int rt2x00queue_clear_beacon(struct rt2x00_dev *rt2x00dev,
struct ieee80211_vif *vif)
{
struct rt2x00_intf *intf = vif_to_intf(vif);
if (unlikely(!intf->beacon))
return -ENOBUFS;
mutex_lock(&intf->beacon_skb_mutex);
/*
* Clean up the beacon skb.
*/
rt2x00queue_free_skb(intf->beacon);
/*
* Clear beacon (single bssid devices don't need to clear the beacon
* since the beacon queue will get stopped anyway).
*/
if (rt2x00dev->ops->lib->clear_beacon)
rt2x00dev->ops->lib->clear_beacon(intf->beacon);
mutex_unlock(&intf->beacon_skb_mutex);
return 0;
}
int rt2x00queue_update_beacon_locked(struct rt2x00_dev *rt2x00dev,
struct ieee80211_vif *vif)
{
struct rt2x00_intf *intf = vif_to_intf(vif);
struct skb_frame_desc *skbdesc;
struct txentry_desc txdesc;
if (unlikely(!intf->beacon))
return -ENOBUFS;
/*
* Clean up the beacon skb.
*/
rt2x00queue_free_skb(intf->beacon);
intf->beacon->skb = ieee80211_beacon_get(rt2x00dev->hw, vif);
if (!intf->beacon->skb)
return -ENOMEM;
/*
* Copy all TX descriptor information into txdesc,
* after that we are free to use the skb->cb array
* for our information.
*/
rt2x00queue_create_tx_descriptor(rt2x00dev, intf->beacon->skb, &txdesc);
/*
* Fill in skb descriptor
*/
skbdesc = get_skb_frame_desc(intf->beacon->skb);
memset(skbdesc, 0, sizeof(*skbdesc));
skbdesc->entry = intf->beacon;
/*
* Send beacon to hardware.
*/
rt2x00dev->ops->lib->write_beacon(intf->beacon, &txdesc);
return 0;
}
int rt2x00queue_update_beacon(struct rt2x00_dev *rt2x00dev,
struct ieee80211_vif *vif)
{
struct rt2x00_intf *intf = vif_to_intf(vif);
int ret;
mutex_lock(&intf->beacon_skb_mutex);
ret = rt2x00queue_update_beacon_locked(rt2x00dev, vif);
mutex_unlock(&intf->beacon_skb_mutex);
return ret;
}
bool rt2x00queue_for_each_entry(struct data_queue *queue,
enum queue_index start,
enum queue_index end,
void *data,
bool (*fn)(struct queue_entry *entry,
void *data))
{
unsigned long irqflags;
unsigned int index_start;
unsigned int index_end;
unsigned int i;
if (unlikely(start >= Q_INDEX_MAX || end >= Q_INDEX_MAX)) {
ERROR(queue->rt2x00dev,
"Entry requested from invalid index range (%d - %d)\n",
start, end);
return true;
}
/*
* Only protect the range we are going to loop over,
* if during our loop a extra entry is set to pending
* it should not be kicked during this run, since it
* is part of another TX operation.
*/
spin_lock_irqsave(&queue->index_lock, irqflags);
index_start = queue->index[start];
index_end = queue->index[end];
spin_unlock_irqrestore(&queue->index_lock, irqflags);
/*
* Start from the TX done pointer, this guarantees that we will
* send out all frames in the correct order.
*/
if (index_start < index_end) {
for (i = index_start; i < index_end; i++) {
if (fn(&queue->entries[i], data))
return true;
}
} else {
for (i = index_start; i < queue->limit; i++) {
if (fn(&queue->entries[i], data))
return true;
}
for (i = 0; i < index_end; i++) {
if (fn(&queue->entries[i], data))
return true;
}
}
return false;
}
EXPORT_SYMBOL_GPL(rt2x00queue_for_each_entry);
struct queue_entry *rt2x00queue_get_entry(struct data_queue *queue,
enum queue_index index)
{
struct queue_entry *entry;
unsigned long irqflags;
if (unlikely(index >= Q_INDEX_MAX)) {
ERROR(queue->rt2x00dev,
"Entry requested from invalid index type (%d)\n", index);
return NULL;
}
spin_lock_irqsave(&queue->index_lock, irqflags);
entry = &queue->entries[queue->index[index]];
spin_unlock_irqrestore(&queue->index_lock, irqflags);
return entry;
}
EXPORT_SYMBOL_GPL(rt2x00queue_get_entry);
void rt2x00queue_index_inc(struct queue_entry *entry, enum queue_index index)
{
struct data_queue *queue = entry->queue;
unsigned long irqflags;
if (unlikely(index >= Q_INDEX_MAX)) {
ERROR(queue->rt2x00dev,
"Index change on invalid index type (%d)\n", index);
return;
}
spin_lock_irqsave(&queue->index_lock, irqflags);
queue->index[index]++;
if (queue->index[index] >= queue->limit)
queue->index[index] = 0;
entry->last_action = jiffies;
if (index == Q_INDEX) {
queue->length++;
} else if (index == Q_INDEX_DONE) {
queue->length--;
queue->count++;
}
spin_unlock_irqrestore(&queue->index_lock, irqflags);
}
void rt2x00queue_pause_queue(struct data_queue *queue)
{
if (!test_bit(DEVICE_STATE_PRESENT, &queue->rt2x00dev->flags) ||
!test_bit(QUEUE_STARTED, &queue->flags) ||
test_and_set_bit(QUEUE_PAUSED, &queue->flags))
return;
switch (queue->qid) {
case QID_AC_VO:
case QID_AC_VI:
case QID_AC_BE:
case QID_AC_BK:
/*
* For TX queues, we have to disable the queue
* inside mac80211.
*/
ieee80211_stop_queue(queue->rt2x00dev->hw, queue->qid);
break;
default:
break;
}
}
EXPORT_SYMBOL_GPL(rt2x00queue_pause_queue);
void rt2x00queue_unpause_queue(struct data_queue *queue)
{
if (!test_bit(DEVICE_STATE_PRESENT, &queue->rt2x00dev->flags) ||
!test_bit(QUEUE_STARTED, &queue->flags) ||
!test_and_clear_bit(QUEUE_PAUSED, &queue->flags))
return;
switch (queue->qid) {
case QID_AC_VO:
case QID_AC_VI:
case QID_AC_BE:
case QID_AC_BK:
/*
* For TX queues, we have to enable the queue
* inside mac80211.
*/
ieee80211_wake_queue(queue->rt2x00dev->hw, queue->qid);
break;
case QID_RX:
/*
* For RX we need to kick the queue now in order to
* receive frames.
*/
queue->rt2x00dev->ops->lib->kick_queue(queue);
default:
break;
}
}
EXPORT_SYMBOL_GPL(rt2x00queue_unpause_queue);
void rt2x00queue_start_queue(struct data_queue *queue)
{
mutex_lock(&queue->status_lock);
if (!test_bit(DEVICE_STATE_PRESENT, &queue->rt2x00dev->flags) ||
test_and_set_bit(QUEUE_STARTED, &queue->flags)) {
mutex_unlock(&queue->status_lock);
return;
}
set_bit(QUEUE_PAUSED, &queue->flags);
queue->rt2x00dev->ops->lib->start_queue(queue);
rt2x00queue_unpause_queue(queue);
mutex_unlock(&queue->status_lock);
}
EXPORT_SYMBOL_GPL(rt2x00queue_start_queue);
void rt2x00queue_stop_queue(struct data_queue *queue)
{
mutex_lock(&queue->status_lock);
if (!test_and_clear_bit(QUEUE_STARTED, &queue->flags)) {
mutex_unlock(&queue->status_lock);
return;
}
rt2x00queue_pause_queue(queue);
queue->rt2x00dev->ops->lib->stop_queue(queue);
mutex_unlock(&queue->status_lock);
}
EXPORT_SYMBOL_GPL(rt2x00queue_stop_queue);
void rt2x00queue_flush_queue(struct data_queue *queue, bool drop)
{
bool started;
bool tx_queue =
(queue->qid == QID_AC_VO) ||
(queue->qid == QID_AC_VI) ||
(queue->qid == QID_AC_BE) ||
(queue->qid == QID_AC_BK);
mutex_lock(&queue->status_lock);
/*
* If the queue has been started, we must stop it temporarily
* to prevent any new frames to be queued on the device. If
* we are not dropping the pending frames, the queue must
* only be stopped in the software and not the hardware,
* otherwise the queue will never become empty on its own.
*/
started = test_bit(QUEUE_STARTED, &queue->flags);
if (started) {
/*
* Pause the queue
*/
rt2x00queue_pause_queue(queue);
/*
* If we are not supposed to drop any pending
* frames, this means we must force a start (=kick)
* to the queue to make sure the hardware will
* start transmitting.
*/
if (!drop && tx_queue)
queue->rt2x00dev->ops->lib->kick_queue(queue);
}
/*
* Check if driver supports flushing, if that is the case we can
* defer the flushing to the driver. Otherwise we must use the
* alternative which just waits for the queue to become empty.
*/
if (likely(queue->rt2x00dev->ops->lib->flush_queue))
queue->rt2x00dev->ops->lib->flush_queue(queue, drop);
/*
* The queue flush has failed...
*/
if (unlikely(!rt2x00queue_empty(queue)))
WARNING(queue->rt2x00dev, "Queue %d failed to flush\n", queue->qid);
/*
* Restore the queue to the previous status
*/
if (started)
rt2x00queue_unpause_queue(queue);
mutex_unlock(&queue->status_lock);
}
EXPORT_SYMBOL_GPL(rt2x00queue_flush_queue);
void rt2x00queue_start_queues(struct rt2x00_dev *rt2x00dev)
{
struct data_queue *queue;
/*
* rt2x00queue_start_queue will call ieee80211_wake_queue
* for each queue after is has been properly initialized.
*/
tx_queue_for_each(rt2x00dev, queue)
rt2x00queue_start_queue(queue);
rt2x00queue_start_queue(rt2x00dev->rx);
}
EXPORT_SYMBOL_GPL(rt2x00queue_start_queues);
void rt2x00queue_stop_queues(struct rt2x00_dev *rt2x00dev)
{
struct data_queue *queue;
/*
* rt2x00queue_stop_queue will call ieee80211_stop_queue
* as well, but we are completely shutting doing everything
* now, so it is much safer to stop all TX queues at once,
* and use rt2x00queue_stop_queue for cleaning up.
*/
ieee80211_stop_queues(rt2x00dev->hw);
tx_queue_for_each(rt2x00dev, queue)
rt2x00queue_stop_queue(queue);
rt2x00queue_stop_queue(rt2x00dev->rx);
}
EXPORT_SYMBOL_GPL(rt2x00queue_stop_queues);
void rt2x00queue_flush_queues(struct rt2x00_dev *rt2x00dev, bool drop)
{
struct data_queue *queue;
tx_queue_for_each(rt2x00dev, queue)
rt2x00queue_flush_queue(queue, drop);
rt2x00queue_flush_queue(rt2x00dev->rx, drop);
}
EXPORT_SYMBOL_GPL(rt2x00queue_flush_queues);
static void rt2x00queue_reset(struct data_queue *queue)
{
unsigned long irqflags;
unsigned int i;
spin_lock_irqsave(&queue->index_lock, irqflags);
queue->count = 0;
queue->length = 0;
for (i = 0; i < Q_INDEX_MAX; i++)
queue->index[i] = 0;
spin_unlock_irqrestore(&queue->index_lock, irqflags);
}
void rt2x00queue_init_queues(struct rt2x00_dev *rt2x00dev)
{
struct data_queue *queue;
unsigned int i;
queue_for_each(rt2x00dev, queue) {
rt2x00queue_reset(queue);
for (i = 0; i < queue->limit; i++)
rt2x00dev->ops->lib->clear_entry(&queue->entries[i]);
}
}
static int rt2x00queue_alloc_entries(struct data_queue *queue,
const struct data_queue_desc *qdesc)
{
struct queue_entry *entries;
unsigned int entry_size;
unsigned int i;
rt2x00queue_reset(queue);
queue->limit = qdesc->entry_num;
queue->threshold = DIV_ROUND_UP(qdesc->entry_num, 10);
queue->data_size = qdesc->data_size;
queue->desc_size = qdesc->desc_size;
/*
* Allocate all queue entries.
*/
entry_size = sizeof(*entries) + qdesc->priv_size;
entries = kcalloc(queue->limit, entry_size, GFP_KERNEL);
if (!entries)
return -ENOMEM;
#define QUEUE_ENTRY_PRIV_OFFSET(__base, __index, __limit, __esize, __psize) \
(((char *)(__base)) + ((__limit) * (__esize)) + \
((__index) * (__psize)))
for (i = 0; i < queue->limit; i++) {
entries[i].flags = 0;
entries[i].queue = queue;
entries[i].skb = NULL;
entries[i].entry_idx = i;
entries[i].priv_data =
QUEUE_ENTRY_PRIV_OFFSET(entries, i, queue->limit,
sizeof(*entries), qdesc->priv_size);
}
#undef QUEUE_ENTRY_PRIV_OFFSET
queue->entries = entries;
return 0;
}
static void rt2x00queue_free_skbs(struct data_queue *queue)
{
unsigned int i;
if (!queue->entries)
return;
for (i = 0; i < queue->limit; i++) {
rt2x00queue_free_skb(&queue->entries[i]);
}
}
static int rt2x00queue_alloc_rxskbs(struct data_queue *queue)
{
unsigned int i;
struct sk_buff *skb;
for (i = 0; i < queue->limit; i++) {
skb = rt2x00queue_alloc_rxskb(&queue->entries[i]);
if (!skb)
return -ENOMEM;
queue->entries[i].skb = skb;
}
return 0;
}
int rt2x00queue_initialize(struct rt2x00_dev *rt2x00dev)
{
struct data_queue *queue;
int status;
status = rt2x00queue_alloc_entries(rt2x00dev->rx, rt2x00dev->ops->rx);
if (status)
goto exit;
tx_queue_for_each(rt2x00dev, queue) {
status = rt2x00queue_alloc_entries(queue, rt2x00dev->ops->tx);
if (status)
goto exit;
}
status = rt2x00queue_alloc_entries(rt2x00dev->bcn, rt2x00dev->ops->bcn);
if (status)
goto exit;
if (test_bit(REQUIRE_ATIM_QUEUE, &rt2x00dev->cap_flags)) {
status = rt2x00queue_alloc_entries(rt2x00dev->atim,
rt2x00dev->ops->atim);
if (status)
goto exit;
}
status = rt2x00queue_alloc_rxskbs(rt2x00dev->rx);
if (status)
goto exit;
return 0;
exit:
ERROR(rt2x00dev, "Queue entries allocation failed.\n");
rt2x00queue_uninitialize(rt2x00dev);
return status;
}
void rt2x00queue_uninitialize(struct rt2x00_dev *rt2x00dev)
{
struct data_queue *queue;
rt2x00queue_free_skbs(rt2x00dev->rx);
queue_for_each(rt2x00dev, queue) {
kfree(queue->entries);
queue->entries = NULL;
}
}
static void rt2x00queue_init(struct rt2x00_dev *rt2x00dev,
struct data_queue *queue, enum data_queue_qid qid)
{
mutex_init(&queue->status_lock);
spin_lock_init(&queue->tx_lock);
spin_lock_init(&queue->index_lock);
queue->rt2x00dev = rt2x00dev;
queue->qid = qid;
queue->txop = 0;
queue->aifs = 2;
queue->cw_min = 5;
queue->cw_max = 10;
}
int rt2x00queue_allocate(struct rt2x00_dev *rt2x00dev)
{
struct data_queue *queue;
enum data_queue_qid qid;
unsigned int req_atim =
!!test_bit(REQUIRE_ATIM_QUEUE, &rt2x00dev->cap_flags);
/*
* We need the following queues:
* RX: 1
* TX: ops->tx_queues
* Beacon: 1
* Atim: 1 (if required)
*/
rt2x00dev->data_queues = 2 + rt2x00dev->ops->tx_queues + req_atim;
queue = kcalloc(rt2x00dev->data_queues, sizeof(*queue), GFP_KERNEL);
if (!queue) {
ERROR(rt2x00dev, "Queue allocation failed.\n");
return -ENOMEM;
}
/*
* Initialize pointers
*/
rt2x00dev->rx = queue;
rt2x00dev->tx = &queue[1];
rt2x00dev->bcn = &queue[1 + rt2x00dev->ops->tx_queues];
rt2x00dev->atim = req_atim ? &queue[2 + rt2x00dev->ops->tx_queues] : NULL;
/*
* Initialize queue parameters.
* RX: qid = QID_RX
* TX: qid = QID_AC_VO + index
* TX: cw_min: 2^5 = 32.
* TX: cw_max: 2^10 = 1024.
* BCN: qid = QID_BEACON
* ATIM: qid = QID_ATIM
*/
rt2x00queue_init(rt2x00dev, rt2x00dev->rx, QID_RX);
qid = QID_AC_VO;
tx_queue_for_each(rt2x00dev, queue)
rt2x00queue_init(rt2x00dev, queue, qid++);
rt2x00queue_init(rt2x00dev, rt2x00dev->bcn, QID_BEACON);
if (req_atim)
rt2x00queue_init(rt2x00dev, rt2x00dev->atim, QID_ATIM);
return 0;
}
void rt2x00queue_free(struct rt2x00_dev *rt2x00dev)
{
kfree(rt2x00dev->rx);
rt2x00dev->rx = NULL;
rt2x00dev->tx = NULL;
rt2x00dev->bcn = NULL;
}
| gpl-2.0 |
temasek/Kernel-Nexus7 | drivers/gpu/drm/radeon/radeon_acpi.c | 2795 | 1571 | #include <linux/pci.h>
#include <linux/acpi.h>
#include <linux/slab.h>
#include <acpi/acpi_drivers.h>
#include <acpi/acpi_bus.h>
#include "drmP.h"
#include "drm.h"
#include "drm_sarea.h"
#include "drm_crtc_helper.h"
#include "radeon.h"
#include <linux/vga_switcheroo.h>
/* Call the ATIF method
*
* Note: currently we discard the output
*/
static int radeon_atif_call(acpi_handle handle)
{
acpi_status status;
union acpi_object atif_arg_elements[2];
struct acpi_object_list atif_arg;
struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL};
atif_arg.count = 2;
atif_arg.pointer = &atif_arg_elements[0];
atif_arg_elements[0].type = ACPI_TYPE_INTEGER;
atif_arg_elements[0].integer.value = 0;
atif_arg_elements[1].type = ACPI_TYPE_INTEGER;
atif_arg_elements[1].integer.value = 0;
status = acpi_evaluate_object(handle, "ATIF", &atif_arg, &buffer);
/* Fail only if calling the method fails and ATIF is supported */
if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) {
printk(KERN_DEBUG "failed to evaluate ATIF got %s\n", acpi_format_exception(status));
kfree(buffer.pointer);
return 1;
}
kfree(buffer.pointer);
return 0;
}
/* Call all ACPI methods here */
int radeon_acpi_init(struct radeon_device *rdev)
{
acpi_handle handle;
int ret;
/* No need to proceed if we're sure that ATIF is not supported */
if (!ASIC_IS_AVIVO(rdev) || !rdev->bios)
return 0;
/* Get the device handle */
handle = DEVICE_ACPI_HANDLE(&rdev->pdev->dev);
/* Call the ATIF method */
ret = radeon_atif_call(handle);
if (ret)
return ret;
return 0;
}
| gpl-2.0 |
csolg/hi35xx-buildroot | linux/linux-3.0.y/drivers/usb/gadget/mv_udc_phy.c | 3051 | 5894 | #include <linux/delay.h>
#include <linux/timer.h>
#include <linux/io.h>
#include <linux/errno.h>
#include <mach/cputype.h>
#ifdef CONFIG_ARCH_MMP
#define UTMI_REVISION 0x0
#define UTMI_CTRL 0x4
#define UTMI_PLL 0x8
#define UTMI_TX 0xc
#define UTMI_RX 0x10
#define UTMI_IVREF 0x14
#define UTMI_T0 0x18
#define UTMI_T1 0x1c
#define UTMI_T2 0x20
#define UTMI_T3 0x24
#define UTMI_T4 0x28
#define UTMI_T5 0x2c
#define UTMI_RESERVE 0x30
#define UTMI_USB_INT 0x34
#define UTMI_DBG_CTL 0x38
#define UTMI_OTG_ADDON 0x3c
/* For UTMICTRL Register */
#define UTMI_CTRL_USB_CLK_EN (1 << 31)
/* pxa168 */
#define UTMI_CTRL_SUSPEND_SET1 (1 << 30)
#define UTMI_CTRL_SUSPEND_SET2 (1 << 29)
#define UTMI_CTRL_RXBUF_PDWN (1 << 24)
#define UTMI_CTRL_TXBUF_PDWN (1 << 11)
#define UTMI_CTRL_INPKT_DELAY_SHIFT 30
#define UTMI_CTRL_INPKT_DELAY_SOF_SHIFT 28
#define UTMI_CTRL_PU_REF_SHIFT 20
#define UTMI_CTRL_ARC_PULLDN_SHIFT 12
#define UTMI_CTRL_PLL_PWR_UP_SHIFT 1
#define UTMI_CTRL_PWR_UP_SHIFT 0
/* For UTMI_PLL Register */
#define UTMI_PLL_CLK_BLK_EN_SHIFT 24
#define UTMI_PLL_FBDIV_SHIFT 4
#define UTMI_PLL_REFDIV_SHIFT 0
#define UTMI_PLL_FBDIV_MASK 0x00000FF0
#define UTMI_PLL_REFDIV_MASK 0x0000000F
#define UTMI_PLL_ICP_MASK 0x00007000
#define UTMI_PLL_KVCO_MASK 0x00031000
#define UTMI_PLL_PLLCALI12_SHIFT 29
#define UTMI_PLL_PLLCALI12_MASK (0x3 << 29)
#define UTMI_PLL_PLLVDD18_SHIFT 27
#define UTMI_PLL_PLLVDD18_MASK (0x3 << 27)
#define UTMI_PLL_PLLVDD12_SHIFT 25
#define UTMI_PLL_PLLVDD12_MASK (0x3 << 25)
#define UTMI_PLL_KVCO_SHIFT 15
#define UTMI_PLL_ICP_SHIFT 12
/* For UTMI_TX Register */
#define UTMI_TX_REG_EXT_FS_RCAL_SHIFT 27
#define UTMI_TX_REG_EXT_FS_RCAL_MASK (0xf << 27)
#define UTMI_TX_REG_EXT_FS_RCAL_EN_MASK 26
#define UTMI_TX_REG_EXT_FS_RCAL_EN (0x1 << 26)
#define UTMI_TX_LOW_VDD_EN_SHIFT 11
#define UTMI_TX_IMPCAL_VTH_SHIFT 14
#define UTMI_TX_IMPCAL_VTH_MASK (0x7 << 14)
#define UTMI_TX_CK60_PHSEL_SHIFT 17
#define UTMI_TX_CK60_PHSEL_MASK (0xf << 17)
#define UTMI_TX_TXVDD12_SHIFT 22
#define UTMI_TX_TXVDD12_MASK (0x3 << 22)
#define UTMI_TX_AMP_SHIFT 0
#define UTMI_TX_AMP_MASK (0x7 << 0)
/* For UTMI_RX Register */
#define UTMI_RX_SQ_THRESH_SHIFT 4
#define UTMI_RX_SQ_THRESH_MASK (0xf << 4)
#define UTMI_REG_SQ_LENGTH_SHIFT 15
#define UTMI_REG_SQ_LENGTH_MASK (0x3 << 15)
#define REG_RCAL_START 0x00001000
#define VCOCAL_START 0x00200000
#define KVCO_EXT 0x00400000
#define PLL_READY 0x00800000
#define CLK_BLK_EN 0x01000000
#endif
static unsigned int u2o_read(unsigned int base, unsigned int offset)
{
return readl(base + offset);
}
static void u2o_set(unsigned int base, unsigned int offset, unsigned int value)
{
unsigned int reg;
reg = readl(base + offset);
reg |= value;
writel(reg, base + offset);
readl(base + offset);
}
static void u2o_clear(unsigned int base, unsigned int offset,
unsigned int value)
{
unsigned int reg;
reg = readl(base + offset);
reg &= ~value;
writel(reg, base + offset);
readl(base + offset);
}
static void u2o_write(unsigned int base, unsigned int offset,
unsigned int value)
{
writel(value, base + offset);
readl(base + offset);
}
#ifdef CONFIG_ARCH_MMP
int mv_udc_phy_init(unsigned int base)
{
unsigned long timeout;
/* Initialize the USB PHY power */
if (cpu_is_pxa910()) {
u2o_set(base, UTMI_CTRL, (1 << UTMI_CTRL_INPKT_DELAY_SOF_SHIFT)
| (1 << UTMI_CTRL_PU_REF_SHIFT));
}
u2o_set(base, UTMI_CTRL, 1 << UTMI_CTRL_PLL_PWR_UP_SHIFT);
u2o_set(base, UTMI_CTRL, 1 << UTMI_CTRL_PWR_UP_SHIFT);
/* UTMI_PLL settings */
u2o_clear(base, UTMI_PLL, UTMI_PLL_PLLVDD18_MASK
| UTMI_PLL_PLLVDD12_MASK | UTMI_PLL_PLLCALI12_MASK
| UTMI_PLL_FBDIV_MASK | UTMI_PLL_REFDIV_MASK
| UTMI_PLL_ICP_MASK | UTMI_PLL_KVCO_MASK);
u2o_set(base, UTMI_PLL, (0xee << UTMI_PLL_FBDIV_SHIFT)
| (0xb << UTMI_PLL_REFDIV_SHIFT)
| (3 << UTMI_PLL_PLLVDD18_SHIFT)
| (3 << UTMI_PLL_PLLVDD12_SHIFT)
| (3 << UTMI_PLL_PLLCALI12_SHIFT)
| (1 << UTMI_PLL_ICP_SHIFT) | (3 << UTMI_PLL_KVCO_SHIFT));
/* UTMI_TX */
u2o_clear(base, UTMI_TX, UTMI_TX_REG_EXT_FS_RCAL_EN_MASK
| UTMI_TX_TXVDD12_MASK
| UTMI_TX_CK60_PHSEL_MASK | UTMI_TX_IMPCAL_VTH_MASK
| UTMI_TX_REG_EXT_FS_RCAL_MASK | UTMI_TX_AMP_MASK);
u2o_set(base, UTMI_TX, (3 << UTMI_TX_TXVDD12_SHIFT)
| (4 << UTMI_TX_CK60_PHSEL_SHIFT)
| (4 << UTMI_TX_IMPCAL_VTH_SHIFT)
| (8 << UTMI_TX_REG_EXT_FS_RCAL_SHIFT)
| (3 << UTMI_TX_AMP_SHIFT));
/* UTMI_RX */
u2o_clear(base, UTMI_RX, UTMI_RX_SQ_THRESH_MASK
| UTMI_REG_SQ_LENGTH_MASK);
if (cpu_is_pxa168())
u2o_set(base, UTMI_RX, (7 << UTMI_RX_SQ_THRESH_SHIFT)
| (2 << UTMI_REG_SQ_LENGTH_SHIFT));
else
u2o_set(base, UTMI_RX, (0x7 << UTMI_RX_SQ_THRESH_SHIFT)
| (2 << UTMI_REG_SQ_LENGTH_SHIFT));
/* UTMI_IVREF */
if (cpu_is_pxa168())
/*
* fixing Microsoft Altair board interface with NEC hub issue -
* Set UTMI_IVREF from 0x4a3 to 0x4bf
*/
u2o_write(base, UTMI_IVREF, 0x4bf);
/* calibrate */
timeout = jiffies + 100;
while ((u2o_read(base, UTMI_PLL) & PLL_READY) == 0) {
if (time_after(jiffies, timeout))
return -ETIME;
cpu_relax();
}
/* toggle VCOCAL_START bit of UTMI_PLL */
udelay(200);
u2o_set(base, UTMI_PLL, VCOCAL_START);
udelay(40);
u2o_clear(base, UTMI_PLL, VCOCAL_START);
/* toggle REG_RCAL_START bit of UTMI_TX */
udelay(200);
u2o_set(base, UTMI_TX, REG_RCAL_START);
udelay(40);
u2o_clear(base, UTMI_TX, REG_RCAL_START);
udelay(200);
/* make sure phy is ready */
timeout = jiffies + 100;
while ((u2o_read(base, UTMI_PLL) & PLL_READY) == 0) {
if (time_after(jiffies, timeout))
return -ETIME;
cpu_relax();
}
if (cpu_is_pxa168()) {
u2o_set(base, UTMI_RESERVE, 1 << 5);
/* Turn on UTMI PHY OTG extension */
u2o_write(base, UTMI_OTG_ADDON, 1);
}
return 0;
}
#else
int mv_udc_phy_init(unsigned int base)
{
return 0;
}
#endif
| gpl-2.0 |
mahirkukreja/delos3geurkernel | arch/arm/mach-omap1/board-generic.c | 4843 | 2342 | /*
* linux/arch/arm/mach-omap1/board-generic.c
*
* Modified from board-innovator1510.c
*
* Code for generic OMAP board. Should work on many OMAP systems where
* the device drivers take care of all the necessary hardware initialization.
* Do not put any board specific code to this file; create a new machine
* type if you need custom low-level initializations.
*
* 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/gpio.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <mach/hardware.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <plat/mux.h>
#include <plat/usb.h>
#include <plat/board.h>
#include "common.h"
/* assume no Mini-AB port */
#ifdef CONFIG_ARCH_OMAP15XX
static struct omap_usb_config generic1510_usb_config __initdata = {
.register_host = 1,
.register_dev = 1,
.hmc_mode = 16,
.pins[0] = 3,
};
#endif
#if defined(CONFIG_ARCH_OMAP16XX)
static struct omap_usb_config generic1610_usb_config __initdata = {
#ifdef CONFIG_USB_OTG
.otg = 1,
#endif
.register_host = 1,
.register_dev = 1,
.hmc_mode = 16,
.pins[0] = 6,
};
#endif
static struct omap_board_config_kernel generic_config[] __initdata = {
};
static void __init omap_generic_init(void)
{
#ifdef CONFIG_ARCH_OMAP15XX
if (cpu_is_omap15xx()) {
/* mux pins for uarts */
omap_cfg_reg(UART1_TX);
omap_cfg_reg(UART1_RTS);
omap_cfg_reg(UART2_TX);
omap_cfg_reg(UART2_RTS);
omap_cfg_reg(UART3_TX);
omap_cfg_reg(UART3_RX);
omap1_usb_init(&generic1510_usb_config);
}
#endif
#if defined(CONFIG_ARCH_OMAP16XX)
if (!cpu_is_omap1510()) {
omap1_usb_init(&generic1610_usb_config);
}
#endif
omap_board_config = generic_config;
omap_board_config_size = ARRAY_SIZE(generic_config);
omap_serial_init();
omap_register_i2c_bus(1, 100, NULL, 0);
}
MACHINE_START(OMAP_GENERIC, "Generic OMAP1510/1610/1710")
/* Maintainer: Tony Lindgren <tony@atomide.com> */
.atag_offset = 0x100,
.map_io = omap16xx_map_io,
.init_early = omap1_init_early,
.reserve = omap_reserve,
.init_irq = omap1_init_irq,
.init_machine = omap_generic_init,
.timer = &omap1_timer,
.restart = omap1_restart,
MACHINE_END
| gpl-2.0 |
Flyhalf205/android_kernel_htc_t6 | drivers/platform/x86/fujitsu-tablet.c | 4843 | 10510 | /*
* Copyright (C) 2006-2012 Robert Gerlach <khnz@gmx.de>
* Copyright (C) 2005-2006 Jan Rychter <jan@rychter.com>
*
* You can redistribute and/or modify this program under the terms of the
* GNU General Public License version 2 as published by the Free Software
* Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place Suite 330, Boston, MA 02111-1307, USA.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/bitops.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/acpi.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/delay.h>
#include <linux/dmi.h>
#define MODULENAME "fujitsu-tablet"
#define ACPI_FUJITSU_CLASS "fujitsu"
#define INVERT_TABLET_MODE_BIT 0x01
#define FORCE_TABLET_MODE_IF_UNDOCK 0x02
#define KEYMAP_LEN 16
static const struct acpi_device_id fujitsu_ids[] = {
{ .id = "FUJ02BD" },
{ .id = "FUJ02BF" },
{ .id = "" }
};
struct fujitsu_config {
unsigned short keymap[KEYMAP_LEN];
unsigned int quirks;
};
static unsigned short keymap_Lifebook_Tseries[KEYMAP_LEN] __initconst = {
KEY_RESERVED,
KEY_RESERVED,
KEY_RESERVED,
KEY_RESERVED,
KEY_SCROLLDOWN,
KEY_SCROLLUP,
KEY_DIRECTION,
KEY_LEFTCTRL,
KEY_BRIGHTNESSUP,
KEY_BRIGHTNESSDOWN,
KEY_BRIGHTNESS_ZERO,
KEY_RESERVED,
KEY_RESERVED,
KEY_RESERVED,
KEY_RESERVED,
KEY_LEFTALT
};
static unsigned short keymap_Lifebook_U810[KEYMAP_LEN] __initconst = {
KEY_RESERVED,
KEY_RESERVED,
KEY_RESERVED,
KEY_RESERVED,
KEY_PROG1,
KEY_PROG2,
KEY_DIRECTION,
KEY_RESERVED,
KEY_RESERVED,
KEY_RESERVED,
KEY_UP,
KEY_DOWN,
KEY_RESERVED,
KEY_RESERVED,
KEY_LEFTCTRL,
KEY_LEFTALT
};
static unsigned short keymap_Stylistic_Tseries[KEYMAP_LEN] __initconst = {
KEY_RESERVED,
KEY_RESERVED,
KEY_RESERVED,
KEY_RESERVED,
KEY_PRINT,
KEY_BACKSPACE,
KEY_SPACE,
KEY_ENTER,
KEY_BRIGHTNESSUP,
KEY_BRIGHTNESSDOWN,
KEY_DOWN,
KEY_UP,
KEY_SCROLLUP,
KEY_SCROLLDOWN,
KEY_LEFTCTRL,
KEY_LEFTALT
};
static unsigned short keymap_Stylistic_ST5xxx[KEYMAP_LEN] __initconst = {
KEY_RESERVED,
KEY_RESERVED,
KEY_RESERVED,
KEY_RESERVED,
KEY_MAIL,
KEY_DIRECTION,
KEY_ESC,
KEY_ENTER,
KEY_BRIGHTNESSUP,
KEY_BRIGHTNESSDOWN,
KEY_DOWN,
KEY_UP,
KEY_SCROLLUP,
KEY_SCROLLDOWN,
KEY_LEFTCTRL,
KEY_LEFTALT
};
static struct {
struct input_dev *idev;
struct fujitsu_config config;
unsigned long prev_keymask;
char phys[21];
int irq;
int io_base;
int io_length;
} fujitsu;
static u8 fujitsu_ack(void)
{
return inb(fujitsu.io_base + 2);
}
static u8 fujitsu_status(void)
{
return inb(fujitsu.io_base + 6);
}
static u8 fujitsu_read_register(const u8 addr)
{
outb(addr, fujitsu.io_base);
return inb(fujitsu.io_base + 4);
}
static void fujitsu_send_state(void)
{
int state;
int dock, tablet_mode;
state = fujitsu_read_register(0xdd);
dock = state & 0x02;
if ((fujitsu.config.quirks & FORCE_TABLET_MODE_IF_UNDOCK) && (!dock)) {
tablet_mode = 1;
} else{
tablet_mode = state & 0x01;
if (fujitsu.config.quirks & INVERT_TABLET_MODE_BIT)
tablet_mode = !tablet_mode;
}
input_report_switch(fujitsu.idev, SW_DOCK, dock);
input_report_switch(fujitsu.idev, SW_TABLET_MODE, tablet_mode);
input_sync(fujitsu.idev);
}
static void fujitsu_reset(void)
{
int timeout = 50;
fujitsu_ack();
while ((fujitsu_status() & 0x02) && (--timeout))
msleep(20);
fujitsu_send_state();
}
static int __devinit input_fujitsu_setup(struct device *parent,
const char *name, const char *phys)
{
struct input_dev *idev;
int error;
int i;
idev = input_allocate_device();
if (!idev)
return -ENOMEM;
idev->dev.parent = parent;
idev->phys = phys;
idev->name = name;
idev->id.bustype = BUS_HOST;
idev->id.vendor = 0x1734; /* Fujitsu Siemens Computer GmbH */
idev->id.product = 0x0001;
idev->id.version = 0x0101;
idev->keycode = fujitsu.config.keymap;
idev->keycodesize = sizeof(fujitsu.config.keymap[0]);
idev->keycodemax = ARRAY_SIZE(fujitsu.config.keymap);
__set_bit(EV_REP, idev->evbit);
for (i = 0; i < ARRAY_SIZE(fujitsu.config.keymap); i++)
if (fujitsu.config.keymap[i])
input_set_capability(idev, EV_KEY, fujitsu.config.keymap[i]);
input_set_capability(idev, EV_MSC, MSC_SCAN);
input_set_capability(idev, EV_SW, SW_DOCK);
input_set_capability(idev, EV_SW, SW_TABLET_MODE);
input_set_capability(idev, EV_SW, SW_DOCK);
input_set_capability(idev, EV_SW, SW_TABLET_MODE);
error = input_register_device(idev);
if (error) {
input_free_device(idev);
return error;
}
fujitsu.idev = idev;
return 0;
}
static void input_fujitsu_remove(void)
{
input_unregister_device(fujitsu.idev);
}
static irqreturn_t fujitsu_interrupt(int irq, void *dev_id)
{
unsigned long keymask, changed;
unsigned int keycode;
int pressed;
int i;
if (unlikely(!(fujitsu_status() & 0x01)))
return IRQ_NONE;
fujitsu_send_state();
keymask = fujitsu_read_register(0xde);
keymask |= fujitsu_read_register(0xdf) << 8;
keymask ^= 0xffff;
changed = keymask ^ fujitsu.prev_keymask;
if (changed) {
fujitsu.prev_keymask = keymask;
for_each_set_bit(i, &changed, KEYMAP_LEN) {
keycode = fujitsu.config.keymap[i];
pressed = keymask & changed & BIT(i);
if (pressed)
input_event(fujitsu.idev, EV_MSC, MSC_SCAN, i);
input_report_key(fujitsu.idev, keycode, pressed);
input_sync(fujitsu.idev);
}
}
fujitsu_ack();
return IRQ_HANDLED;
}
static int __devinit fujitsu_dmi_default(const struct dmi_system_id *dmi)
{
printk(KERN_INFO MODULENAME ": %s\n", dmi->ident);
memcpy(fujitsu.config.keymap, dmi->driver_data,
sizeof(fujitsu.config.keymap));
return 1;
}
static int __devinit fujitsu_dmi_stylistic(const struct dmi_system_id *dmi)
{
fujitsu_dmi_default(dmi);
fujitsu.config.quirks |= FORCE_TABLET_MODE_IF_UNDOCK;
fujitsu.config.quirks |= INVERT_TABLET_MODE_BIT;
return 1;
}
static struct dmi_system_id dmi_ids[] __initconst = {
{
.callback = fujitsu_dmi_default,
.ident = "Fujitsu Siemens P/T Series",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "LIFEBOOK")
},
.driver_data = keymap_Lifebook_Tseries
},
{
.callback = fujitsu_dmi_default,
.ident = "Fujitsu Lifebook T Series",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "LifeBook T")
},
.driver_data = keymap_Lifebook_Tseries
},
{
.callback = fujitsu_dmi_stylistic,
.ident = "Fujitsu Siemens Stylistic T Series",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "Stylistic T")
},
.driver_data = keymap_Stylistic_Tseries
},
{
.callback = fujitsu_dmi_default,
.ident = "Fujitsu LifeBook U810",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "LifeBook U810")
},
.driver_data = keymap_Lifebook_U810
},
{
.callback = fujitsu_dmi_stylistic,
.ident = "Fujitsu Siemens Stylistic ST5xxx Series",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "STYLISTIC ST5")
},
.driver_data = keymap_Stylistic_ST5xxx
},
{
.callback = fujitsu_dmi_stylistic,
.ident = "Fujitsu Siemens Stylistic ST5xxx Series",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "Stylistic ST5")
},
.driver_data = keymap_Stylistic_ST5xxx
},
{
.callback = fujitsu_dmi_default,
.ident = "Unknown (using defaults)",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, ""),
DMI_MATCH(DMI_PRODUCT_NAME, "")
},
.driver_data = keymap_Lifebook_Tseries
},
{ NULL }
};
static acpi_status __devinit
fujitsu_walk_resources(struct acpi_resource *res, void *data)
{
switch (res->type) {
case ACPI_RESOURCE_TYPE_IRQ:
fujitsu.irq = res->data.irq.interrupts[0];
return AE_OK;
case ACPI_RESOURCE_TYPE_IO:
fujitsu.io_base = res->data.io.minimum;
fujitsu.io_length = res->data.io.address_length;
return AE_OK;
case ACPI_RESOURCE_TYPE_END_TAG:
if (fujitsu.irq && fujitsu.io_base)
return AE_OK;
else
return AE_NOT_FOUND;
default:
return AE_ERROR;
}
}
static int __devinit acpi_fujitsu_add(struct acpi_device *adev)
{
acpi_status status;
int error;
if (!adev)
return -EINVAL;
status = acpi_walk_resources(adev->handle, METHOD_NAME__CRS,
fujitsu_walk_resources, NULL);
if (ACPI_FAILURE(status) || !fujitsu.irq || !fujitsu.io_base)
return -ENODEV;
sprintf(acpi_device_name(adev), "Fujitsu %s", acpi_device_hid(adev));
sprintf(acpi_device_class(adev), "%s", ACPI_FUJITSU_CLASS);
snprintf(fujitsu.phys, sizeof(fujitsu.phys),
"%s/input0", acpi_device_hid(adev));
error = input_fujitsu_setup(&adev->dev,
acpi_device_name(adev), fujitsu.phys);
if (error)
return error;
if (!request_region(fujitsu.io_base, fujitsu.io_length, MODULENAME)) {
input_fujitsu_remove();
return -EBUSY;
}
fujitsu_reset();
error = request_irq(fujitsu.irq, fujitsu_interrupt,
IRQF_SHARED, MODULENAME, fujitsu_interrupt);
if (error) {
release_region(fujitsu.io_base, fujitsu.io_length);
input_fujitsu_remove();
return error;
}
return 0;
}
static int __devexit acpi_fujitsu_remove(struct acpi_device *adev, int type)
{
free_irq(fujitsu.irq, fujitsu_interrupt);
release_region(fujitsu.io_base, fujitsu.io_length);
input_fujitsu_remove();
return 0;
}
static int acpi_fujitsu_resume(struct acpi_device *adev)
{
fujitsu_reset();
return 0;
}
static struct acpi_driver acpi_fujitsu_driver = {
.name = MODULENAME,
.class = "hotkey",
.ids = fujitsu_ids,
.ops = {
.add = acpi_fujitsu_add,
.remove = acpi_fujitsu_remove,
.resume = acpi_fujitsu_resume,
}
};
static int __init fujitsu_module_init(void)
{
int error;
dmi_check_system(dmi_ids);
error = acpi_bus_register_driver(&acpi_fujitsu_driver);
if (error)
return error;
return 0;
}
static void __exit fujitsu_module_exit(void)
{
acpi_bus_unregister_driver(&acpi_fujitsu_driver);
}
module_init(fujitsu_module_init);
module_exit(fujitsu_module_exit);
MODULE_AUTHOR("Robert Gerlach <khnz@gmx.de>");
MODULE_DESCRIPTION("Fujitsu tablet pc extras driver");
MODULE_LICENSE("GPL");
MODULE_VERSION("2.4");
MODULE_DEVICE_TABLE(acpi, fujitsu_ids);
| gpl-2.0 |
cameron581/kernel_msm | fs/reiserfs/file.c | 4843 | 10681 | /*
* Copyright 2000 by Hans Reiser, licensing governed by reiserfs/README
*/
#include <linux/time.h>
#include "reiserfs.h"
#include "acl.h"
#include "xattr.h"
#include <asm/uaccess.h>
#include <linux/pagemap.h>
#include <linux/swap.h>
#include <linux/writeback.h>
#include <linux/blkdev.h>
#include <linux/buffer_head.h>
#include <linux/quotaops.h>
/*
** We pack the tails of files on file close, not at the time they are written.
** This implies an unnecessary copy of the tail and an unnecessary indirect item
** insertion/balancing, for files that are written in one write.
** It avoids unnecessary tail packings (balances) for files that are written in
** multiple writes and are small enough to have tails.
**
** file_release is called by the VFS layer when the file is closed. If
** this is the last open file descriptor, and the file
** small enough to have a tail, and the tail is currently in an
** unformatted node, the tail is converted back into a direct item.
**
** We use reiserfs_truncate_file to pack the tail, since it already has
** all the conditions coded.
*/
static int reiserfs_file_release(struct inode *inode, struct file *filp)
{
struct reiserfs_transaction_handle th;
int err;
int jbegin_failure = 0;
BUG_ON(!S_ISREG(inode->i_mode));
if (atomic_add_unless(&REISERFS_I(inode)->openers, -1, 1))
return 0;
mutex_lock(&(REISERFS_I(inode)->tailpack));
if (!atomic_dec_and_test(&REISERFS_I(inode)->openers)) {
mutex_unlock(&(REISERFS_I(inode)->tailpack));
return 0;
}
/* fast out for when nothing needs to be done */
if ((!(REISERFS_I(inode)->i_flags & i_pack_on_close_mask) ||
!tail_has_to_be_packed(inode)) &&
REISERFS_I(inode)->i_prealloc_count <= 0) {
mutex_unlock(&(REISERFS_I(inode)->tailpack));
return 0;
}
reiserfs_write_lock(inode->i_sb);
/* freeing preallocation only involves relogging blocks that
* are already in the current transaction. preallocation gets
* freed at the end of each transaction, so it is impossible for
* us to log any additional blocks (including quota blocks)
*/
err = journal_begin(&th, inode->i_sb, 1);
if (err) {
/* uh oh, we can't allow the inode to go away while there
* is still preallocation blocks pending. Try to join the
* aborted transaction
*/
jbegin_failure = err;
err = journal_join_abort(&th, inode->i_sb, 1);
if (err) {
/* hmpf, our choices here aren't good. We can pin the inode
* which will disallow unmount from every happening, we can
* do nothing, which will corrupt random memory on unmount,
* or we can forcibly remove the file from the preallocation
* list, which will leak blocks on disk. Lets pin the inode
* and let the admin know what is going on.
*/
igrab(inode);
reiserfs_warning(inode->i_sb, "clm-9001",
"pinning inode %lu because the "
"preallocation can't be freed",
inode->i_ino);
goto out;
}
}
reiserfs_update_inode_transaction(inode);
#ifdef REISERFS_PREALLOCATE
reiserfs_discard_prealloc(&th, inode);
#endif
err = journal_end(&th, inode->i_sb, 1);
/* copy back the error code from journal_begin */
if (!err)
err = jbegin_failure;
if (!err &&
(REISERFS_I(inode)->i_flags & i_pack_on_close_mask) &&
tail_has_to_be_packed(inode)) {
/* if regular file is released by last holder and it has been
appended (we append by unformatted node only) or its direct
item(s) had to be converted, then it may have to be
indirect2direct converted */
err = reiserfs_truncate_file(inode, 0);
}
out:
reiserfs_write_unlock(inode->i_sb);
mutex_unlock(&(REISERFS_I(inode)->tailpack));
return err;
}
static int reiserfs_file_open(struct inode *inode, struct file *file)
{
int err = dquot_file_open(inode, file);
if (!atomic_inc_not_zero(&REISERFS_I(inode)->openers)) {
/* somebody might be tailpacking on final close; wait for it */
mutex_lock(&(REISERFS_I(inode)->tailpack));
atomic_inc(&REISERFS_I(inode)->openers);
mutex_unlock(&(REISERFS_I(inode)->tailpack));
}
return err;
}
static void reiserfs_vfs_truncate_file(struct inode *inode)
{
mutex_lock(&(REISERFS_I(inode)->tailpack));
reiserfs_truncate_file(inode, 1);
mutex_unlock(&(REISERFS_I(inode)->tailpack));
}
/* Sync a reiserfs file. */
/*
* FIXME: sync_mapping_buffers() never has anything to sync. Can
* be removed...
*/
static int reiserfs_sync_file(struct file *filp, loff_t start, loff_t end,
int datasync)
{
struct inode *inode = filp->f_mapping->host;
int err;
int barrier_done;
err = filemap_write_and_wait_range(inode->i_mapping, start, end);
if (err)
return err;
mutex_lock(&inode->i_mutex);
BUG_ON(!S_ISREG(inode->i_mode));
err = sync_mapping_buffers(inode->i_mapping);
reiserfs_write_lock(inode->i_sb);
barrier_done = reiserfs_commit_for_inode(inode);
reiserfs_write_unlock(inode->i_sb);
if (barrier_done != 1 && reiserfs_barrier_flush(inode->i_sb))
blkdev_issue_flush(inode->i_sb->s_bdev, GFP_KERNEL, NULL);
mutex_unlock(&inode->i_mutex);
if (barrier_done < 0)
return barrier_done;
return (err < 0) ? -EIO : 0;
}
/* taken fs/buffer.c:__block_commit_write */
int reiserfs_commit_page(struct inode *inode, struct page *page,
unsigned from, unsigned to)
{
unsigned block_start, block_end;
int partial = 0;
unsigned blocksize;
struct buffer_head *bh, *head;
unsigned long i_size_index = inode->i_size >> PAGE_CACHE_SHIFT;
int new;
int logit = reiserfs_file_data_log(inode);
struct super_block *s = inode->i_sb;
int bh_per_page = PAGE_CACHE_SIZE / s->s_blocksize;
struct reiserfs_transaction_handle th;
int ret = 0;
th.t_trans_id = 0;
blocksize = 1 << inode->i_blkbits;
if (logit) {
reiserfs_write_lock(s);
ret = journal_begin(&th, s, bh_per_page + 1);
if (ret)
goto drop_write_lock;
reiserfs_update_inode_transaction(inode);
}
for (bh = head = page_buffers(page), block_start = 0;
bh != head || !block_start;
block_start = block_end, bh = bh->b_this_page) {
new = buffer_new(bh);
clear_buffer_new(bh);
block_end = block_start + blocksize;
if (block_end <= from || block_start >= to) {
if (!buffer_uptodate(bh))
partial = 1;
} else {
set_buffer_uptodate(bh);
if (logit) {
reiserfs_prepare_for_journal(s, bh, 1);
journal_mark_dirty(&th, s, bh);
} else if (!buffer_dirty(bh)) {
mark_buffer_dirty(bh);
/* do data=ordered on any page past the end
* of file and any buffer marked BH_New.
*/
if (reiserfs_data_ordered(inode->i_sb) &&
(new || page->index >= i_size_index)) {
reiserfs_add_ordered_list(inode, bh);
}
}
}
}
if (logit) {
ret = journal_end(&th, s, bh_per_page + 1);
drop_write_lock:
reiserfs_write_unlock(s);
}
/*
* If this is a partial write which happened to make all buffers
* uptodate then we can optimize away a bogus readpage() for
* the next read(). Here we 'discover' whether the page went
* uptodate as a result of this (potentially partial) write.
*/
if (!partial)
SetPageUptodate(page);
return ret;
}
/* Write @count bytes at position @ppos in a file indicated by @file
from the buffer @buf.
generic_file_write() is only appropriate for filesystems that are not seeking to optimize performance and want
something simple that works. It is not for serious use by general purpose filesystems, excepting the one that it was
written for (ext2/3). This is for several reasons:
* It has no understanding of any filesystem specific optimizations.
* It enters the filesystem repeatedly for each page that is written.
* It depends on reiserfs_get_block() function which if implemented by reiserfs performs costly search_by_key
* operation for each page it is supplied with. By contrast reiserfs_file_write() feeds as much as possible at a time
* to reiserfs which allows for fewer tree traversals.
* Each indirect pointer insertion takes a lot of cpu, because it involves memory moves inside of blocks.
* Asking the block allocation code for blocks one at a time is slightly less efficient.
All of these reasons for not using only generic file write were understood back when reiserfs was first miscoded to
use it, but we were in a hurry to make code freeze, and so it couldn't be revised then. This new code should make
things right finally.
Future Features: providing search_by_key with hints.
*/
static ssize_t reiserfs_file_write(struct file *file, /* the file we are going to write into */
const char __user * buf, /* pointer to user supplied data
(in userspace) */
size_t count, /* amount of bytes to write */
loff_t * ppos /* pointer to position in file that we start writing at. Should be updated to
* new current position before returning. */
)
{
struct inode *inode = file->f_path.dentry->d_inode; // Inode of the file that we are writing to.
/* To simplify coding at this time, we store
locked pages in array for now */
struct reiserfs_transaction_handle th;
th.t_trans_id = 0;
/* If a filesystem is converted from 3.5 to 3.6, we'll have v3.5 items
* lying around (most of the disk, in fact). Despite the filesystem
* now being a v3.6 format, the old items still can't support large
* file sizes. Catch this case here, as the rest of the VFS layer is
* oblivious to the different limitations between old and new items.
* reiserfs_setattr catches this for truncates. This chunk is lifted
* from generic_write_checks. */
if (get_inode_item_key_version (inode) == KEY_FORMAT_3_5 &&
*ppos + count > MAX_NON_LFS) {
if (*ppos >= MAX_NON_LFS) {
return -EFBIG;
}
if (count > MAX_NON_LFS - (unsigned long)*ppos)
count = MAX_NON_LFS - (unsigned long)*ppos;
}
return do_sync_write(file, buf, count, ppos);
}
const struct file_operations reiserfs_file_operations = {
.read = do_sync_read,
.write = reiserfs_file_write,
.unlocked_ioctl = reiserfs_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = reiserfs_compat_ioctl,
#endif
.mmap = generic_file_mmap,
.open = reiserfs_file_open,
.release = reiserfs_file_release,
.fsync = reiserfs_sync_file,
.aio_read = generic_file_aio_read,
.aio_write = generic_file_aio_write,
.splice_read = generic_file_splice_read,
.splice_write = generic_file_splice_write,
.llseek = generic_file_llseek,
};
const struct inode_operations reiserfs_file_inode_operations = {
.truncate = reiserfs_vfs_truncate_file,
.setattr = reiserfs_setattr,
.setxattr = reiserfs_setxattr,
.getxattr = reiserfs_getxattr,
.listxattr = reiserfs_listxattr,
.removexattr = reiserfs_removexattr,
.permission = reiserfs_permission,
.get_acl = reiserfs_get_acl,
};
| gpl-2.0 |
aldencolerain/mc2kernel | Documentation/ia64/aliasing-test.c | 4843 | 6145 | /*
* Exercise /dev/mem mmap cases that have been troublesome in the past
*
* (c) Copyright 2007 Hewlett-Packard Development Company, L.P.
* Bjorn Helgaas <bjorn.helgaas@hp.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 <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <linux/pci.h>
int sum;
static int map_mem(char *path, off_t offset, size_t length, int touch)
{
int fd, rc;
void *addr;
int *c;
fd = open(path, O_RDWR);
if (fd == -1) {
perror(path);
return -1;
}
if (fnmatch("/proc/bus/pci/*", path, 0) == 0) {
rc = ioctl(fd, PCIIOC_MMAP_IS_MEM);
if (rc == -1)
perror("PCIIOC_MMAP_IS_MEM ioctl");
}
addr = mmap(NULL, length, PROT_READ|PROT_WRITE, MAP_SHARED, fd, offset);
if (addr == MAP_FAILED)
return 1;
if (touch) {
c = (int *) addr;
while (c < (int *) (addr + length))
sum += *c++;
}
rc = munmap(addr, length);
if (rc == -1) {
perror("munmap");
return -1;
}
close(fd);
return 0;
}
static int scan_tree(char *path, char *file, off_t offset, size_t length, int touch)
{
struct dirent **namelist;
char *name, *path2;
int i, n, r, rc = 0, result = 0;
struct stat buf;
n = scandir(path, &namelist, 0, alphasort);
if (n < 0) {
perror("scandir");
return -1;
}
for (i = 0; i < n; i++) {
name = namelist[i]->d_name;
if (fnmatch(".", name, 0) == 0)
goto skip;
if (fnmatch("..", name, 0) == 0)
goto skip;
path2 = malloc(strlen(path) + strlen(name) + 3);
strcpy(path2, path);
strcat(path2, "/");
strcat(path2, name);
if (fnmatch(file, name, 0) == 0) {
rc = map_mem(path2, offset, length, touch);
if (rc == 0)
fprintf(stderr, "PASS: %s 0x%lx-0x%lx is %s\n", path2, offset, offset + length, touch ? "readable" : "mappable");
else if (rc > 0)
fprintf(stderr, "PASS: %s 0x%lx-0x%lx not mappable\n", path2, offset, offset + length);
else {
fprintf(stderr, "FAIL: %s 0x%lx-0x%lx not accessible\n", path2, offset, offset + length);
return rc;
}
} else {
r = lstat(path2, &buf);
if (r == 0 && S_ISDIR(buf.st_mode)) {
rc = scan_tree(path2, file, offset, length, touch);
if (rc < 0)
return rc;
}
}
result |= rc;
free(path2);
skip:
free(namelist[i]);
}
free(namelist);
return result;
}
char buf[1024];
static int read_rom(char *path)
{
int fd, rc;
size_t size = 0;
fd = open(path, O_RDWR);
if (fd == -1) {
perror(path);
return -1;
}
rc = write(fd, "1", 2);
if (rc <= 0) {
close(fd);
perror("write");
return -1;
}
do {
rc = read(fd, buf, sizeof(buf));
if (rc > 0)
size += rc;
} while (rc > 0);
close(fd);
return size;
}
static int scan_rom(char *path, char *file)
{
struct dirent **namelist;
char *name, *path2;
int i, n, r, rc = 0, result = 0;
struct stat buf;
n = scandir(path, &namelist, 0, alphasort);
if (n < 0) {
perror("scandir");
return -1;
}
for (i = 0; i < n; i++) {
name = namelist[i]->d_name;
if (fnmatch(".", name, 0) == 0)
goto skip;
if (fnmatch("..", name, 0) == 0)
goto skip;
path2 = malloc(strlen(path) + strlen(name) + 3);
strcpy(path2, path);
strcat(path2, "/");
strcat(path2, name);
if (fnmatch(file, name, 0) == 0) {
rc = read_rom(path2);
/*
* It's OK if the ROM is unreadable. Maybe there
* is no ROM, or some other error occurred. The
* important thing is that no MCA happened.
*/
if (rc > 0)
fprintf(stderr, "PASS: %s read %d bytes\n", path2, rc);
else {
fprintf(stderr, "PASS: %s not readable\n", path2);
return rc;
}
} else {
r = lstat(path2, &buf);
if (r == 0 && S_ISDIR(buf.st_mode)) {
rc = scan_rom(path2, file);
if (rc < 0)
return rc;
}
}
result |= rc;
free(path2);
skip:
free(namelist[i]);
}
free(namelist);
return result;
}
int main(void)
{
int rc;
if (map_mem("/dev/mem", 0, 0xA0000, 1) == 0)
fprintf(stderr, "PASS: /dev/mem 0x0-0xa0000 is readable\n");
else
fprintf(stderr, "FAIL: /dev/mem 0x0-0xa0000 not accessible\n");
/*
* It's not safe to blindly read the VGA frame buffer. If you know
* how to poke the card the right way, it should respond, but it's
* not safe in general. Many machines, e.g., Intel chipsets, cover
* up a non-responding card by just returning -1, but others will
* report the failure as a machine check.
*/
if (map_mem("/dev/mem", 0xA0000, 0x20000, 0) == 0)
fprintf(stderr, "PASS: /dev/mem 0xa0000-0xc0000 is mappable\n");
else
fprintf(stderr, "FAIL: /dev/mem 0xa0000-0xc0000 not accessible\n");
if (map_mem("/dev/mem", 0xC0000, 0x40000, 1) == 0)
fprintf(stderr, "PASS: /dev/mem 0xc0000-0x100000 is readable\n");
else
fprintf(stderr, "FAIL: /dev/mem 0xc0000-0x100000 not accessible\n");
/*
* Often you can map all the individual pieces above (0-0xA0000,
* 0xA0000-0xC0000, and 0xC0000-0x100000), but can't map the whole
* thing at once. This is because the individual pieces use different
* attributes, and there's no single attribute supported over the
* whole region.
*/
rc = map_mem("/dev/mem", 0, 1024*1024, 0);
if (rc == 0)
fprintf(stderr, "PASS: /dev/mem 0x0-0x100000 is mappable\n");
else if (rc > 0)
fprintf(stderr, "PASS: /dev/mem 0x0-0x100000 not mappable\n");
else
fprintf(stderr, "FAIL: /dev/mem 0x0-0x100000 not accessible\n");
scan_tree("/sys/class/pci_bus", "legacy_mem", 0, 0xA0000, 1);
scan_tree("/sys/class/pci_bus", "legacy_mem", 0xA0000, 0x20000, 0);
scan_tree("/sys/class/pci_bus", "legacy_mem", 0xC0000, 0x40000, 1);
scan_tree("/sys/class/pci_bus", "legacy_mem", 0, 1024*1024, 0);
scan_rom("/sys/devices", "rom");
scan_tree("/proc/bus/pci", "??.?", 0, 0xA0000, 1);
scan_tree("/proc/bus/pci", "??.?", 0xA0000, 0x20000, 0);
scan_tree("/proc/bus/pci", "??.?", 0xC0000, 0x40000, 1);
scan_tree("/proc/bus/pci", "??.?", 0, 1024*1024, 0);
return rc;
}
| gpl-2.0 |
TeamButter/android_kernel_samsung_mint2g | drivers/media/dvb/dvb-usb/vp7045-fe.c | 5099 | 5077 | /* DVB frontend part of the Linux driver for TwinhanDTV Alpha/MagicBoxII USB2.0
* DVB-T receiver.
*
* Copyright (C) 2004-5 Patrick Boettcher (patrick.boettcher@desy.de)
*
* Thanks to Twinhan who kindly provided hardware and information.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 2.
*
* see Documentation/dvb/README.dvb-usb for more information
*
*/
#include "vp7045.h"
/* It is a Zarlink MT352 within a Samsung Tuner (DNOS404ZH102A) - 040929 - AAT
*
* Programming is hidden inside the firmware, so set_frontend is very easy.
* Even though there is a Firmware command that one can use to access the demod
* via its registers. This is used for status information.
*/
struct vp7045_fe_state {
struct dvb_frontend fe;
struct dvb_usb_device *d;
};
static int vp7045_fe_read_status(struct dvb_frontend* fe, fe_status_t *status)
{
struct vp7045_fe_state *state = fe->demodulator_priv;
u8 s0 = vp7045_read_reg(state->d,0x00),
s1 = vp7045_read_reg(state->d,0x01),
s3 = vp7045_read_reg(state->d,0x03);
*status = 0;
if (s0 & (1 << 4))
*status |= FE_HAS_CARRIER;
if (s0 & (1 << 1))
*status |= FE_HAS_VITERBI;
if (s0 & (1 << 5))
*status |= FE_HAS_LOCK;
if (s1 & (1 << 1))
*status |= FE_HAS_SYNC;
if (s3 & (1 << 6))
*status |= FE_HAS_SIGNAL;
if ((*status & (FE_HAS_CARRIER | FE_HAS_VITERBI | FE_HAS_SYNC)) !=
(FE_HAS_CARRIER | FE_HAS_VITERBI | FE_HAS_SYNC))
*status &= ~FE_HAS_LOCK;
return 0;
}
static int vp7045_fe_read_ber(struct dvb_frontend* fe, u32 *ber)
{
struct vp7045_fe_state *state = fe->demodulator_priv;
*ber = (vp7045_read_reg(state->d, 0x0D) << 16) |
(vp7045_read_reg(state->d, 0x0E) << 8) |
vp7045_read_reg(state->d, 0x0F);
return 0;
}
static int vp7045_fe_read_unc_blocks(struct dvb_frontend* fe, u32 *unc)
{
struct vp7045_fe_state *state = fe->demodulator_priv;
*unc = (vp7045_read_reg(state->d, 0x10) << 8) |
vp7045_read_reg(state->d, 0x11);
return 0;
}
static int vp7045_fe_read_signal_strength(struct dvb_frontend* fe, u16 *strength)
{
struct vp7045_fe_state *state = fe->demodulator_priv;
u16 signal = (vp7045_read_reg(state->d, 0x14) << 8) |
vp7045_read_reg(state->d, 0x15);
*strength = ~signal;
return 0;
}
static int vp7045_fe_read_snr(struct dvb_frontend* fe, u16 *snr)
{
struct vp7045_fe_state *state = fe->demodulator_priv;
u8 _snr = vp7045_read_reg(state->d, 0x09);
*snr = (_snr << 8) | _snr;
return 0;
}
static int vp7045_fe_init(struct dvb_frontend* fe)
{
return 0;
}
static int vp7045_fe_sleep(struct dvb_frontend* fe)
{
return 0;
}
static int vp7045_fe_get_tune_settings(struct dvb_frontend* fe, struct dvb_frontend_tune_settings *tune)
{
tune->min_delay_ms = 800;
return 0;
}
static int vp7045_fe_set_frontend(struct dvb_frontend* fe,
struct dvb_frontend_parameters *fep)
{
struct vp7045_fe_state *state = fe->demodulator_priv;
u8 buf[5];
u32 freq = fep->frequency / 1000;
buf[0] = (freq >> 16) & 0xff;
buf[1] = (freq >> 8) & 0xff;
buf[2] = freq & 0xff;
buf[3] = 0;
switch (fep->u.ofdm.bandwidth) {
case BANDWIDTH_8_MHZ: buf[4] = 8; break;
case BANDWIDTH_7_MHZ: buf[4] = 7; break;
case BANDWIDTH_6_MHZ: buf[4] = 6; break;
case BANDWIDTH_AUTO: return -EOPNOTSUPP;
default:
return -EINVAL;
}
vp7045_usb_op(state->d,LOCK_TUNER_COMMAND,buf,5,NULL,0,200);
return 0;
}
static int vp7045_fe_get_frontend(struct dvb_frontend* fe,
struct dvb_frontend_parameters *fep)
{
return 0;
}
static void vp7045_fe_release(struct dvb_frontend* fe)
{
struct vp7045_fe_state *state = fe->demodulator_priv;
kfree(state);
}
static struct dvb_frontend_ops vp7045_fe_ops;
struct dvb_frontend * vp7045_fe_attach(struct dvb_usb_device *d)
{
struct vp7045_fe_state *s = kzalloc(sizeof(struct vp7045_fe_state), GFP_KERNEL);
if (s == NULL)
goto error;
s->d = d;
memcpy(&s->fe.ops, &vp7045_fe_ops, sizeof(struct dvb_frontend_ops));
s->fe.demodulator_priv = s;
return &s->fe;
error:
return NULL;
}
static struct dvb_frontend_ops vp7045_fe_ops = {
.info = {
.name = "Twinhan VP7045/46 USB DVB-T",
.type = FE_OFDM,
.frequency_min = 44250000,
.frequency_max = 867250000,
.frequency_stepsize = 1000,
.caps = FE_CAN_INVERSION_AUTO |
FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO |
FE_CAN_QPSK | FE_CAN_QAM_16 | FE_CAN_QAM_64 | FE_CAN_QAM_AUTO |
FE_CAN_TRANSMISSION_MODE_AUTO |
FE_CAN_GUARD_INTERVAL_AUTO |
FE_CAN_RECOVER |
FE_CAN_HIERARCHY_AUTO,
},
.release = vp7045_fe_release,
.init = vp7045_fe_init,
.sleep = vp7045_fe_sleep,
.set_frontend = vp7045_fe_set_frontend,
.get_frontend = vp7045_fe_get_frontend,
.get_tune_settings = vp7045_fe_get_tune_settings,
.read_status = vp7045_fe_read_status,
.read_ber = vp7045_fe_read_ber,
.read_signal_strength = vp7045_fe_read_signal_strength,
.read_snr = vp7045_fe_read_snr,
.read_ucblocks = vp7045_fe_read_unc_blocks,
};
| gpl-2.0 |
keily90/tf101-nv-linux | drivers/media/dvb/dvb-usb/vp7045-fe.c | 5099 | 5077 | /* DVB frontend part of the Linux driver for TwinhanDTV Alpha/MagicBoxII USB2.0
* DVB-T receiver.
*
* Copyright (C) 2004-5 Patrick Boettcher (patrick.boettcher@desy.de)
*
* Thanks to Twinhan who kindly provided hardware and information.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 2.
*
* see Documentation/dvb/README.dvb-usb for more information
*
*/
#include "vp7045.h"
/* It is a Zarlink MT352 within a Samsung Tuner (DNOS404ZH102A) - 040929 - AAT
*
* Programming is hidden inside the firmware, so set_frontend is very easy.
* Even though there is a Firmware command that one can use to access the demod
* via its registers. This is used for status information.
*/
struct vp7045_fe_state {
struct dvb_frontend fe;
struct dvb_usb_device *d;
};
static int vp7045_fe_read_status(struct dvb_frontend* fe, fe_status_t *status)
{
struct vp7045_fe_state *state = fe->demodulator_priv;
u8 s0 = vp7045_read_reg(state->d,0x00),
s1 = vp7045_read_reg(state->d,0x01),
s3 = vp7045_read_reg(state->d,0x03);
*status = 0;
if (s0 & (1 << 4))
*status |= FE_HAS_CARRIER;
if (s0 & (1 << 1))
*status |= FE_HAS_VITERBI;
if (s0 & (1 << 5))
*status |= FE_HAS_LOCK;
if (s1 & (1 << 1))
*status |= FE_HAS_SYNC;
if (s3 & (1 << 6))
*status |= FE_HAS_SIGNAL;
if ((*status & (FE_HAS_CARRIER | FE_HAS_VITERBI | FE_HAS_SYNC)) !=
(FE_HAS_CARRIER | FE_HAS_VITERBI | FE_HAS_SYNC))
*status &= ~FE_HAS_LOCK;
return 0;
}
static int vp7045_fe_read_ber(struct dvb_frontend* fe, u32 *ber)
{
struct vp7045_fe_state *state = fe->demodulator_priv;
*ber = (vp7045_read_reg(state->d, 0x0D) << 16) |
(vp7045_read_reg(state->d, 0x0E) << 8) |
vp7045_read_reg(state->d, 0x0F);
return 0;
}
static int vp7045_fe_read_unc_blocks(struct dvb_frontend* fe, u32 *unc)
{
struct vp7045_fe_state *state = fe->demodulator_priv;
*unc = (vp7045_read_reg(state->d, 0x10) << 8) |
vp7045_read_reg(state->d, 0x11);
return 0;
}
static int vp7045_fe_read_signal_strength(struct dvb_frontend* fe, u16 *strength)
{
struct vp7045_fe_state *state = fe->demodulator_priv;
u16 signal = (vp7045_read_reg(state->d, 0x14) << 8) |
vp7045_read_reg(state->d, 0x15);
*strength = ~signal;
return 0;
}
static int vp7045_fe_read_snr(struct dvb_frontend* fe, u16 *snr)
{
struct vp7045_fe_state *state = fe->demodulator_priv;
u8 _snr = vp7045_read_reg(state->d, 0x09);
*snr = (_snr << 8) | _snr;
return 0;
}
static int vp7045_fe_init(struct dvb_frontend* fe)
{
return 0;
}
static int vp7045_fe_sleep(struct dvb_frontend* fe)
{
return 0;
}
static int vp7045_fe_get_tune_settings(struct dvb_frontend* fe, struct dvb_frontend_tune_settings *tune)
{
tune->min_delay_ms = 800;
return 0;
}
static int vp7045_fe_set_frontend(struct dvb_frontend* fe,
struct dvb_frontend_parameters *fep)
{
struct vp7045_fe_state *state = fe->demodulator_priv;
u8 buf[5];
u32 freq = fep->frequency / 1000;
buf[0] = (freq >> 16) & 0xff;
buf[1] = (freq >> 8) & 0xff;
buf[2] = freq & 0xff;
buf[3] = 0;
switch (fep->u.ofdm.bandwidth) {
case BANDWIDTH_8_MHZ: buf[4] = 8; break;
case BANDWIDTH_7_MHZ: buf[4] = 7; break;
case BANDWIDTH_6_MHZ: buf[4] = 6; break;
case BANDWIDTH_AUTO: return -EOPNOTSUPP;
default:
return -EINVAL;
}
vp7045_usb_op(state->d,LOCK_TUNER_COMMAND,buf,5,NULL,0,200);
return 0;
}
static int vp7045_fe_get_frontend(struct dvb_frontend* fe,
struct dvb_frontend_parameters *fep)
{
return 0;
}
static void vp7045_fe_release(struct dvb_frontend* fe)
{
struct vp7045_fe_state *state = fe->demodulator_priv;
kfree(state);
}
static struct dvb_frontend_ops vp7045_fe_ops;
struct dvb_frontend * vp7045_fe_attach(struct dvb_usb_device *d)
{
struct vp7045_fe_state *s = kzalloc(sizeof(struct vp7045_fe_state), GFP_KERNEL);
if (s == NULL)
goto error;
s->d = d;
memcpy(&s->fe.ops, &vp7045_fe_ops, sizeof(struct dvb_frontend_ops));
s->fe.demodulator_priv = s;
return &s->fe;
error:
return NULL;
}
static struct dvb_frontend_ops vp7045_fe_ops = {
.info = {
.name = "Twinhan VP7045/46 USB DVB-T",
.type = FE_OFDM,
.frequency_min = 44250000,
.frequency_max = 867250000,
.frequency_stepsize = 1000,
.caps = FE_CAN_INVERSION_AUTO |
FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO |
FE_CAN_QPSK | FE_CAN_QAM_16 | FE_CAN_QAM_64 | FE_CAN_QAM_AUTO |
FE_CAN_TRANSMISSION_MODE_AUTO |
FE_CAN_GUARD_INTERVAL_AUTO |
FE_CAN_RECOVER |
FE_CAN_HIERARCHY_AUTO,
},
.release = vp7045_fe_release,
.init = vp7045_fe_init,
.sleep = vp7045_fe_sleep,
.set_frontend = vp7045_fe_set_frontend,
.get_frontend = vp7045_fe_get_frontend,
.get_tune_settings = vp7045_fe_get_tune_settings,
.read_status = vp7045_fe_read_status,
.read_ber = vp7045_fe_read_ber,
.read_signal_strength = vp7045_fe_read_signal_strength,
.read_snr = vp7045_fe_read_snr,
.read_ucblocks = vp7045_fe_read_unc_blocks,
};
| gpl-2.0 |
SudaMod-devices/android_kernel_google_msm | drivers/scsi/arm/cumana_2.c | 8171 | 14691 | /*
* linux/drivers/acorn/scsi/cumana_2.c
*
* Copyright (C) 1997-2005 Russell King
*
* 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.
*
* Changelog:
* 30-08-1997 RMK 0.0.0 Created, READONLY version.
* 22-01-1998 RMK 0.0.1 Updated to 2.1.80.
* 15-04-1998 RMK 0.0.1 Only do PIO if FAS216 will allow it.
* 02-05-1998 RMK 0.0.2 Updated & added DMA support.
* 27-06-1998 RMK Changed asm/delay.h to linux/delay.h
* 18-08-1998 RMK 0.0.3 Fixed synchronous transfer depth.
* 02-04-2000 RMK 0.0.4 Updated for new error handling code.
*/
#include <linux/module.h>
#include <linux/blkdev.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/ioport.h>
#include <linux/proc_fs.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/dma-mapping.h>
#include <asm/dma.h>
#include <asm/ecard.h>
#include <asm/io.h>
#include <asm/pgtable.h>
#include "../scsi.h"
#include <scsi/scsi_host.h>
#include "fas216.h"
#include "scsi.h"
#include <scsi/scsicam.h>
#define CUMANASCSI2_STATUS (0x0000)
#define STATUS_INT (1 << 0)
#define STATUS_DRQ (1 << 1)
#define STATUS_LATCHED (1 << 3)
#define CUMANASCSI2_ALATCH (0x0014)
#define ALATCH_ENA_INT (3)
#define ALATCH_DIS_INT (2)
#define ALATCH_ENA_TERM (5)
#define ALATCH_DIS_TERM (4)
#define ALATCH_ENA_BIT32 (11)
#define ALATCH_DIS_BIT32 (10)
#define ALATCH_ENA_DMA (13)
#define ALATCH_DIS_DMA (12)
#define ALATCH_DMA_OUT (15)
#define ALATCH_DMA_IN (14)
#define CUMANASCSI2_PSEUDODMA (0x0200)
#define CUMANASCSI2_FAS216_OFFSET (0x0300)
#define CUMANASCSI2_FAS216_SHIFT 2
/*
* Version
*/
#define VERSION "1.00 (13/11/2002 2.5.47)"
/*
* Use term=0,1,0,0,0 to turn terminators on/off
*/
static int term[MAX_ECARDS] = { 1, 1, 1, 1, 1, 1, 1, 1 };
#define NR_SG 256
struct cumanascsi2_info {
FAS216_Info info;
struct expansion_card *ec;
void __iomem *base;
unsigned int terms; /* Terminator state */
struct scatterlist sg[NR_SG]; /* Scatter DMA list */
};
#define CSTATUS_IRQ (1 << 0)
#define CSTATUS_DRQ (1 << 1)
/* Prototype: void cumanascsi_2_irqenable(ec, irqnr)
* Purpose : Enable interrupts on Cumana SCSI 2 card
* Params : ec - expansion card structure
* : irqnr - interrupt number
*/
static void
cumanascsi_2_irqenable(struct expansion_card *ec, int irqnr)
{
struct cumanascsi2_info *info = ec->irq_data;
writeb(ALATCH_ENA_INT, info->base + CUMANASCSI2_ALATCH);
}
/* Prototype: void cumanascsi_2_irqdisable(ec, irqnr)
* Purpose : Disable interrupts on Cumana SCSI 2 card
* Params : ec - expansion card structure
* : irqnr - interrupt number
*/
static void
cumanascsi_2_irqdisable(struct expansion_card *ec, int irqnr)
{
struct cumanascsi2_info *info = ec->irq_data;
writeb(ALATCH_DIS_INT, info->base + CUMANASCSI2_ALATCH);
}
static const expansioncard_ops_t cumanascsi_2_ops = {
.irqenable = cumanascsi_2_irqenable,
.irqdisable = cumanascsi_2_irqdisable,
};
/* Prototype: void cumanascsi_2_terminator_ctl(host, on_off)
* Purpose : Turn the Cumana SCSI 2 terminators on or off
* Params : host - card to turn on/off
* : on_off - !0 to turn on, 0 to turn off
*/
static void
cumanascsi_2_terminator_ctl(struct Scsi_Host *host, int on_off)
{
struct cumanascsi2_info *info = (struct cumanascsi2_info *)host->hostdata;
if (on_off) {
info->terms = 1;
writeb(ALATCH_ENA_TERM, info->base + CUMANASCSI2_ALATCH);
} else {
info->terms = 0;
writeb(ALATCH_DIS_TERM, info->base + CUMANASCSI2_ALATCH);
}
}
/* Prototype: void cumanascsi_2_intr(irq, *dev_id, *regs)
* Purpose : handle interrupts from Cumana SCSI 2 card
* Params : irq - interrupt number
* dev_id - user-defined (Scsi_Host structure)
*/
static irqreturn_t
cumanascsi_2_intr(int irq, void *dev_id)
{
struct cumanascsi2_info *info = dev_id;
return fas216_intr(&info->info);
}
/* Prototype: fasdmatype_t cumanascsi_2_dma_setup(host, SCpnt, direction, min_type)
* Purpose : initialises DMA/PIO
* Params : host - host
* SCpnt - command
* direction - DMA on to/off of card
* min_type - minimum DMA support that we must have for this transfer
* Returns : type of transfer to be performed
*/
static fasdmatype_t
cumanascsi_2_dma_setup(struct Scsi_Host *host, struct scsi_pointer *SCp,
fasdmadir_t direction, fasdmatype_t min_type)
{
struct cumanascsi2_info *info = (struct cumanascsi2_info *)host->hostdata;
struct device *dev = scsi_get_device(host);
int dmach = info->info.scsi.dma;
writeb(ALATCH_DIS_DMA, info->base + CUMANASCSI2_ALATCH);
if (dmach != NO_DMA &&
(min_type == fasdma_real_all || SCp->this_residual >= 512)) {
int bufs, map_dir, dma_dir, alatch_dir;
bufs = copy_SCp_to_sg(&info->sg[0], SCp, NR_SG);
if (direction == DMA_OUT)
map_dir = DMA_TO_DEVICE,
dma_dir = DMA_MODE_WRITE,
alatch_dir = ALATCH_DMA_OUT;
else
map_dir = DMA_FROM_DEVICE,
dma_dir = DMA_MODE_READ,
alatch_dir = ALATCH_DMA_IN;
dma_map_sg(dev, info->sg, bufs, map_dir);
disable_dma(dmach);
set_dma_sg(dmach, info->sg, bufs);
writeb(alatch_dir, info->base + CUMANASCSI2_ALATCH);
set_dma_mode(dmach, dma_dir);
enable_dma(dmach);
writeb(ALATCH_ENA_DMA, info->base + CUMANASCSI2_ALATCH);
writeb(ALATCH_DIS_BIT32, info->base + CUMANASCSI2_ALATCH);
return fasdma_real_all;
}
/*
* If we're not doing DMA,
* we'll do pseudo DMA
*/
return fasdma_pio;
}
/*
* Prototype: void cumanascsi_2_dma_pseudo(host, SCpnt, direction, transfer)
* Purpose : handles pseudo DMA
* Params : host - host
* SCpnt - command
* direction - DMA on to/off of card
* transfer - minimum number of bytes we expect to transfer
*/
static void
cumanascsi_2_dma_pseudo(struct Scsi_Host *host, struct scsi_pointer *SCp,
fasdmadir_t direction, int transfer)
{
struct cumanascsi2_info *info = (struct cumanascsi2_info *)host->hostdata;
unsigned int length;
unsigned char *addr;
length = SCp->this_residual;
addr = SCp->ptr;
if (direction == DMA_OUT)
#if 0
while (length > 1) {
unsigned long word;
unsigned int status = readb(info->base + CUMANASCSI2_STATUS);
if (status & STATUS_INT)
goto end;
if (!(status & STATUS_DRQ))
continue;
word = *addr | *(addr + 1) << 8;
writew(word, info->base + CUMANASCSI2_PSEUDODMA);
addr += 2;
length -= 2;
}
#else
printk ("PSEUDO_OUT???\n");
#endif
else {
if (transfer && (transfer & 255)) {
while (length >= 256) {
unsigned int status = readb(info->base + CUMANASCSI2_STATUS);
if (status & STATUS_INT)
return;
if (!(status & STATUS_DRQ))
continue;
readsw(info->base + CUMANASCSI2_PSEUDODMA,
addr, 256 >> 1);
addr += 256;
length -= 256;
}
}
while (length > 0) {
unsigned long word;
unsigned int status = readb(info->base + CUMANASCSI2_STATUS);
if (status & STATUS_INT)
return;
if (!(status & STATUS_DRQ))
continue;
word = readw(info->base + CUMANASCSI2_PSEUDODMA);
*addr++ = word;
if (--length > 0) {
*addr++ = word >> 8;
length --;
}
}
}
}
/* Prototype: int cumanascsi_2_dma_stop(host, SCpnt)
* Purpose : stops DMA/PIO
* Params : host - host
* SCpnt - command
*/
static void
cumanascsi_2_dma_stop(struct Scsi_Host *host, struct scsi_pointer *SCp)
{
struct cumanascsi2_info *info = (struct cumanascsi2_info *)host->hostdata;
if (info->info.scsi.dma != NO_DMA) {
writeb(ALATCH_DIS_DMA, info->base + CUMANASCSI2_ALATCH);
disable_dma(info->info.scsi.dma);
}
}
/* Prototype: const char *cumanascsi_2_info(struct Scsi_Host * host)
* Purpose : returns a descriptive string about this interface,
* Params : host - driver host structure to return info for.
* Returns : pointer to a static buffer containing null terminated string.
*/
const char *cumanascsi_2_info(struct Scsi_Host *host)
{
struct cumanascsi2_info *info = (struct cumanascsi2_info *)host->hostdata;
static char string[150];
sprintf(string, "%s (%s) in slot %d v%s terminators o%s",
host->hostt->name, info->info.scsi.type, info->ec->slot_no,
VERSION, info->terms ? "n" : "ff");
return string;
}
/* Prototype: int cumanascsi_2_set_proc_info(struct Scsi_Host *host, char *buffer, int length)
* Purpose : Set a driver specific function
* Params : host - host to setup
* : buffer - buffer containing string describing operation
* : length - length of string
* Returns : -EINVAL, or 0
*/
static int
cumanascsi_2_set_proc_info(struct Scsi_Host *host, char *buffer, int length)
{
int ret = length;
if (length >= 11 && strncmp(buffer, "CUMANASCSI2", 11) == 0) {
buffer += 11;
length -= 11;
if (length >= 5 && strncmp(buffer, "term=", 5) == 0) {
if (buffer[5] == '1')
cumanascsi_2_terminator_ctl(host, 1);
else if (buffer[5] == '0')
cumanascsi_2_terminator_ctl(host, 0);
else
ret = -EINVAL;
} else
ret = -EINVAL;
} else
ret = -EINVAL;
return ret;
}
/* Prototype: int cumanascsi_2_proc_info(char *buffer, char **start, off_t offset,
* int length, int host_no, int inout)
* Purpose : Return information about the driver to a user process accessing
* the /proc filesystem.
* Params : buffer - a buffer to write information to
* start - a pointer into this buffer set by this routine to the start
* of the required information.
* offset - offset into information that we have read up to.
* length - length of buffer
* host_no - host number to return information for
* inout - 0 for reading, 1 for writing.
* Returns : length of data written to buffer.
*/
int cumanascsi_2_proc_info (struct Scsi_Host *host, char *buffer, char **start, off_t offset,
int length, int inout)
{
struct cumanascsi2_info *info;
char *p = buffer;
int pos;
if (inout == 1)
return cumanascsi_2_set_proc_info(host, buffer, length);
info = (struct cumanascsi2_info *)host->hostdata;
p += sprintf(p, "Cumana SCSI II driver v%s\n", VERSION);
p += fas216_print_host(&info->info, p);
p += sprintf(p, "Term : o%s\n",
info->terms ? "n" : "ff");
p += fas216_print_stats(&info->info, p);
p += fas216_print_devices(&info->info, p);
*start = buffer + offset;
pos = p - buffer - offset;
if (pos > length)
pos = length;
return pos;
}
static struct scsi_host_template cumanascsi2_template = {
.module = THIS_MODULE,
.proc_info = cumanascsi_2_proc_info,
.name = "Cumana SCSI II",
.info = cumanascsi_2_info,
.queuecommand = fas216_queue_command,
.eh_host_reset_handler = fas216_eh_host_reset,
.eh_bus_reset_handler = fas216_eh_bus_reset,
.eh_device_reset_handler = fas216_eh_device_reset,
.eh_abort_handler = fas216_eh_abort,
.can_queue = 1,
.this_id = 7,
.sg_tablesize = SCSI_MAX_SG_CHAIN_SEGMENTS,
.dma_boundary = IOMD_DMA_BOUNDARY,
.cmd_per_lun = 1,
.use_clustering = DISABLE_CLUSTERING,
.proc_name = "cumanascsi2",
};
static int __devinit
cumanascsi2_probe(struct expansion_card *ec, const struct ecard_id *id)
{
struct Scsi_Host *host;
struct cumanascsi2_info *info;
void __iomem *base;
int ret;
ret = ecard_request_resources(ec);
if (ret)
goto out;
base = ecardm_iomap(ec, ECARD_RES_MEMC, 0, 0);
if (!base) {
ret = -ENOMEM;
goto out_region;
}
host = scsi_host_alloc(&cumanascsi2_template,
sizeof(struct cumanascsi2_info));
if (!host) {
ret = -ENOMEM;
goto out_region;
}
ecard_set_drvdata(ec, host);
info = (struct cumanascsi2_info *)host->hostdata;
info->ec = ec;
info->base = base;
cumanascsi_2_terminator_ctl(host, term[ec->slot_no]);
info->info.scsi.io_base = base + CUMANASCSI2_FAS216_OFFSET;
info->info.scsi.io_shift = CUMANASCSI2_FAS216_SHIFT;
info->info.scsi.irq = ec->irq;
info->info.scsi.dma = ec->dma;
info->info.ifcfg.clockrate = 40; /* MHz */
info->info.ifcfg.select_timeout = 255;
info->info.ifcfg.asyncperiod = 200; /* ns */
info->info.ifcfg.sync_max_depth = 7;
info->info.ifcfg.cntl3 = CNTL3_BS8 | CNTL3_FASTSCSI | CNTL3_FASTCLK;
info->info.ifcfg.disconnect_ok = 1;
info->info.ifcfg.wide_max_size = 0;
info->info.ifcfg.capabilities = FASCAP_PSEUDODMA;
info->info.dma.setup = cumanascsi_2_dma_setup;
info->info.dma.pseudo = cumanascsi_2_dma_pseudo;
info->info.dma.stop = cumanascsi_2_dma_stop;
ec->irqaddr = info->base + CUMANASCSI2_STATUS;
ec->irqmask = STATUS_INT;
ecard_setirq(ec, &cumanascsi_2_ops, info);
ret = fas216_init(host);
if (ret)
goto out_free;
ret = request_irq(ec->irq, cumanascsi_2_intr,
IRQF_DISABLED, "cumanascsi2", info);
if (ret) {
printk("scsi%d: IRQ%d not free: %d\n",
host->host_no, ec->irq, ret);
goto out_release;
}
if (info->info.scsi.dma != NO_DMA) {
if (request_dma(info->info.scsi.dma, "cumanascsi2")) {
printk("scsi%d: DMA%d not free, using PIO\n",
host->host_no, info->info.scsi.dma);
info->info.scsi.dma = NO_DMA;
} else {
set_dma_speed(info->info.scsi.dma, 180);
info->info.ifcfg.capabilities |= FASCAP_DMA;
}
}
ret = fas216_add(host, &ec->dev);
if (ret == 0)
goto out;
if (info->info.scsi.dma != NO_DMA)
free_dma(info->info.scsi.dma);
free_irq(ec->irq, host);
out_release:
fas216_release(host);
out_free:
scsi_host_put(host);
out_region:
ecard_release_resources(ec);
out:
return ret;
}
static void __devexit cumanascsi2_remove(struct expansion_card *ec)
{
struct Scsi_Host *host = ecard_get_drvdata(ec);
struct cumanascsi2_info *info = (struct cumanascsi2_info *)host->hostdata;
ecard_set_drvdata(ec, NULL);
fas216_remove(host);
if (info->info.scsi.dma != NO_DMA)
free_dma(info->info.scsi.dma);
free_irq(ec->irq, info);
fas216_release(host);
scsi_host_put(host);
ecard_release_resources(ec);
}
static const struct ecard_id cumanascsi2_cids[] = {
{ MANU_CUMANA, PROD_CUMANA_SCSI_2 },
{ 0xffff, 0xffff },
};
static struct ecard_driver cumanascsi2_driver = {
.probe = cumanascsi2_probe,
.remove = __devexit_p(cumanascsi2_remove),
.id_table = cumanascsi2_cids,
.drv = {
.name = "cumanascsi2",
},
};
static int __init cumanascsi2_init(void)
{
return ecard_register_driver(&cumanascsi2_driver);
}
static void __exit cumanascsi2_exit(void)
{
ecard_remove_driver(&cumanascsi2_driver);
}
module_init(cumanascsi2_init);
module_exit(cumanascsi2_exit);
MODULE_AUTHOR("Russell King");
MODULE_DESCRIPTION("Cumana SCSI-2 driver for Acorn machines");
module_param_array(term, int, NULL, 0);
MODULE_PARM_DESC(term, "SCSI bus termination");
MODULE_LICENSE("GPL");
| gpl-2.0 |
simonvanderveldt/android_kernel_samsung_jf | arch/sh/kernel/cpu/sh4a/clock-sh7780.c | 9195 | 2852 | /*
* arch/sh/kernel/cpu/sh4a/clock-sh7780.c
*
* SH7780 support for the clock framework
*
* Copyright (C) 2005 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/io.h>
#include <linux/clkdev.h>
#include <asm/clock.h>
#include <asm/freq.h>
#include <asm/io.h>
static int ifc_divisors[] = { 2, 4 };
static int bfc_divisors[] = { 1, 1, 1, 8, 12, 16, 24, 1 };
static int pfc_divisors[] = { 1, 24, 24, 1 };
static int cfc_divisors[] = { 1, 1, 4, 1, 6, 1, 1, 1 };
static void master_clk_init(struct clk *clk)
{
clk->rate *= pfc_divisors[__raw_readl(FRQCR) & 0x0003];
}
static struct sh_clk_ops sh7780_master_clk_ops = {
.init = master_clk_init,
};
static unsigned long module_clk_recalc(struct clk *clk)
{
int idx = (__raw_readl(FRQCR) & 0x0003);
return clk->parent->rate / pfc_divisors[idx];
}
static struct sh_clk_ops sh7780_module_clk_ops = {
.recalc = module_clk_recalc,
};
static unsigned long bus_clk_recalc(struct clk *clk)
{
int idx = ((__raw_readl(FRQCR) >> 16) & 0x0007);
return clk->parent->rate / bfc_divisors[idx];
}
static struct sh_clk_ops sh7780_bus_clk_ops = {
.recalc = bus_clk_recalc,
};
static unsigned long cpu_clk_recalc(struct clk *clk)
{
int idx = ((__raw_readl(FRQCR) >> 24) & 0x0001);
return clk->parent->rate / ifc_divisors[idx];
}
static struct sh_clk_ops sh7780_cpu_clk_ops = {
.recalc = cpu_clk_recalc,
};
static struct sh_clk_ops *sh7780_clk_ops[] = {
&sh7780_master_clk_ops,
&sh7780_module_clk_ops,
&sh7780_bus_clk_ops,
&sh7780_cpu_clk_ops,
};
void __init arch_init_clk_ops(struct sh_clk_ops **ops, int idx)
{
if (idx < ARRAY_SIZE(sh7780_clk_ops))
*ops = sh7780_clk_ops[idx];
}
static unsigned long shyway_clk_recalc(struct clk *clk)
{
int idx = ((__raw_readl(FRQCR) >> 20) & 0x0007);
return clk->parent->rate / cfc_divisors[idx];
}
static struct sh_clk_ops sh7780_shyway_clk_ops = {
.recalc = shyway_clk_recalc,
};
static struct clk sh7780_shyway_clk = {
.flags = CLK_ENABLE_ON_INIT,
.ops = &sh7780_shyway_clk_ops,
};
/*
* Additional SH7780-specific on-chip clocks that aren't already part of the
* clock framework
*/
static struct clk *sh7780_onchip_clocks[] = {
&sh7780_shyway_clk,
};
static struct clk_lookup lookups[] = {
/* main clocks */
CLKDEV_CON_ID("shyway_clk", &sh7780_shyway_clk),
};
int __init arch_clk_init(void)
{
struct clk *clk;
int i, ret = 0;
cpg_clk_init();
clk = clk_get(NULL, "master_clk");
for (i = 0; i < ARRAY_SIZE(sh7780_onchip_clocks); i++) {
struct clk *clkp = sh7780_onchip_clocks[i];
clkp->parent = clk;
ret |= clk_register(clkp);
}
clk_put(clk);
clkdev_add_table(lookups, ARRAY_SIZE(lookups));
return ret;
}
| gpl-2.0 |
wanam/Adam-Kernel-GalaxyS6-G925F | arch/sh/kernel/cpu/sh4/clock-sh4-202.c | 9195 | 4031 | /*
* arch/sh/kernel/cpu/sh4/clock-sh4-202.c
*
* Additional SH4-202 support for the clock framework
*
* Copyright (C) 2005 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/clkdev.h>
#include <asm/clock.h>
#include <asm/freq.h>
#define CPG2_FRQCR3 0xfe0a0018
static int frqcr3_divisors[] = { 1, 2, 3, 4, 6, 8, 16 };
static int frqcr3_values[] = { 0, 1, 2, 3, 4, 5, 6 };
static unsigned long emi_clk_recalc(struct clk *clk)
{
int idx = __raw_readl(CPG2_FRQCR3) & 0x0007;
return clk->parent->rate / frqcr3_divisors[idx];
}
static inline int frqcr3_lookup(struct clk *clk, unsigned long rate)
{
int divisor = clk->parent->rate / rate;
int i;
for (i = 0; i < ARRAY_SIZE(frqcr3_divisors); i++)
if (frqcr3_divisors[i] == divisor)
return frqcr3_values[i];
/* Safe fallback */
return 5;
}
static struct sh_clk_ops sh4202_emi_clk_ops = {
.recalc = emi_clk_recalc,
};
static struct clk sh4202_emi_clk = {
.flags = CLK_ENABLE_ON_INIT,
.ops = &sh4202_emi_clk_ops,
};
static unsigned long femi_clk_recalc(struct clk *clk)
{
int idx = (__raw_readl(CPG2_FRQCR3) >> 3) & 0x0007;
return clk->parent->rate / frqcr3_divisors[idx];
}
static struct sh_clk_ops sh4202_femi_clk_ops = {
.recalc = femi_clk_recalc,
};
static struct clk sh4202_femi_clk = {
.flags = CLK_ENABLE_ON_INIT,
.ops = &sh4202_femi_clk_ops,
};
static void shoc_clk_init(struct clk *clk)
{
int i;
/*
* For some reason, the shoc_clk seems to be set to some really
* insane value at boot (values outside of the allowable frequency
* range for instance). We deal with this by scaling it back down
* to something sensible just in case.
*
* Start scaling from the high end down until we find something
* that passes rate verification..
*/
for (i = 0; i < ARRAY_SIZE(frqcr3_divisors); i++) {
int divisor = frqcr3_divisors[i];
if (clk->ops->set_rate(clk, clk->parent->rate / divisor) == 0)
break;
}
WARN_ON(i == ARRAY_SIZE(frqcr3_divisors)); /* Undefined clock */
}
static unsigned long shoc_clk_recalc(struct clk *clk)
{
int idx = (__raw_readl(CPG2_FRQCR3) >> 6) & 0x0007;
return clk->parent->rate / frqcr3_divisors[idx];
}
static int shoc_clk_verify_rate(struct clk *clk, unsigned long rate)
{
struct clk *bclk = clk_get(NULL, "bus_clk");
unsigned long bclk_rate = clk_get_rate(bclk);
clk_put(bclk);
if (rate > bclk_rate)
return 1;
if (rate > 66000000)
return 1;
return 0;
}
static int shoc_clk_set_rate(struct clk *clk, unsigned long rate)
{
unsigned long frqcr3;
unsigned int tmp;
/* Make sure we have something sensible to switch to */
if (shoc_clk_verify_rate(clk, rate) != 0)
return -EINVAL;
tmp = frqcr3_lookup(clk, rate);
frqcr3 = __raw_readl(CPG2_FRQCR3);
frqcr3 &= ~(0x0007 << 6);
frqcr3 |= tmp << 6;
__raw_writel(frqcr3, CPG2_FRQCR3);
clk->rate = clk->parent->rate / frqcr3_divisors[tmp];
return 0;
}
static struct sh_clk_ops sh4202_shoc_clk_ops = {
.init = shoc_clk_init,
.recalc = shoc_clk_recalc,
.set_rate = shoc_clk_set_rate,
};
static struct clk sh4202_shoc_clk = {
.flags = CLK_ENABLE_ON_INIT,
.ops = &sh4202_shoc_clk_ops,
};
static struct clk *sh4202_onchip_clocks[] = {
&sh4202_emi_clk,
&sh4202_femi_clk,
&sh4202_shoc_clk,
};
static struct clk_lookup lookups[] = {
/* main clocks */
CLKDEV_CON_ID("emi_clk", &sh4202_emi_clk),
CLKDEV_CON_ID("femi_clk", &sh4202_femi_clk),
CLKDEV_CON_ID("shoc_clk", &sh4202_shoc_clk),
};
int __init arch_clk_init(void)
{
struct clk *clk;
int i, ret = 0;
cpg_clk_init();
clk = clk_get(NULL, "master_clk");
for (i = 0; i < ARRAY_SIZE(sh4202_onchip_clocks); i++) {
struct clk *clkp = sh4202_onchip_clocks[i];
clkp->parent = clk;
ret |= clk_register(clkp);
}
clk_put(clk);
clkdev_add_table(lookups, ARRAY_SIZE(lookups));
return ret;
}
| gpl-2.0 |
doadin/kernel_gravitysmart | arch/x86/kernel/tlb_uv.c | 492 | 23457 | /*
* SGI UltraViolet TLB flush routines.
*
* (c) 2008 Cliff Wickman <cpw@sgi.com>, SGI.
*
* This code is released under the GNU General Public License version 2 or
* later.
*/
#include <linux/seq_file.h>
#include <linux/proc_fs.h>
#include <linux/kernel.h>
#include <asm/mmu_context.h>
#include <asm/uv/uv.h>
#include <asm/uv/uv_mmrs.h>
#include <asm/uv/uv_hub.h>
#include <asm/uv/uv_bau.h>
#include <asm/apic.h>
#include <asm/idle.h>
#include <asm/tsc.h>
#include <asm/irq_vectors.h>
static struct bau_control **uv_bau_table_bases __read_mostly;
static int uv_bau_retry_limit __read_mostly;
/* base pnode in this partition */
static int uv_partition_base_pnode __read_mostly;
static unsigned long uv_mmask __read_mostly;
static DEFINE_PER_CPU(struct ptc_stats, ptcstats);
static DEFINE_PER_CPU(struct bau_control, bau_control);
/*
* Determine the first node on a blade.
*/
static int __init blade_to_first_node(int blade)
{
int node, b;
for_each_online_node(node) {
b = uv_node_to_blade_id(node);
if (blade == b)
return node;
}
return -1; /* shouldn't happen */
}
/*
* Determine the apicid of the first cpu on a blade.
*/
static int __init blade_to_first_apicid(int blade)
{
int cpu;
for_each_present_cpu(cpu)
if (blade == uv_cpu_to_blade_id(cpu))
return per_cpu(x86_cpu_to_apicid, cpu);
return -1;
}
/*
* Free a software acknowledge hardware resource by clearing its Pending
* bit. This will return a reply to the sender.
* If the message has timed out, a reply has already been sent by the
* hardware but the resource has not been released. In that case our
* clear of the Timeout bit (as well) will free the resource. No reply will
* be sent (the hardware will only do one reply per message).
*/
static void uv_reply_to_message(int resource,
struct bau_payload_queue_entry *msg,
struct bau_msg_status *msp)
{
unsigned long dw;
dw = (1 << (resource + UV_SW_ACK_NPENDING)) | (1 << resource);
msg->replied_to = 1;
msg->sw_ack_vector = 0;
if (msp)
msp->seen_by.bits = 0;
uv_write_local_mmr(UVH_LB_BAU_INTD_SOFTWARE_ACKNOWLEDGE_ALIAS, dw);
}
/*
* Do all the things a cpu should do for a TLB shootdown message.
* Other cpu's may come here at the same time for this message.
*/
static void uv_bau_process_message(struct bau_payload_queue_entry *msg,
int msg_slot, int sw_ack_slot)
{
unsigned long this_cpu_mask;
struct bau_msg_status *msp;
int cpu;
msp = __get_cpu_var(bau_control).msg_statuses + msg_slot;
cpu = uv_blade_processor_id();
msg->number_of_cpus =
uv_blade_nr_online_cpus(uv_node_to_blade_id(numa_node_id()));
this_cpu_mask = 1UL << cpu;
if (msp->seen_by.bits & this_cpu_mask)
return;
atomic_or_long(&msp->seen_by.bits, this_cpu_mask);
if (msg->replied_to == 1)
return;
if (msg->address == TLB_FLUSH_ALL) {
local_flush_tlb();
__get_cpu_var(ptcstats).alltlb++;
} else {
__flush_tlb_one(msg->address);
__get_cpu_var(ptcstats).onetlb++;
}
__get_cpu_var(ptcstats).requestee++;
atomic_inc_short(&msg->acknowledge_count);
if (msg->number_of_cpus == msg->acknowledge_count)
uv_reply_to_message(sw_ack_slot, msg, msp);
}
/*
* Examine the payload queue on one distribution node to see
* which messages have not been seen, and which cpu(s) have not seen them.
*
* Returns the number of cpu's that have not responded.
*/
static int uv_examine_destination(struct bau_control *bau_tablesp, int sender)
{
struct bau_payload_queue_entry *msg;
struct bau_msg_status *msp;
int count = 0;
int i;
int j;
for (msg = bau_tablesp->va_queue_first, i = 0; i < DEST_Q_SIZE;
msg++, i++) {
if ((msg->sending_cpu == sender) && (!msg->replied_to)) {
msp = bau_tablesp->msg_statuses + i;
printk(KERN_DEBUG
"blade %d: address:%#lx %d of %d, not cpu(s): ",
i, msg->address, msg->acknowledge_count,
msg->number_of_cpus);
for (j = 0; j < msg->number_of_cpus; j++) {
if (!((1L << j) & msp->seen_by.bits)) {
count++;
printk("%d ", j);
}
}
printk("\n");
}
}
return count;
}
/*
* Examine the payload queue on all the distribution nodes to see
* which messages have not been seen, and which cpu(s) have not seen them.
*
* Returns the number of cpu's that have not responded.
*/
static int uv_examine_destinations(struct bau_target_nodemask *distribution)
{
int sender;
int i;
int count = 0;
sender = smp_processor_id();
for (i = 0; i < sizeof(struct bau_target_nodemask) * BITSPERBYTE; i++) {
if (!bau_node_isset(i, distribution))
continue;
count += uv_examine_destination(uv_bau_table_bases[i], sender);
}
return count;
}
/*
* wait for completion of a broadcast message
*
* return COMPLETE, RETRY or GIVEUP
*/
static int uv_wait_completion(struct bau_desc *bau_desc,
unsigned long mmr_offset, int right_shift)
{
int exams = 0;
long destination_timeouts = 0;
long source_timeouts = 0;
unsigned long descriptor_status;
while ((descriptor_status = (((unsigned long)
uv_read_local_mmr(mmr_offset) >>
right_shift) & UV_ACT_STATUS_MASK)) !=
DESC_STATUS_IDLE) {
if (descriptor_status == DESC_STATUS_SOURCE_TIMEOUT) {
source_timeouts++;
if (source_timeouts > SOURCE_TIMEOUT_LIMIT)
source_timeouts = 0;
__get_cpu_var(ptcstats).s_retry++;
return FLUSH_RETRY;
}
/*
* spin here looking for progress at the destinations
*/
if (descriptor_status == DESC_STATUS_DESTINATION_TIMEOUT) {
destination_timeouts++;
if (destination_timeouts > DESTINATION_TIMEOUT_LIMIT) {
/*
* returns number of cpus not responding
*/
if (uv_examine_destinations
(&bau_desc->distribution) == 0) {
__get_cpu_var(ptcstats).d_retry++;
return FLUSH_RETRY;
}
exams++;
if (exams >= uv_bau_retry_limit) {
printk(KERN_DEBUG
"uv_flush_tlb_others");
printk("giving up on cpu %d\n",
smp_processor_id());
return FLUSH_GIVEUP;
}
/*
* delays can hang the simulator
udelay(1000);
*/
destination_timeouts = 0;
}
}
cpu_relax();
}
return FLUSH_COMPLETE;
}
/**
* uv_flush_send_and_wait
*
* Send a broadcast and wait for a broadcast message to complete.
*
* The flush_mask contains the cpus the broadcast was sent to.
*
* Returns NULL if all remote flushing was done. The mask is zeroed.
* Returns @flush_mask if some remote flushing remains to be done. The
* mask will have some bits still set.
*/
const struct cpumask *uv_flush_send_and_wait(int cpu, int this_pnode,
struct bau_desc *bau_desc,
struct cpumask *flush_mask)
{
int completion_status = 0;
int right_shift;
int tries = 0;
int pnode;
int bit;
unsigned long mmr_offset;
unsigned long index;
cycles_t time1;
cycles_t time2;
if (cpu < UV_CPUS_PER_ACT_STATUS) {
mmr_offset = UVH_LB_BAU_SB_ACTIVATION_STATUS_0;
right_shift = cpu * UV_ACT_STATUS_SIZE;
} else {
mmr_offset = UVH_LB_BAU_SB_ACTIVATION_STATUS_1;
right_shift =
((cpu - UV_CPUS_PER_ACT_STATUS) * UV_ACT_STATUS_SIZE);
}
time1 = get_cycles();
do {
tries++;
index = (1UL << UVH_LB_BAU_SB_ACTIVATION_CONTROL_PUSH_SHFT) |
cpu;
uv_write_local_mmr(UVH_LB_BAU_SB_ACTIVATION_CONTROL, index);
completion_status = uv_wait_completion(bau_desc, mmr_offset,
right_shift);
} while (completion_status == FLUSH_RETRY);
time2 = get_cycles();
__get_cpu_var(ptcstats).sflush += (time2 - time1);
if (tries > 1)
__get_cpu_var(ptcstats).retriesok++;
if (completion_status == FLUSH_GIVEUP) {
/*
* Cause the caller to do an IPI-style TLB shootdown on
* the cpu's, all of which are still in the mask.
*/
__get_cpu_var(ptcstats).ptc_i++;
return flush_mask;
}
/*
* Success, so clear the remote cpu's from the mask so we don't
* use the IPI method of shootdown on them.
*/
for_each_cpu(bit, flush_mask) {
pnode = uv_cpu_to_pnode(bit);
if (pnode == this_pnode)
continue;
cpumask_clear_cpu(bit, flush_mask);
}
if (!cpumask_empty(flush_mask))
return flush_mask;
return NULL;
}
static DEFINE_PER_CPU(cpumask_var_t, uv_flush_tlb_mask);
/**
* uv_flush_tlb_others - globally purge translation cache of a virtual
* address or all TLB's
* @cpumask: mask of all cpu's in which the address is to be removed
* @mm: mm_struct containing virtual address range
* @va: virtual address to be removed (or TLB_FLUSH_ALL for all TLB's on cpu)
* @cpu: the current cpu
*
* This is the entry point for initiating any UV global TLB shootdown.
*
* Purges the translation caches of all specified processors of the given
* virtual address, or purges all TLB's on specified processors.
*
* The caller has derived the cpumask from the mm_struct. This function
* is called only if there are bits set in the mask. (e.g. flush_tlb_page())
*
* The cpumask is converted into a nodemask of the nodes containing
* the cpus.
*
* Note that this function should be called with preemption disabled.
*
* Returns NULL if all remote flushing was done.
* Returns pointer to cpumask if some remote flushing remains to be
* done. The returned pointer is valid till preemption is re-enabled.
*/
const struct cpumask *uv_flush_tlb_others(const struct cpumask *cpumask,
struct mm_struct *mm,
unsigned long va, unsigned int cpu)
{
struct cpumask *flush_mask = __get_cpu_var(uv_flush_tlb_mask);
int i;
int bit;
int pnode;
int uv_cpu;
int this_pnode;
int locals = 0;
struct bau_desc *bau_desc;
cpumask_andnot(flush_mask, cpumask, cpumask_of(cpu));
uv_cpu = uv_blade_processor_id();
this_pnode = uv_hub_info->pnode;
bau_desc = __get_cpu_var(bau_control).descriptor_base;
bau_desc += UV_ITEMS_PER_DESCRIPTOR * uv_cpu;
bau_nodes_clear(&bau_desc->distribution, UV_DISTRIBUTION_SIZE);
i = 0;
for_each_cpu(bit, flush_mask) {
pnode = uv_cpu_to_pnode(bit);
BUG_ON(pnode > (UV_DISTRIBUTION_SIZE - 1));
if (pnode == this_pnode) {
locals++;
continue;
}
bau_node_set(pnode - uv_partition_base_pnode,
&bau_desc->distribution);
i++;
}
if (i == 0) {
/*
* no off_node flushing; return status for local node
*/
if (locals)
return flush_mask;
else
return NULL;
}
__get_cpu_var(ptcstats).requestor++;
__get_cpu_var(ptcstats).ntargeted += i;
bau_desc->payload.address = va;
bau_desc->payload.sending_cpu = cpu;
return uv_flush_send_and_wait(uv_cpu, this_pnode, bau_desc, flush_mask);
}
/*
* The BAU message interrupt comes here. (registered by set_intr_gate)
* See entry_64.S
*
* We received a broadcast assist message.
*
* Interrupts may have been disabled; this interrupt could represent
* the receipt of several messages.
*
* All cores/threads on this node get this interrupt.
* The last one to see it does the s/w ack.
* (the resource will not be freed until noninterruptable cpus see this
* interrupt; hardware will timeout the s/w ack and reply ERROR)
*/
void uv_bau_message_interrupt(struct pt_regs *regs)
{
struct bau_payload_queue_entry *va_queue_first;
struct bau_payload_queue_entry *va_queue_last;
struct bau_payload_queue_entry *msg;
struct pt_regs *old_regs = set_irq_regs(regs);
cycles_t time1;
cycles_t time2;
int msg_slot;
int sw_ack_slot;
int fw;
int count = 0;
unsigned long local_pnode;
ack_APIC_irq();
exit_idle();
irq_enter();
time1 = get_cycles();
local_pnode = uv_blade_to_pnode(uv_numa_blade_id());
va_queue_first = __get_cpu_var(bau_control).va_queue_first;
va_queue_last = __get_cpu_var(bau_control).va_queue_last;
msg = __get_cpu_var(bau_control).bau_msg_head;
while (msg->sw_ack_vector) {
count++;
fw = msg->sw_ack_vector;
msg_slot = msg - va_queue_first;
sw_ack_slot = ffs(fw) - 1;
uv_bau_process_message(msg, msg_slot, sw_ack_slot);
msg++;
if (msg > va_queue_last)
msg = va_queue_first;
__get_cpu_var(bau_control).bau_msg_head = msg;
}
if (!count)
__get_cpu_var(ptcstats).nomsg++;
else if (count > 1)
__get_cpu_var(ptcstats).multmsg++;
time2 = get_cycles();
__get_cpu_var(ptcstats).dflush += (time2 - time1);
irq_exit();
set_irq_regs(old_regs);
}
/*
* uv_enable_timeouts
*
* Each target blade (i.e. blades that have cpu's) needs to have
* shootdown message timeouts enabled. The timeout does not cause
* an interrupt, but causes an error message to be returned to
* the sender.
*/
static void uv_enable_timeouts(void)
{
int blade;
int nblades;
int pnode;
unsigned long mmr_image;
nblades = uv_num_possible_blades();
for (blade = 0; blade < nblades; blade++) {
if (!uv_blade_nr_possible_cpus(blade))
continue;
pnode = uv_blade_to_pnode(blade);
mmr_image =
uv_read_global_mmr64(pnode, UVH_LB_BAU_MISC_CONTROL);
/*
* Set the timeout period and then lock it in, in three
* steps; captures and locks in the period.
*
* To program the period, the SOFT_ACK_MODE must be off.
*/
mmr_image &= ~((unsigned long)1 <<
UV_ENABLE_INTD_SOFT_ACK_MODE_SHIFT);
uv_write_global_mmr64
(pnode, UVH_LB_BAU_MISC_CONTROL, mmr_image);
/*
* Set the 4-bit period.
*/
mmr_image &= ~((unsigned long)0xf <<
UV_INTD_SOFT_ACK_TIMEOUT_PERIOD_SHIFT);
mmr_image |= (UV_INTD_SOFT_ACK_TIMEOUT_PERIOD <<
UV_INTD_SOFT_ACK_TIMEOUT_PERIOD_SHIFT);
uv_write_global_mmr64
(pnode, UVH_LB_BAU_MISC_CONTROL, mmr_image);
/*
* Subsequent reversals of the timebase bit (3) cause an
* immediate timeout of one or all INTD resources as
* indicated in bits 2:0 (7 causes all of them to timeout).
*/
mmr_image |= ((unsigned long)1 <<
UV_ENABLE_INTD_SOFT_ACK_MODE_SHIFT);
uv_write_global_mmr64
(pnode, UVH_LB_BAU_MISC_CONTROL, mmr_image);
}
}
static void *uv_ptc_seq_start(struct seq_file *file, loff_t *offset)
{
if (*offset < num_possible_cpus())
return offset;
return NULL;
}
static void *uv_ptc_seq_next(struct seq_file *file, void *data, loff_t *offset)
{
(*offset)++;
if (*offset < num_possible_cpus())
return offset;
return NULL;
}
static void uv_ptc_seq_stop(struct seq_file *file, void *data)
{
}
/*
* Display the statistics thru /proc
* data points to the cpu number
*/
static int uv_ptc_seq_show(struct seq_file *file, void *data)
{
struct ptc_stats *stat;
int cpu;
cpu = *(loff_t *)data;
if (!cpu) {
seq_printf(file,
"# cpu requestor requestee one all sretry dretry ptc_i ");
seq_printf(file,
"sw_ack sflush dflush sok dnomsg dmult starget\n");
}
if (cpu < num_possible_cpus() && cpu_online(cpu)) {
stat = &per_cpu(ptcstats, cpu);
seq_printf(file, "cpu %d %ld %ld %ld %ld %ld %ld %ld ",
cpu, stat->requestor,
stat->requestee, stat->onetlb, stat->alltlb,
stat->s_retry, stat->d_retry, stat->ptc_i);
seq_printf(file, "%lx %ld %ld %ld %ld %ld %ld\n",
uv_read_global_mmr64(uv_cpu_to_pnode(cpu),
UVH_LB_BAU_INTD_SOFTWARE_ACKNOWLEDGE),
stat->sflush, stat->dflush,
stat->retriesok, stat->nomsg,
stat->multmsg, stat->ntargeted);
}
return 0;
}
/*
* 0: display meaning of the statistics
* >0: retry limit
*/
static ssize_t uv_ptc_proc_write(struct file *file, const char __user *user,
size_t count, loff_t *data)
{
long newmode;
char optstr[64];
if (count == 0 || count > sizeof(optstr))
return -EINVAL;
if (copy_from_user(optstr, user, count))
return -EFAULT;
optstr[count - 1] = '\0';
if (strict_strtoul(optstr, 10, &newmode) < 0) {
printk(KERN_DEBUG "%s is invalid\n", optstr);
return -EINVAL;
}
if (newmode == 0) {
printk(KERN_DEBUG "# cpu: cpu number\n");
printk(KERN_DEBUG
"requestor: times this cpu was the flush requestor\n");
printk(KERN_DEBUG
"requestee: times this cpu was requested to flush its TLBs\n");
printk(KERN_DEBUG
"one: times requested to flush a single address\n");
printk(KERN_DEBUG
"all: times requested to flush all TLB's\n");
printk(KERN_DEBUG
"sretry: number of retries of source-side timeouts\n");
printk(KERN_DEBUG
"dretry: number of retries of destination-side timeouts\n");
printk(KERN_DEBUG
"ptc_i: times UV fell through to IPI-style flushes\n");
printk(KERN_DEBUG
"sw_ack: image of UVH_LB_BAU_INTD_SOFTWARE_ACKNOWLEDGE\n");
printk(KERN_DEBUG
"sflush_us: cycles spent in uv_flush_tlb_others()\n");
printk(KERN_DEBUG
"dflush_us: cycles spent in handling flush requests\n");
printk(KERN_DEBUG "sok: successes on retry\n");
printk(KERN_DEBUG "dnomsg: interrupts with no message\n");
printk(KERN_DEBUG
"dmult: interrupts with multiple messages\n");
printk(KERN_DEBUG "starget: nodes targeted\n");
} else {
uv_bau_retry_limit = newmode;
printk(KERN_DEBUG "timeout retry limit:%d\n",
uv_bau_retry_limit);
}
return count;
}
static const struct seq_operations uv_ptc_seq_ops = {
.start = uv_ptc_seq_start,
.next = uv_ptc_seq_next,
.stop = uv_ptc_seq_stop,
.show = uv_ptc_seq_show
};
static int uv_ptc_proc_open(struct inode *inode, struct file *file)
{
return seq_open(file, &uv_ptc_seq_ops);
}
static const struct file_operations proc_uv_ptc_operations = {
.open = uv_ptc_proc_open,
.read = seq_read,
.write = uv_ptc_proc_write,
.llseek = seq_lseek,
.release = seq_release,
};
static int __init uv_ptc_init(void)
{
struct proc_dir_entry *proc_uv_ptc;
if (!is_uv_system())
return 0;
proc_uv_ptc = proc_create(UV_PTC_BASENAME, 0444, NULL,
&proc_uv_ptc_operations);
if (!proc_uv_ptc) {
printk(KERN_ERR "unable to create %s proc entry\n",
UV_PTC_BASENAME);
return -EINVAL;
}
return 0;
}
/*
* begin the initialization of the per-blade control structures
*/
static struct bau_control * __init uv_table_bases_init(int blade, int node)
{
int i;
struct bau_msg_status *msp;
struct bau_control *bau_tabp;
bau_tabp =
kmalloc_node(sizeof(struct bau_control), GFP_KERNEL, node);
BUG_ON(!bau_tabp);
bau_tabp->msg_statuses =
kmalloc_node(sizeof(struct bau_msg_status) *
DEST_Q_SIZE, GFP_KERNEL, node);
BUG_ON(!bau_tabp->msg_statuses);
for (i = 0, msp = bau_tabp->msg_statuses; i < DEST_Q_SIZE; i++, msp++)
bau_cpubits_clear(&msp->seen_by, (int)
uv_blade_nr_possible_cpus(blade));
uv_bau_table_bases[blade] = bau_tabp;
return bau_tabp;
}
/*
* finish the initialization of the per-blade control structures
*/
static void __init
uv_table_bases_finish(int blade,
struct bau_control *bau_tablesp,
struct bau_desc *adp)
{
struct bau_control *bcp;
int cpu;
for_each_present_cpu(cpu) {
if (blade != uv_cpu_to_blade_id(cpu))
continue;
bcp = (struct bau_control *)&per_cpu(bau_control, cpu);
bcp->bau_msg_head = bau_tablesp->va_queue_first;
bcp->va_queue_first = bau_tablesp->va_queue_first;
bcp->va_queue_last = bau_tablesp->va_queue_last;
bcp->msg_statuses = bau_tablesp->msg_statuses;
bcp->descriptor_base = adp;
}
}
/*
* initialize the sending side's sending buffers
*/
static struct bau_desc * __init
uv_activation_descriptor_init(int node, int pnode)
{
int i;
unsigned long pa;
unsigned long m;
unsigned long n;
struct bau_desc *adp;
struct bau_desc *ad2;
/*
* each bau_desc is 64 bytes; there are 8 (UV_ITEMS_PER_DESCRIPTOR)
* per cpu; and up to 32 (UV_ADP_SIZE) cpu's per blade
*/
adp = (struct bau_desc *)kmalloc_node(sizeof(struct bau_desc)*
UV_ADP_SIZE*UV_ITEMS_PER_DESCRIPTOR, GFP_KERNEL, node);
BUG_ON(!adp);
pa = uv_gpa(adp); /* need the real nasid*/
n = uv_gpa_to_pnode(pa);
m = pa & uv_mmask;
uv_write_global_mmr64(pnode, UVH_LB_BAU_SB_DESCRIPTOR_BASE,
(n << UV_DESC_BASE_PNODE_SHIFT | m));
/*
* initializing all 8 (UV_ITEMS_PER_DESCRIPTOR) descriptors for each
* cpu even though we only use the first one; one descriptor can
* describe a broadcast to 256 nodes.
*/
for (i = 0, ad2 = adp; i < (UV_ADP_SIZE*UV_ITEMS_PER_DESCRIPTOR);
i++, ad2++) {
memset(ad2, 0, sizeof(struct bau_desc));
ad2->header.sw_ack_flag = 1;
/*
* base_dest_nodeid is the first node in the partition, so
* the bit map will indicate partition-relative node numbers.
* note that base_dest_nodeid is actually a nasid.
*/
ad2->header.base_dest_nodeid = uv_partition_base_pnode << 1;
ad2->header.dest_subnodeid = 0x10; /* the LB */
ad2->header.command = UV_NET_ENDPOINT_INTD;
ad2->header.int_both = 1;
/*
* all others need to be set to zero:
* fairness chaining multilevel count replied_to
*/
}
return adp;
}
/*
* initialize the destination side's receiving buffers
*/
static struct bau_payload_queue_entry * __init
uv_payload_queue_init(int node, int pnode, struct bau_control *bau_tablesp)
{
struct bau_payload_queue_entry *pqp;
unsigned long pa;
int pn;
char *cp;
pqp = (struct bau_payload_queue_entry *) kmalloc_node(
(DEST_Q_SIZE + 1) * sizeof(struct bau_payload_queue_entry),
GFP_KERNEL, node);
BUG_ON(!pqp);
cp = (char *)pqp + 31;
pqp = (struct bau_payload_queue_entry *)(((unsigned long)cp >> 5) << 5);
bau_tablesp->va_queue_first = pqp;
/*
* need the pnode of where the memory was really allocated
*/
pa = uv_gpa(pqp);
pn = uv_gpa_to_pnode(pa);
uv_write_global_mmr64(pnode,
UVH_LB_BAU_INTD_PAYLOAD_QUEUE_FIRST,
((unsigned long)pn << UV_PAYLOADQ_PNODE_SHIFT) |
uv_physnodeaddr(pqp));
uv_write_global_mmr64(pnode, UVH_LB_BAU_INTD_PAYLOAD_QUEUE_TAIL,
uv_physnodeaddr(pqp));
bau_tablesp->va_queue_last = pqp + (DEST_Q_SIZE - 1);
uv_write_global_mmr64(pnode, UVH_LB_BAU_INTD_PAYLOAD_QUEUE_LAST,
(unsigned long)
uv_physnodeaddr(bau_tablesp->va_queue_last));
memset(pqp, 0, sizeof(struct bau_payload_queue_entry) * DEST_Q_SIZE);
return pqp;
}
/*
* Initialization of each UV blade's structures
*/
static int __init uv_init_blade(int blade)
{
int node;
int pnode;
unsigned long pa;
unsigned long apicid;
struct bau_desc *adp;
struct bau_payload_queue_entry *pqp;
struct bau_control *bau_tablesp;
node = blade_to_first_node(blade);
bau_tablesp = uv_table_bases_init(blade, node);
pnode = uv_blade_to_pnode(blade);
adp = uv_activation_descriptor_init(node, pnode);
pqp = uv_payload_queue_init(node, pnode, bau_tablesp);
uv_table_bases_finish(blade, bau_tablesp, adp);
/*
* the below initialization can't be in firmware because the
* messaging IRQ will be determined by the OS
*/
apicid = blade_to_first_apicid(blade);
pa = uv_read_global_mmr64(pnode, UVH_BAU_DATA_CONFIG);
uv_write_global_mmr64(pnode, UVH_BAU_DATA_CONFIG,
((apicid << 32) | UV_BAU_MESSAGE));
return 0;
}
/*
* Initialization of BAU-related structures
*/
static int __init uv_bau_init(void)
{
int blade;
int nblades;
int cur_cpu;
if (!is_uv_system())
return 0;
for_each_possible_cpu(cur_cpu)
zalloc_cpumask_var_node(&per_cpu(uv_flush_tlb_mask, cur_cpu),
GFP_KERNEL, cpu_to_node(cur_cpu));
uv_bau_retry_limit = 1;
uv_mmask = (1UL << uv_hub_info->m_val) - 1;
nblades = uv_num_possible_blades();
uv_bau_table_bases = (struct bau_control **)
kmalloc(nblades * sizeof(struct bau_control *), GFP_KERNEL);
BUG_ON(!uv_bau_table_bases);
uv_partition_base_pnode = 0x7fffffff;
for (blade = 0; blade < nblades; blade++)
if (uv_blade_nr_possible_cpus(blade) &&
(uv_blade_to_pnode(blade) < uv_partition_base_pnode))
uv_partition_base_pnode = uv_blade_to_pnode(blade);
for (blade = 0; blade < nblades; blade++)
if (uv_blade_nr_possible_cpus(blade))
uv_init_blade(blade);
alloc_intr_gate(UV_BAU_MESSAGE, uv_bau_message_intr1);
uv_enable_timeouts();
return 0;
}
__initcall(uv_bau_init);
__initcall(uv_ptc_init);
| gpl-2.0 |
lyapota/s7e_nougat | drivers/acpi/acpica/uthex.c | 492 | 3627 | /******************************************************************************
*
* Module Name: uthex -- Hex/ASCII support functions
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2014, 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.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#define _COMPONENT ACPI_COMPILER
ACPI_MODULE_NAME("uthex")
/* Hex to ASCII conversion table */
static char acpi_gbl_hex_to_ascii[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
'E', 'F'
};
/*******************************************************************************
*
* FUNCTION: acpi_ut_hex_to_ascii_char
*
* PARAMETERS: integer - Contains the hex digit
* position - bit position of the digit within the
* integer (multiple of 4)
*
* RETURN: The converted Ascii character
*
* DESCRIPTION: Convert a hex digit to an Ascii character
*
******************************************************************************/
char acpi_ut_hex_to_ascii_char(u64 integer, u32 position)
{
return (acpi_gbl_hex_to_ascii[(integer >> position) & 0xF]);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_hex_char_to_value
*
* PARAMETERS: ascii_char - Hex character in Ascii
*
* RETURN: The binary value of the ascii/hex character
*
* DESCRIPTION: Perform ascii-to-hex translation
*
******************************************************************************/
u8 acpi_ut_ascii_char_to_hex(int hex_char)
{
if (hex_char <= 0x39) {
return ((u8)(hex_char - 0x30));
}
if (hex_char <= 0x46) {
return ((u8)(hex_char - 0x37));
}
return ((u8)(hex_char - 0x57));
}
| gpl-2.0 |
dizgustipated/BOCA-2.6.35.14 | drivers/mtd/maps/physmap.c | 748 | 7257 | /*
* Normal mappings of chips in physical memory
*
* Copyright (C) 2003 MontaVista Software Inc.
* Author: Jun Sun, jsun@mvista.com or jsun@junsun.net
*
* 031022 - [jsun] add run-time configure and partition setup
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <linux/mtd/concat.h>
#include <linux/io.h>
#define MAX_RESOURCES 4
struct physmap_flash_info {
struct mtd_info *mtd[MAX_RESOURCES];
struct mtd_info *cmtd;
struct map_info map[MAX_RESOURCES];
#ifdef CONFIG_MTD_PARTITIONS
int nr_parts;
struct mtd_partition *parts;
#endif
};
static int physmap_flash_remove(struct platform_device *dev)
{
struct physmap_flash_info *info;
struct physmap_flash_data *physmap_data;
int i;
info = platform_get_drvdata(dev);
if (info == NULL)
return 0;
platform_set_drvdata(dev, NULL);
physmap_data = dev->dev.platform_data;
if (info->cmtd) {
#ifdef CONFIG_MTD_PARTITIONS
if (info->nr_parts || physmap_data->nr_parts) {
del_mtd_partitions(info->cmtd);
if (info->nr_parts)
kfree(info->parts);
} else {
del_mtd_device(info->cmtd);
}
#else
del_mtd_device(info->cmtd);
#endif
#ifdef CONFIG_MTD_CONCAT
if (info->cmtd != info->mtd[0])
mtd_concat_destroy(info->cmtd);
#endif
}
for (i = 0; i < MAX_RESOURCES; i++) {
if (info->mtd[i] != NULL)
map_destroy(info->mtd[i]);
}
return 0;
}
static const char *rom_probe_types[] = {
"cfi_probe",
"jedec_probe",
"qinfo_probe",
"map_rom",
NULL };
#ifdef CONFIG_MTD_PARTITIONS
static const char *part_probe_types[] = { "cmdlinepart", "RedBoot", NULL };
#endif
static int physmap_flash_probe(struct platform_device *dev)
{
struct physmap_flash_data *physmap_data;
struct physmap_flash_info *info;
const char **probe_type;
int err = 0;
int i;
int devices_found = 0;
physmap_data = dev->dev.platform_data;
if (physmap_data == NULL)
return -ENODEV;
info = devm_kzalloc(&dev->dev, sizeof(struct physmap_flash_info),
GFP_KERNEL);
if (info == NULL) {
err = -ENOMEM;
goto err_out;
}
platform_set_drvdata(dev, info);
for (i = 0; i < dev->num_resources; i++) {
printk(KERN_NOTICE "physmap platform flash device: %.8llx at %.8llx\n",
(unsigned long long)(dev->resource[i].end - dev->resource[i].start + 1),
(unsigned long long)dev->resource[i].start);
if (!devm_request_mem_region(&dev->dev,
dev->resource[i].start,
dev->resource[i].end - dev->resource[i].start + 1,
dev_name(&dev->dev))) {
dev_err(&dev->dev, "Could not reserve memory region\n");
err = -ENOMEM;
goto err_out;
}
info->map[i].name = dev_name(&dev->dev);
info->map[i].phys = dev->resource[i].start;
info->map[i].size = dev->resource[i].end - dev->resource[i].start + 1;
info->map[i].bankwidth = physmap_data->width;
info->map[i].set_vpp = physmap_data->set_vpp;
info->map[i].pfow_base = physmap_data->pfow_base;
info->map[i].virt = devm_ioremap(&dev->dev, info->map[i].phys,
info->map[i].size);
if (info->map[i].virt == NULL) {
dev_err(&dev->dev, "Failed to ioremap flash region\n");
err = -EIO;
goto err_out;
}
simple_map_init(&info->map[i]);
probe_type = rom_probe_types;
for (; info->mtd[i] == NULL && *probe_type != NULL; probe_type++)
info->mtd[i] = do_map_probe(*probe_type, &info->map[i]);
if (info->mtd[i] == NULL) {
dev_err(&dev->dev, "map_probe failed\n");
err = -ENXIO;
goto err_out;
} else {
devices_found++;
}
info->mtd[i]->owner = THIS_MODULE;
info->mtd[i]->dev.parent = &dev->dev;
}
if (devices_found == 1) {
info->cmtd = info->mtd[0];
} else if (devices_found > 1) {
/*
* We detected multiple devices. Concatenate them together.
*/
#ifdef CONFIG_MTD_CONCAT
info->cmtd = mtd_concat_create(info->mtd, devices_found, dev_name(&dev->dev));
if (info->cmtd == NULL)
err = -ENXIO;
#else
printk(KERN_ERR "physmap-flash: multiple devices "
"found but MTD concat support disabled.\n");
err = -ENXIO;
#endif
}
if (err)
goto err_out;
#ifdef CONFIG_MTD_PARTITIONS
err = parse_mtd_partitions(info->cmtd, part_probe_types,
&info->parts, 0);
if (err > 0) {
add_mtd_partitions(info->cmtd, info->parts, err);
info->nr_parts = err;
return 0;
}
if (physmap_data->nr_parts) {
printk(KERN_NOTICE "Using physmap partition information\n");
add_mtd_partitions(info->cmtd, physmap_data->parts,
physmap_data->nr_parts);
return 0;
}
#endif
add_mtd_device(info->cmtd);
return 0;
err_out:
physmap_flash_remove(dev);
return err;
}
#ifdef CONFIG_PM
static void physmap_flash_shutdown(struct platform_device *dev)
{
struct physmap_flash_info *info = platform_get_drvdata(dev);
int i;
for (i = 0; i < MAX_RESOURCES && info->mtd[i]; i++)
if (info->mtd[i]->suspend && info->mtd[i]->resume)
if (info->mtd[i]->suspend(info->mtd[i]) == 0)
info->mtd[i]->resume(info->mtd[i]);
}
#else
#define physmap_flash_shutdown NULL
#endif
static struct platform_driver physmap_flash_driver = {
.probe = physmap_flash_probe,
.remove = physmap_flash_remove,
.shutdown = physmap_flash_shutdown,
.driver = {
.name = "physmap-flash",
.owner = THIS_MODULE,
},
};
#ifdef CONFIG_MTD_PHYSMAP_COMPAT
static struct physmap_flash_data physmap_flash_data = {
.width = CONFIG_MTD_PHYSMAP_BANKWIDTH,
};
static struct resource physmap_flash_resource = {
.start = CONFIG_MTD_PHYSMAP_START,
.end = CONFIG_MTD_PHYSMAP_START + CONFIG_MTD_PHYSMAP_LEN - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device physmap_flash = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &physmap_flash_data,
},
.num_resources = 1,
.resource = &physmap_flash_resource,
};
void physmap_configure(unsigned long addr, unsigned long size,
int bankwidth, void (*set_vpp)(struct map_info *, int))
{
physmap_flash_resource.start = addr;
physmap_flash_resource.end = addr + size - 1;
physmap_flash_data.width = bankwidth;
physmap_flash_data.set_vpp = set_vpp;
}
#ifdef CONFIG_MTD_PARTITIONS
void physmap_set_partitions(struct mtd_partition *parts, int num_parts)
{
physmap_flash_data.nr_parts = num_parts;
physmap_flash_data.parts = parts;
}
#endif
#endif
static int __init physmap_init(void)
{
int err;
err = platform_driver_register(&physmap_flash_driver);
#ifdef CONFIG_MTD_PHYSMAP_COMPAT
if (err == 0) {
err = platform_device_register(&physmap_flash);
if (err)
platform_driver_unregister(&physmap_flash_driver);
}
#endif
return err;
}
static void __exit physmap_exit(void)
{
#ifdef CONFIG_MTD_PHYSMAP_COMPAT
platform_device_unregister(&physmap_flash);
#endif
platform_driver_unregister(&physmap_flash_driver);
}
module_init(physmap_init);
module_exit(physmap_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("David Woodhouse <dwmw2@infradead.org>");
MODULE_DESCRIPTION("Generic configurable MTD map driver");
/* legacy platform drivers can't hotplug or coldplg */
#ifndef CONFIG_MTD_PHYSMAP_COMPAT
/* work with hotplug and coldplug */
MODULE_ALIAS("platform:physmap-flash");
#endif
| gpl-2.0 |
thaskell1/linux | drivers/misc/altera-stapl/altera.c | 1004 | 57447 | /*
* altera.c
*
* altera FPGA driver
*
* Copyright (C) Altera Corporation 1998-2001
* Copyright (C) 2010,2011 NetUP Inc.
* Copyright (C) 2010,2011 Igor M. Liplianin <liplianin@netup.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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* GNU 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 <asm/unaligned.h>
#include <linux/ctype.h>
#include <linux/string.h>
#include <linux/firmware.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <misc/altera.h>
#include "altera-exprt.h"
#include "altera-jtag.h"
static int debug = 1;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "enable debugging information");
MODULE_DESCRIPTION("altera FPGA kernel module");
MODULE_AUTHOR("Igor M. Liplianin <liplianin@netup.ru>");
MODULE_LICENSE("GPL");
#define dprintk(args...) \
if (debug) { \
printk(KERN_DEBUG args); \
}
enum altera_fpga_opcode {
OP_NOP = 0,
OP_DUP,
OP_SWP,
OP_ADD,
OP_SUB,
OP_MULT,
OP_DIV,
OP_MOD,
OP_SHL,
OP_SHR,
OP_NOT,
OP_AND,
OP_OR,
OP_XOR,
OP_INV,
OP_GT,
OP_LT,
OP_RET,
OP_CMPS,
OP_PINT,
OP_PRNT,
OP_DSS,
OP_DSSC,
OP_ISS,
OP_ISSC,
OP_DPR = 0x1c,
OP_DPRL,
OP_DPO,
OP_DPOL,
OP_IPR,
OP_IPRL,
OP_IPO,
OP_IPOL,
OP_PCHR,
OP_EXIT,
OP_EQU,
OP_POPT,
OP_ABS = 0x2c,
OP_BCH0,
OP_PSH0 = 0x2f,
OP_PSHL = 0x40,
OP_PSHV,
OP_JMP,
OP_CALL,
OP_NEXT,
OP_PSTR,
OP_SINT = 0x47,
OP_ST,
OP_ISTP,
OP_DSTP,
OP_SWPN,
OP_DUPN,
OP_POPV,
OP_POPE,
OP_POPA,
OP_JMPZ,
OP_DS,
OP_IS,
OP_DPRA,
OP_DPOA,
OP_IPRA,
OP_IPOA,
OP_EXPT,
OP_PSHE,
OP_PSHA,
OP_DYNA,
OP_EXPV = 0x5c,
OP_COPY = 0x80,
OP_REVA,
OP_DSC,
OP_ISC,
OP_WAIT,
OP_VS,
OP_CMPA = 0xc0,
OP_VSC,
};
struct altera_procinfo {
char *name;
u8 attrs;
struct altera_procinfo *next;
};
/* This function checks if enough parameters are available on the stack. */
static int altera_check_stack(int stack_ptr, int count, int *status)
{
if (stack_ptr < count) {
*status = -EOVERFLOW;
return 0;
}
return 1;
}
static void altera_export_int(char *key, s32 value)
{
dprintk("Export: key = \"%s\", value = %d\n", key, value);
}
#define HEX_LINE_CHARS 72
#define HEX_LINE_BITS (HEX_LINE_CHARS * 4)
static void altera_export_bool_array(char *key, u8 *data, s32 count)
{
char string[HEX_LINE_CHARS + 1];
s32 i, offset;
u32 size, line, lines, linebits, value, j, k;
if (count > HEX_LINE_BITS) {
dprintk("Export: key = \"%s\", %d bits, value = HEX\n",
key, count);
lines = (count + (HEX_LINE_BITS - 1)) / HEX_LINE_BITS;
for (line = 0; line < lines; ++line) {
if (line < (lines - 1)) {
linebits = HEX_LINE_BITS;
size = HEX_LINE_CHARS;
offset = count - ((line + 1) * HEX_LINE_BITS);
} else {
linebits =
count - ((lines - 1) * HEX_LINE_BITS);
size = (linebits + 3) / 4;
offset = 0L;
}
string[size] = '\0';
j = size - 1;
value = 0;
for (k = 0; k < linebits; ++k) {
i = k + offset;
if (data[i >> 3] & (1 << (i & 7)))
value |= (1 << (i & 3));
if ((i & 3) == 3) {
sprintf(&string[j], "%1x", value);
value = 0;
--j;
}
}
if ((k & 3) > 0)
sprintf(&string[j], "%1x", value);
dprintk("%s\n", string);
}
} else {
size = (count + 3) / 4;
string[size] = '\0';
j = size - 1;
value = 0;
for (i = 0; i < count; ++i) {
if (data[i >> 3] & (1 << (i & 7)))
value |= (1 << (i & 3));
if ((i & 3) == 3) {
sprintf(&string[j], "%1x", value);
value = 0;
--j;
}
}
if ((i & 3) > 0)
sprintf(&string[j], "%1x", value);
dprintk("Export: key = \"%s\", %d bits, value = HEX %s\n",
key, count, string);
}
}
static int altera_execute(struct altera_state *astate,
u8 *p,
s32 program_size,
s32 *error_address,
int *exit_code,
int *format_version)
{
struct altera_config *aconf = astate->config;
char *msg_buff = astate->msg_buff;
long *stack = astate->stack;
int status = 0;
u32 first_word = 0L;
u32 action_table = 0L;
u32 proc_table = 0L;
u32 str_table = 0L;
u32 sym_table = 0L;
u32 data_sect = 0L;
u32 code_sect = 0L;
u32 debug_sect = 0L;
u32 action_count = 0L;
u32 proc_count = 0L;
u32 sym_count = 0L;
long *vars = NULL;
s32 *var_size = NULL;
char *attrs = NULL;
u8 *proc_attributes = NULL;
u32 pc;
u32 opcode_address;
u32 args[3];
u32 opcode;
u32 name_id;
u8 charbuf[4];
long long_tmp;
u32 variable_id;
u8 *charptr_tmp;
u8 *charptr_tmp2;
long *longptr_tmp;
int version = 0;
int delta = 0;
int stack_ptr = 0;
u32 arg_count;
int done = 0;
int bad_opcode = 0;
u32 count;
u32 index;
u32 index2;
s32 long_count;
s32 long_idx;
s32 long_idx2;
u32 i;
u32 j;
u32 uncomp_size;
u32 offset;
u32 value;
int current_proc = 0;
int reverse;
char *name;
dprintk("%s\n", __func__);
/* Read header information */
if (program_size > 52L) {
first_word = get_unaligned_be32(&p[0]);
version = (first_word & 1L);
*format_version = version + 1;
delta = version * 8;
action_table = get_unaligned_be32(&p[4]);
proc_table = get_unaligned_be32(&p[8]);
str_table = get_unaligned_be32(&p[4 + delta]);
sym_table = get_unaligned_be32(&p[16 + delta]);
data_sect = get_unaligned_be32(&p[20 + delta]);
code_sect = get_unaligned_be32(&p[24 + delta]);
debug_sect = get_unaligned_be32(&p[28 + delta]);
action_count = get_unaligned_be32(&p[40 + delta]);
proc_count = get_unaligned_be32(&p[44 + delta]);
sym_count = get_unaligned_be32(&p[48 + (2 * delta)]);
}
if ((first_word != 0x4A414D00L) && (first_word != 0x4A414D01L)) {
done = 1;
status = -EIO;
goto exit_done;
}
if (sym_count <= 0)
goto exit_done;
vars = kzalloc(sym_count * sizeof(long), GFP_KERNEL);
if (vars == NULL)
status = -ENOMEM;
if (status == 0) {
var_size = kzalloc(sym_count * sizeof(s32), GFP_KERNEL);
if (var_size == NULL)
status = -ENOMEM;
}
if (status == 0) {
attrs = kzalloc(sym_count, GFP_KERNEL);
if (attrs == NULL)
status = -ENOMEM;
}
if ((status == 0) && (version > 0)) {
proc_attributes = kzalloc(proc_count, GFP_KERNEL);
if (proc_attributes == NULL)
status = -ENOMEM;
}
if (status != 0)
goto exit_done;
delta = version * 2;
for (i = 0; i < sym_count; ++i) {
offset = (sym_table + ((11 + delta) * i));
value = get_unaligned_be32(&p[offset + 3 + delta]);
attrs[i] = p[offset];
/*
* use bit 7 of attribute byte to indicate that
* this buffer was dynamically allocated
* and should be freed later
*/
attrs[i] &= 0x7f;
var_size[i] = get_unaligned_be32(&p[offset + 7 + delta]);
/*
* Attribute bits:
* bit 0: 0 = read-only, 1 = read-write
* bit 1: 0 = not compressed, 1 = compressed
* bit 2: 0 = not initialized, 1 = initialized
* bit 3: 0 = scalar, 1 = array
* bit 4: 0 = Boolean, 1 = integer
* bit 5: 0 = declared variable,
* 1 = compiler created temporary variable
*/
if ((attrs[i] & 0x0c) == 0x04)
/* initialized scalar variable */
vars[i] = value;
else if ((attrs[i] & 0x1e) == 0x0e) {
/* initialized compressed Boolean array */
uncomp_size = get_unaligned_le32(&p[data_sect + value]);
/* allocate a buffer for the uncompressed data */
vars[i] = (long)kzalloc(uncomp_size, GFP_KERNEL);
if (vars[i] == 0L)
status = -ENOMEM;
else {
/* set flag so buffer will be freed later */
attrs[i] |= 0x80;
/* uncompress the data */
if (altera_shrink(&p[data_sect + value],
var_size[i],
(u8 *)vars[i],
uncomp_size,
version) != uncomp_size)
/* decompression failed */
status = -EIO;
else
var_size[i] = uncomp_size * 8L;
}
} else if ((attrs[i] & 0x1e) == 0x0c) {
/* initialized Boolean array */
vars[i] = value + data_sect + (long)p;
} else if ((attrs[i] & 0x1c) == 0x1c) {
/* initialized integer array */
vars[i] = value + data_sect;
} else if ((attrs[i] & 0x0c) == 0x08) {
/* uninitialized array */
/* flag attrs so that memory is freed */
attrs[i] |= 0x80;
if (var_size[i] > 0) {
u32 size;
if (attrs[i] & 0x10)
/* integer array */
size = (var_size[i] * sizeof(s32));
else
/* Boolean array */
size = ((var_size[i] + 7L) / 8L);
vars[i] = (long)kzalloc(size, GFP_KERNEL);
if (vars[i] == 0) {
status = -ENOMEM;
} else {
/* zero out memory */
for (j = 0; j < size; ++j)
((u8 *)(vars[i]))[j] = 0;
}
} else
vars[i] = 0;
} else
vars[i] = 0;
}
exit_done:
if (status != 0)
done = 1;
altera_jinit(astate);
pc = code_sect;
msg_buff[0] = '\0';
/*
* For JBC version 2, we will execute the procedures corresponding to
* the selected ACTION
*/
if (version > 0) {
if (aconf->action == NULL) {
status = -EINVAL;
done = 1;
} else {
int action_found = 0;
for (i = 0; (i < action_count) && !action_found; ++i) {
name_id = get_unaligned_be32(&p[action_table +
(12 * i)]);
name = &p[str_table + name_id];
if (strncasecmp(aconf->action, name, strlen(name)) == 0) {
action_found = 1;
current_proc =
get_unaligned_be32(&p[action_table +
(12 * i) + 8]);
}
}
if (!action_found) {
status = -EINVAL;
done = 1;
}
}
if (status == 0) {
int first_time = 1;
i = current_proc;
while ((i != 0) || first_time) {
first_time = 0;
/* check procedure attribute byte */
proc_attributes[i] =
(p[proc_table +
(13 * i) + 8] &
0x03);
/*
* BIT0 - OPTIONAL
* BIT1 - RECOMMENDED
* BIT6 - FORCED OFF
* BIT7 - FORCED ON
*/
i = get_unaligned_be32(&p[proc_table +
(13 * i) + 4]);
}
/*
* Set current_proc to the first procedure
* to be executed
*/
i = current_proc;
while ((i != 0) &&
((proc_attributes[i] == 1) ||
((proc_attributes[i] & 0xc0) == 0x40))) {
i = get_unaligned_be32(&p[proc_table +
(13 * i) + 4]);
}
if ((i != 0) || ((i == 0) && (current_proc == 0) &&
((proc_attributes[0] != 1) &&
((proc_attributes[0] & 0xc0) != 0x40)))) {
current_proc = i;
pc = code_sect +
get_unaligned_be32(&p[proc_table +
(13 * i) + 9]);
if ((pc < code_sect) || (pc >= debug_sect))
status = -ERANGE;
} else
/* there are no procedures to execute! */
done = 1;
}
}
msg_buff[0] = '\0';
while (!done) {
opcode = (p[pc] & 0xff);
opcode_address = pc;
++pc;
if (debug > 1)
printk("opcode: %02x\n", opcode);
arg_count = (opcode >> 6) & 3;
for (i = 0; i < arg_count; ++i) {
args[i] = get_unaligned_be32(&p[pc]);
pc += 4;
}
switch (opcode) {
case OP_NOP:
break;
case OP_DUP:
if (altera_check_stack(stack_ptr, 1, &status)) {
stack[stack_ptr] = stack[stack_ptr - 1];
++stack_ptr;
}
break;
case OP_SWP:
if (altera_check_stack(stack_ptr, 2, &status)) {
long_tmp = stack[stack_ptr - 2];
stack[stack_ptr - 2] = stack[stack_ptr - 1];
stack[stack_ptr - 1] = long_tmp;
}
break;
case OP_ADD:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] += stack[stack_ptr];
}
break;
case OP_SUB:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] -= stack[stack_ptr];
}
break;
case OP_MULT:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] *= stack[stack_ptr];
}
break;
case OP_DIV:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] /= stack[stack_ptr];
}
break;
case OP_MOD:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] %= stack[stack_ptr];
}
break;
case OP_SHL:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] <<= stack[stack_ptr];
}
break;
case OP_SHR:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] >>= stack[stack_ptr];
}
break;
case OP_NOT:
if (altera_check_stack(stack_ptr, 1, &status))
stack[stack_ptr - 1] ^= (-1L);
break;
case OP_AND:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] &= stack[stack_ptr];
}
break;
case OP_OR:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] |= stack[stack_ptr];
}
break;
case OP_XOR:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] ^= stack[stack_ptr];
}
break;
case OP_INV:
if (!altera_check_stack(stack_ptr, 1, &status))
break;
stack[stack_ptr - 1] = stack[stack_ptr - 1] ? 0L : 1L;
break;
case OP_GT:
if (!altera_check_stack(stack_ptr, 2, &status))
break;
--stack_ptr;
stack[stack_ptr - 1] =
(stack[stack_ptr - 1] > stack[stack_ptr]) ?
1L : 0L;
break;
case OP_LT:
if (!altera_check_stack(stack_ptr, 2, &status))
break;
--stack_ptr;
stack[stack_ptr - 1] =
(stack[stack_ptr - 1] < stack[stack_ptr]) ?
1L : 0L;
break;
case OP_RET:
if ((version > 0) && (stack_ptr == 0)) {
/*
* We completed one of the main procedures
* of an ACTION.
* Find the next procedure
* to be executed and jump to it.
* If there are no more procedures, then EXIT.
*/
i = get_unaligned_be32(&p[proc_table +
(13 * current_proc) + 4]);
while ((i != 0) &&
((proc_attributes[i] == 1) ||
((proc_attributes[i] & 0xc0) == 0x40)))
i = get_unaligned_be32(&p[proc_table +
(13 * i) + 4]);
if (i == 0) {
/* no procedures to execute! */
done = 1;
*exit_code = 0; /* success */
} else {
current_proc = i;
pc = code_sect + get_unaligned_be32(
&p[proc_table +
(13 * i) + 9]);
if ((pc < code_sect) ||
(pc >= debug_sect))
status = -ERANGE;
}
} else
if (altera_check_stack(stack_ptr, 1, &status)) {
pc = stack[--stack_ptr] + code_sect;
if ((pc <= code_sect) ||
(pc >= debug_sect))
status = -ERANGE;
}
break;
case OP_CMPS:
/*
* Array short compare
* ...stack 0 is source 1 value
* ...stack 1 is source 2 value
* ...stack 2 is mask value
* ...stack 3 is count
*/
if (altera_check_stack(stack_ptr, 4, &status)) {
s32 a = stack[--stack_ptr];
s32 b = stack[--stack_ptr];
long_tmp = stack[--stack_ptr];
count = stack[stack_ptr - 1];
if ((count < 1) || (count > 32))
status = -ERANGE;
else {
long_tmp &= ((-1L) >> (32 - count));
stack[stack_ptr - 1] =
((a & long_tmp) == (b & long_tmp))
? 1L : 0L;
}
}
break;
case OP_PINT:
/*
* PRINT add integer
* ...stack 0 is integer value
*/
if (!altera_check_stack(stack_ptr, 1, &status))
break;
sprintf(&msg_buff[strlen(msg_buff)],
"%ld", stack[--stack_ptr]);
break;
case OP_PRNT:
/* PRINT finish */
if (debug)
printk(msg_buff, "\n");
msg_buff[0] = '\0';
break;
case OP_DSS:
/*
* DRSCAN short
* ...stack 0 is scan data
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
long_tmp = stack[--stack_ptr];
count = stack[--stack_ptr];
put_unaligned_le32(long_tmp, &charbuf[0]);
status = altera_drscan(astate, count, charbuf, 0);
break;
case OP_DSSC:
/*
* DRSCAN short with capture
* ...stack 0 is scan data
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
long_tmp = stack[--stack_ptr];
count = stack[stack_ptr - 1];
put_unaligned_le32(long_tmp, &charbuf[0]);
status = altera_swap_dr(astate, count, charbuf,
0, charbuf, 0);
stack[stack_ptr - 1] = get_unaligned_le32(&charbuf[0]);
break;
case OP_ISS:
/*
* IRSCAN short
* ...stack 0 is scan data
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
long_tmp = stack[--stack_ptr];
count = stack[--stack_ptr];
put_unaligned_le32(long_tmp, &charbuf[0]);
status = altera_irscan(astate, count, charbuf, 0);
break;
case OP_ISSC:
/*
* IRSCAN short with capture
* ...stack 0 is scan data
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
long_tmp = stack[--stack_ptr];
count = stack[stack_ptr - 1];
put_unaligned_le32(long_tmp, &charbuf[0]);
status = altera_swap_ir(astate, count, charbuf,
0, charbuf, 0);
stack[stack_ptr - 1] = get_unaligned_le32(&charbuf[0]);
break;
case OP_DPR:
if (!altera_check_stack(stack_ptr, 1, &status))
break;
count = stack[--stack_ptr];
status = altera_set_dr_pre(&astate->js, count, 0, NULL);
break;
case OP_DPRL:
/*
* DRPRE with literal data
* ...stack 0 is count
* ...stack 1 is literal data
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
count = stack[--stack_ptr];
long_tmp = stack[--stack_ptr];
put_unaligned_le32(long_tmp, &charbuf[0]);
status = altera_set_dr_pre(&astate->js, count, 0,
charbuf);
break;
case OP_DPO:
/*
* DRPOST
* ...stack 0 is count
*/
if (altera_check_stack(stack_ptr, 1, &status)) {
count = stack[--stack_ptr];
status = altera_set_dr_post(&astate->js, count,
0, NULL);
}
break;
case OP_DPOL:
/*
* DRPOST with literal data
* ...stack 0 is count
* ...stack 1 is literal data
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
count = stack[--stack_ptr];
long_tmp = stack[--stack_ptr];
put_unaligned_le32(long_tmp, &charbuf[0]);
status = altera_set_dr_post(&astate->js, count, 0,
charbuf);
break;
case OP_IPR:
if (altera_check_stack(stack_ptr, 1, &status)) {
count = stack[--stack_ptr];
status = altera_set_ir_pre(&astate->js, count,
0, NULL);
}
break;
case OP_IPRL:
/*
* IRPRE with literal data
* ...stack 0 is count
* ...stack 1 is literal data
*/
if (altera_check_stack(stack_ptr, 2, &status)) {
count = stack[--stack_ptr];
long_tmp = stack[--stack_ptr];
put_unaligned_le32(long_tmp, &charbuf[0]);
status = altera_set_ir_pre(&astate->js, count,
0, charbuf);
}
break;
case OP_IPO:
/*
* IRPOST
* ...stack 0 is count
*/
if (altera_check_stack(stack_ptr, 1, &status)) {
count = stack[--stack_ptr];
status = altera_set_ir_post(&astate->js, count,
0, NULL);
}
break;
case OP_IPOL:
/*
* IRPOST with literal data
* ...stack 0 is count
* ...stack 1 is literal data
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
count = stack[--stack_ptr];
long_tmp = stack[--stack_ptr];
put_unaligned_le32(long_tmp, &charbuf[0]);
status = altera_set_ir_post(&astate->js, count, 0,
charbuf);
break;
case OP_PCHR:
if (altera_check_stack(stack_ptr, 1, &status)) {
u8 ch;
count = strlen(msg_buff);
ch = (char) stack[--stack_ptr];
if ((ch < 1) || (ch > 127)) {
/*
* character code out of range
* instead of flagging an error,
* force the value to 127
*/
ch = 127;
}
msg_buff[count] = ch;
msg_buff[count + 1] = '\0';
}
break;
case OP_EXIT:
if (altera_check_stack(stack_ptr, 1, &status))
*exit_code = stack[--stack_ptr];
done = 1;
break;
case OP_EQU:
if (!altera_check_stack(stack_ptr, 2, &status))
break;
--stack_ptr;
stack[stack_ptr - 1] =
(stack[stack_ptr - 1] == stack[stack_ptr]) ?
1L : 0L;
break;
case OP_POPT:
if (altera_check_stack(stack_ptr, 1, &status))
--stack_ptr;
break;
case OP_ABS:
if (!altera_check_stack(stack_ptr, 1, &status))
break;
if (stack[stack_ptr - 1] < 0)
stack[stack_ptr - 1] = 0 - stack[stack_ptr - 1];
break;
case OP_BCH0:
/*
* Batch operation 0
* SWP
* SWPN 7
* SWP
* SWPN 6
* DUPN 8
* SWPN 2
* SWP
* DUPN 6
* DUPN 6
*/
/* SWP */
if (altera_check_stack(stack_ptr, 2, &status)) {
long_tmp = stack[stack_ptr - 2];
stack[stack_ptr - 2] = stack[stack_ptr - 1];
stack[stack_ptr - 1] = long_tmp;
}
/* SWPN 7 */
index = 7 + 1;
if (altera_check_stack(stack_ptr, index, &status)) {
long_tmp = stack[stack_ptr - index];
stack[stack_ptr - index] = stack[stack_ptr - 1];
stack[stack_ptr - 1] = long_tmp;
}
/* SWP */
if (altera_check_stack(stack_ptr, 2, &status)) {
long_tmp = stack[stack_ptr - 2];
stack[stack_ptr - 2] = stack[stack_ptr - 1];
stack[stack_ptr - 1] = long_tmp;
}
/* SWPN 6 */
index = 6 + 1;
if (altera_check_stack(stack_ptr, index, &status)) {
long_tmp = stack[stack_ptr - index];
stack[stack_ptr - index] = stack[stack_ptr - 1];
stack[stack_ptr - 1] = long_tmp;
}
/* DUPN 8 */
index = 8 + 1;
if (altera_check_stack(stack_ptr, index, &status)) {
stack[stack_ptr] = stack[stack_ptr - index];
++stack_ptr;
}
/* SWPN 2 */
index = 2 + 1;
if (altera_check_stack(stack_ptr, index, &status)) {
long_tmp = stack[stack_ptr - index];
stack[stack_ptr - index] = stack[stack_ptr - 1];
stack[stack_ptr - 1] = long_tmp;
}
/* SWP */
if (altera_check_stack(stack_ptr, 2, &status)) {
long_tmp = stack[stack_ptr - 2];
stack[stack_ptr - 2] = stack[stack_ptr - 1];
stack[stack_ptr - 1] = long_tmp;
}
/* DUPN 6 */
index = 6 + 1;
if (altera_check_stack(stack_ptr, index, &status)) {
stack[stack_ptr] = stack[stack_ptr - index];
++stack_ptr;
}
/* DUPN 6 */
index = 6 + 1;
if (altera_check_stack(stack_ptr, index, &status)) {
stack[stack_ptr] = stack[stack_ptr - index];
++stack_ptr;
}
break;
case OP_PSH0:
stack[stack_ptr++] = 0;
break;
case OP_PSHL:
stack[stack_ptr++] = (s32) args[0];
break;
case OP_PSHV:
stack[stack_ptr++] = vars[args[0]];
break;
case OP_JMP:
pc = args[0] + code_sect;
if ((pc < code_sect) || (pc >= debug_sect))
status = -ERANGE;
break;
case OP_CALL:
stack[stack_ptr++] = pc;
pc = args[0] + code_sect;
if ((pc < code_sect) || (pc >= debug_sect))
status = -ERANGE;
break;
case OP_NEXT:
/*
* Process FOR / NEXT loop
* ...argument 0 is variable ID
* ...stack 0 is step value
* ...stack 1 is end value
* ...stack 2 is top address
*/
if (altera_check_stack(stack_ptr, 3, &status)) {
s32 step = stack[stack_ptr - 1];
s32 end = stack[stack_ptr - 2];
s32 top = stack[stack_ptr - 3];
s32 iterator = vars[args[0]];
int break_out = 0;
if (step < 0) {
if (iterator <= end)
break_out = 1;
} else if (iterator >= end)
break_out = 1;
if (break_out) {
stack_ptr -= 3;
} else {
vars[args[0]] = iterator + step;
pc = top + code_sect;
if ((pc < code_sect) ||
(pc >= debug_sect))
status = -ERANGE;
}
}
break;
case OP_PSTR:
/*
* PRINT add string
* ...argument 0 is string ID
*/
count = strlen(msg_buff);
strlcpy(&msg_buff[count],
&p[str_table + args[0]],
ALTERA_MESSAGE_LENGTH - count);
break;
case OP_SINT:
/*
* STATE intermediate state
* ...argument 0 is state code
*/
status = altera_goto_jstate(astate, args[0]);
break;
case OP_ST:
/*
* STATE final state
* ...argument 0 is state code
*/
status = altera_goto_jstate(astate, args[0]);
break;
case OP_ISTP:
/*
* IRSTOP state
* ...argument 0 is state code
*/
status = altera_set_irstop(&astate->js, args[0]);
break;
case OP_DSTP:
/*
* DRSTOP state
* ...argument 0 is state code
*/
status = altera_set_drstop(&astate->js, args[0]);
break;
case OP_SWPN:
/*
* Exchange top with Nth stack value
* ...argument 0 is 0-based stack entry
* to swap with top element
*/
index = (args[0]) + 1;
if (altera_check_stack(stack_ptr, index, &status)) {
long_tmp = stack[stack_ptr - index];
stack[stack_ptr - index] = stack[stack_ptr - 1];
stack[stack_ptr - 1] = long_tmp;
}
break;
case OP_DUPN:
/*
* Duplicate Nth stack value
* ...argument 0 is 0-based stack entry to duplicate
*/
index = (args[0]) + 1;
if (altera_check_stack(stack_ptr, index, &status)) {
stack[stack_ptr] = stack[stack_ptr - index];
++stack_ptr;
}
break;
case OP_POPV:
/*
* Pop stack into scalar variable
* ...argument 0 is variable ID
* ...stack 0 is value
*/
if (altera_check_stack(stack_ptr, 1, &status))
vars[args[0]] = stack[--stack_ptr];
break;
case OP_POPE:
/*
* Pop stack into integer array element
* ...argument 0 is variable ID
* ...stack 0 is array index
* ...stack 1 is value
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
variable_id = args[0];
/*
* If variable is read-only,
* convert to writable array
*/
if ((version > 0) &&
((attrs[variable_id] & 0x9c) == 0x1c)) {
/* Allocate a writable buffer for this array */
count = var_size[variable_id];
long_tmp = vars[variable_id];
longptr_tmp = kzalloc(count * sizeof(long),
GFP_KERNEL);
vars[variable_id] = (long)longptr_tmp;
if (vars[variable_id] == 0) {
status = -ENOMEM;
break;
}
/* copy previous contents into buffer */
for (i = 0; i < count; ++i) {
longptr_tmp[i] =
get_unaligned_be32(&p[long_tmp]);
long_tmp += sizeof(long);
}
/*
* set bit 7 - buffer was
* dynamically allocated
*/
attrs[variable_id] |= 0x80;
/* clear bit 2 - variable is writable */
attrs[variable_id] &= ~0x04;
attrs[variable_id] |= 0x01;
}
/* check that variable is a writable integer array */
if ((attrs[variable_id] & 0x1c) != 0x18)
status = -ERANGE;
else {
longptr_tmp = (long *)vars[variable_id];
/* pop the array index */
index = stack[--stack_ptr];
/* pop the value and store it into the array */
longptr_tmp[index] = stack[--stack_ptr];
}
break;
case OP_POPA:
/*
* Pop stack into Boolean array
* ...argument 0 is variable ID
* ...stack 0 is count
* ...stack 1 is array index
* ...stack 2 is value
*/
if (!altera_check_stack(stack_ptr, 3, &status))
break;
variable_id = args[0];
/*
* If variable is read-only,
* convert to writable array
*/
if ((version > 0) &&
((attrs[variable_id] & 0x9c) == 0x0c)) {
/* Allocate a writable buffer for this array */
long_tmp =
(var_size[variable_id] + 7L) >> 3L;
charptr_tmp2 = (u8 *)vars[variable_id];
charptr_tmp =
kzalloc(long_tmp, GFP_KERNEL);
vars[variable_id] = (long)charptr_tmp;
if (vars[variable_id] == 0) {
status = -ENOMEM;
break;
}
/* zero the buffer */
for (long_idx = 0L;
long_idx < long_tmp;
++long_idx) {
charptr_tmp[long_idx] = 0;
}
/* copy previous contents into buffer */
for (long_idx = 0L;
long_idx < var_size[variable_id];
++long_idx) {
long_idx2 = long_idx;
if (charptr_tmp2[long_idx2 >> 3] &
(1 << (long_idx2 & 7))) {
charptr_tmp[long_idx >> 3] |=
(1 << (long_idx & 7));
}
}
/*
* set bit 7 - buffer was
* dynamically allocated
*/
attrs[variable_id] |= 0x80;
/* clear bit 2 - variable is writable */
attrs[variable_id] &= ~0x04;
attrs[variable_id] |= 0x01;
}
/*
* check that variable is
* a writable Boolean array
*/
if ((attrs[variable_id] & 0x1c) != 0x08) {
status = -ERANGE;
break;
}
charptr_tmp = (u8 *)vars[variable_id];
/* pop the count (number of bits to copy) */
long_count = stack[--stack_ptr];
/* pop the array index */
long_idx = stack[--stack_ptr];
reverse = 0;
if (version > 0) {
/*
* stack 0 = array right index
* stack 1 = array left index
*/
if (long_idx > long_count) {
reverse = 1;
long_tmp = long_count;
long_count = 1 + long_idx -
long_count;
long_idx = long_tmp;
/* reverse POPA is not supported */
status = -ERANGE;
break;
} else
long_count = 1 + long_count -
long_idx;
}
/* pop the data */
long_tmp = stack[--stack_ptr];
if (long_count < 1) {
status = -ERANGE;
break;
}
for (i = 0; i < long_count; ++i) {
if (long_tmp & (1L << (s32) i))
charptr_tmp[long_idx >> 3L] |=
(1L << (long_idx & 7L));
else
charptr_tmp[long_idx >> 3L] &=
~(1L << (long_idx & 7L));
++long_idx;
}
break;
case OP_JMPZ:
/*
* Pop stack and branch if zero
* ...argument 0 is address
* ...stack 0 is condition value
*/
if (altera_check_stack(stack_ptr, 1, &status)) {
if (stack[--stack_ptr] == 0) {
pc = args[0] + code_sect;
if ((pc < code_sect) ||
(pc >= debug_sect))
status = -ERANGE;
}
}
break;
case OP_DS:
case OP_IS:
/*
* DRSCAN
* IRSCAN
* ...argument 0 is scan data variable ID
* ...stack 0 is array index
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
long_idx = stack[--stack_ptr];
long_count = stack[--stack_ptr];
reverse = 0;
if (version > 0) {
/*
* stack 0 = array right index
* stack 1 = array left index
* stack 2 = count
*/
long_tmp = long_count;
long_count = stack[--stack_ptr];
if (long_idx > long_tmp) {
reverse = 1;
long_idx = long_tmp;
}
}
charptr_tmp = (u8 *)vars[args[0]];
if (reverse) {
/*
* allocate a buffer
* and reverse the data order
*/
charptr_tmp2 = charptr_tmp;
charptr_tmp = kzalloc((long_count >> 3) + 1,
GFP_KERNEL);
if (charptr_tmp == NULL) {
status = -ENOMEM;
break;
}
long_tmp = long_idx + long_count - 1;
long_idx2 = 0;
while (long_idx2 < long_count) {
if (charptr_tmp2[long_tmp >> 3] &
(1 << (long_tmp & 7)))
charptr_tmp[long_idx2 >> 3] |=
(1 << (long_idx2 & 7));
else
charptr_tmp[long_idx2 >> 3] &=
~(1 << (long_idx2 & 7));
--long_tmp;
++long_idx2;
}
}
if (opcode == 0x51) /* DS */
status = altera_drscan(astate, long_count,
charptr_tmp, long_idx);
else /* IS */
status = altera_irscan(astate, long_count,
charptr_tmp, long_idx);
if (reverse)
kfree(charptr_tmp);
break;
case OP_DPRA:
/*
* DRPRE with array data
* ...argument 0 is variable ID
* ...stack 0 is array index
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
index = stack[--stack_ptr];
count = stack[--stack_ptr];
if (version > 0)
/*
* stack 0 = array right index
* stack 1 = array left index
*/
count = 1 + count - index;
charptr_tmp = (u8 *)vars[args[0]];
status = altera_set_dr_pre(&astate->js, count, index,
charptr_tmp);
break;
case OP_DPOA:
/*
* DRPOST with array data
* ...argument 0 is variable ID
* ...stack 0 is array index
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
index = stack[--stack_ptr];
count = stack[--stack_ptr];
if (version > 0)
/*
* stack 0 = array right index
* stack 1 = array left index
*/
count = 1 + count - index;
charptr_tmp = (u8 *)vars[args[0]];
status = altera_set_dr_post(&astate->js, count, index,
charptr_tmp);
break;
case OP_IPRA:
/*
* IRPRE with array data
* ...argument 0 is variable ID
* ...stack 0 is array index
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
index = stack[--stack_ptr];
count = stack[--stack_ptr];
if (version > 0)
/*
* stack 0 = array right index
* stack 1 = array left index
*/
count = 1 + count - index;
charptr_tmp = (u8 *)vars[args[0]];
status = altera_set_ir_pre(&astate->js, count, index,
charptr_tmp);
break;
case OP_IPOA:
/*
* IRPOST with array data
* ...argument 0 is variable ID
* ...stack 0 is array index
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
index = stack[--stack_ptr];
count = stack[--stack_ptr];
if (version > 0)
/*
* stack 0 = array right index
* stack 1 = array left index
*/
count = 1 + count - index;
charptr_tmp = (u8 *)vars[args[0]];
status = altera_set_ir_post(&astate->js, count, index,
charptr_tmp);
break;
case OP_EXPT:
/*
* EXPORT
* ...argument 0 is string ID
* ...stack 0 is integer expression
*/
if (altera_check_stack(stack_ptr, 1, &status)) {
name = &p[str_table + args[0]];
long_tmp = stack[--stack_ptr];
altera_export_int(name, long_tmp);
}
break;
case OP_PSHE:
/*
* Push integer array element
* ...argument 0 is variable ID
* ...stack 0 is array index
*/
if (!altera_check_stack(stack_ptr, 1, &status))
break;
variable_id = args[0];
index = stack[stack_ptr - 1];
/* check variable type */
if ((attrs[variable_id] & 0x1f) == 0x19) {
/* writable integer array */
longptr_tmp = (long *)vars[variable_id];
stack[stack_ptr - 1] = longptr_tmp[index];
} else if ((attrs[variable_id] & 0x1f) == 0x1c) {
/* read-only integer array */
long_tmp = vars[variable_id] +
(index * sizeof(long));
stack[stack_ptr - 1] =
get_unaligned_be32(&p[long_tmp]);
} else
status = -ERANGE;
break;
case OP_PSHA:
/*
* Push Boolean array
* ...argument 0 is variable ID
* ...stack 0 is count
* ...stack 1 is array index
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
variable_id = args[0];
/* check that variable is a Boolean array */
if ((attrs[variable_id] & 0x18) != 0x08) {
status = -ERANGE;
break;
}
charptr_tmp = (u8 *)vars[variable_id];
/* pop the count (number of bits to copy) */
count = stack[--stack_ptr];
/* pop the array index */
index = stack[stack_ptr - 1];
if (version > 0)
/*
* stack 0 = array right index
* stack 1 = array left index
*/
count = 1 + count - index;
if ((count < 1) || (count > 32)) {
status = -ERANGE;
break;
}
long_tmp = 0L;
for (i = 0; i < count; ++i)
if (charptr_tmp[(i + index) >> 3] &
(1 << ((i + index) & 7)))
long_tmp |= (1L << i);
stack[stack_ptr - 1] = long_tmp;
break;
case OP_DYNA:
/*
* Dynamically change size of array
* ...argument 0 is variable ID
* ...stack 0 is new size
*/
if (!altera_check_stack(stack_ptr, 1, &status))
break;
variable_id = args[0];
long_tmp = stack[--stack_ptr];
if (long_tmp > var_size[variable_id]) {
var_size[variable_id] = long_tmp;
if (attrs[variable_id] & 0x10)
/* allocate integer array */
long_tmp *= sizeof(long);
else
/* allocate Boolean array */
long_tmp = (long_tmp + 7) >> 3;
/*
* If the buffer was previously allocated,
* free it
*/
if (attrs[variable_id] & 0x80) {
kfree((void *)vars[variable_id]);
vars[variable_id] = 0;
}
/*
* Allocate a new buffer
* of the requested size
*/
vars[variable_id] = (long)
kzalloc(long_tmp, GFP_KERNEL);
if (vars[variable_id] == 0) {
status = -ENOMEM;
break;
}
/*
* Set the attribute bit to indicate that
* this buffer was dynamically allocated and
* should be freed later
*/
attrs[variable_id] |= 0x80;
/* zero out memory */
count = ((var_size[variable_id] + 7L) /
8L);
charptr_tmp = (u8 *)(vars[variable_id]);
for (index = 0; index < count; ++index)
charptr_tmp[index] = 0;
}
break;
case OP_EXPV:
/*
* Export Boolean array
* ...argument 0 is string ID
* ...stack 0 is variable ID
* ...stack 1 is array right index
* ...stack 2 is array left index
*/
if (!altera_check_stack(stack_ptr, 3, &status))
break;
if (version == 0) {
/* EXPV is not supported in JBC 1.0 */
bad_opcode = 1;
break;
}
name = &p[str_table + args[0]];
variable_id = stack[--stack_ptr];
long_idx = stack[--stack_ptr];/* right indx */
long_idx2 = stack[--stack_ptr];/* left indx */
if (long_idx > long_idx2) {
/* reverse indices not supported */
status = -ERANGE;
break;
}
long_count = 1 + long_idx2 - long_idx;
charptr_tmp = (u8 *)vars[variable_id];
charptr_tmp2 = NULL;
if ((long_idx & 7L) != 0) {
s32 k = long_idx;
charptr_tmp2 =
kzalloc(((long_count + 7L) / 8L),
GFP_KERNEL);
if (charptr_tmp2 == NULL) {
status = -ENOMEM;
break;
}
for (i = 0; i < long_count; ++i) {
if (charptr_tmp[k >> 3] &
(1 << (k & 7)))
charptr_tmp2[i >> 3] |=
(1 << (i & 7));
else
charptr_tmp2[i >> 3] &=
~(1 << (i & 7));
++k;
}
charptr_tmp = charptr_tmp2;
} else if (long_idx != 0)
charptr_tmp = &charptr_tmp[long_idx >> 3];
altera_export_bool_array(name, charptr_tmp,
long_count);
/* free allocated buffer */
if ((long_idx & 7L) != 0)
kfree(charptr_tmp2);
break;
case OP_COPY: {
/*
* Array copy
* ...argument 0 is dest ID
* ...argument 1 is source ID
* ...stack 0 is count
* ...stack 1 is dest index
* ...stack 2 is source index
*/
s32 copy_count;
s32 copy_index;
s32 copy_index2;
s32 destleft;
s32 src_count;
s32 dest_count;
int src_reverse = 0;
int dest_reverse = 0;
if (!altera_check_stack(stack_ptr, 3, &status))
break;
copy_count = stack[--stack_ptr];
copy_index = stack[--stack_ptr];
copy_index2 = stack[--stack_ptr];
reverse = 0;
if (version > 0) {
/*
* stack 0 = source right index
* stack 1 = source left index
* stack 2 = destination right index
* stack 3 = destination left index
*/
destleft = stack[--stack_ptr];
if (copy_count > copy_index) {
src_reverse = 1;
reverse = 1;
src_count = 1 + copy_count - copy_index;
/* copy_index = source start index */
} else {
src_count = 1 + copy_index - copy_count;
/* source start index */
copy_index = copy_count;
}
if (copy_index2 > destleft) {
dest_reverse = 1;
reverse = !reverse;
dest_count = 1 + copy_index2 - destleft;
/* destination start index */
copy_index2 = destleft;
} else
dest_count = 1 + destleft - copy_index2;
copy_count = (src_count < dest_count) ?
src_count : dest_count;
if ((src_reverse || dest_reverse) &&
(src_count != dest_count))
/*
* If either the source or destination
* is reversed, we can't tolerate
* a length mismatch, because we
* "left justify" arrays when copying.
* This won't work correctly
* with reversed arrays.
*/
status = -ERANGE;
}
count = copy_count;
index = copy_index;
index2 = copy_index2;
/*
* If destination is a read-only array,
* allocate a buffer and convert it to a writable array
*/
variable_id = args[1];
if ((version > 0) &&
((attrs[variable_id] & 0x9c) == 0x0c)) {
/* Allocate a writable buffer for this array */
long_tmp =
(var_size[variable_id] + 7L) >> 3L;
charptr_tmp2 = (u8 *)vars[variable_id];
charptr_tmp =
kzalloc(long_tmp, GFP_KERNEL);
vars[variable_id] = (long)charptr_tmp;
if (vars[variable_id] == 0) {
status = -ENOMEM;
break;
}
/* zero the buffer */
for (long_idx = 0L; long_idx < long_tmp;
++long_idx)
charptr_tmp[long_idx] = 0;
/* copy previous contents into buffer */
for (long_idx = 0L;
long_idx < var_size[variable_id];
++long_idx) {
long_idx2 = long_idx;
if (charptr_tmp2[long_idx2 >> 3] &
(1 << (long_idx2 & 7)))
charptr_tmp[long_idx >> 3] |=
(1 << (long_idx & 7));
}
/*
set bit 7 - buffer was dynamically allocated */
attrs[variable_id] |= 0x80;
/* clear bit 2 - variable is writable */
attrs[variable_id] &= ~0x04;
attrs[variable_id] |= 0x01;
}
charptr_tmp = (u8 *)vars[args[1]];
charptr_tmp2 = (u8 *)vars[args[0]];
/* check if destination is a writable Boolean array */
if ((attrs[args[1]] & 0x1c) != 0x08) {
status = -ERANGE;
break;
}
if (count < 1) {
status = -ERANGE;
break;
}
if (reverse)
index2 += (count - 1);
for (i = 0; i < count; ++i) {
if (charptr_tmp2[index >> 3] &
(1 << (index & 7)))
charptr_tmp[index2 >> 3] |=
(1 << (index2 & 7));
else
charptr_tmp[index2 >> 3] &=
~(1 << (index2 & 7));
++index;
if (reverse)
--index2;
else
++index2;
}
break;
}
case OP_DSC:
case OP_ISC: {
/*
* DRSCAN with capture
* IRSCAN with capture
* ...argument 0 is scan data variable ID
* ...argument 1 is capture variable ID
* ...stack 0 is capture index
* ...stack 1 is scan data index
* ...stack 2 is count
*/
s32 scan_right, scan_left;
s32 capture_count = 0;
s32 scan_count = 0;
s32 capture_index;
s32 scan_index;
if (!altera_check_stack(stack_ptr, 3, &status))
break;
capture_index = stack[--stack_ptr];
scan_index = stack[--stack_ptr];
if (version > 0) {
/*
* stack 0 = capture right index
* stack 1 = capture left index
* stack 2 = scan right index
* stack 3 = scan left index
* stack 4 = count
*/
scan_right = stack[--stack_ptr];
scan_left = stack[--stack_ptr];
capture_count = 1 + scan_index - capture_index;
scan_count = 1 + scan_left - scan_right;
scan_index = scan_right;
}
long_count = stack[--stack_ptr];
/*
* If capture array is read-only, allocate a buffer
* and convert it to a writable array
*/
variable_id = args[1];
if ((version > 0) &&
((attrs[variable_id] & 0x9c) == 0x0c)) {
/* Allocate a writable buffer for this array */
long_tmp =
(var_size[variable_id] + 7L) >> 3L;
charptr_tmp2 = (u8 *)vars[variable_id];
charptr_tmp =
kzalloc(long_tmp, GFP_KERNEL);
vars[variable_id] = (long)charptr_tmp;
if (vars[variable_id] == 0) {
status = -ENOMEM;
break;
}
/* zero the buffer */
for (long_idx = 0L; long_idx < long_tmp;
++long_idx)
charptr_tmp[long_idx] = 0;
/* copy previous contents into buffer */
for (long_idx = 0L;
long_idx < var_size[variable_id];
++long_idx) {
long_idx2 = long_idx;
if (charptr_tmp2[long_idx2 >> 3] &
(1 << (long_idx2 & 7)))
charptr_tmp[long_idx >> 3] |=
(1 << (long_idx & 7));
}
/*
* set bit 7 - buffer was
* dynamically allocated
*/
attrs[variable_id] |= 0x80;
/* clear bit 2 - variable is writable */
attrs[variable_id] &= ~0x04;
attrs[variable_id] |= 0x01;
}
charptr_tmp = (u8 *)vars[args[0]];
charptr_tmp2 = (u8 *)vars[args[1]];
if ((version > 0) &&
((long_count > capture_count) ||
(long_count > scan_count))) {
status = -ERANGE;
break;
}
/*
* check that capture array
* is a writable Boolean array
*/
if ((attrs[args[1]] & 0x1c) != 0x08) {
status = -ERANGE;
break;
}
if (status == 0) {
if (opcode == 0x82) /* DSC */
status = altera_swap_dr(astate,
long_count,
charptr_tmp,
scan_index,
charptr_tmp2,
capture_index);
else /* ISC */
status = altera_swap_ir(astate,
long_count,
charptr_tmp,
scan_index,
charptr_tmp2,
capture_index);
}
break;
}
case OP_WAIT:
/*
* WAIT
* ...argument 0 is wait state
* ...argument 1 is end state
* ...stack 0 is cycles
* ...stack 1 is microseconds
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
long_tmp = stack[--stack_ptr];
if (long_tmp != 0L)
status = altera_wait_cycles(astate, long_tmp,
args[0]);
long_tmp = stack[--stack_ptr];
if ((status == 0) && (long_tmp != 0L))
status = altera_wait_msecs(astate,
long_tmp,
args[0]);
if ((status == 0) && (args[1] != args[0]))
status = altera_goto_jstate(astate,
args[1]);
if (version > 0) {
--stack_ptr; /* throw away MAX cycles */
--stack_ptr; /* throw away MAX microseconds */
}
break;
case OP_CMPA: {
/*
* Array compare
* ...argument 0 is source 1 ID
* ...argument 1 is source 2 ID
* ...argument 2 is mask ID
* ...stack 0 is source 1 index
* ...stack 1 is source 2 index
* ...stack 2 is mask index
* ...stack 3 is count
*/
s32 a, b;
u8 *source1 = (u8 *)vars[args[0]];
u8 *source2 = (u8 *)vars[args[1]];
u8 *mask = (u8 *)vars[args[2]];
u32 index1;
u32 index2;
u32 mask_index;
if (!altera_check_stack(stack_ptr, 4, &status))
break;
index1 = stack[--stack_ptr];
index2 = stack[--stack_ptr];
mask_index = stack[--stack_ptr];
long_count = stack[--stack_ptr];
if (version > 0) {
/*
* stack 0 = source 1 right index
* stack 1 = source 1 left index
* stack 2 = source 2 right index
* stack 3 = source 2 left index
* stack 4 = mask right index
* stack 5 = mask left index
*/
s32 mask_right = stack[--stack_ptr];
s32 mask_left = stack[--stack_ptr];
/* source 1 count */
a = 1 + index2 - index1;
/* source 2 count */
b = 1 + long_count - mask_index;
a = (a < b) ? a : b;
/* mask count */
b = 1 + mask_left - mask_right;
a = (a < b) ? a : b;
/* source 2 start index */
index2 = mask_index;
/* mask start index */
mask_index = mask_right;
long_count = a;
}
long_tmp = 1L;
if (long_count < 1)
status = -ERANGE;
else {
count = long_count;
for (i = 0; i < count; ++i) {
if (mask[mask_index >> 3] &
(1 << (mask_index & 7))) {
a = source1[index1 >> 3] &
(1 << (index1 & 7))
? 1 : 0;
b = source2[index2 >> 3] &
(1 << (index2 & 7))
? 1 : 0;
if (a != b) /* failure */
long_tmp = 0L;
}
++index1;
++index2;
++mask_index;
}
}
stack[stack_ptr++] = long_tmp;
break;
}
default:
/* Unrecognized opcode -- ERROR! */
bad_opcode = 1;
break;
}
if (bad_opcode)
status = -ENOSYS;
if ((stack_ptr < 0) || (stack_ptr >= ALTERA_STACK_SIZE))
status = -EOVERFLOW;
if (status != 0) {
done = 1;
*error_address = (s32)(opcode_address - code_sect);
}
}
altera_free_buffers(astate);
/* Free all dynamically allocated arrays */
if ((attrs != NULL) && (vars != NULL))
for (i = 0; i < sym_count; ++i)
if (attrs[i] & 0x80)
kfree((void *)vars[i]);
kfree(vars);
kfree(var_size);
kfree(attrs);
kfree(proc_attributes);
return status;
}
static int altera_get_note(u8 *p, s32 program_size,
s32 *offset, char *key, char *value, int length)
/*
* Gets key and value of NOTE fields in the JBC file.
* Can be called in two modes: if offset pointer is NULL,
* then the function searches for note fields which match
* the key string provided. If offset is not NULL, then
* the function finds the next note field of any key,
* starting at the offset specified by the offset pointer.
* Returns 0 for success, else appropriate error code
*/
{
int status = -ENODATA;
u32 note_strings = 0L;
u32 note_table = 0L;
u32 note_count = 0L;
u32 first_word = 0L;
int version = 0;
int delta = 0;
char *key_ptr;
char *value_ptr;
int i;
/* Read header information */
if (program_size > 52L) {
first_word = get_unaligned_be32(&p[0]);
version = (first_word & 1L);
delta = version * 8;
note_strings = get_unaligned_be32(&p[8 + delta]);
note_table = get_unaligned_be32(&p[12 + delta]);
note_count = get_unaligned_be32(&p[44 + (2 * delta)]);
}
if ((first_word != 0x4A414D00L) && (first_word != 0x4A414D01L))
return -EIO;
if (note_count <= 0L)
return status;
if (offset == NULL) {
/*
* We will search for the first note with a specific key,
* and return only the value
*/
for (i = 0; (i < note_count) &&
(status != 0); ++i) {
key_ptr = &p[note_strings +
get_unaligned_be32(
&p[note_table + (8 * i)])];
if ((strncasecmp(key, key_ptr, strlen(key_ptr)) == 0) &&
(key != NULL)) {
status = 0;
value_ptr = &p[note_strings +
get_unaligned_be32(
&p[note_table + (8 * i) + 4])];
if (value != NULL)
strlcpy(value, value_ptr, length);
}
}
} else {
/*
* We will search for the next note, regardless of the key,
* and return both the value and the key
*/
i = *offset;
if ((i >= 0) && (i < note_count)) {
status = 0;
if (key != NULL)
strlcpy(key, &p[note_strings +
get_unaligned_be32(
&p[note_table + (8 * i)])],
length);
if (value != NULL)
strlcpy(value, &p[note_strings +
get_unaligned_be32(
&p[note_table + (8 * i) + 4])],
length);
*offset = i + 1;
}
}
return status;
}
static int altera_check_crc(u8 *p, s32 program_size)
{
int status = 0;
u16 local_expected = 0,
local_actual = 0,
shift_reg = 0xffff;
int bit, feedback;
u8 databyte;
u32 i;
u32 crc_section = 0L;
u32 first_word = 0L;
int version = 0;
int delta = 0;
if (program_size > 52L) {
first_word = get_unaligned_be32(&p[0]);
version = (first_word & 1L);
delta = version * 8;
crc_section = get_unaligned_be32(&p[32 + delta]);
}
if ((first_word != 0x4A414D00L) && (first_word != 0x4A414D01L))
status = -EIO;
if (crc_section >= program_size)
status = -EIO;
if (status == 0) {
local_expected = (u16)get_unaligned_be16(&p[crc_section]);
for (i = 0; i < crc_section; ++i) {
databyte = p[i];
for (bit = 0; bit < 8; bit++) {
feedback = (databyte ^ shift_reg) & 0x01;
shift_reg >>= 1;
if (feedback)
shift_reg ^= 0x8408;
databyte >>= 1;
}
}
local_actual = (u16)~shift_reg;
if (local_expected != local_actual)
status = -EILSEQ;
}
if (debug || status) {
switch (status) {
case 0:
printk(KERN_INFO "%s: CRC matched: %04x\n", __func__,
local_actual);
break;
case -EILSEQ:
printk(KERN_ERR "%s: CRC mismatch: expected %04x, "
"actual %04x\n", __func__, local_expected,
local_actual);
break;
case -ENODATA:
printk(KERN_ERR "%s: expected CRC not found, "
"actual CRC = %04x\n", __func__,
local_actual);
break;
case -EIO:
printk(KERN_ERR "%s: error: format isn't "
"recognized.\n", __func__);
break;
default:
printk(KERN_ERR "%s: CRC function returned error "
"code %d\n", __func__, status);
break;
}
}
return status;
}
static int altera_get_file_info(u8 *p,
s32 program_size,
int *format_version,
int *action_count,
int *procedure_count)
{
int status = -EIO;
u32 first_word = 0;
int version = 0;
if (program_size <= 52L)
return status;
first_word = get_unaligned_be32(&p[0]);
if ((first_word == 0x4A414D00L) || (first_word == 0x4A414D01L)) {
status = 0;
version = (first_word & 1L);
*format_version = version + 1;
if (version > 0) {
*action_count = get_unaligned_be32(&p[48]);
*procedure_count = get_unaligned_be32(&p[52]);
}
}
return status;
}
static int altera_get_act_info(u8 *p,
s32 program_size,
int index,
char **name,
char **description,
struct altera_procinfo **proc_list)
{
int status = -EIO;
struct altera_procinfo *procptr = NULL;
struct altera_procinfo *tmpptr = NULL;
u32 first_word = 0L;
u32 action_table = 0L;
u32 proc_table = 0L;
u32 str_table = 0L;
u32 note_strings = 0L;
u32 action_count = 0L;
u32 proc_count = 0L;
u32 act_name_id = 0L;
u32 act_desc_id = 0L;
u32 act_proc_id = 0L;
u32 act_proc_name = 0L;
u8 act_proc_attribute = 0;
if (program_size <= 52L)
return status;
/* Read header information */
first_word = get_unaligned_be32(&p[0]);
if (first_word != 0x4A414D01L)
return status;
action_table = get_unaligned_be32(&p[4]);
proc_table = get_unaligned_be32(&p[8]);
str_table = get_unaligned_be32(&p[12]);
note_strings = get_unaligned_be32(&p[16]);
action_count = get_unaligned_be32(&p[48]);
proc_count = get_unaligned_be32(&p[52]);
if (index >= action_count)
return status;
act_name_id = get_unaligned_be32(&p[action_table + (12 * index)]);
act_desc_id = get_unaligned_be32(&p[action_table + (12 * index) + 4]);
act_proc_id = get_unaligned_be32(&p[action_table + (12 * index) + 8]);
*name = &p[str_table + act_name_id];
if (act_desc_id < (note_strings - str_table))
*description = &p[str_table + act_desc_id];
do {
act_proc_name = get_unaligned_be32(
&p[proc_table + (13 * act_proc_id)]);
act_proc_attribute =
(p[proc_table + (13 * act_proc_id) + 8] & 0x03);
procptr =
kzalloc(sizeof(struct altera_procinfo),
GFP_KERNEL);
if (procptr == NULL)
status = -ENOMEM;
else {
procptr->name = &p[str_table + act_proc_name];
procptr->attrs = act_proc_attribute;
procptr->next = NULL;
/* add record to end of linked list */
if (*proc_list == NULL)
*proc_list = procptr;
else {
tmpptr = *proc_list;
while (tmpptr->next != NULL)
tmpptr = tmpptr->next;
tmpptr->next = procptr;
}
}
act_proc_id = get_unaligned_be32(
&p[proc_table + (13 * act_proc_id) + 4]);
} while ((act_proc_id != 0) && (act_proc_id < proc_count));
return status;
}
int altera_init(struct altera_config *config, const struct firmware *fw)
{
struct altera_state *astate = NULL;
struct altera_procinfo *proc_list = NULL;
struct altera_procinfo *procptr = NULL;
char *key = NULL;
char *value = NULL;
char *action_name = NULL;
char *description = NULL;
int exec_result = 0;
int exit_code = 0;
int format_version = 0;
int action_count = 0;
int procedure_count = 0;
int index = 0;
s32 offset = 0L;
s32 error_address = 0L;
int retval = 0;
key = kzalloc(33, GFP_KERNEL);
if (!key) {
retval = -ENOMEM;
goto out;
}
value = kzalloc(257, GFP_KERNEL);
if (!value) {
retval = -ENOMEM;
goto free_key;
}
astate = kzalloc(sizeof(struct altera_state), GFP_KERNEL);
if (!astate) {
retval = -ENOMEM;
goto free_value;
}
astate->config = config;
if (!astate->config->jtag_io) {
dprintk("%s: using byteblaster!\n", __func__);
astate->config->jtag_io = netup_jtag_io_lpt;
}
altera_check_crc((u8 *)fw->data, fw->size);
if (debug) {
altera_get_file_info((u8 *)fw->data, fw->size, &format_version,
&action_count, &procedure_count);
printk(KERN_INFO "%s: File format is %s ByteCode format\n",
__func__, (format_version == 2) ? "Jam STAPL" :
"pre-standardized Jam 1.1");
while (altera_get_note((u8 *)fw->data, fw->size,
&offset, key, value, 256) == 0)
printk(KERN_INFO "%s: NOTE \"%s\" = \"%s\"\n",
__func__, key, value);
}
if (debug && (format_version == 2) && (action_count > 0)) {
printk(KERN_INFO "%s: Actions available:\n", __func__);
for (index = 0; index < action_count; ++index) {
altera_get_act_info((u8 *)fw->data, fw->size,
index, &action_name,
&description,
&proc_list);
if (description == NULL)
printk(KERN_INFO "%s: %s\n",
__func__,
action_name);
else
printk(KERN_INFO "%s: %s \"%s\"\n",
__func__,
action_name,
description);
procptr = proc_list;
while (procptr != NULL) {
if (procptr->attrs != 0)
printk(KERN_INFO "%s: %s (%s)\n",
__func__,
procptr->name,
(procptr->attrs == 1) ?
"optional" : "recommended");
proc_list = procptr->next;
kfree(procptr);
procptr = proc_list;
}
}
printk(KERN_INFO "\n");
}
exec_result = altera_execute(astate, (u8 *)fw->data, fw->size,
&error_address, &exit_code, &format_version);
if (exit_code)
exec_result = -EREMOTEIO;
if ((format_version == 2) && (exec_result == -EINVAL)) {
if (astate->config->action == NULL)
printk(KERN_ERR "%s: error: no action specified for "
"Jam STAPL file.\nprogram terminated.\n",
__func__);
else
printk(KERN_ERR "%s: error: action \"%s\""
" is not supported "
"for this Jam STAPL file.\n"
"Program terminated.\n", __func__,
astate->config->action);
} else if (exec_result)
printk(KERN_ERR "%s: error %d\n", __func__, exec_result);
kfree(astate);
free_value:
kfree(value);
free_key:
kfree(key);
out:
return retval;
}
EXPORT_SYMBOL(altera_init);
| gpl-2.0 |
zarboz/DLXPUL_RELOADED | arch/m68k/platform/68328/ints.c | 4588 | 4291 | /*
* linux/arch/m68knommu/platform/68328/ints.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.
*
* Copyright 1996 Roman Zippel
* Copyright 1999 D. Jeff Dionne <jeff@rt-control.com>
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <asm/traps.h>
#include <asm/io.h>
#include <asm/machdep.h>
#if defined(CONFIG_M68328)
#include <asm/MC68328.h>
#elif defined(CONFIG_M68EZ328)
#include <asm/MC68EZ328.h>
#elif defined(CONFIG_M68VZ328)
#include <asm/MC68VZ328.h>
#endif
/* assembler routines */
asmlinkage void system_call(void);
asmlinkage void buserr(void);
asmlinkage void trap(void);
asmlinkage void trap3(void);
asmlinkage void trap4(void);
asmlinkage void trap5(void);
asmlinkage void trap6(void);
asmlinkage void trap7(void);
asmlinkage void trap8(void);
asmlinkage void trap9(void);
asmlinkage void trap10(void);
asmlinkage void trap11(void);
asmlinkage void trap12(void);
asmlinkage void trap13(void);
asmlinkage void trap14(void);
asmlinkage void trap15(void);
asmlinkage void trap33(void);
asmlinkage void trap34(void);
asmlinkage void trap35(void);
asmlinkage void trap36(void);
asmlinkage void trap37(void);
asmlinkage void trap38(void);
asmlinkage void trap39(void);
asmlinkage void trap40(void);
asmlinkage void trap41(void);
asmlinkage void trap42(void);
asmlinkage void trap43(void);
asmlinkage void trap44(void);
asmlinkage void trap45(void);
asmlinkage void trap46(void);
asmlinkage void trap47(void);
asmlinkage irqreturn_t bad_interrupt(int, void *);
asmlinkage irqreturn_t inthandler(void);
asmlinkage irqreturn_t inthandler1(void);
asmlinkage irqreturn_t inthandler2(void);
asmlinkage irqreturn_t inthandler3(void);
asmlinkage irqreturn_t inthandler4(void);
asmlinkage irqreturn_t inthandler5(void);
asmlinkage irqreturn_t inthandler6(void);
asmlinkage irqreturn_t inthandler7(void);
/* The 68k family did not have a good way to determine the source
* of interrupts until later in the family. The EC000 core does
* not provide the vector number on the stack, we vector everything
* into one vector and look in the blasted mask register...
* This code is designed to be fast, almost constant time, not clean!
*/
void process_int(int vec, struct pt_regs *fp)
{
int irq;
int mask;
unsigned long pend = ISR;
while (pend) {
if (pend & 0x0000ffff) {
if (pend & 0x000000ff) {
if (pend & 0x0000000f) {
mask = 0x00000001;
irq = 0;
} else {
mask = 0x00000010;
irq = 4;
}
} else {
if (pend & 0x00000f00) {
mask = 0x00000100;
irq = 8;
} else {
mask = 0x00001000;
irq = 12;
}
}
} else {
if (pend & 0x00ff0000) {
if (pend & 0x000f0000) {
mask = 0x00010000;
irq = 16;
} else {
mask = 0x00100000;
irq = 20;
}
} else {
if (pend & 0x0f000000) {
mask = 0x01000000;
irq = 24;
} else {
mask = 0x10000000;
irq = 28;
}
}
}
while (! (mask & pend)) {
mask <<=1;
irq++;
}
do_IRQ(irq, fp);
pend &= ~mask;
}
}
static void intc_irq_unmask(struct irq_data *d)
{
IMR &= ~(1 << d->irq);
}
static void intc_irq_mask(struct irq_data *d)
{
IMR |= (1 << d->irq);
}
static struct irq_chip intc_irq_chip = {
.name = "M68K-INTC",
.irq_mask = intc_irq_mask,
.irq_unmask = intc_irq_unmask,
};
/*
* This function should be called during kernel startup to initialize
* the machine vector table.
*/
void __init trap_init(void)
{
int i;
/* set up the vectors */
for (i = 72; i < 256; ++i)
_ramvec[i] = (e_vector) bad_interrupt;
_ramvec[32] = system_call;
_ramvec[65] = (e_vector) inthandler1;
_ramvec[66] = (e_vector) inthandler2;
_ramvec[67] = (e_vector) inthandler3;
_ramvec[68] = (e_vector) inthandler4;
_ramvec[69] = (e_vector) inthandler5;
_ramvec[70] = (e_vector) inthandler6;
_ramvec[71] = (e_vector) inthandler7;
}
void __init init_IRQ(void)
{
int i;
IVR = 0x40; /* Set DragonBall IVR (interrupt base) to 64 */
/* turn off all interrupts */
IMR = ~0;
for (i = 0; (i < NR_IRQS); i++) {
irq_set_chip(i, &intc_irq_chip);
irq_set_handler(i, handle_level_irq);
}
}
| gpl-2.0 |
FG6Q-Dev/android_kernel_quanta_fg6q | arch/arm/mach-omap2/pm-debug.c | 4844 | 6063 | /*
* OMAP Power Management debug routines
*
* Copyright (C) 2005 Texas Instruments, Inc.
* Copyright (C) 2006-2008 Nokia Corporation
*
* Written by:
* Richard Woodruff <r-woodruff2@ti.com>
* Tony Lindgren
* Juha Yrjola
* Amit Kucheria <amit.kucheria@nokia.com>
* Igor Stoppa <igor.stoppa@nokia.com>
* Jouni Hogander
*
* Based on pm.c for omap2
*
* 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/sched.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <plat/clock.h>
#include <plat/board.h>
#include "powerdomain.h"
#include "clockdomain.h"
#include <plat/dmtimer.h>
#include <plat/omap-pm.h>
#include "cm2xxx_3xxx.h"
#include "prm2xxx_3xxx.h"
#include "pm.h"
u32 enable_off_mode;
#ifdef CONFIG_DEBUG_FS
#include <linux/debugfs.h>
#include <linux/seq_file.h>
static int pm_dbg_init_done;
static int pm_dbg_init(void);
enum {
DEBUG_FILE_COUNTERS = 0,
DEBUG_FILE_TIMERS,
};
static const char pwrdm_state_names[][PWRDM_MAX_PWRSTS] = {
"OFF",
"RET",
"INA",
"ON"
};
void pm_dbg_update_time(struct powerdomain *pwrdm, int prev)
{
s64 t;
if (!pm_dbg_init_done)
return ;
/* Update timer for previous state */
t = sched_clock();
pwrdm->state_timer[prev] += t - pwrdm->timer;
pwrdm->timer = t;
}
static int clkdm_dbg_show_counter(struct clockdomain *clkdm, void *user)
{
struct seq_file *s = (struct seq_file *)user;
if (strcmp(clkdm->name, "emu_clkdm") == 0 ||
strcmp(clkdm->name, "wkup_clkdm") == 0 ||
strncmp(clkdm->name, "dpll", 4) == 0)
return 0;
seq_printf(s, "%s->%s (%d)", clkdm->name,
clkdm->pwrdm.ptr->name,
atomic_read(&clkdm->usecount));
seq_printf(s, "\n");
return 0;
}
static int pwrdm_dbg_show_counter(struct powerdomain *pwrdm, void *user)
{
struct seq_file *s = (struct seq_file *)user;
int i;
if (strcmp(pwrdm->name, "emu_pwrdm") == 0 ||
strcmp(pwrdm->name, "wkup_pwrdm") == 0 ||
strncmp(pwrdm->name, "dpll", 4) == 0)
return 0;
if (pwrdm->state != pwrdm_read_pwrst(pwrdm))
printk(KERN_ERR "pwrdm state mismatch(%s) %d != %d\n",
pwrdm->name, pwrdm->state, pwrdm_read_pwrst(pwrdm));
seq_printf(s, "%s (%s)", pwrdm->name,
pwrdm_state_names[pwrdm->state]);
for (i = 0; i < PWRDM_MAX_PWRSTS; i++)
seq_printf(s, ",%s:%d", pwrdm_state_names[i],
pwrdm->state_counter[i]);
seq_printf(s, ",RET-LOGIC-OFF:%d", pwrdm->ret_logic_off_counter);
for (i = 0; i < pwrdm->banks; i++)
seq_printf(s, ",RET-MEMBANK%d-OFF:%d", i + 1,
pwrdm->ret_mem_off_counter[i]);
seq_printf(s, "\n");
return 0;
}
static int pwrdm_dbg_show_timer(struct powerdomain *pwrdm, void *user)
{
struct seq_file *s = (struct seq_file *)user;
int i;
if (strcmp(pwrdm->name, "emu_pwrdm") == 0 ||
strcmp(pwrdm->name, "wkup_pwrdm") == 0 ||
strncmp(pwrdm->name, "dpll", 4) == 0)
return 0;
pwrdm_state_switch(pwrdm);
seq_printf(s, "%s (%s)", pwrdm->name,
pwrdm_state_names[pwrdm->state]);
for (i = 0; i < 4; i++)
seq_printf(s, ",%s:%lld", pwrdm_state_names[i],
pwrdm->state_timer[i]);
seq_printf(s, "\n");
return 0;
}
static int pm_dbg_show_counters(struct seq_file *s, void *unused)
{
pwrdm_for_each(pwrdm_dbg_show_counter, s);
clkdm_for_each(clkdm_dbg_show_counter, s);
return 0;
}
static int pm_dbg_show_timers(struct seq_file *s, void *unused)
{
pwrdm_for_each(pwrdm_dbg_show_timer, s);
return 0;
}
static int pm_dbg_open(struct inode *inode, struct file *file)
{
switch ((int)inode->i_private) {
case DEBUG_FILE_COUNTERS:
return single_open(file, pm_dbg_show_counters,
&inode->i_private);
case DEBUG_FILE_TIMERS:
default:
return single_open(file, pm_dbg_show_timers,
&inode->i_private);
};
}
static const struct file_operations debug_fops = {
.open = pm_dbg_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int pwrdm_suspend_get(void *data, u64 *val)
{
int ret = -EINVAL;
if (cpu_is_omap34xx())
ret = omap3_pm_get_suspend_state((struct powerdomain *)data);
*val = ret;
if (ret >= 0)
return 0;
return *val;
}
static int pwrdm_suspend_set(void *data, u64 val)
{
if (cpu_is_omap34xx())
return omap3_pm_set_suspend_state(
(struct powerdomain *)data, (int)val);
return -EINVAL;
}
DEFINE_SIMPLE_ATTRIBUTE(pwrdm_suspend_fops, pwrdm_suspend_get,
pwrdm_suspend_set, "%llu\n");
static int __init pwrdms_setup(struct powerdomain *pwrdm, void *dir)
{
int i;
s64 t;
struct dentry *d;
t = sched_clock();
for (i = 0; i < 4; i++)
pwrdm->state_timer[i] = 0;
pwrdm->timer = t;
if (strncmp(pwrdm->name, "dpll", 4) == 0)
return 0;
d = debugfs_create_dir(pwrdm->name, (struct dentry *)dir);
if (!(IS_ERR_OR_NULL(d)))
(void) debugfs_create_file("suspend", S_IRUGO|S_IWUSR, d,
(void *)pwrdm, &pwrdm_suspend_fops);
return 0;
}
static int option_get(void *data, u64 *val)
{
u32 *option = data;
*val = *option;
return 0;
}
static int option_set(void *data, u64 val)
{
u32 *option = data;
*option = val;
if (option == &enable_off_mode) {
if (val)
omap_pm_enable_off_mode();
else
omap_pm_disable_off_mode();
if (cpu_is_omap34xx())
omap3_pm_off_mode_enable(val);
}
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(pm_dbg_option_fops, option_get, option_set, "%llu\n");
static int __init pm_dbg_init(void)
{
struct dentry *d;
if (pm_dbg_init_done)
return 0;
d = debugfs_create_dir("pm_debug", NULL);
if (IS_ERR_OR_NULL(d))
return PTR_ERR(d);
(void) debugfs_create_file("count", S_IRUGO,
d, (void *)DEBUG_FILE_COUNTERS, &debug_fops);
(void) debugfs_create_file("time", S_IRUGO,
d, (void *)DEBUG_FILE_TIMERS, &debug_fops);
pwrdm_for_each(pwrdms_setup, (void *)d);
(void) debugfs_create_file("enable_off_mode", S_IRUGO | S_IWUSR, d,
&enable_off_mode, &pm_dbg_option_fops);
pm_dbg_init_done = 1;
return 0;
}
arch_initcall(pm_dbg_init);
#endif
| gpl-2.0 |
ac0ra/huawei-s7-dev | drivers/char/snsc.c | 10732 | 11216 | /*
* SN Platform system controller communication support
*
* 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.
*
* Copyright (C) 2004, 2006 Silicon Graphics, Inc. All rights reserved.
*/
/*
* System controller communication driver
*
* This driver allows a user process to communicate with the system
* controller (a.k.a. "IRouter") network in an SGI SN system.
*/
#include <linux/interrupt.h>
#include <linux/sched.h>
#include <linux/device.h>
#include <linux/poll.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/mutex.h>
#include <asm/sn/io.h>
#include <asm/sn/sn_sal.h>
#include <asm/sn/module.h>
#include <asm/sn/geo.h>
#include <asm/sn/nodepda.h>
#include "snsc.h"
#define SYSCTL_BASENAME "snsc"
#define SCDRV_BUFSZ 2048
#define SCDRV_TIMEOUT 1000
static DEFINE_MUTEX(scdrv_mutex);
static irqreturn_t
scdrv_interrupt(int irq, void *subch_data)
{
struct subch_data_s *sd = subch_data;
unsigned long flags;
int status;
spin_lock_irqsave(&sd->sd_rlock, flags);
spin_lock(&sd->sd_wlock);
status = ia64_sn_irtr_intr(sd->sd_nasid, sd->sd_subch);
if (status > 0) {
if (status & SAL_IROUTER_INTR_RECV) {
wake_up(&sd->sd_rq);
}
if (status & SAL_IROUTER_INTR_XMIT) {
ia64_sn_irtr_intr_disable
(sd->sd_nasid, sd->sd_subch,
SAL_IROUTER_INTR_XMIT);
wake_up(&sd->sd_wq);
}
}
spin_unlock(&sd->sd_wlock);
spin_unlock_irqrestore(&sd->sd_rlock, flags);
return IRQ_HANDLED;
}
/*
* scdrv_open
*
* Reserve a subchannel for system controller communication.
*/
static int
scdrv_open(struct inode *inode, struct file *file)
{
struct sysctl_data_s *scd;
struct subch_data_s *sd;
int rv;
/* look up device info for this device file */
scd = container_of(inode->i_cdev, struct sysctl_data_s, scd_cdev);
/* allocate memory for subchannel data */
sd = kzalloc(sizeof (struct subch_data_s), GFP_KERNEL);
if (sd == NULL) {
printk("%s: couldn't allocate subchannel data\n",
__func__);
return -ENOMEM;
}
/* initialize subch_data_s fields */
sd->sd_nasid = scd->scd_nasid;
sd->sd_subch = ia64_sn_irtr_open(scd->scd_nasid);
if (sd->sd_subch < 0) {
kfree(sd);
printk("%s: couldn't allocate subchannel\n", __func__);
return -EBUSY;
}
spin_lock_init(&sd->sd_rlock);
spin_lock_init(&sd->sd_wlock);
init_waitqueue_head(&sd->sd_rq);
init_waitqueue_head(&sd->sd_wq);
sema_init(&sd->sd_rbs, 1);
sema_init(&sd->sd_wbs, 1);
file->private_data = sd;
/* hook this subchannel up to the system controller interrupt */
mutex_lock(&scdrv_mutex);
rv = request_irq(SGI_UART_VECTOR, scdrv_interrupt,
IRQF_SHARED | IRQF_DISABLED,
SYSCTL_BASENAME, sd);
if (rv) {
ia64_sn_irtr_close(sd->sd_nasid, sd->sd_subch);
kfree(sd);
printk("%s: irq request failed (%d)\n", __func__, rv);
mutex_unlock(&scdrv_mutex);
return -EBUSY;
}
mutex_unlock(&scdrv_mutex);
return 0;
}
/*
* scdrv_release
*
* Release a previously-reserved subchannel.
*/
static int
scdrv_release(struct inode *inode, struct file *file)
{
struct subch_data_s *sd = (struct subch_data_s *) file->private_data;
int rv;
/* free the interrupt */
free_irq(SGI_UART_VECTOR, sd);
/* ask SAL to close the subchannel */
rv = ia64_sn_irtr_close(sd->sd_nasid, sd->sd_subch);
kfree(sd);
return rv;
}
/*
* scdrv_read
*
* Called to read bytes from the open IRouter pipe.
*
*/
static inline int
read_status_check(struct subch_data_s *sd, int *len)
{
return ia64_sn_irtr_recv(sd->sd_nasid, sd->sd_subch, sd->sd_rb, len);
}
static ssize_t
scdrv_read(struct file *file, char __user *buf, size_t count, loff_t *f_pos)
{
int status;
int len;
unsigned long flags;
struct subch_data_s *sd = (struct subch_data_s *) file->private_data;
/* try to get control of the read buffer */
if (down_trylock(&sd->sd_rbs)) {
/* somebody else has it now;
* if we're non-blocking, then exit...
*/
if (file->f_flags & O_NONBLOCK) {
return -EAGAIN;
}
/* ...or if we want to block, then do so here */
if (down_interruptible(&sd->sd_rbs)) {
/* something went wrong with wait */
return -ERESTARTSYS;
}
}
/* anything to read? */
len = CHUNKSIZE;
spin_lock_irqsave(&sd->sd_rlock, flags);
status = read_status_check(sd, &len);
/* if not, and we're blocking I/O, loop */
while (status < 0) {
DECLARE_WAITQUEUE(wait, current);
if (file->f_flags & O_NONBLOCK) {
spin_unlock_irqrestore(&sd->sd_rlock, flags);
up(&sd->sd_rbs);
return -EAGAIN;
}
len = CHUNKSIZE;
set_current_state(TASK_INTERRUPTIBLE);
add_wait_queue(&sd->sd_rq, &wait);
spin_unlock_irqrestore(&sd->sd_rlock, flags);
schedule_timeout(SCDRV_TIMEOUT);
remove_wait_queue(&sd->sd_rq, &wait);
if (signal_pending(current)) {
/* wait was interrupted */
up(&sd->sd_rbs);
return -ERESTARTSYS;
}
spin_lock_irqsave(&sd->sd_rlock, flags);
status = read_status_check(sd, &len);
}
spin_unlock_irqrestore(&sd->sd_rlock, flags);
if (len > 0) {
/* we read something in the last read_status_check(); copy
* it out to user space
*/
if (count < len) {
pr_debug("%s: only accepting %d of %d bytes\n",
__func__, (int) count, len);
}
len = min((int) count, len);
if (copy_to_user(buf, sd->sd_rb, len))
len = -EFAULT;
}
/* release the read buffer and wake anyone who might be
* waiting for it
*/
up(&sd->sd_rbs);
/* return the number of characters read in */
return len;
}
/*
* scdrv_write
*
* Writes a chunk of an IRouter packet (or other system controller data)
* to the system controller.
*
*/
static inline int
write_status_check(struct subch_data_s *sd, int count)
{
return ia64_sn_irtr_send(sd->sd_nasid, sd->sd_subch, sd->sd_wb, count);
}
static ssize_t
scdrv_write(struct file *file, const char __user *buf,
size_t count, loff_t *f_pos)
{
unsigned long flags;
int status;
struct subch_data_s *sd = (struct subch_data_s *) file->private_data;
/* try to get control of the write buffer */
if (down_trylock(&sd->sd_wbs)) {
/* somebody else has it now;
* if we're non-blocking, then exit...
*/
if (file->f_flags & O_NONBLOCK) {
return -EAGAIN;
}
/* ...or if we want to block, then do so here */
if (down_interruptible(&sd->sd_wbs)) {
/* something went wrong with wait */
return -ERESTARTSYS;
}
}
count = min((int) count, CHUNKSIZE);
if (copy_from_user(sd->sd_wb, buf, count)) {
up(&sd->sd_wbs);
return -EFAULT;
}
/* try to send the buffer */
spin_lock_irqsave(&sd->sd_wlock, flags);
status = write_status_check(sd, count);
/* if we failed, and we want to block, then loop */
while (status <= 0) {
DECLARE_WAITQUEUE(wait, current);
if (file->f_flags & O_NONBLOCK) {
spin_unlock(&sd->sd_wlock);
up(&sd->sd_wbs);
return -EAGAIN;
}
set_current_state(TASK_INTERRUPTIBLE);
add_wait_queue(&sd->sd_wq, &wait);
spin_unlock_irqrestore(&sd->sd_wlock, flags);
schedule_timeout(SCDRV_TIMEOUT);
remove_wait_queue(&sd->sd_wq, &wait);
if (signal_pending(current)) {
/* wait was interrupted */
up(&sd->sd_wbs);
return -ERESTARTSYS;
}
spin_lock_irqsave(&sd->sd_wlock, flags);
status = write_status_check(sd, count);
}
spin_unlock_irqrestore(&sd->sd_wlock, flags);
/* release the write buffer and wake anyone who's waiting for it */
up(&sd->sd_wbs);
/* return the number of characters accepted (should be the complete
* "chunk" as requested)
*/
if ((status >= 0) && (status < count)) {
pr_debug("Didn't accept the full chunk; %d of %d\n",
status, (int) count);
}
return status;
}
static unsigned int
scdrv_poll(struct file *file, struct poll_table_struct *wait)
{
unsigned int mask = 0;
int status = 0;
struct subch_data_s *sd = (struct subch_data_s *) file->private_data;
unsigned long flags;
poll_wait(file, &sd->sd_rq, wait);
poll_wait(file, &sd->sd_wq, wait);
spin_lock_irqsave(&sd->sd_rlock, flags);
spin_lock(&sd->sd_wlock);
status = ia64_sn_irtr_intr(sd->sd_nasid, sd->sd_subch);
spin_unlock(&sd->sd_wlock);
spin_unlock_irqrestore(&sd->sd_rlock, flags);
if (status > 0) {
if (status & SAL_IROUTER_INTR_RECV) {
mask |= POLLIN | POLLRDNORM;
}
if (status & SAL_IROUTER_INTR_XMIT) {
mask |= POLLOUT | POLLWRNORM;
}
}
return mask;
}
static const struct file_operations scdrv_fops = {
.owner = THIS_MODULE,
.read = scdrv_read,
.write = scdrv_write,
.poll = scdrv_poll,
.open = scdrv_open,
.release = scdrv_release,
.llseek = noop_llseek,
};
static struct class *snsc_class;
/*
* scdrv_init
*
* Called at boot time to initialize the system controller communication
* facility.
*/
int __init
scdrv_init(void)
{
geoid_t geoid;
cnodeid_t cnode;
char devname[32];
char *devnamep;
struct sysctl_data_s *scd;
void *salbuf;
dev_t first_dev, dev;
nasid_t event_nasid;
if (!ia64_platform_is("sn2"))
return -ENODEV;
event_nasid = ia64_sn_get_console_nasid();
if (alloc_chrdev_region(&first_dev, 0, num_cnodes,
SYSCTL_BASENAME) < 0) {
printk("%s: failed to register SN system controller device\n",
__func__);
return -ENODEV;
}
snsc_class = class_create(THIS_MODULE, SYSCTL_BASENAME);
for (cnode = 0; cnode < num_cnodes; cnode++) {
geoid = cnodeid_get_geoid(cnode);
devnamep = devname;
format_module_id(devnamep, geo_module(geoid),
MODULE_FORMAT_BRIEF);
devnamep = devname + strlen(devname);
sprintf(devnamep, "^%d#%d", geo_slot(geoid),
geo_slab(geoid));
/* allocate sysctl device data */
scd = kzalloc(sizeof (struct sysctl_data_s),
GFP_KERNEL);
if (!scd) {
printk("%s: failed to allocate device info"
"for %s/%s\n", __func__,
SYSCTL_BASENAME, devname);
continue;
}
/* initialize sysctl device data fields */
scd->scd_nasid = cnodeid_to_nasid(cnode);
if (!(salbuf = kmalloc(SCDRV_BUFSZ, GFP_KERNEL))) {
printk("%s: failed to allocate driver buffer"
"(%s%s)\n", __func__,
SYSCTL_BASENAME, devname);
kfree(scd);
continue;
}
if (ia64_sn_irtr_init(scd->scd_nasid, salbuf,
SCDRV_BUFSZ) < 0) {
printk
("%s: failed to initialize SAL for"
" system controller communication"
" (%s/%s): outdated PROM?\n",
__func__, SYSCTL_BASENAME, devname);
kfree(scd);
kfree(salbuf);
continue;
}
dev = first_dev + cnode;
cdev_init(&scd->scd_cdev, &scdrv_fops);
if (cdev_add(&scd->scd_cdev, dev, 1)) {
printk("%s: failed to register system"
" controller device (%s%s)\n",
__func__, SYSCTL_BASENAME, devname);
kfree(scd);
kfree(salbuf);
continue;
}
device_create(snsc_class, NULL, dev, NULL,
"%s", devname);
ia64_sn_irtr_intr_enable(scd->scd_nasid,
0 /*ignored */ ,
SAL_IROUTER_INTR_RECV);
/* on the console nasid, prepare to receive
* system controller environmental events
*/
if(scd->scd_nasid == event_nasid) {
scdrv_event_init(scd);
}
}
return 0;
}
module_init(scdrv_init);
| gpl-2.0 |
dmansfield/linux | fs/sync.c | 749 | 9943 | /*
* High-level sync()-related operations
*/
#include <linux/kernel.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <linux/namei.h>
#include <linux/sched.h>
#include <linux/writeback.h>
#include <linux/syscalls.h>
#include <linux/linkage.h>
#include <linux/pagemap.h>
#include <linux/quotaops.h>
#include <linux/backing-dev.h>
#include "internal.h"
#define VALID_FLAGS (SYNC_FILE_RANGE_WAIT_BEFORE|SYNC_FILE_RANGE_WRITE| \
SYNC_FILE_RANGE_WAIT_AFTER)
/*
* Do the filesystem syncing work. For simple filesystems
* writeback_inodes_sb(sb) just dirties buffers with inodes so we have to
* submit IO for these buffers via __sync_blockdev(). This also speeds up the
* wait == 1 case since in that case write_inode() functions do
* sync_dirty_buffer() and thus effectively write one block at a time.
*/
static int __sync_filesystem(struct super_block *sb, int wait)
{
if (wait)
sync_inodes_sb(sb);
else
writeback_inodes_sb(sb, WB_REASON_SYNC);
if (sb->s_op->sync_fs)
sb->s_op->sync_fs(sb, wait);
return __sync_blockdev(sb->s_bdev, wait);
}
/*
* Write out and wait upon all dirty data associated with this
* superblock. Filesystem data as well as the underlying block
* device. Takes the superblock lock.
*/
int sync_filesystem(struct super_block *sb)
{
int ret;
/*
* We need to be protected against the filesystem going from
* r/o to r/w or vice versa.
*/
WARN_ON(!rwsem_is_locked(&sb->s_umount));
/*
* No point in syncing out anything if the filesystem is read-only.
*/
if (sb->s_flags & MS_RDONLY)
return 0;
ret = __sync_filesystem(sb, 0);
if (ret < 0)
return ret;
return __sync_filesystem(sb, 1);
}
EXPORT_SYMBOL(sync_filesystem);
static void sync_inodes_one_sb(struct super_block *sb, void *arg)
{
if (!(sb->s_flags & MS_RDONLY))
sync_inodes_sb(sb);
}
static void sync_fs_one_sb(struct super_block *sb, void *arg)
{
if (!(sb->s_flags & MS_RDONLY) && sb->s_op->sync_fs)
sb->s_op->sync_fs(sb, *(int *)arg);
}
static void fdatawrite_one_bdev(struct block_device *bdev, void *arg)
{
filemap_fdatawrite(bdev->bd_inode->i_mapping);
}
static void fdatawait_one_bdev(struct block_device *bdev, void *arg)
{
filemap_fdatawait(bdev->bd_inode->i_mapping);
}
/*
* Sync everything. We start by waking flusher threads so that most of
* writeback runs on all devices in parallel. Then we sync all inodes reliably
* which effectively also waits for all flusher threads to finish doing
* writeback. At this point all data is on disk so metadata should be stable
* and we tell filesystems to sync their metadata via ->sync_fs() calls.
* Finally, we writeout all block devices because some filesystems (e.g. ext2)
* just write metadata (such as inodes or bitmaps) to block device page cache
* and do not sync it on their own in ->sync_fs().
*/
SYSCALL_DEFINE0(sync)
{
int nowait = 0, wait = 1;
wakeup_flusher_threads(0, WB_REASON_SYNC);
iterate_supers(sync_inodes_one_sb, NULL);
iterate_supers(sync_fs_one_sb, &nowait);
iterate_supers(sync_fs_one_sb, &wait);
iterate_bdevs(fdatawrite_one_bdev, NULL);
iterate_bdevs(fdatawait_one_bdev, NULL);
if (unlikely(laptop_mode))
laptop_sync_completion();
return 0;
}
static void do_sync_work(struct work_struct *work)
{
int nowait = 0;
/*
* Sync twice to reduce the possibility we skipped some inodes / pages
* because they were temporarily locked
*/
iterate_supers(sync_inodes_one_sb, &nowait);
iterate_supers(sync_fs_one_sb, &nowait);
iterate_bdevs(fdatawrite_one_bdev, NULL);
iterate_supers(sync_inodes_one_sb, &nowait);
iterate_supers(sync_fs_one_sb, &nowait);
iterate_bdevs(fdatawrite_one_bdev, NULL);
printk("Emergency Sync complete\n");
kfree(work);
}
void emergency_sync(void)
{
struct work_struct *work;
work = kmalloc(sizeof(*work), GFP_ATOMIC);
if (work) {
INIT_WORK(work, do_sync_work);
schedule_work(work);
}
}
/*
* sync a single super
*/
SYSCALL_DEFINE1(syncfs, int, fd)
{
struct fd f = fdget(fd);
struct super_block *sb;
int ret;
if (!f.file)
return -EBADF;
sb = f.file->f_path.dentry->d_sb;
down_read(&sb->s_umount);
ret = sync_filesystem(sb);
up_read(&sb->s_umount);
fdput(f);
return ret;
}
/**
* vfs_fsync_range - helper to sync a range of data & metadata to disk
* @file: file to sync
* @start: offset in bytes of the beginning of data range to sync
* @end: offset in bytes of the end of data range (inclusive)
* @datasync: perform only datasync
*
* Write back data in range @start..@end and metadata for @file to disk. If
* @datasync is set only metadata needed to access modified file data is
* written.
*/
int vfs_fsync_range(struct file *file, loff_t start, loff_t end, int datasync)
{
struct inode *inode = file->f_mapping->host;
if (!file->f_op->fsync)
return -EINVAL;
if (!datasync && (inode->i_state & I_DIRTY_TIME)) {
spin_lock(&inode->i_lock);
inode->i_state &= ~I_DIRTY_TIME;
spin_unlock(&inode->i_lock);
mark_inode_dirty_sync(inode);
}
return file->f_op->fsync(file, start, end, datasync);
}
EXPORT_SYMBOL(vfs_fsync_range);
/**
* vfs_fsync - perform a fsync or fdatasync on a file
* @file: file to sync
* @datasync: only perform a fdatasync operation
*
* Write back data and metadata for @file to disk. If @datasync is
* set only metadata needed to access modified file data is written.
*/
int vfs_fsync(struct file *file, int datasync)
{
return vfs_fsync_range(file, 0, LLONG_MAX, datasync);
}
EXPORT_SYMBOL(vfs_fsync);
static int do_fsync(unsigned int fd, int datasync)
{
struct fd f = fdget(fd);
int ret = -EBADF;
if (f.file) {
ret = vfs_fsync(f.file, datasync);
fdput(f);
}
return ret;
}
SYSCALL_DEFINE1(fsync, unsigned int, fd)
{
return do_fsync(fd, 0);
}
SYSCALL_DEFINE1(fdatasync, unsigned int, fd)
{
return do_fsync(fd, 1);
}
/*
* sys_sync_file_range() permits finely controlled syncing over a segment of
* a file in the range offset .. (offset+nbytes-1) inclusive. If nbytes is
* zero then sys_sync_file_range() will operate from offset out to EOF.
*
* The flag bits are:
*
* SYNC_FILE_RANGE_WAIT_BEFORE: wait upon writeout of all pages in the range
* before performing the write.
*
* SYNC_FILE_RANGE_WRITE: initiate writeout of all those dirty pages in the
* range which are not presently under writeback. Note that this may block for
* significant periods due to exhaustion of disk request structures.
*
* SYNC_FILE_RANGE_WAIT_AFTER: wait upon writeout of all pages in the range
* after performing the write.
*
* Useful combinations of the flag bits are:
*
* SYNC_FILE_RANGE_WAIT_BEFORE|SYNC_FILE_RANGE_WRITE: ensures that all pages
* in the range which were dirty on entry to sys_sync_file_range() are placed
* under writeout. This is a start-write-for-data-integrity operation.
*
* SYNC_FILE_RANGE_WRITE: start writeout of all dirty pages in the range which
* are not presently under writeout. This is an asynchronous flush-to-disk
* operation. Not suitable for data integrity operations.
*
* SYNC_FILE_RANGE_WAIT_BEFORE (or SYNC_FILE_RANGE_WAIT_AFTER): wait for
* completion of writeout of all pages in the range. This will be used after an
* earlier SYNC_FILE_RANGE_WAIT_BEFORE|SYNC_FILE_RANGE_WRITE operation to wait
* for that operation to complete and to return the result.
*
* SYNC_FILE_RANGE_WAIT_BEFORE|SYNC_FILE_RANGE_WRITE|SYNC_FILE_RANGE_WAIT_AFTER:
* a traditional sync() operation. This is a write-for-data-integrity operation
* which will ensure that all pages in the range which were dirty on entry to
* sys_sync_file_range() are committed to disk.
*
*
* SYNC_FILE_RANGE_WAIT_BEFORE and SYNC_FILE_RANGE_WAIT_AFTER will detect any
* I/O errors or ENOSPC conditions and will return those to the caller, after
* clearing the EIO and ENOSPC flags in the address_space.
*
* It should be noted that none of these operations write out the file's
* metadata. So unless the application is strictly performing overwrites of
* already-instantiated disk blocks, there are no guarantees here that the data
* will be available after a crash.
*/
SYSCALL_DEFINE4(sync_file_range, int, fd, loff_t, offset, loff_t, nbytes,
unsigned int, flags)
{
int ret;
struct fd f;
struct address_space *mapping;
loff_t endbyte; /* inclusive */
umode_t i_mode;
ret = -EINVAL;
if (flags & ~VALID_FLAGS)
goto out;
endbyte = offset + nbytes;
if ((s64)offset < 0)
goto out;
if ((s64)endbyte < 0)
goto out;
if (endbyte < offset)
goto out;
if (sizeof(pgoff_t) == 4) {
if (offset >= (0x100000000ULL << PAGE_CACHE_SHIFT)) {
/*
* The range starts outside a 32 bit machine's
* pagecache addressing capabilities. Let it "succeed"
*/
ret = 0;
goto out;
}
if (endbyte >= (0x100000000ULL << PAGE_CACHE_SHIFT)) {
/*
* Out to EOF
*/
nbytes = 0;
}
}
if (nbytes == 0)
endbyte = LLONG_MAX;
else
endbyte--; /* inclusive */
ret = -EBADF;
f = fdget(fd);
if (!f.file)
goto out;
i_mode = file_inode(f.file)->i_mode;
ret = -ESPIPE;
if (!S_ISREG(i_mode) && !S_ISBLK(i_mode) && !S_ISDIR(i_mode) &&
!S_ISLNK(i_mode))
goto out_put;
mapping = f.file->f_mapping;
if (!mapping) {
ret = -EINVAL;
goto out_put;
}
ret = 0;
if (flags & SYNC_FILE_RANGE_WAIT_BEFORE) {
ret = filemap_fdatawait_range(mapping, offset, endbyte);
if (ret < 0)
goto out_put;
}
if (flags & SYNC_FILE_RANGE_WRITE) {
ret = filemap_fdatawrite_range(mapping, offset, endbyte);
if (ret < 0)
goto out_put;
}
if (flags & SYNC_FILE_RANGE_WAIT_AFTER)
ret = filemap_fdatawait_range(mapping, offset, endbyte);
out_put:
fdput(f);
out:
return ret;
}
/* It would be nice if people remember that not all the world's an i386
when they introduce new system calls */
SYSCALL_DEFINE4(sync_file_range2, int, fd, unsigned int, flags,
loff_t, offset, loff_t, nbytes)
{
return sys_sync_file_range(fd, offset, nbytes, flags);
}
| gpl-2.0 |
Klozz/XPerience_Kernel_msm8226_mmi_Falcon | net/ipv4/tcp_cong.c | 1517 | 10667 | /*
* Plugable TCP congestion control support and newReno
* congestion control.
* Based on ideas from I/O scheduler suport and Web100.
*
* Copyright (C) 2005 Stephen Hemminger <shemminger@osdl.org>
*/
#define pr_fmt(fmt) "TCP: " fmt
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/types.h>
#include <linux/list.h>
#include <linux/gfp.h>
#include <net/tcp.h>
int sysctl_tcp_max_ssthresh = 0;
static DEFINE_SPINLOCK(tcp_cong_list_lock);
static LIST_HEAD(tcp_cong_list);
/* Simple linear search, don't expect many entries! */
static struct tcp_congestion_ops *tcp_ca_find(const char *name)
{
struct tcp_congestion_ops *e;
list_for_each_entry_rcu(e, &tcp_cong_list, list) {
if (strcmp(e->name, name) == 0)
return e;
}
return NULL;
}
/*
* Attach new congestion control algorithm to the list
* of available options.
*/
int tcp_register_congestion_control(struct tcp_congestion_ops *ca)
{
int ret = 0;
/* all algorithms must implement ssthresh and cong_avoid ops */
if (!ca->ssthresh || !ca->cong_avoid) {
pr_err("%s does not implement required ops\n", ca->name);
return -EINVAL;
}
spin_lock(&tcp_cong_list_lock);
if (tcp_ca_find(ca->name)) {
pr_notice("%s already registered\n", ca->name);
ret = -EEXIST;
} else {
list_add_tail_rcu(&ca->list, &tcp_cong_list);
pr_info("%s registered\n", ca->name);
}
spin_unlock(&tcp_cong_list_lock);
return ret;
}
EXPORT_SYMBOL_GPL(tcp_register_congestion_control);
/*
* Remove congestion control algorithm, called from
* the module's remove function. Module ref counts are used
* to ensure that this can't be done till all sockets using
* that method are closed.
*/
void tcp_unregister_congestion_control(struct tcp_congestion_ops *ca)
{
spin_lock(&tcp_cong_list_lock);
list_del_rcu(&ca->list);
spin_unlock(&tcp_cong_list_lock);
}
EXPORT_SYMBOL_GPL(tcp_unregister_congestion_control);
/* Assign choice of congestion control. */
void tcp_init_congestion_control(struct sock *sk)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_congestion_ops *ca;
/* if no choice made yet assign the current value set as default */
if (icsk->icsk_ca_ops == &tcp_init_congestion_ops) {
rcu_read_lock();
list_for_each_entry_rcu(ca, &tcp_cong_list, list) {
if (try_module_get(ca->owner)) {
icsk->icsk_ca_ops = ca;
break;
}
/* fallback to next available */
}
rcu_read_unlock();
}
if (icsk->icsk_ca_ops->init)
icsk->icsk_ca_ops->init(sk);
}
/* Manage refcounts on socket close. */
void tcp_cleanup_congestion_control(struct sock *sk)
{
struct inet_connection_sock *icsk = inet_csk(sk);
if (icsk->icsk_ca_ops->release)
icsk->icsk_ca_ops->release(sk);
module_put(icsk->icsk_ca_ops->owner);
}
/* Used by sysctl to change default congestion control */
int tcp_set_default_congestion_control(const char *name)
{
struct tcp_congestion_ops *ca;
int ret = -ENOENT;
spin_lock(&tcp_cong_list_lock);
ca = tcp_ca_find(name);
#ifdef CONFIG_MODULES
if (!ca && capable(CAP_NET_ADMIN)) {
spin_unlock(&tcp_cong_list_lock);
request_module("tcp_%s", name);
spin_lock(&tcp_cong_list_lock);
ca = tcp_ca_find(name);
}
#endif
if (ca) {
ca->flags |= TCP_CONG_NON_RESTRICTED; /* default is always allowed */
list_move(&ca->list, &tcp_cong_list);
ret = 0;
}
spin_unlock(&tcp_cong_list_lock);
return ret;
}
/* Set default value from kernel configuration at bootup */
static int __init tcp_congestion_default(void)
{
return tcp_set_default_congestion_control(CONFIG_DEFAULT_TCP_CONG);
}
late_initcall(tcp_congestion_default);
/* Build string with list of available congestion control values */
void tcp_get_available_congestion_control(char *buf, size_t maxlen)
{
struct tcp_congestion_ops *ca;
size_t offs = 0;
rcu_read_lock();
list_for_each_entry_rcu(ca, &tcp_cong_list, list) {
offs += snprintf(buf + offs, maxlen - offs,
"%s%s",
offs == 0 ? "" : " ", ca->name);
}
rcu_read_unlock();
}
/* Get current default congestion control */
void tcp_get_default_congestion_control(char *name)
{
struct tcp_congestion_ops *ca;
/* We will always have reno... */
BUG_ON(list_empty(&tcp_cong_list));
rcu_read_lock();
ca = list_entry(tcp_cong_list.next, struct tcp_congestion_ops, list);
strncpy(name, ca->name, TCP_CA_NAME_MAX);
rcu_read_unlock();
}
/* Built list of non-restricted congestion control values */
void tcp_get_allowed_congestion_control(char *buf, size_t maxlen)
{
struct tcp_congestion_ops *ca;
size_t offs = 0;
*buf = '\0';
rcu_read_lock();
list_for_each_entry_rcu(ca, &tcp_cong_list, list) {
if (!(ca->flags & TCP_CONG_NON_RESTRICTED))
continue;
offs += snprintf(buf + offs, maxlen - offs,
"%s%s",
offs == 0 ? "" : " ", ca->name);
}
rcu_read_unlock();
}
/* Change list of non-restricted congestion control */
int tcp_set_allowed_congestion_control(char *val)
{
struct tcp_congestion_ops *ca;
char *saved_clone, *clone, *name;
int ret = 0;
saved_clone = clone = kstrdup(val, GFP_USER);
if (!clone)
return -ENOMEM;
spin_lock(&tcp_cong_list_lock);
/* pass 1 check for bad entries */
while ((name = strsep(&clone, " ")) && *name) {
ca = tcp_ca_find(name);
if (!ca) {
ret = -ENOENT;
goto out;
}
}
/* pass 2 clear old values */
list_for_each_entry_rcu(ca, &tcp_cong_list, list)
ca->flags &= ~TCP_CONG_NON_RESTRICTED;
/* pass 3 mark as allowed */
while ((name = strsep(&val, " ")) && *name) {
ca = tcp_ca_find(name);
WARN_ON(!ca);
if (ca)
ca->flags |= TCP_CONG_NON_RESTRICTED;
}
out:
spin_unlock(&tcp_cong_list_lock);
kfree(saved_clone);
return ret;
}
/* Change congestion control for socket */
int tcp_set_congestion_control(struct sock *sk, const char *name)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_congestion_ops *ca;
int err = 0;
rcu_read_lock();
ca = tcp_ca_find(name);
/* no change asking for existing value */
if (ca == icsk->icsk_ca_ops)
goto out;
#ifdef CONFIG_MODULES
/* not found attempt to autoload module */
if (!ca && capable(CAP_NET_ADMIN)) {
rcu_read_unlock();
request_module("tcp_%s", name);
rcu_read_lock();
ca = tcp_ca_find(name);
}
#endif
if (!ca)
err = -ENOENT;
else if (!((ca->flags & TCP_CONG_NON_RESTRICTED) || capable(CAP_NET_ADMIN)))
err = -EPERM;
else if (!try_module_get(ca->owner))
err = -EBUSY;
else {
tcp_cleanup_congestion_control(sk);
icsk->icsk_ca_ops = ca;
if (sk->sk_state != TCP_CLOSE && icsk->icsk_ca_ops->init)
icsk->icsk_ca_ops->init(sk);
}
out:
rcu_read_unlock();
return err;
}
/* RFC2861 Check whether we are limited by application or congestion window
* This is the inverse of cwnd check in tcp_tso_should_defer
*/
int tcp_is_cwnd_limited(const struct sock *sk, u32 in_flight)
{
const struct tcp_sock *tp = tcp_sk(sk);
u32 left;
if (in_flight >= tp->snd_cwnd)
return 1;
left = tp->snd_cwnd - in_flight;
if (sk_can_gso(sk) &&
left * sysctl_tcp_tso_win_divisor < tp->snd_cwnd &&
left * tp->mss_cache < sk->sk_gso_max_size &&
left < sk->sk_gso_max_segs)
return 1;
return left <= tcp_max_tso_deferred_mss(tp);
}
EXPORT_SYMBOL_GPL(tcp_is_cwnd_limited);
/*
* Slow start is used when congestion window is less than slow start
* threshold. This version implements the basic RFC2581 version
* and optionally supports:
* RFC3742 Limited Slow Start - growth limited to max_ssthresh
* RFC3465 Appropriate Byte Counting - growth limited by bytes acknowledged
*/
void tcp_slow_start(struct tcp_sock *tp)
{
int cnt; /* increase in packets */
/* RFC3465: ABC Slow start
* Increase only after a full MSS of bytes is acked
*
* TCP sender SHOULD increase cwnd by the number of
* previously unacknowledged bytes ACKed by each incoming
* acknowledgment, provided the increase is not more than L
*/
if (sysctl_tcp_abc && tp->bytes_acked < tp->mss_cache)
return;
if (sysctl_tcp_max_ssthresh > 0 && tp->snd_cwnd > sysctl_tcp_max_ssthresh)
cnt = sysctl_tcp_max_ssthresh >> 1; /* limited slow start */
else
cnt = tp->snd_cwnd; /* exponential increase */
/* RFC3465: ABC
* We MAY increase by 2 if discovered delayed ack
*/
if (sysctl_tcp_abc > 1 && tp->bytes_acked >= 2*tp->mss_cache)
cnt <<= 1;
tp->bytes_acked = 0;
tp->snd_cwnd_cnt += cnt;
while (tp->snd_cwnd_cnt >= tp->snd_cwnd) {
tp->snd_cwnd_cnt -= tp->snd_cwnd;
if (tp->snd_cwnd < tp->snd_cwnd_clamp)
tp->snd_cwnd++;
}
}
EXPORT_SYMBOL_GPL(tcp_slow_start);
/* In theory this is tp->snd_cwnd += 1 / tp->snd_cwnd (or alternative w) */
void tcp_cong_avoid_ai(struct tcp_sock *tp, u32 w)
{
if (tp->snd_cwnd_cnt >= w) {
if (tp->snd_cwnd < tp->snd_cwnd_clamp)
tp->snd_cwnd++;
tp->snd_cwnd_cnt = 0;
} else {
tp->snd_cwnd_cnt++;
}
}
EXPORT_SYMBOL_GPL(tcp_cong_avoid_ai);
/*
* TCP Reno congestion control
* This is special case used for fallback as well.
*/
/* This is Jacobson's slow start and congestion avoidance.
* SIGCOMM '88, p. 328.
*/
void tcp_reno_cong_avoid(struct sock *sk, u32 ack, u32 in_flight)
{
struct tcp_sock *tp = tcp_sk(sk);
if (!tcp_is_cwnd_limited(sk, in_flight))
return;
/* In "safe" area, increase. */
if (tp->snd_cwnd <= tp->snd_ssthresh)
tcp_slow_start(tp);
/* In dangerous area, increase slowly. */
else if (sysctl_tcp_abc) {
/* RFC3465: Appropriate Byte Count
* increase once for each full cwnd acked
*/
if (tp->bytes_acked >= tp->snd_cwnd*tp->mss_cache) {
tp->bytes_acked -= tp->snd_cwnd*tp->mss_cache;
if (tp->snd_cwnd < tp->snd_cwnd_clamp)
tp->snd_cwnd++;
}
} else {
tcp_cong_avoid_ai(tp, tp->snd_cwnd);
}
}
EXPORT_SYMBOL_GPL(tcp_reno_cong_avoid);
/* Slow start threshold is half the congestion window (min 2) */
u32 tcp_reno_ssthresh(struct sock *sk)
{
const struct tcp_sock *tp = tcp_sk(sk);
return max(tp->snd_cwnd >> 1U, 2U);
}
EXPORT_SYMBOL_GPL(tcp_reno_ssthresh);
/* Lower bound on congestion window with halving. */
u32 tcp_reno_min_cwnd(const struct sock *sk)
{
const struct tcp_sock *tp = tcp_sk(sk);
return tp->snd_ssthresh/2;
}
EXPORT_SYMBOL_GPL(tcp_reno_min_cwnd);
struct tcp_congestion_ops tcp_reno = {
.flags = TCP_CONG_NON_RESTRICTED,
.name = "reno",
.owner = THIS_MODULE,
.ssthresh = tcp_reno_ssthresh,
.cong_avoid = tcp_reno_cong_avoid,
.min_cwnd = tcp_reno_min_cwnd,
};
/* Initial congestion control used (until SYN)
* really reno under another name so we can tell difference
* during tcp_set_default_congestion_control
*/
struct tcp_congestion_ops tcp_init_congestion_ops = {
.name = "",
.owner = THIS_MODULE,
.ssthresh = tcp_reno_ssthresh,
.cong_avoid = tcp_reno_cong_avoid,
.min_cwnd = tcp_reno_min_cwnd,
};
EXPORT_SYMBOL_GPL(tcp_init_congestion_ops);
| gpl-2.0 |
alwaysadeel/AJ-Kernel | arch/x86/kernel/apic/apic.c | 1517 | 57952 | /*
* Local APIC handling, local APIC timers
*
* (c) 1999, 2000, 2009 Ingo Molnar <mingo@redhat.com>
*
* Fixes
* Maciej W. Rozycki : Bits for genuine 82489DX APICs;
* thanks to Eric Gilmore
* and Rolf G. Tews
* for testing these extensively.
* Maciej W. Rozycki : Various updates and fixes.
* Mikael Pettersson : Power Management for UP-APIC.
* Pavel Machek and
* Mikael Pettersson : PM converted to driver model.
*/
#include <linux/perf_event.h>
#include <linux/kernel_stat.h>
#include <linux/mc146818rtc.h>
#include <linux/acpi_pmtmr.h>
#include <linux/clockchips.h>
#include <linux/interrupt.h>
#include <linux/bootmem.h>
#include <linux/ftrace.h>
#include <linux/ioport.h>
#include <linux/module.h>
#include <linux/syscore_ops.h>
#include <linux/delay.h>
#include <linux/timex.h>
#include <linux/dmar.h>
#include <linux/init.h>
#include <linux/cpu.h>
#include <linux/dmi.h>
#include <linux/smp.h>
#include <linux/mm.h>
#include <asm/perf_event.h>
#include <asm/x86_init.h>
#include <asm/pgalloc.h>
#include <asm/atomic.h>
#include <asm/mpspec.h>
#include <asm/i8253.h>
#include <asm/i8259.h>
#include <asm/proto.h>
#include <asm/apic.h>
#include <asm/io_apic.h>
#include <asm/desc.h>
#include <asm/hpet.h>
#include <asm/idle.h>
#include <asm/mtrr.h>
#include <asm/smp.h>
#include <asm/mce.h>
#include <asm/tsc.h>
#include <asm/hypervisor.h>
unsigned int num_processors;
unsigned disabled_cpus __cpuinitdata;
/* Processor that is doing the boot up */
unsigned int boot_cpu_physical_apicid = -1U;
/*
* The highest APIC ID seen during enumeration.
*/
unsigned int max_physical_apicid;
/*
* Bitmask of physically existing CPUs:
*/
physid_mask_t phys_cpu_present_map;
/*
* Map cpu index to physical APIC ID
*/
DEFINE_EARLY_PER_CPU(u16, x86_cpu_to_apicid, BAD_APICID);
DEFINE_EARLY_PER_CPU(u16, x86_bios_cpu_apicid, BAD_APICID);
EXPORT_EARLY_PER_CPU_SYMBOL(x86_cpu_to_apicid);
EXPORT_EARLY_PER_CPU_SYMBOL(x86_bios_cpu_apicid);
#ifdef CONFIG_X86_32
/*
* On x86_32, the mapping between cpu and logical apicid may vary
* depending on apic in use. The following early percpu variable is
* used for the mapping. This is where the behaviors of x86_64 and 32
* actually diverge. Let's keep it ugly for now.
*/
DEFINE_EARLY_PER_CPU(int, x86_cpu_to_logical_apicid, BAD_APICID);
/*
* Knob to control our willingness to enable the local APIC.
*
* +1=force-enable
*/
static int force_enable_local_apic __initdata;
/*
* APIC command line parameters
*/
static int __init parse_lapic(char *arg)
{
force_enable_local_apic = 1;
return 0;
}
early_param("lapic", parse_lapic);
/* Local APIC was disabled by the BIOS and enabled by the kernel */
static int enabled_via_apicbase;
/*
* Handle interrupt mode configuration register (IMCR).
* This register controls whether the interrupt signals
* that reach the BSP come from the master PIC or from the
* local APIC. Before entering Symmetric I/O Mode, either
* the BIOS or the operating system must switch out of
* PIC Mode by changing the IMCR.
*/
static inline void imcr_pic_to_apic(void)
{
/* select IMCR register */
outb(0x70, 0x22);
/* NMI and 8259 INTR go through APIC */
outb(0x01, 0x23);
}
static inline void imcr_apic_to_pic(void)
{
/* select IMCR register */
outb(0x70, 0x22);
/* NMI and 8259 INTR go directly to BSP */
outb(0x00, 0x23);
}
#endif
#ifdef CONFIG_X86_64
static int apic_calibrate_pmtmr __initdata;
static __init int setup_apicpmtimer(char *s)
{
apic_calibrate_pmtmr = 1;
notsc_setup(NULL);
return 0;
}
__setup("apicpmtimer", setup_apicpmtimer);
#endif
int x2apic_mode;
#ifdef CONFIG_X86_X2APIC
/* x2apic enabled before OS handover */
static int x2apic_preenabled;
static __init int setup_nox2apic(char *str)
{
if (x2apic_enabled()) {
pr_warning("Bios already enabled x2apic, "
"can't enforce nox2apic");
return 0;
}
setup_clear_cpu_cap(X86_FEATURE_X2APIC);
return 0;
}
early_param("nox2apic", setup_nox2apic);
#endif
unsigned long mp_lapic_addr;
int disable_apic;
/* Disable local APIC timer from the kernel commandline or via dmi quirk */
static int disable_apic_timer __initdata;
/* Local APIC timer works in C2 */
int local_apic_timer_c2_ok;
EXPORT_SYMBOL_GPL(local_apic_timer_c2_ok);
int first_system_vector = 0xfe;
/*
* Debug level, exported for io_apic.c
*/
unsigned int apic_verbosity;
int pic_mode;
/* Have we found an MP table */
int smp_found_config;
static struct resource lapic_resource = {
.name = "Local APIC",
.flags = IORESOURCE_MEM | IORESOURCE_BUSY,
};
static unsigned int calibration_result;
static void apic_pm_activate(void);
static unsigned long apic_phys;
/*
* Get the LAPIC version
*/
static inline int lapic_get_version(void)
{
return GET_APIC_VERSION(apic_read(APIC_LVR));
}
/*
* Check, if the APIC is integrated or a separate chip
*/
static inline int lapic_is_integrated(void)
{
#ifdef CONFIG_X86_64
return 1;
#else
return APIC_INTEGRATED(lapic_get_version());
#endif
}
/*
* Check, whether this is a modern or a first generation APIC
*/
static int modern_apic(void)
{
/* AMD systems use old APIC versions, so check the CPU */
if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD &&
boot_cpu_data.x86 >= 0xf)
return 1;
return lapic_get_version() >= 0x14;
}
/*
* right after this call apic become NOOP driven
* so apic->write/read doesn't do anything
*/
static void __init apic_disable(void)
{
pr_info("APIC: switched to apic NOOP\n");
apic = &apic_noop;
}
void native_apic_wait_icr_idle(void)
{
while (apic_read(APIC_ICR) & APIC_ICR_BUSY)
cpu_relax();
}
u32 native_safe_apic_wait_icr_idle(void)
{
u32 send_status;
int timeout;
timeout = 0;
do {
send_status = apic_read(APIC_ICR) & APIC_ICR_BUSY;
if (!send_status)
break;
udelay(100);
} while (timeout++ < 1000);
return send_status;
}
void native_apic_icr_write(u32 low, u32 id)
{
apic_write(APIC_ICR2, SET_APIC_DEST_FIELD(id));
apic_write(APIC_ICR, low);
}
u64 native_apic_icr_read(void)
{
u32 icr1, icr2;
icr2 = apic_read(APIC_ICR2);
icr1 = apic_read(APIC_ICR);
return icr1 | ((u64)icr2 << 32);
}
#ifdef CONFIG_X86_32
/**
* get_physical_broadcast - Get number of physical broadcast IDs
*/
int get_physical_broadcast(void)
{
return modern_apic() ? 0xff : 0xf;
}
#endif
/**
* lapic_get_maxlvt - get the maximum number of local vector table entries
*/
int lapic_get_maxlvt(void)
{
unsigned int v;
v = apic_read(APIC_LVR);
/*
* - we always have APIC integrated on 64bit mode
* - 82489DXs do not report # of LVT entries
*/
return APIC_INTEGRATED(GET_APIC_VERSION(v)) ? GET_APIC_MAXLVT(v) : 2;
}
/*
* Local APIC timer
*/
/* Clock divisor */
#define APIC_DIVISOR 16
/*
* This function sets up the local APIC timer, with a timeout of
* 'clocks' APIC bus clock. During calibration we actually call
* this function twice on the boot CPU, once with a bogus timeout
* value, second time for real. The other (noncalibrating) CPUs
* call this function only once, with the real, calibrated value.
*
* We do reads before writes even if unnecessary, to get around the
* P5 APIC double write bug.
*/
static void __setup_APIC_LVTT(unsigned int clocks, int oneshot, int irqen)
{
unsigned int lvtt_value, tmp_value;
lvtt_value = LOCAL_TIMER_VECTOR;
if (!oneshot)
lvtt_value |= APIC_LVT_TIMER_PERIODIC;
if (!lapic_is_integrated())
lvtt_value |= SET_APIC_TIMER_BASE(APIC_TIMER_BASE_DIV);
if (!irqen)
lvtt_value |= APIC_LVT_MASKED;
apic_write(APIC_LVTT, lvtt_value);
/*
* Divide PICLK by 16
*/
tmp_value = apic_read(APIC_TDCR);
apic_write(APIC_TDCR,
(tmp_value & ~(APIC_TDR_DIV_1 | APIC_TDR_DIV_TMBASE)) |
APIC_TDR_DIV_16);
if (!oneshot)
apic_write(APIC_TMICT, clocks / APIC_DIVISOR);
}
/*
* Setup extended LVT, AMD specific
*
* Software should use the LVT offsets the BIOS provides. The offsets
* are determined by the subsystems using it like those for MCE
* threshold or IBS. On K8 only offset 0 (APIC500) and MCE interrupts
* are supported. Beginning with family 10h at least 4 offsets are
* available.
*
* Since the offsets must be consistent for all cores, we keep track
* of the LVT offsets in software and reserve the offset for the same
* vector also to be used on other cores. An offset is freed by
* setting the entry to APIC_EILVT_MASKED.
*
* If the BIOS is right, there should be no conflicts. Otherwise a
* "[Firmware Bug]: ..." error message is generated. However, if
* software does not properly determines the offsets, it is not
* necessarily a BIOS bug.
*/
static atomic_t eilvt_offsets[APIC_EILVT_NR_MAX];
static inline int eilvt_entry_is_changeable(unsigned int old, unsigned int new)
{
return (old & APIC_EILVT_MASKED)
|| (new == APIC_EILVT_MASKED)
|| ((new & ~APIC_EILVT_MASKED) == old);
}
static unsigned int reserve_eilvt_offset(int offset, unsigned int new)
{
unsigned int rsvd; /* 0: uninitialized */
if (offset >= APIC_EILVT_NR_MAX)
return ~0;
rsvd = atomic_read(&eilvt_offsets[offset]) & ~APIC_EILVT_MASKED;
do {
if (rsvd &&
!eilvt_entry_is_changeable(rsvd, new))
/* may not change if vectors are different */
return rsvd;
rsvd = atomic_cmpxchg(&eilvt_offsets[offset], rsvd, new);
} while (rsvd != new);
return new;
}
/*
* If mask=1, the LVT entry does not generate interrupts while mask=0
* enables the vector. See also the BKDGs. Must be called with
* preemption disabled.
*/
int setup_APIC_eilvt(u8 offset, u8 vector, u8 msg_type, u8 mask)
{
unsigned long reg = APIC_EILVTn(offset);
unsigned int new, old, reserved;
new = (mask << 16) | (msg_type << 8) | vector;
old = apic_read(reg);
reserved = reserve_eilvt_offset(offset, new);
if (reserved != new) {
pr_err(FW_BUG "cpu %d, try to use APIC%lX (LVT offset %d) for "
"vector 0x%x, but the register is already in use for "
"vector 0x%x on another cpu\n",
smp_processor_id(), reg, offset, new, reserved);
return -EINVAL;
}
if (!eilvt_entry_is_changeable(old, new)) {
pr_err(FW_BUG "cpu %d, try to use APIC%lX (LVT offset %d) for "
"vector 0x%x, but the register is already in use for "
"vector 0x%x on this cpu\n",
smp_processor_id(), reg, offset, new, old);
return -EBUSY;
}
apic_write(reg, new);
return 0;
}
EXPORT_SYMBOL_GPL(setup_APIC_eilvt);
/*
* Program the next event, relative to now
*/
static int lapic_next_event(unsigned long delta,
struct clock_event_device *evt)
{
apic_write(APIC_TMICT, delta);
return 0;
}
/*
* Setup the lapic timer in periodic or oneshot mode
*/
static void lapic_timer_setup(enum clock_event_mode mode,
struct clock_event_device *evt)
{
unsigned long flags;
unsigned int v;
/* Lapic used as dummy for broadcast ? */
if (evt->features & CLOCK_EVT_FEAT_DUMMY)
return;
local_irq_save(flags);
switch (mode) {
case CLOCK_EVT_MODE_PERIODIC:
case CLOCK_EVT_MODE_ONESHOT:
__setup_APIC_LVTT(calibration_result,
mode != CLOCK_EVT_MODE_PERIODIC, 1);
break;
case CLOCK_EVT_MODE_UNUSED:
case CLOCK_EVT_MODE_SHUTDOWN:
v = apic_read(APIC_LVTT);
v |= (APIC_LVT_MASKED | LOCAL_TIMER_VECTOR);
apic_write(APIC_LVTT, v);
apic_write(APIC_TMICT, 0);
break;
case CLOCK_EVT_MODE_RESUME:
/* Nothing to do here */
break;
}
local_irq_restore(flags);
}
/*
* Local APIC timer broadcast function
*/
static void lapic_timer_broadcast(const struct cpumask *mask)
{
#ifdef CONFIG_SMP
apic->send_IPI_mask(mask, LOCAL_TIMER_VECTOR);
#endif
}
/*
* The local apic timer can be used for any function which is CPU local.
*/
static struct clock_event_device lapic_clockevent = {
.name = "lapic",
.features = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT
| CLOCK_EVT_FEAT_C3STOP | CLOCK_EVT_FEAT_DUMMY,
.shift = 32,
.set_mode = lapic_timer_setup,
.set_next_event = lapic_next_event,
.broadcast = lapic_timer_broadcast,
.rating = 100,
.irq = -1,
};
static DEFINE_PER_CPU(struct clock_event_device, lapic_events);
/*
* Setup the local APIC timer for this CPU. Copy the initialized values
* of the boot CPU and register the clock event in the framework.
*/
static void __cpuinit setup_APIC_timer(void)
{
struct clock_event_device *levt = &__get_cpu_var(lapic_events);
if (this_cpu_has(X86_FEATURE_ARAT)) {
lapic_clockevent.features &= ~CLOCK_EVT_FEAT_C3STOP;
/* Make LAPIC timer preferrable over percpu HPET */
lapic_clockevent.rating = 150;
}
memcpy(levt, &lapic_clockevent, sizeof(*levt));
levt->cpumask = cpumask_of(smp_processor_id());
clockevents_register_device(levt);
}
/*
* In this functions we calibrate APIC bus clocks to the external timer.
*
* We want to do the calibration only once since we want to have local timer
* irqs syncron. CPUs connected by the same APIC bus have the very same bus
* frequency.
*
* This was previously done by reading the PIT/HPET and waiting for a wrap
* around to find out, that a tick has elapsed. I have a box, where the PIT
* readout is broken, so it never gets out of the wait loop again. This was
* also reported by others.
*
* Monitoring the jiffies value is inaccurate and the clockevents
* infrastructure allows us to do a simple substitution of the interrupt
* handler.
*
* The calibration routine also uses the pm_timer when possible, as the PIT
* happens to run way too slow (factor 2.3 on my VAIO CoreDuo, which goes
* back to normal later in the boot process).
*/
#define LAPIC_CAL_LOOPS (HZ/10)
static __initdata int lapic_cal_loops = -1;
static __initdata long lapic_cal_t1, lapic_cal_t2;
static __initdata unsigned long long lapic_cal_tsc1, lapic_cal_tsc2;
static __initdata unsigned long lapic_cal_pm1, lapic_cal_pm2;
static __initdata unsigned long lapic_cal_j1, lapic_cal_j2;
/*
* Temporary interrupt handler.
*/
static void __init lapic_cal_handler(struct clock_event_device *dev)
{
unsigned long long tsc = 0;
long tapic = apic_read(APIC_TMCCT);
unsigned long pm = acpi_pm_read_early();
if (cpu_has_tsc)
rdtscll(tsc);
switch (lapic_cal_loops++) {
case 0:
lapic_cal_t1 = tapic;
lapic_cal_tsc1 = tsc;
lapic_cal_pm1 = pm;
lapic_cal_j1 = jiffies;
break;
case LAPIC_CAL_LOOPS:
lapic_cal_t2 = tapic;
lapic_cal_tsc2 = tsc;
if (pm < lapic_cal_pm1)
pm += ACPI_PM_OVRRUN;
lapic_cal_pm2 = pm;
lapic_cal_j2 = jiffies;
break;
}
}
static int __init
calibrate_by_pmtimer(long deltapm, long *delta, long *deltatsc)
{
const long pm_100ms = PMTMR_TICKS_PER_SEC / 10;
const long pm_thresh = pm_100ms / 100;
unsigned long mult;
u64 res;
#ifndef CONFIG_X86_PM_TIMER
return -1;
#endif
apic_printk(APIC_VERBOSE, "... PM-Timer delta = %ld\n", deltapm);
/* Check, if the PM timer is available */
if (!deltapm)
return -1;
mult = clocksource_hz2mult(PMTMR_TICKS_PER_SEC, 22);
if (deltapm > (pm_100ms - pm_thresh) &&
deltapm < (pm_100ms + pm_thresh)) {
apic_printk(APIC_VERBOSE, "... PM-Timer result ok\n");
return 0;
}
res = (((u64)deltapm) * mult) >> 22;
do_div(res, 1000000);
pr_warning("APIC calibration not consistent "
"with PM-Timer: %ldms instead of 100ms\n",(long)res);
/* Correct the lapic counter value */
res = (((u64)(*delta)) * pm_100ms);
do_div(res, deltapm);
pr_info("APIC delta adjusted to PM-Timer: "
"%lu (%ld)\n", (unsigned long)res, *delta);
*delta = (long)res;
/* Correct the tsc counter value */
if (cpu_has_tsc) {
res = (((u64)(*deltatsc)) * pm_100ms);
do_div(res, deltapm);
apic_printk(APIC_VERBOSE, "TSC delta adjusted to "
"PM-Timer: %lu (%ld)\n",
(unsigned long)res, *deltatsc);
*deltatsc = (long)res;
}
return 0;
}
static int __init calibrate_APIC_clock(void)
{
struct clock_event_device *levt = &__get_cpu_var(lapic_events);
void (*real_handler)(struct clock_event_device *dev);
unsigned long deltaj;
long delta, deltatsc;
int pm_referenced = 0;
local_irq_disable();
/* Replace the global interrupt handler */
real_handler = global_clock_event->event_handler;
global_clock_event->event_handler = lapic_cal_handler;
/*
* Setup the APIC counter to maximum. There is no way the lapic
* can underflow in the 100ms detection time frame
*/
__setup_APIC_LVTT(0xffffffff, 0, 0);
/* Let the interrupts run */
local_irq_enable();
while (lapic_cal_loops <= LAPIC_CAL_LOOPS)
cpu_relax();
local_irq_disable();
/* Restore the real event handler */
global_clock_event->event_handler = real_handler;
/* Build delta t1-t2 as apic timer counts down */
delta = lapic_cal_t1 - lapic_cal_t2;
apic_printk(APIC_VERBOSE, "... lapic delta = %ld\n", delta);
deltatsc = (long)(lapic_cal_tsc2 - lapic_cal_tsc1);
/* we trust the PM based calibration if possible */
pm_referenced = !calibrate_by_pmtimer(lapic_cal_pm2 - lapic_cal_pm1,
&delta, &deltatsc);
/* Calculate the scaled math multiplication factor */
lapic_clockevent.mult = div_sc(delta, TICK_NSEC * LAPIC_CAL_LOOPS,
lapic_clockevent.shift);
lapic_clockevent.max_delta_ns =
clockevent_delta2ns(0x7FFFFFFF, &lapic_clockevent);
lapic_clockevent.min_delta_ns =
clockevent_delta2ns(0xF, &lapic_clockevent);
calibration_result = (delta * APIC_DIVISOR) / LAPIC_CAL_LOOPS;
apic_printk(APIC_VERBOSE, "..... delta %ld\n", delta);
apic_printk(APIC_VERBOSE, "..... mult: %u\n", lapic_clockevent.mult);
apic_printk(APIC_VERBOSE, "..... calibration result: %u\n",
calibration_result);
if (cpu_has_tsc) {
apic_printk(APIC_VERBOSE, "..... CPU clock speed is "
"%ld.%04ld MHz.\n",
(deltatsc / LAPIC_CAL_LOOPS) / (1000000 / HZ),
(deltatsc / LAPIC_CAL_LOOPS) % (1000000 / HZ));
}
apic_printk(APIC_VERBOSE, "..... host bus clock speed is "
"%u.%04u MHz.\n",
calibration_result / (1000000 / HZ),
calibration_result % (1000000 / HZ));
/*
* Do a sanity check on the APIC calibration result
*/
if (calibration_result < (1000000 / HZ)) {
local_irq_enable();
pr_warning("APIC frequency too slow, disabling apic timer\n");
return -1;
}
levt->features &= ~CLOCK_EVT_FEAT_DUMMY;
/*
* PM timer calibration failed or not turned on
* so lets try APIC timer based calibration
*/
if (!pm_referenced) {
apic_printk(APIC_VERBOSE, "... verify APIC timer\n");
/*
* Setup the apic timer manually
*/
levt->event_handler = lapic_cal_handler;
lapic_timer_setup(CLOCK_EVT_MODE_PERIODIC, levt);
lapic_cal_loops = -1;
/* Let the interrupts run */
local_irq_enable();
while (lapic_cal_loops <= LAPIC_CAL_LOOPS)
cpu_relax();
/* Stop the lapic timer */
lapic_timer_setup(CLOCK_EVT_MODE_SHUTDOWN, levt);
/* Jiffies delta */
deltaj = lapic_cal_j2 - lapic_cal_j1;
apic_printk(APIC_VERBOSE, "... jiffies delta = %lu\n", deltaj);
/* Check, if the jiffies result is consistent */
if (deltaj >= LAPIC_CAL_LOOPS-2 && deltaj <= LAPIC_CAL_LOOPS+2)
apic_printk(APIC_VERBOSE, "... jiffies result ok\n");
else
levt->features |= CLOCK_EVT_FEAT_DUMMY;
} else
local_irq_enable();
if (levt->features & CLOCK_EVT_FEAT_DUMMY) {
pr_warning("APIC timer disabled due to verification failure\n");
return -1;
}
return 0;
}
/*
* Setup the boot APIC
*
* Calibrate and verify the result.
*/
void __init setup_boot_APIC_clock(void)
{
/*
* The local apic timer can be disabled via the kernel
* commandline or from the CPU detection code. Register the lapic
* timer as a dummy clock event source on SMP systems, so the
* broadcast mechanism is used. On UP systems simply ignore it.
*/
if (disable_apic_timer) {
pr_info("Disabling APIC timer\n");
/* No broadcast on UP ! */
if (num_possible_cpus() > 1) {
lapic_clockevent.mult = 1;
setup_APIC_timer();
}
return;
}
apic_printk(APIC_VERBOSE, "Using local APIC timer interrupts.\n"
"calibrating APIC timer ...\n");
if (calibrate_APIC_clock()) {
/* No broadcast on UP ! */
if (num_possible_cpus() > 1)
setup_APIC_timer();
return;
}
/*
* If nmi_watchdog is set to IO_APIC, we need the
* PIT/HPET going. Otherwise register lapic as a dummy
* device.
*/
lapic_clockevent.features &= ~CLOCK_EVT_FEAT_DUMMY;
/* Setup the lapic or request the broadcast */
setup_APIC_timer();
}
void __cpuinit setup_secondary_APIC_clock(void)
{
setup_APIC_timer();
}
/*
* The guts of the apic timer interrupt
*/
static void local_apic_timer_interrupt(void)
{
int cpu = smp_processor_id();
struct clock_event_device *evt = &per_cpu(lapic_events, cpu);
/*
* Normally we should not be here till LAPIC has been initialized but
* in some cases like kdump, its possible that there is a pending LAPIC
* timer interrupt from previous kernel's context and is delivered in
* new kernel the moment interrupts are enabled.
*
* Interrupts are enabled early and LAPIC is setup much later, hence
* its possible that when we get here evt->event_handler is NULL.
* Check for event_handler being NULL and discard the interrupt as
* spurious.
*/
if (!evt->event_handler) {
pr_warning("Spurious LAPIC timer interrupt on cpu %d\n", cpu);
/* Switch it off */
lapic_timer_setup(CLOCK_EVT_MODE_SHUTDOWN, evt);
return;
}
/*
* the NMI deadlock-detector uses this.
*/
inc_irq_stat(apic_timer_irqs);
evt->event_handler(evt);
}
/*
* Local APIC timer interrupt. This is the most natural way for doing
* local interrupts, but local timer interrupts can be emulated by
* broadcast interrupts too. [in case the hw doesn't support APIC timers]
*
* [ if a single-CPU system runs an SMP kernel then we call the local
* interrupt as well. Thus we cannot inline the local irq ... ]
*/
void __irq_entry smp_apic_timer_interrupt(struct pt_regs *regs)
{
struct pt_regs *old_regs = set_irq_regs(regs);
/*
* NOTE! We'd better ACK the irq immediately,
* because timer handling can be slow.
*/
ack_APIC_irq();
/*
* update_process_times() expects us to have done irq_enter().
* Besides, if we don't timer interrupts ignore the global
* interrupt lock, which is the WrongThing (tm) to do.
*/
exit_idle();
irq_enter();
local_apic_timer_interrupt();
irq_exit();
set_irq_regs(old_regs);
}
int setup_profiling_timer(unsigned int multiplier)
{
return -EINVAL;
}
/*
* Local APIC start and shutdown
*/
/**
* clear_local_APIC - shutdown the local APIC
*
* This is called, when a CPU is disabled and before rebooting, so the state of
* the local APIC has no dangling leftovers. Also used to cleanout any BIOS
* leftovers during boot.
*/
void clear_local_APIC(void)
{
int maxlvt;
u32 v;
/* APIC hasn't been mapped yet */
if (!x2apic_mode && !apic_phys)
return;
maxlvt = lapic_get_maxlvt();
/*
* Masking an LVT entry can trigger a local APIC error
* if the vector is zero. Mask LVTERR first to prevent this.
*/
if (maxlvt >= 3) {
v = ERROR_APIC_VECTOR; /* any non-zero vector will do */
apic_write(APIC_LVTERR, v | APIC_LVT_MASKED);
}
/*
* Careful: we have to set masks only first to deassert
* any level-triggered sources.
*/
v = apic_read(APIC_LVTT);
apic_write(APIC_LVTT, v | APIC_LVT_MASKED);
v = apic_read(APIC_LVT0);
apic_write(APIC_LVT0, v | APIC_LVT_MASKED);
v = apic_read(APIC_LVT1);
apic_write(APIC_LVT1, v | APIC_LVT_MASKED);
if (maxlvt >= 4) {
v = apic_read(APIC_LVTPC);
apic_write(APIC_LVTPC, v | APIC_LVT_MASKED);
}
/* lets not touch this if we didn't frob it */
#ifdef CONFIG_X86_THERMAL_VECTOR
if (maxlvt >= 5) {
v = apic_read(APIC_LVTTHMR);
apic_write(APIC_LVTTHMR, v | APIC_LVT_MASKED);
}
#endif
#ifdef CONFIG_X86_MCE_INTEL
if (maxlvt >= 6) {
v = apic_read(APIC_LVTCMCI);
if (!(v & APIC_LVT_MASKED))
apic_write(APIC_LVTCMCI, v | APIC_LVT_MASKED);
}
#endif
/*
* Clean APIC state for other OSs:
*/
apic_write(APIC_LVTT, APIC_LVT_MASKED);
apic_write(APIC_LVT0, APIC_LVT_MASKED);
apic_write(APIC_LVT1, APIC_LVT_MASKED);
if (maxlvt >= 3)
apic_write(APIC_LVTERR, APIC_LVT_MASKED);
if (maxlvt >= 4)
apic_write(APIC_LVTPC, APIC_LVT_MASKED);
/* Integrated APIC (!82489DX) ? */
if (lapic_is_integrated()) {
if (maxlvt > 3)
/* Clear ESR due to Pentium errata 3AP and 11AP */
apic_write(APIC_ESR, 0);
apic_read(APIC_ESR);
}
}
/**
* disable_local_APIC - clear and disable the local APIC
*/
void disable_local_APIC(void)
{
unsigned int value;
/* APIC hasn't been mapped yet */
if (!x2apic_mode && !apic_phys)
return;
clear_local_APIC();
/*
* Disable APIC (implies clearing of registers
* for 82489DX!).
*/
value = apic_read(APIC_SPIV);
value &= ~APIC_SPIV_APIC_ENABLED;
apic_write(APIC_SPIV, value);
#ifdef CONFIG_X86_32
/*
* When LAPIC was disabled by the BIOS and enabled by the kernel,
* restore the disabled state.
*/
if (enabled_via_apicbase) {
unsigned int l, h;
rdmsr(MSR_IA32_APICBASE, l, h);
l &= ~MSR_IA32_APICBASE_ENABLE;
wrmsr(MSR_IA32_APICBASE, l, h);
}
#endif
}
/*
* If Linux enabled the LAPIC against the BIOS default disable it down before
* re-entering the BIOS on shutdown. Otherwise the BIOS may get confused and
* not power-off. Additionally clear all LVT entries before disable_local_APIC
* for the case where Linux didn't enable the LAPIC.
*/
void lapic_shutdown(void)
{
unsigned long flags;
if (!cpu_has_apic && !apic_from_smp_config())
return;
local_irq_save(flags);
#ifdef CONFIG_X86_32
if (!enabled_via_apicbase)
clear_local_APIC();
else
#endif
disable_local_APIC();
local_irq_restore(flags);
}
/*
* This is to verify that we're looking at a real local APIC.
* Check these against your board if the CPUs aren't getting
* started for no apparent reason.
*/
int __init verify_local_APIC(void)
{
unsigned int reg0, reg1;
/*
* The version register is read-only in a real APIC.
*/
reg0 = apic_read(APIC_LVR);
apic_printk(APIC_DEBUG, "Getting VERSION: %x\n", reg0);
apic_write(APIC_LVR, reg0 ^ APIC_LVR_MASK);
reg1 = apic_read(APIC_LVR);
apic_printk(APIC_DEBUG, "Getting VERSION: %x\n", reg1);
/*
* The two version reads above should print the same
* numbers. If the second one is different, then we
* poke at a non-APIC.
*/
if (reg1 != reg0)
return 0;
/*
* Check if the version looks reasonably.
*/
reg1 = GET_APIC_VERSION(reg0);
if (reg1 == 0x00 || reg1 == 0xff)
return 0;
reg1 = lapic_get_maxlvt();
if (reg1 < 0x02 || reg1 == 0xff)
return 0;
/*
* The ID register is read/write in a real APIC.
*/
reg0 = apic_read(APIC_ID);
apic_printk(APIC_DEBUG, "Getting ID: %x\n", reg0);
apic_write(APIC_ID, reg0 ^ apic->apic_id_mask);
reg1 = apic_read(APIC_ID);
apic_printk(APIC_DEBUG, "Getting ID: %x\n", reg1);
apic_write(APIC_ID, reg0);
if (reg1 != (reg0 ^ apic->apic_id_mask))
return 0;
/*
* The next two are just to see if we have sane values.
* They're only really relevant if we're in Virtual Wire
* compatibility mode, but most boxes are anymore.
*/
reg0 = apic_read(APIC_LVT0);
apic_printk(APIC_DEBUG, "Getting LVT0: %x\n", reg0);
reg1 = apic_read(APIC_LVT1);
apic_printk(APIC_DEBUG, "Getting LVT1: %x\n", reg1);
return 1;
}
/**
* sync_Arb_IDs - synchronize APIC bus arbitration IDs
*/
void __init sync_Arb_IDs(void)
{
/*
* Unsupported on P4 - see Intel Dev. Manual Vol. 3, Ch. 8.6.1 And not
* needed on AMD.
*/
if (modern_apic() || boot_cpu_data.x86_vendor == X86_VENDOR_AMD)
return;
/*
* Wait for idle.
*/
apic_wait_icr_idle();
apic_printk(APIC_DEBUG, "Synchronizing Arb IDs.\n");
apic_write(APIC_ICR, APIC_DEST_ALLINC |
APIC_INT_LEVELTRIG | APIC_DM_INIT);
}
/*
* An initial setup of the virtual wire mode.
*/
void __init init_bsp_APIC(void)
{
unsigned int value;
/*
* Don't do the setup now if we have a SMP BIOS as the
* through-I/O-APIC virtual wire mode might be active.
*/
if (smp_found_config || !cpu_has_apic)
return;
/*
* Do not trust the local APIC being empty at bootup.
*/
clear_local_APIC();
/*
* Enable APIC.
*/
value = apic_read(APIC_SPIV);
value &= ~APIC_VECTOR_MASK;
value |= APIC_SPIV_APIC_ENABLED;
#ifdef CONFIG_X86_32
/* This bit is reserved on P4/Xeon and should be cleared */
if ((boot_cpu_data.x86_vendor == X86_VENDOR_INTEL) &&
(boot_cpu_data.x86 == 15))
value &= ~APIC_SPIV_FOCUS_DISABLED;
else
#endif
value |= APIC_SPIV_FOCUS_DISABLED;
value |= SPURIOUS_APIC_VECTOR;
apic_write(APIC_SPIV, value);
/*
* Set up the virtual wire mode.
*/
apic_write(APIC_LVT0, APIC_DM_EXTINT);
value = APIC_DM_NMI;
if (!lapic_is_integrated()) /* 82489DX */
value |= APIC_LVT_LEVEL_TRIGGER;
apic_write(APIC_LVT1, value);
}
static void __cpuinit lapic_setup_esr(void)
{
unsigned int oldvalue, value, maxlvt;
if (!lapic_is_integrated()) {
pr_info("No ESR for 82489DX.\n");
return;
}
if (apic->disable_esr) {
/*
* Something untraceable is creating bad interrupts on
* secondary quads ... for the moment, just leave the
* ESR disabled - we can't do anything useful with the
* errors anyway - mbligh
*/
pr_info("Leaving ESR disabled.\n");
return;
}
maxlvt = lapic_get_maxlvt();
if (maxlvt > 3) /* Due to the Pentium erratum 3AP. */
apic_write(APIC_ESR, 0);
oldvalue = apic_read(APIC_ESR);
/* enables sending errors */
value = ERROR_APIC_VECTOR;
apic_write(APIC_LVTERR, value);
/*
* spec says clear errors after enabling vector.
*/
if (maxlvt > 3)
apic_write(APIC_ESR, 0);
value = apic_read(APIC_ESR);
if (value != oldvalue)
apic_printk(APIC_VERBOSE, "ESR value before enabling "
"vector: 0x%08x after: 0x%08x\n",
oldvalue, value);
}
/**
* setup_local_APIC - setup the local APIC
*
* Used to setup local APIC while initializing BSP or bringin up APs.
* Always called with preemption disabled.
*/
void __cpuinit setup_local_APIC(void)
{
int cpu = smp_processor_id();
unsigned int value, queued;
int i, j, acked = 0;
unsigned long long tsc = 0, ntsc;
long long max_loops = cpu_khz;
if (cpu_has_tsc)
rdtscll(tsc);
if (disable_apic) {
disable_ioapic_support();
return;
}
#ifdef CONFIG_X86_32
/* Pound the ESR really hard over the head with a big hammer - mbligh */
if (lapic_is_integrated() && apic->disable_esr) {
apic_write(APIC_ESR, 0);
apic_write(APIC_ESR, 0);
apic_write(APIC_ESR, 0);
apic_write(APIC_ESR, 0);
}
#endif
perf_events_lapic_init();
/*
* Double-check whether this APIC is really registered.
* This is meaningless in clustered apic mode, so we skip it.
*/
BUG_ON(!apic->apic_id_registered());
/*
* Intel recommends to set DFR, LDR and TPR before enabling
* an APIC. See e.g. "AP-388 82489DX User's Manual" (Intel
* document number 292116). So here it goes...
*/
apic->init_apic_ldr();
#ifdef CONFIG_X86_32
/*
* APIC LDR is initialized. If logical_apicid mapping was
* initialized during get_smp_config(), make sure it matches the
* actual value.
*/
i = early_per_cpu(x86_cpu_to_logical_apicid, cpu);
WARN_ON(i != BAD_APICID && i != logical_smp_processor_id());
/* always use the value from LDR */
early_per_cpu(x86_cpu_to_logical_apicid, cpu) =
logical_smp_processor_id();
/*
* Some NUMA implementations (NUMAQ) don't initialize apicid to
* node mapping during NUMA init. Now that logical apicid is
* guaranteed to be known, give it another chance. This is already
* a bit too late - percpu allocation has already happened without
* proper NUMA affinity.
*/
if (apic->x86_32_numa_cpu_node)
set_apicid_to_node(early_per_cpu(x86_cpu_to_apicid, cpu),
apic->x86_32_numa_cpu_node(cpu));
#endif
/*
* Set Task Priority to 'accept all'. We never change this
* later on.
*/
value = apic_read(APIC_TASKPRI);
value &= ~APIC_TPRI_MASK;
apic_write(APIC_TASKPRI, value);
/*
* After a crash, we no longer service the interrupts and a pending
* interrupt from previous kernel might still have ISR bit set.
*
* Most probably by now CPU has serviced that pending interrupt and
* it might not have done the ack_APIC_irq() because it thought,
* interrupt came from i8259 as ExtInt. LAPIC did not get EOI so it
* does not clear the ISR bit and cpu thinks it has already serivced
* the interrupt. Hence a vector might get locked. It was noticed
* for timer irq (vector 0x31). Issue an extra EOI to clear ISR.
*/
do {
queued = 0;
for (i = APIC_ISR_NR - 1; i >= 0; i--)
queued |= apic_read(APIC_IRR + i*0x10);
for (i = APIC_ISR_NR - 1; i >= 0; i--) {
value = apic_read(APIC_ISR + i*0x10);
for (j = 31; j >= 0; j--) {
if (value & (1<<j)) {
ack_APIC_irq();
acked++;
}
}
}
if (acked > 256) {
printk(KERN_ERR "LAPIC pending interrupts after %d EOI\n",
acked);
break;
}
if (cpu_has_tsc) {
rdtscll(ntsc);
max_loops = (cpu_khz << 10) - (ntsc - tsc);
} else
max_loops--;
} while (queued && max_loops > 0);
WARN_ON(max_loops <= 0);
/*
* Now that we are all set up, enable the APIC
*/
value = apic_read(APIC_SPIV);
value &= ~APIC_VECTOR_MASK;
/*
* Enable APIC
*/
value |= APIC_SPIV_APIC_ENABLED;
#ifdef CONFIG_X86_32
/*
* Some unknown Intel IO/APIC (or APIC) errata is biting us with
* certain networking cards. If high frequency interrupts are
* happening on a particular IOAPIC pin, plus the IOAPIC routing
* entry is masked/unmasked at a high rate as well then sooner or
* later IOAPIC line gets 'stuck', no more interrupts are received
* from the device. If focus CPU is disabled then the hang goes
* away, oh well :-(
*
* [ This bug can be reproduced easily with a level-triggered
* PCI Ne2000 networking cards and PII/PIII processors, dual
* BX chipset. ]
*/
/*
* Actually disabling the focus CPU check just makes the hang less
* frequent as it makes the interrupt distributon model be more
* like LRU than MRU (the short-term load is more even across CPUs).
* See also the comment in end_level_ioapic_irq(). --macro
*/
/*
* - enable focus processor (bit==0)
* - 64bit mode always use processor focus
* so no need to set it
*/
value &= ~APIC_SPIV_FOCUS_DISABLED;
#endif
/*
* Set spurious IRQ vector
*/
value |= SPURIOUS_APIC_VECTOR;
apic_write(APIC_SPIV, value);
/*
* Set up LVT0, LVT1:
*
* set up through-local-APIC on the BP's LINT0. This is not
* strictly necessary in pure symmetric-IO mode, but sometimes
* we delegate interrupts to the 8259A.
*/
/*
* TODO: set up through-local-APIC from through-I/O-APIC? --macro
*/
value = apic_read(APIC_LVT0) & APIC_LVT_MASKED;
if (!cpu && (pic_mode || !value)) {
value = APIC_DM_EXTINT;
apic_printk(APIC_VERBOSE, "enabled ExtINT on CPU#%d\n", cpu);
} else {
value = APIC_DM_EXTINT | APIC_LVT_MASKED;
apic_printk(APIC_VERBOSE, "masked ExtINT on CPU#%d\n", cpu);
}
apic_write(APIC_LVT0, value);
/*
* only the BP should see the LINT1 NMI signal, obviously.
*/
if (!cpu)
value = APIC_DM_NMI;
else
value = APIC_DM_NMI | APIC_LVT_MASKED;
if (!lapic_is_integrated()) /* 82489DX */
value |= APIC_LVT_LEVEL_TRIGGER;
apic_write(APIC_LVT1, value);
#ifdef CONFIG_X86_MCE_INTEL
/* Recheck CMCI information after local APIC is up on CPU #0 */
if (!cpu)
cmci_recheck();
#endif
}
void __cpuinit end_local_APIC_setup(void)
{
lapic_setup_esr();
#ifdef CONFIG_X86_32
{
unsigned int value;
/* Disable the local apic timer */
value = apic_read(APIC_LVTT);
value |= (APIC_LVT_MASKED | LOCAL_TIMER_VECTOR);
apic_write(APIC_LVTT, value);
}
#endif
apic_pm_activate();
}
void __init bsp_end_local_APIC_setup(void)
{
end_local_APIC_setup();
/*
* Now that local APIC setup is completed for BP, configure the fault
* handling for interrupt remapping.
*/
if (intr_remapping_enabled)
enable_drhd_fault_handling();
}
#ifdef CONFIG_X86_X2APIC
void check_x2apic(void)
{
if (x2apic_enabled()) {
pr_info("x2apic enabled by BIOS, switching to x2apic ops\n");
x2apic_preenabled = x2apic_mode = 1;
}
}
void enable_x2apic(void)
{
int msr, msr2;
if (!x2apic_mode)
return;
rdmsr(MSR_IA32_APICBASE, msr, msr2);
if (!(msr & X2APIC_ENABLE)) {
printk_once(KERN_INFO "Enabling x2apic\n");
wrmsr(MSR_IA32_APICBASE, msr | X2APIC_ENABLE, 0);
}
}
#endif /* CONFIG_X86_X2APIC */
int __init enable_IR(void)
{
#ifdef CONFIG_INTR_REMAP
if (!intr_remapping_supported()) {
pr_debug("intr-remapping not supported\n");
return 0;
}
if (!x2apic_preenabled && skip_ioapic_setup) {
pr_info("Skipped enabling intr-remap because of skipping "
"io-apic setup\n");
return 0;
}
if (enable_intr_remapping(x2apic_supported()))
return 0;
pr_info("Enabled Interrupt-remapping\n");
return 1;
#endif
return 0;
}
void __init enable_IR_x2apic(void)
{
unsigned long flags;
int ret, x2apic_enabled = 0;
int dmar_table_init_ret;
dmar_table_init_ret = dmar_table_init();
if (dmar_table_init_ret && !x2apic_supported())
return;
ret = save_ioapic_entries();
if (ret) {
pr_info("Saving IO-APIC state failed: %d\n", ret);
goto out;
}
local_irq_save(flags);
legacy_pic->mask_all();
mask_ioapic_entries();
if (dmar_table_init_ret)
ret = 0;
else
ret = enable_IR();
if (!ret) {
/* IR is required if there is APIC ID > 255 even when running
* under KVM
*/
if (max_physical_apicid > 255 ||
!hypervisor_x2apic_available())
goto nox2apic;
/*
* without IR all CPUs can be addressed by IOAPIC/MSI
* only in physical mode
*/
x2apic_force_phys();
}
x2apic_enabled = 1;
if (x2apic_supported() && !x2apic_mode) {
x2apic_mode = 1;
enable_x2apic();
pr_info("Enabled x2apic\n");
}
nox2apic:
if (!ret) /* IR enabling failed */
restore_ioapic_entries();
legacy_pic->restore_mask();
local_irq_restore(flags);
out:
if (x2apic_enabled)
return;
if (x2apic_preenabled)
panic("x2apic: enabled by BIOS but kernel init failed.");
else if (cpu_has_x2apic)
pr_info("Not enabling x2apic, Intr-remapping init failed.\n");
}
#ifdef CONFIG_X86_64
/*
* Detect and enable local APICs on non-SMP boards.
* Original code written by Keir Fraser.
* On AMD64 we trust the BIOS - if it says no APIC it is likely
* not correctly set up (usually the APIC timer won't work etc.)
*/
static int __init detect_init_APIC(void)
{
if (!cpu_has_apic) {
pr_info("No local APIC present\n");
return -1;
}
mp_lapic_addr = APIC_DEFAULT_PHYS_BASE;
return 0;
}
#else
static int __init apic_verify(void)
{
u32 features, h, l;
/*
* The APIC feature bit should now be enabled
* in `cpuid'
*/
features = cpuid_edx(1);
if (!(features & (1 << X86_FEATURE_APIC))) {
pr_warning("Could not enable APIC!\n");
return -1;
}
set_cpu_cap(&boot_cpu_data, X86_FEATURE_APIC);
mp_lapic_addr = APIC_DEFAULT_PHYS_BASE;
/* The BIOS may have set up the APIC at some other address */
if (boot_cpu_data.x86 >= 6) {
rdmsr(MSR_IA32_APICBASE, l, h);
if (l & MSR_IA32_APICBASE_ENABLE)
mp_lapic_addr = l & MSR_IA32_APICBASE_BASE;
}
pr_info("Found and enabled local APIC!\n");
return 0;
}
int __init apic_force_enable(unsigned long addr)
{
u32 h, l;
if (disable_apic)
return -1;
/*
* Some BIOSes disable the local APIC in the APIC_BASE
* MSR. This can only be done in software for Intel P6 or later
* and AMD K7 (Model > 1) or later.
*/
if (boot_cpu_data.x86 >= 6) {
rdmsr(MSR_IA32_APICBASE, l, h);
if (!(l & MSR_IA32_APICBASE_ENABLE)) {
pr_info("Local APIC disabled by BIOS -- reenabling.\n");
l &= ~MSR_IA32_APICBASE_BASE;
l |= MSR_IA32_APICBASE_ENABLE | addr;
wrmsr(MSR_IA32_APICBASE, l, h);
enabled_via_apicbase = 1;
}
}
return apic_verify();
}
/*
* Detect and initialize APIC
*/
static int __init detect_init_APIC(void)
{
/* Disabled by kernel option? */
if (disable_apic)
return -1;
switch (boot_cpu_data.x86_vendor) {
case X86_VENDOR_AMD:
if ((boot_cpu_data.x86 == 6 && boot_cpu_data.x86_model > 1) ||
(boot_cpu_data.x86 >= 15))
break;
goto no_apic;
case X86_VENDOR_INTEL:
if (boot_cpu_data.x86 == 6 || boot_cpu_data.x86 == 15 ||
(boot_cpu_data.x86 == 5 && cpu_has_apic))
break;
goto no_apic;
default:
goto no_apic;
}
if (!cpu_has_apic) {
/*
* Over-ride BIOS and try to enable the local APIC only if
* "lapic" specified.
*/
if (!force_enable_local_apic) {
pr_info("Local APIC disabled by BIOS -- "
"you can enable it with \"lapic\"\n");
return -1;
}
if (apic_force_enable(APIC_DEFAULT_PHYS_BASE))
return -1;
} else {
if (apic_verify())
return -1;
}
apic_pm_activate();
return 0;
no_apic:
pr_info("No local APIC present or hardware disabled\n");
return -1;
}
#endif
/**
* init_apic_mappings - initialize APIC mappings
*/
void __init init_apic_mappings(void)
{
unsigned int new_apicid;
if (x2apic_mode) {
boot_cpu_physical_apicid = read_apic_id();
return;
}
/* If no local APIC can be found return early */
if (!smp_found_config && detect_init_APIC()) {
/* lets NOP'ify apic operations */
pr_info("APIC: disable apic facility\n");
apic_disable();
} else {
apic_phys = mp_lapic_addr;
/*
* acpi lapic path already maps that address in
* acpi_register_lapic_address()
*/
if (!acpi_lapic && !smp_found_config)
register_lapic_address(apic_phys);
}
/*
* Fetch the APIC ID of the BSP in case we have a
* default configuration (or the MP table is broken).
*/
new_apicid = read_apic_id();
if (boot_cpu_physical_apicid != new_apicid) {
boot_cpu_physical_apicid = new_apicid;
/*
* yeah -- we lie about apic_version
* in case if apic was disabled via boot option
* but it's not a problem for SMP compiled kernel
* since smp_sanity_check is prepared for such a case
* and disable smp mode
*/
apic_version[new_apicid] =
GET_APIC_VERSION(apic_read(APIC_LVR));
}
}
void __init register_lapic_address(unsigned long address)
{
mp_lapic_addr = address;
if (!x2apic_mode) {
set_fixmap_nocache(FIX_APIC_BASE, address);
apic_printk(APIC_VERBOSE, "mapped APIC to %16lx (%16lx)\n",
APIC_BASE, mp_lapic_addr);
}
if (boot_cpu_physical_apicid == -1U) {
boot_cpu_physical_apicid = read_apic_id();
apic_version[boot_cpu_physical_apicid] =
GET_APIC_VERSION(apic_read(APIC_LVR));
}
}
/*
* This initializes the IO-APIC and APIC hardware if this is
* a UP kernel.
*/
int apic_version[MAX_LOCAL_APIC];
int __init APIC_init_uniprocessor(void)
{
if (disable_apic) {
pr_info("Apic disabled\n");
return -1;
}
#ifdef CONFIG_X86_64
if (!cpu_has_apic) {
disable_apic = 1;
pr_info("Apic disabled by BIOS\n");
return -1;
}
#else
if (!smp_found_config && !cpu_has_apic)
return -1;
/*
* Complain if the BIOS pretends there is one.
*/
if (!cpu_has_apic &&
APIC_INTEGRATED(apic_version[boot_cpu_physical_apicid])) {
pr_err("BIOS bug, local APIC 0x%x not detected!...\n",
boot_cpu_physical_apicid);
return -1;
}
#endif
default_setup_apic_routing();
verify_local_APIC();
connect_bsp_APIC();
#ifdef CONFIG_X86_64
apic_write(APIC_ID, SET_APIC_ID(boot_cpu_physical_apicid));
#else
/*
* Hack: In case of kdump, after a crash, kernel might be booting
* on a cpu with non-zero lapic id. But boot_cpu_physical_apicid
* might be zero if read from MP tables. Get it from LAPIC.
*/
# ifdef CONFIG_CRASH_DUMP
boot_cpu_physical_apicid = read_apic_id();
# endif
#endif
physid_set_mask_of_physid(boot_cpu_physical_apicid, &phys_cpu_present_map);
setup_local_APIC();
#ifdef CONFIG_X86_IO_APIC
/*
* Now enable IO-APICs, actually call clear_IO_APIC
* We need clear_IO_APIC before enabling error vector
*/
if (!skip_ioapic_setup && nr_ioapics)
enable_IO_APIC();
#endif
bsp_end_local_APIC_setup();
#ifdef CONFIG_X86_IO_APIC
if (smp_found_config && !skip_ioapic_setup && nr_ioapics)
setup_IO_APIC();
else {
nr_ioapics = 0;
}
#endif
x86_init.timers.setup_percpu_clockev();
return 0;
}
/*
* Local APIC interrupts
*/
/*
* This interrupt should _never_ happen with our APIC/SMP architecture
*/
void smp_spurious_interrupt(struct pt_regs *regs)
{
u32 v;
exit_idle();
irq_enter();
/*
* Check if this really is a spurious interrupt and ACK it
* if it is a vectored one. Just in case...
* Spurious interrupts should not be ACKed.
*/
v = apic_read(APIC_ISR + ((SPURIOUS_APIC_VECTOR & ~0x1f) >> 1));
if (v & (1 << (SPURIOUS_APIC_VECTOR & 0x1f)))
ack_APIC_irq();
inc_irq_stat(irq_spurious_count);
/* see sw-dev-man vol 3, chapter 7.4.13.5 */
pr_info("spurious APIC interrupt on CPU#%d, "
"should never happen.\n", smp_processor_id());
irq_exit();
}
/*
* This interrupt should never happen with our APIC/SMP architecture
*/
void smp_error_interrupt(struct pt_regs *regs)
{
u32 v0, v1;
u32 i = 0;
static const char * const error_interrupt_reason[] = {
"Send CS error", /* APIC Error Bit 0 */
"Receive CS error", /* APIC Error Bit 1 */
"Send accept error", /* APIC Error Bit 2 */
"Receive accept error", /* APIC Error Bit 3 */
"Redirectable IPI", /* APIC Error Bit 4 */
"Send illegal vector", /* APIC Error Bit 5 */
"Received illegal vector", /* APIC Error Bit 6 */
"Illegal register address", /* APIC Error Bit 7 */
};
exit_idle();
irq_enter();
/* First tickle the hardware, only then report what went on. -- REW */
v0 = apic_read(APIC_ESR);
apic_write(APIC_ESR, 0);
v1 = apic_read(APIC_ESR);
ack_APIC_irq();
atomic_inc(&irq_err_count);
apic_printk(APIC_DEBUG, KERN_DEBUG "APIC error on CPU%d: %02x(%02x)",
smp_processor_id(), v0 , v1);
v1 = v1 & 0xff;
while (v1) {
if (v1 & 0x1)
apic_printk(APIC_DEBUG, KERN_CONT " : %s", error_interrupt_reason[i]);
i++;
v1 >>= 1;
};
apic_printk(APIC_DEBUG, KERN_CONT "\n");
irq_exit();
}
/**
* connect_bsp_APIC - attach the APIC to the interrupt system
*/
void __init connect_bsp_APIC(void)
{
#ifdef CONFIG_X86_32
if (pic_mode) {
/*
* Do not trust the local APIC being empty at bootup.
*/
clear_local_APIC();
/*
* PIC mode, enable APIC mode in the IMCR, i.e. connect BSP's
* local APIC to INT and NMI lines.
*/
apic_printk(APIC_VERBOSE, "leaving PIC mode, "
"enabling APIC mode.\n");
imcr_pic_to_apic();
}
#endif
if (apic->enable_apic_mode)
apic->enable_apic_mode();
}
/**
* disconnect_bsp_APIC - detach the APIC from the interrupt system
* @virt_wire_setup: indicates, whether virtual wire mode is selected
*
* Virtual wire mode is necessary to deliver legacy interrupts even when the
* APIC is disabled.
*/
void disconnect_bsp_APIC(int virt_wire_setup)
{
unsigned int value;
#ifdef CONFIG_X86_32
if (pic_mode) {
/*
* Put the board back into PIC mode (has an effect only on
* certain older boards). Note that APIC interrupts, including
* IPIs, won't work beyond this point! The only exception are
* INIT IPIs.
*/
apic_printk(APIC_VERBOSE, "disabling APIC mode, "
"entering PIC mode.\n");
imcr_apic_to_pic();
return;
}
#endif
/* Go back to Virtual Wire compatibility mode */
/* For the spurious interrupt use vector F, and enable it */
value = apic_read(APIC_SPIV);
value &= ~APIC_VECTOR_MASK;
value |= APIC_SPIV_APIC_ENABLED;
value |= 0xf;
apic_write(APIC_SPIV, value);
if (!virt_wire_setup) {
/*
* For LVT0 make it edge triggered, active high,
* external and enabled
*/
value = apic_read(APIC_LVT0);
value &= ~(APIC_MODE_MASK | APIC_SEND_PENDING |
APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED);
value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_EXTINT);
apic_write(APIC_LVT0, value);
} else {
/* Disable LVT0 */
apic_write(APIC_LVT0, APIC_LVT_MASKED);
}
/*
* For LVT1 make it edge triggered, active high,
* nmi and enabled
*/
value = apic_read(APIC_LVT1);
value &= ~(APIC_MODE_MASK | APIC_SEND_PENDING |
APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED);
value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_NMI);
apic_write(APIC_LVT1, value);
}
void __cpuinit generic_processor_info(int apicid, int version)
{
int cpu;
if (num_processors >= nr_cpu_ids) {
int max = nr_cpu_ids;
int thiscpu = max + disabled_cpus;
pr_warning(
"ACPI: NR_CPUS/possible_cpus limit of %i reached."
" Processor %d/0x%x ignored.\n", max, thiscpu, apicid);
disabled_cpus++;
return;
}
num_processors++;
if (apicid == boot_cpu_physical_apicid) {
/*
* x86_bios_cpu_apicid is required to have processors listed
* in same order as logical cpu numbers. Hence the first
* entry is BSP, and so on.
* boot_cpu_init() already hold bit 0 in cpu_present_mask
* for BSP.
*/
cpu = 0;
} else
cpu = cpumask_next_zero(-1, cpu_present_mask);
/*
* Validate version
*/
if (version == 0x0) {
pr_warning("BIOS bug: APIC version is 0 for CPU %d/0x%x, fixing up to 0x10\n",
cpu, apicid);
version = 0x10;
}
apic_version[apicid] = version;
if (version != apic_version[boot_cpu_physical_apicid]) {
pr_warning("BIOS bug: APIC version mismatch, boot CPU: %x, CPU %d: version %x\n",
apic_version[boot_cpu_physical_apicid], cpu, version);
}
physid_set(apicid, phys_cpu_present_map);
if (apicid > max_physical_apicid)
max_physical_apicid = apicid;
#if defined(CONFIG_SMP) || defined(CONFIG_X86_64)
early_per_cpu(x86_cpu_to_apicid, cpu) = apicid;
early_per_cpu(x86_bios_cpu_apicid, cpu) = apicid;
#endif
#ifdef CONFIG_X86_32
early_per_cpu(x86_cpu_to_logical_apicid, cpu) =
apic->x86_32_early_logical_apicid(cpu);
#endif
set_cpu_possible(cpu, true);
set_cpu_present(cpu, true);
}
int hard_smp_processor_id(void)
{
return read_apic_id();
}
void default_init_apic_ldr(void)
{
unsigned long val;
apic_write(APIC_DFR, APIC_DFR_VALUE);
val = apic_read(APIC_LDR) & ~APIC_LDR_MASK;
val |= SET_APIC_LOGICAL_ID(1UL << smp_processor_id());
apic_write(APIC_LDR, val);
}
/*
* Power management
*/
#ifdef CONFIG_PM
static struct {
/*
* 'active' is true if the local APIC was enabled by us and
* not the BIOS; this signifies that we are also responsible
* for disabling it before entering apm/acpi suspend
*/
int active;
/* r/w apic fields */
unsigned int apic_id;
unsigned int apic_taskpri;
unsigned int apic_ldr;
unsigned int apic_dfr;
unsigned int apic_spiv;
unsigned int apic_lvtt;
unsigned int apic_lvtpc;
unsigned int apic_lvt0;
unsigned int apic_lvt1;
unsigned int apic_lvterr;
unsigned int apic_tmict;
unsigned int apic_tdcr;
unsigned int apic_thmr;
} apic_pm_state;
static int lapic_suspend(void)
{
unsigned long flags;
int maxlvt;
if (!apic_pm_state.active)
return 0;
maxlvt = lapic_get_maxlvt();
apic_pm_state.apic_id = apic_read(APIC_ID);
apic_pm_state.apic_taskpri = apic_read(APIC_TASKPRI);
apic_pm_state.apic_ldr = apic_read(APIC_LDR);
apic_pm_state.apic_dfr = apic_read(APIC_DFR);
apic_pm_state.apic_spiv = apic_read(APIC_SPIV);
apic_pm_state.apic_lvtt = apic_read(APIC_LVTT);
if (maxlvt >= 4)
apic_pm_state.apic_lvtpc = apic_read(APIC_LVTPC);
apic_pm_state.apic_lvt0 = apic_read(APIC_LVT0);
apic_pm_state.apic_lvt1 = apic_read(APIC_LVT1);
apic_pm_state.apic_lvterr = apic_read(APIC_LVTERR);
apic_pm_state.apic_tmict = apic_read(APIC_TMICT);
apic_pm_state.apic_tdcr = apic_read(APIC_TDCR);
#ifdef CONFIG_X86_THERMAL_VECTOR
if (maxlvt >= 5)
apic_pm_state.apic_thmr = apic_read(APIC_LVTTHMR);
#endif
local_irq_save(flags);
disable_local_APIC();
if (intr_remapping_enabled)
disable_intr_remapping();
local_irq_restore(flags);
return 0;
}
static void lapic_resume(void)
{
unsigned int l, h;
unsigned long flags;
int maxlvt;
if (!apic_pm_state.active)
return;
local_irq_save(flags);
if (intr_remapping_enabled) {
/*
* IO-APIC and PIC have their own resume routines.
* We just mask them here to make sure the interrupt
* subsystem is completely quiet while we enable x2apic
* and interrupt-remapping.
*/
mask_ioapic_entries();
legacy_pic->mask_all();
}
if (x2apic_mode)
enable_x2apic();
else {
/*
* Make sure the APICBASE points to the right address
*
* FIXME! This will be wrong if we ever support suspend on
* SMP! We'll need to do this as part of the CPU restore!
*/
if (boot_cpu_data.x86 >= 6) {
rdmsr(MSR_IA32_APICBASE, l, h);
l &= ~MSR_IA32_APICBASE_BASE;
l |= MSR_IA32_APICBASE_ENABLE | mp_lapic_addr;
wrmsr(MSR_IA32_APICBASE, l, h);
}
}
maxlvt = lapic_get_maxlvt();
apic_write(APIC_LVTERR, ERROR_APIC_VECTOR | APIC_LVT_MASKED);
apic_write(APIC_ID, apic_pm_state.apic_id);
apic_write(APIC_DFR, apic_pm_state.apic_dfr);
apic_write(APIC_LDR, apic_pm_state.apic_ldr);
apic_write(APIC_TASKPRI, apic_pm_state.apic_taskpri);
apic_write(APIC_SPIV, apic_pm_state.apic_spiv);
apic_write(APIC_LVT0, apic_pm_state.apic_lvt0);
apic_write(APIC_LVT1, apic_pm_state.apic_lvt1);
#if defined(CONFIG_X86_MCE_P4THERMAL) || defined(CONFIG_X86_MCE_INTEL)
if (maxlvt >= 5)
apic_write(APIC_LVTTHMR, apic_pm_state.apic_thmr);
#endif
if (maxlvt >= 4)
apic_write(APIC_LVTPC, apic_pm_state.apic_lvtpc);
apic_write(APIC_LVTT, apic_pm_state.apic_lvtt);
apic_write(APIC_TDCR, apic_pm_state.apic_tdcr);
apic_write(APIC_TMICT, apic_pm_state.apic_tmict);
apic_write(APIC_ESR, 0);
apic_read(APIC_ESR);
apic_write(APIC_LVTERR, apic_pm_state.apic_lvterr);
apic_write(APIC_ESR, 0);
apic_read(APIC_ESR);
if (intr_remapping_enabled)
reenable_intr_remapping(x2apic_mode);
local_irq_restore(flags);
}
/*
* This device has no shutdown method - fully functioning local APICs
* are needed on every CPU up until machine_halt/restart/poweroff.
*/
static struct syscore_ops lapic_syscore_ops = {
.resume = lapic_resume,
.suspend = lapic_suspend,
};
static void __cpuinit apic_pm_activate(void)
{
apic_pm_state.active = 1;
}
static int __init init_lapic_sysfs(void)
{
/* XXX: remove suspend/resume procs if !apic_pm_state.active? */
if (cpu_has_apic)
register_syscore_ops(&lapic_syscore_ops);
return 0;
}
/* local apic needs to resume before other devices access its registers. */
core_initcall(init_lapic_sysfs);
#else /* CONFIG_PM */
static void apic_pm_activate(void) { }
#endif /* CONFIG_PM */
#ifdef CONFIG_X86_64
static int __cpuinit apic_cluster_num(void)
{
int i, clusters, zeros;
unsigned id;
u16 *bios_cpu_apicid;
DECLARE_BITMAP(clustermap, NUM_APIC_CLUSTERS);
bios_cpu_apicid = early_per_cpu_ptr(x86_bios_cpu_apicid);
bitmap_zero(clustermap, NUM_APIC_CLUSTERS);
for (i = 0; i < nr_cpu_ids; i++) {
/* are we being called early in kernel startup? */
if (bios_cpu_apicid) {
id = bios_cpu_apicid[i];
} else if (i < nr_cpu_ids) {
if (cpu_present(i))
id = per_cpu(x86_bios_cpu_apicid, i);
else
continue;
} else
break;
if (id != BAD_APICID)
__set_bit(APIC_CLUSTERID(id), clustermap);
}
/* Problem: Partially populated chassis may not have CPUs in some of
* the APIC clusters they have been allocated. Only present CPUs have
* x86_bios_cpu_apicid entries, thus causing zeroes in the bitmap.
* Since clusters are allocated sequentially, count zeros only if
* they are bounded by ones.
*/
clusters = 0;
zeros = 0;
for (i = 0; i < NUM_APIC_CLUSTERS; i++) {
if (test_bit(i, clustermap)) {
clusters += 1 + zeros;
zeros = 0;
} else
++zeros;
}
return clusters;
}
static int __cpuinitdata multi_checked;
static int __cpuinitdata multi;
static int __cpuinit set_multi(const struct dmi_system_id *d)
{
if (multi)
return 0;
pr_info("APIC: %s detected, Multi Chassis\n", d->ident);
multi = 1;
return 0;
}
static const __cpuinitconst struct dmi_system_id multi_dmi_table[] = {
{
.callback = set_multi,
.ident = "IBM System Summit2",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "IBM"),
DMI_MATCH(DMI_PRODUCT_NAME, "Summit2"),
},
},
{}
};
static void __cpuinit dmi_check_multi(void)
{
if (multi_checked)
return;
dmi_check_system(multi_dmi_table);
multi_checked = 1;
}
/*
* apic_is_clustered_box() -- Check if we can expect good TSC
*
* Thus far, the major user of this is IBM's Summit2 series:
* Clustered boxes may have unsynced TSC problems if they are
* multi-chassis.
* Use DMI to check them
*/
__cpuinit int apic_is_clustered_box(void)
{
dmi_check_multi();
if (multi)
return 1;
if (!is_vsmp_box())
return 0;
/*
* ScaleMP vSMPowered boxes have one cluster per board and TSCs are
* not guaranteed to be synced between boards
*/
if (apic_cluster_num() > 1)
return 1;
return 0;
}
#endif
/*
* APIC command line parameters
*/
static int __init setup_disableapic(char *arg)
{
disable_apic = 1;
setup_clear_cpu_cap(X86_FEATURE_APIC);
return 0;
}
early_param("disableapic", setup_disableapic);
/* same as disableapic, for compatibility */
static int __init setup_nolapic(char *arg)
{
return setup_disableapic(arg);
}
early_param("nolapic", setup_nolapic);
static int __init parse_lapic_timer_c2_ok(char *arg)
{
local_apic_timer_c2_ok = 1;
return 0;
}
early_param("lapic_timer_c2_ok", parse_lapic_timer_c2_ok);
static int __init parse_disable_apic_timer(char *arg)
{
disable_apic_timer = 1;
return 0;
}
early_param("noapictimer", parse_disable_apic_timer);
static int __init parse_nolapic_timer(char *arg)
{
disable_apic_timer = 1;
return 0;
}
early_param("nolapic_timer", parse_nolapic_timer);
static int __init apic_set_verbosity(char *arg)
{
if (!arg) {
#ifdef CONFIG_X86_64
skip_ioapic_setup = 0;
return 0;
#endif
return -EINVAL;
}
if (strcmp("debug", arg) == 0)
apic_verbosity = APIC_DEBUG;
else if (strcmp("verbose", arg) == 0)
apic_verbosity = APIC_VERBOSE;
else {
pr_warning("APIC Verbosity level %s not recognised"
" use apic=verbose or apic=debug\n", arg);
return -EINVAL;
}
return 0;
}
early_param("apic", apic_set_verbosity);
static int __init lapic_insert_resource(void)
{
if (!apic_phys)
return -1;
/* Put local APIC into the resource map. */
lapic_resource.start = apic_phys;
lapic_resource.end = lapic_resource.start + PAGE_SIZE - 1;
insert_resource(&iomem_resource, &lapic_resource);
return 0;
}
/*
* need call insert after e820_reserve_resources()
* that is using request_resource
*/
late_initcall(lapic_insert_resource);
| gpl-2.0 |
lovers-fancy/SC-05D_Kernel | kernel/trace/trace_stack.c | 1773 | 7919 | /*
* Copyright (C) 2008 Steven Rostedt <srostedt@redhat.com>
*
*/
#include <linux/stacktrace.h>
#include <linux/kallsyms.h>
#include <linux/seq_file.h>
#include <linux/spinlock.h>
#include <linux/uaccess.h>
#include <linux/debugfs.h>
#include <linux/ftrace.h>
#include <linux/module.h>
#include <linux/sysctl.h>
#include <linux/init.h>
#include <linux/fs.h>
#include "trace.h"
#define STACK_TRACE_ENTRIES 500
static unsigned long stack_dump_trace[STACK_TRACE_ENTRIES+1] =
{ [0 ... (STACK_TRACE_ENTRIES)] = ULONG_MAX };
static unsigned stack_dump_index[STACK_TRACE_ENTRIES];
static struct stack_trace max_stack_trace = {
.max_entries = STACK_TRACE_ENTRIES,
.entries = stack_dump_trace,
};
static unsigned long max_stack_size;
static arch_spinlock_t max_stack_lock =
(arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
static int stack_trace_disabled __read_mostly;
static DEFINE_PER_CPU(int, trace_active);
static DEFINE_MUTEX(stack_sysctl_mutex);
int stack_tracer_enabled;
static int last_stack_tracer_enabled;
static inline void check_stack(void)
{
unsigned long this_size, flags;
unsigned long *p, *top, *start;
int i;
this_size = ((unsigned long)&this_size) & (THREAD_SIZE-1);
this_size = THREAD_SIZE - this_size;
if (this_size <= max_stack_size)
return;
/* we do not handle interrupt stacks yet */
if (!object_is_on_stack(&this_size))
return;
local_irq_save(flags);
arch_spin_lock(&max_stack_lock);
/* a race could have already updated it */
if (this_size <= max_stack_size)
goto out;
max_stack_size = this_size;
max_stack_trace.nr_entries = 0;
max_stack_trace.skip = 3;
save_stack_trace(&max_stack_trace);
/*
* Now find where in the stack these are.
*/
i = 0;
start = &this_size;
top = (unsigned long *)
(((unsigned long)start & ~(THREAD_SIZE-1)) + THREAD_SIZE);
/*
* Loop through all the entries. One of the entries may
* for some reason be missed on the stack, so we may
* have to account for them. If they are all there, this
* loop will only happen once. This code only takes place
* on a new max, so it is far from a fast path.
*/
while (i < max_stack_trace.nr_entries) {
int found = 0;
stack_dump_index[i] = this_size;
p = start;
for (; p < top && i < max_stack_trace.nr_entries; p++) {
if (*p == stack_dump_trace[i]) {
this_size = stack_dump_index[i++] =
(top - p) * sizeof(unsigned long);
found = 1;
/* Start the search from here */
start = p + 1;
}
}
if (!found)
i++;
}
out:
arch_spin_unlock(&max_stack_lock);
local_irq_restore(flags);
}
static void
stack_trace_call(unsigned long ip, unsigned long parent_ip)
{
int cpu;
if (unlikely(!ftrace_enabled || stack_trace_disabled))
return;
preempt_disable_notrace();
cpu = raw_smp_processor_id();
/* no atomic needed, we only modify this variable by this cpu */
if (per_cpu(trace_active, cpu)++ != 0)
goto out;
check_stack();
out:
per_cpu(trace_active, cpu)--;
/* prevent recursion in schedule */
preempt_enable_notrace();
}
static struct ftrace_ops trace_ops __read_mostly =
{
.func = stack_trace_call,
.flags = FTRACE_OPS_FL_GLOBAL,
};
static ssize_t
stack_max_size_read(struct file *filp, char __user *ubuf,
size_t count, loff_t *ppos)
{
unsigned long *ptr = filp->private_data;
char buf[64];
int r;
r = snprintf(buf, sizeof(buf), "%ld\n", *ptr);
if (r > sizeof(buf))
r = sizeof(buf);
return simple_read_from_buffer(ubuf, count, ppos, buf, r);
}
static ssize_t
stack_max_size_write(struct file *filp, const char __user *ubuf,
size_t count, loff_t *ppos)
{
long *ptr = filp->private_data;
unsigned long val, flags;
char buf[64];
int ret;
int cpu;
if (count >= sizeof(buf))
return -EINVAL;
if (copy_from_user(&buf, ubuf, count))
return -EFAULT;
buf[count] = 0;
ret = strict_strtoul(buf, 10, &val);
if (ret < 0)
return ret;
local_irq_save(flags);
/*
* In case we trace inside arch_spin_lock() or after (NMI),
* we will cause circular lock, so we also need to increase
* the percpu trace_active here.
*/
cpu = smp_processor_id();
per_cpu(trace_active, cpu)++;
arch_spin_lock(&max_stack_lock);
*ptr = val;
arch_spin_unlock(&max_stack_lock);
per_cpu(trace_active, cpu)--;
local_irq_restore(flags);
return count;
}
static const struct file_operations stack_max_size_fops = {
.open = tracing_open_generic,
.read = stack_max_size_read,
.write = stack_max_size_write,
.llseek = default_llseek,
};
static void *
__next(struct seq_file *m, loff_t *pos)
{
long n = *pos - 1;
if (n >= max_stack_trace.nr_entries || stack_dump_trace[n] == ULONG_MAX)
return NULL;
m->private = (void *)n;
return &m->private;
}
static void *
t_next(struct seq_file *m, void *v, loff_t *pos)
{
(*pos)++;
return __next(m, pos);
}
static void *t_start(struct seq_file *m, loff_t *pos)
{
int cpu;
local_irq_disable();
cpu = smp_processor_id();
per_cpu(trace_active, cpu)++;
arch_spin_lock(&max_stack_lock);
if (*pos == 0)
return SEQ_START_TOKEN;
return __next(m, pos);
}
static void t_stop(struct seq_file *m, void *p)
{
int cpu;
arch_spin_unlock(&max_stack_lock);
cpu = smp_processor_id();
per_cpu(trace_active, cpu)--;
local_irq_enable();
}
static int trace_lookup_stack(struct seq_file *m, long i)
{
unsigned long addr = stack_dump_trace[i];
return seq_printf(m, "%pS\n", (void *)addr);
}
static void print_disabled(struct seq_file *m)
{
seq_puts(m, "#\n"
"# Stack tracer disabled\n"
"#\n"
"# To enable the stack tracer, either add 'stacktrace' to the\n"
"# kernel command line\n"
"# or 'echo 1 > /proc/sys/kernel/stack_tracer_enabled'\n"
"#\n");
}
static int t_show(struct seq_file *m, void *v)
{
long i;
int size;
if (v == SEQ_START_TOKEN) {
seq_printf(m, " Depth Size Location"
" (%d entries)\n"
" ----- ---- --------\n",
max_stack_trace.nr_entries - 1);
if (!stack_tracer_enabled && !max_stack_size)
print_disabled(m);
return 0;
}
i = *(long *)v;
if (i >= max_stack_trace.nr_entries ||
stack_dump_trace[i] == ULONG_MAX)
return 0;
if (i+1 == max_stack_trace.nr_entries ||
stack_dump_trace[i+1] == ULONG_MAX)
size = stack_dump_index[i];
else
size = stack_dump_index[i] - stack_dump_index[i+1];
seq_printf(m, "%3ld) %8d %5d ", i, stack_dump_index[i], size);
trace_lookup_stack(m, i);
return 0;
}
static const struct seq_operations stack_trace_seq_ops = {
.start = t_start,
.next = t_next,
.stop = t_stop,
.show = t_show,
};
static int stack_trace_open(struct inode *inode, struct file *file)
{
return seq_open(file, &stack_trace_seq_ops);
}
static const struct file_operations stack_trace_fops = {
.open = stack_trace_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
int
stack_trace_sysctl(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int ret;
mutex_lock(&stack_sysctl_mutex);
ret = proc_dointvec(table, write, buffer, lenp, ppos);
if (ret || !write ||
(last_stack_tracer_enabled == !!stack_tracer_enabled))
goto out;
last_stack_tracer_enabled = !!stack_tracer_enabled;
if (stack_tracer_enabled)
register_ftrace_function(&trace_ops);
else
unregister_ftrace_function(&trace_ops);
out:
mutex_unlock(&stack_sysctl_mutex);
return ret;
}
static __init int enable_stacktrace(char *str)
{
stack_tracer_enabled = 1;
last_stack_tracer_enabled = 1;
return 1;
}
__setup("stacktrace", enable_stacktrace);
static __init int stack_trace_init(void)
{
struct dentry *d_tracer;
d_tracer = tracing_init_dentry();
trace_create_file("stack_max_size", 0644, d_tracer,
&max_stack_size, &stack_max_size_fops);
trace_create_file("stack_trace", 0444, d_tracer,
NULL, &stack_trace_fops);
if (stack_tracer_enabled)
register_ftrace_function(&trace_ops);
return 0;
}
device_initcall(stack_trace_init);
| gpl-2.0 |
Constellation/linux-3.10.17 | drivers/net/hamradio/scc.c | 2285 | 55510 | #define RCS_ID "$Id: scc.c,v 1.75 1998/11/04 15:15:01 jreuter Exp jreuter $"
#define VERSION "3.0"
/*
* Please use z8530drv-utils-3.0 with this version.
* ------------------
*
* You can find a subset of the documentation in
* Documentation/networking/z8530drv.txt.
*/
/*
********************************************************************
* SCC.C - Linux driver for Z8530 based HDLC cards for AX.25 *
********************************************************************
********************************************************************
Copyright (c) 1993, 2000 Joerg Reuter DL1BKE
portions (c) 1993 Guido ten Dolle PE1NNZ
********************************************************************
The driver and the programs in the archive are UNDER CONSTRUCTION.
The code is likely to fail, and so your kernel could --- even
a whole network.
This driver is intended for Amateur Radio use. If you are running it
for commercial purposes, please drop me a note. I am nosy...
...BUT:
! You m u s t recognize the appropriate legislations of your country !
! before you connect a radio to the SCC board and start to transmit or !
! receive. The GPL allows you to use the d r i v e r, NOT the RADIO! !
For non-Amateur-Radio use please note that you might need a special
allowance/licence from the designer of the SCC Board and/or the
MODEM.
This program is free software; you can redistribute it and/or modify
it under the terms of the (modified) GNU General Public License
delivered with the Linux kernel source.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should find a copy of the GNU General Public License in
/usr/src/linux/COPYING;
********************************************************************
Incomplete history of z8530drv:
-------------------------------
1994-09-13 started to write the driver, rescued most of my own
code (and Hans Alblas' memory buffer pool concept) from
an earlier project "sccdrv" which was initiated by
Guido ten Dolle. Not much of the old driver survived,
though. The first version I put my hands on was sccdrv1.3
from August 1993. The memory buffer pool concept
appeared in an unauthorized sccdrv version (1.5) from
August 1994.
1995-01-31 changed copyright notice to GPL without limitations.
.
. <SNIP>
.
1996-10-05 New semester, new driver...
* KISS TNC emulator removed (TTY driver)
* Source moved to drivers/net/
* Includes Z8530 defines from drivers/net/z8530.h
* Uses sk_buffer memory management
* Reduced overhead of /proc/net/z8530drv output
* Streamlined quite a lot things
* Invents brand new bugs... ;-)
The move to version number 3.0 reflects theses changes.
You can use 'kissbridge' if you need a KISS TNC emulator.
1996-12-13 Fixed for Linux networking changes. (G4KLX)
1997-01-08 Fixed the remaining problems.
1997-04-02 Hopefully fixed the problems with the new *_timer()
routines, added calibration code.
1997-10-12 Made SCC_DELAY a CONFIG option, added CONFIG_SCC_TRXECHO
1998-01-29 Small fix to avoid lock-up on initialization
1998-09-29 Fixed the "grouping" bugs, tx_inhibit works again,
using dev->tx_queue_len now instead of MAXQUEUE now.
1998-10-21 Postponed the spinlock changes, would need a lot of
testing I currently don't have the time to. Softdcd doesn't
work.
1998-11-04 Softdcd does not work correctly in DPLL mode, in fact it
never did. The DPLL locks on noise, the SYNC unit sees
flags that aren't... Restarting the DPLL does not help
either, it resynchronizes too slow and the first received
frame gets lost.
2000-02-13 Fixed for new network driver interface changes, still
does TX timeouts itself since it uses its own queue
scheme.
Thanks to all who contributed to this driver with ideas and bug
reports!
NB -- if you find errors, change something, please let me know
first before you distribute it... And please don't touch
the version number. Just replace my callsign in
"v3.0.dl1bke" with your own. Just to avoid confusion...
If you want to add your modification to the linux distribution
please (!) contact me first.
New versions of the driver will be announced on the linux-hams
mailing list on vger.kernel.org. To subscribe send an e-mail
to majordomo@vger.kernel.org with the following line in
the body of the mail:
subscribe linux-hams
The content of the "Subject" field will be ignored.
vy 73,
Joerg Reuter ampr-net: dl1bke@db0pra.ampr.org
AX-25 : DL1BKE @ DB0ABH.#BAY.DEU.EU
Internet: jreuter@yaina.de
www : http://yaina.de/jreuter
*/
/* ----------------------------------------------------------------------- */
#undef SCC_LDELAY /* slow it even a bit more down */
#undef SCC_DONT_CHECK /* don't look if the SCCs you specified are available */
#define SCC_MAXCHIPS 4 /* number of max. supported chips */
#define SCC_BUFSIZE 384 /* must not exceed 4096 */
#undef SCC_DEBUG
#define SCC_DEFAULT_CLOCK 4915200
/* default pclock if nothing is specified */
/* ----------------------------------------------------------------------- */
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/signal.h>
#include <linux/timer.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/string.h>
#include <linux/in.h>
#include <linux/fcntl.h>
#include <linux/ptrace.h>
#include <linux/delay.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/rtnetlink.h>
#include <linux/if_ether.h>
#include <linux/if_arp.h>
#include <linux/socket.h>
#include <linux/init.h>
#include <linux/scc.h>
#include <linux/ctype.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/bitops.h>
#include <net/net_namespace.h>
#include <net/ax25.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include "z8530.h"
static const char banner[] __initconst = KERN_INFO \
"AX.25: Z8530 SCC driver version "VERSION".dl1bke\n";
static void t_dwait(unsigned long);
static void t_txdelay(unsigned long);
static void t_tail(unsigned long);
static void t_busy(unsigned long);
static void t_maxkeyup(unsigned long);
static void t_idle(unsigned long);
static void scc_tx_done(struct scc_channel *);
static void scc_start_tx_timer(struct scc_channel *, void (*)(unsigned long), unsigned long);
static void scc_start_maxkeyup(struct scc_channel *);
static void scc_start_defer(struct scc_channel *);
static void z8530_init(void);
static void init_channel(struct scc_channel *scc);
static void scc_key_trx (struct scc_channel *scc, char tx);
static void scc_init_timer(struct scc_channel *scc);
static int scc_net_alloc(const char *name, struct scc_channel *scc);
static void scc_net_setup(struct net_device *dev);
static int scc_net_open(struct net_device *dev);
static int scc_net_close(struct net_device *dev);
static void scc_net_rx(struct scc_channel *scc, struct sk_buff *skb);
static netdev_tx_t scc_net_tx(struct sk_buff *skb,
struct net_device *dev);
static int scc_net_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd);
static int scc_net_set_mac_address(struct net_device *dev, void *addr);
static struct net_device_stats * scc_net_get_stats(struct net_device *dev);
static unsigned char SCC_DriverName[] = "scc";
static struct irqflags { unsigned char used : 1; } Ivec[NR_IRQS];
static struct scc_channel SCC_Info[2 * SCC_MAXCHIPS]; /* information per channel */
static struct scc_ctrl {
io_port chan_A;
io_port chan_B;
int irq;
} SCC_ctrl[SCC_MAXCHIPS+1];
static unsigned char Driver_Initialized;
static int Nchips;
static io_port Vector_Latch;
/* ******************************************************************** */
/* * Port Access Functions * */
/* ******************************************************************** */
/* These provide interrupt save 2-step access to the Z8530 registers */
static DEFINE_SPINLOCK(iolock); /* Guards paired accesses */
static inline unsigned char InReg(io_port port, unsigned char reg)
{
unsigned long flags;
unsigned char r;
spin_lock_irqsave(&iolock, flags);
#ifdef SCC_LDELAY
Outb(port, reg);
udelay(SCC_LDELAY);
r=Inb(port);
udelay(SCC_LDELAY);
#else
Outb(port, reg);
r=Inb(port);
#endif
spin_unlock_irqrestore(&iolock, flags);
return r;
}
static inline void OutReg(io_port port, unsigned char reg, unsigned char val)
{
unsigned long flags;
spin_lock_irqsave(&iolock, flags);
#ifdef SCC_LDELAY
Outb(port, reg); udelay(SCC_LDELAY);
Outb(port, val); udelay(SCC_LDELAY);
#else
Outb(port, reg);
Outb(port, val);
#endif
spin_unlock_irqrestore(&iolock, flags);
}
static inline void wr(struct scc_channel *scc, unsigned char reg,
unsigned char val)
{
OutReg(scc->ctrl, reg, (scc->wreg[reg] = val));
}
static inline void or(struct scc_channel *scc, unsigned char reg, unsigned char val)
{
OutReg(scc->ctrl, reg, (scc->wreg[reg] |= val));
}
static inline void cl(struct scc_channel *scc, unsigned char reg, unsigned char val)
{
OutReg(scc->ctrl, reg, (scc->wreg[reg] &= ~val));
}
/* ******************************************************************** */
/* * Some useful macros * */
/* ******************************************************************** */
static inline void scc_discard_buffers(struct scc_channel *scc)
{
unsigned long flags;
spin_lock_irqsave(&scc->lock, flags);
if (scc->tx_buff != NULL)
{
dev_kfree_skb(scc->tx_buff);
scc->tx_buff = NULL;
}
while (!skb_queue_empty(&scc->tx_queue))
dev_kfree_skb(skb_dequeue(&scc->tx_queue));
spin_unlock_irqrestore(&scc->lock, flags);
}
/* ******************************************************************** */
/* * Interrupt Service Routines * */
/* ******************************************************************** */
/* ----> subroutines for the interrupt handlers <---- */
static inline void scc_notify(struct scc_channel *scc, int event)
{
struct sk_buff *skb;
char *bp;
if (scc->kiss.fulldup != KISS_DUPLEX_OPTIMA)
return;
skb = dev_alloc_skb(2);
if (skb != NULL)
{
bp = skb_put(skb, 2);
*bp++ = PARAM_HWEVENT;
*bp++ = event;
scc_net_rx(scc, skb);
} else
scc->stat.nospace++;
}
static inline void flush_rx_FIFO(struct scc_channel *scc)
{
int k;
for (k=0; k<3; k++)
Inb(scc->data);
if(scc->rx_buff != NULL) /* did we receive something? */
{
scc->stat.rxerrs++; /* then count it as an error */
dev_kfree_skb_irq(scc->rx_buff);
scc->rx_buff = NULL;
}
}
static void start_hunt(struct scc_channel *scc)
{
if ((scc->modem.clocksrc != CLK_EXTERNAL))
OutReg(scc->ctrl,R14,SEARCH|scc->wreg[R14]); /* DPLL: enter search mode */
or(scc,R3,ENT_HM|RxENABLE); /* enable the receiver, hunt mode */
}
/* ----> four different interrupt handlers for Tx, Rx, changing of */
/* DCD/CTS and Rx/Tx errors */
/* Transmitter interrupt handler */
static inline void scc_txint(struct scc_channel *scc)
{
struct sk_buff *skb;
scc->stat.txints++;
skb = scc->tx_buff;
/* send first octet */
if (skb == NULL)
{
skb = skb_dequeue(&scc->tx_queue);
scc->tx_buff = skb;
netif_wake_queue(scc->dev);
if (skb == NULL)
{
scc_tx_done(scc);
Outb(scc->ctrl, RES_Tx_P);
return;
}
if (skb->len == 0) /* Paranoia... */
{
dev_kfree_skb_irq(skb);
scc->tx_buff = NULL;
scc_tx_done(scc);
Outb(scc->ctrl, RES_Tx_P);
return;
}
scc->stat.tx_state = TXS_ACTIVE;
OutReg(scc->ctrl, R0, RES_Tx_CRC);
/* reset CRC generator */
or(scc,R10,ABUNDER); /* re-install underrun protection */
Outb(scc->data,*skb->data); /* send byte */
skb_pull(skb, 1);
if (!scc->enhanced) /* reset EOM latch */
Outb(scc->ctrl,RES_EOM_L);
return;
}
/* End Of Frame... */
if (skb->len == 0)
{
Outb(scc->ctrl, RES_Tx_P); /* reset pending int */
cl(scc, R10, ABUNDER); /* send CRC */
dev_kfree_skb_irq(skb);
scc->tx_buff = NULL;
scc->stat.tx_state = TXS_NEWFRAME; /* next frame... */
return;
}
/* send octet */
Outb(scc->data,*skb->data);
skb_pull(skb, 1);
}
/* External/Status interrupt handler */
static inline void scc_exint(struct scc_channel *scc)
{
unsigned char status,changes,chg_and_stat;
scc->stat.exints++;
status = InReg(scc->ctrl,R0);
changes = status ^ scc->status;
chg_and_stat = changes & status;
/* ABORT: generated whenever DCD drops while receiving */
if (chg_and_stat & BRK_ABRT) /* Received an ABORT */
flush_rx_FIFO(scc);
/* HUNT: software DCD; on = waiting for SYNC, off = receiving frame */
if ((changes & SYNC_HUNT) && scc->kiss.softdcd)
{
if (status & SYNC_HUNT)
{
scc->dcd = 0;
flush_rx_FIFO(scc);
if ((scc->modem.clocksrc != CLK_EXTERNAL))
OutReg(scc->ctrl,R14,SEARCH|scc->wreg[R14]); /* DPLL: enter search mode */
} else {
scc->dcd = 1;
}
scc_notify(scc, scc->dcd? HWEV_DCD_OFF:HWEV_DCD_ON);
}
/* DCD: on = start to receive packet, off = ABORT condition */
/* (a successfully received packet generates a special condition int) */
if((changes & DCD) && !scc->kiss.softdcd) /* DCD input changed state */
{
if(status & DCD) /* DCD is now ON */
{
start_hunt(scc);
scc->dcd = 1;
} else { /* DCD is now OFF */
cl(scc,R3,ENT_HM|RxENABLE); /* disable the receiver */
flush_rx_FIFO(scc);
scc->dcd = 0;
}
scc_notify(scc, scc->dcd? HWEV_DCD_ON:HWEV_DCD_OFF);
}
#ifdef notdef
/* CTS: use external TxDelay (what's that good for?!)
* Anyway: If we _could_ use it (BayCom USCC uses CTS for
* own purposes) we _should_ use the "autoenable" feature
* of the Z8530 and not this interrupt...
*/
if (chg_and_stat & CTS) /* CTS is now ON */
{
if (scc->kiss.txdelay == 0) /* zero TXDELAY = wait for CTS */
scc_start_tx_timer(scc, t_txdelay, 0);
}
#endif
if (scc->stat.tx_state == TXS_ACTIVE && (status & TxEOM))
{
scc->stat.tx_under++; /* oops, an underrun! count 'em */
Outb(scc->ctrl, RES_EXT_INT); /* reset ext/status interrupts */
if (scc->tx_buff != NULL)
{
dev_kfree_skb_irq(scc->tx_buff);
scc->tx_buff = NULL;
}
or(scc,R10,ABUNDER);
scc_start_tx_timer(scc, t_txdelay, 0); /* restart transmission */
}
scc->status = status;
Outb(scc->ctrl,RES_EXT_INT);
}
/* Receiver interrupt handler */
static inline void scc_rxint(struct scc_channel *scc)
{
struct sk_buff *skb;
scc->stat.rxints++;
if((scc->wreg[5] & RTS) && scc->kiss.fulldup == KISS_DUPLEX_HALF)
{
Inb(scc->data); /* discard char */
or(scc,R3,ENT_HM); /* enter hunt mode for next flag */
return;
}
skb = scc->rx_buff;
if (skb == NULL)
{
skb = dev_alloc_skb(scc->stat.bufsize);
if (skb == NULL)
{
scc->dev_stat.rx_dropped++;
scc->stat.nospace++;
Inb(scc->data);
or(scc, R3, ENT_HM);
return;
}
scc->rx_buff = skb;
*(skb_put(skb, 1)) = 0; /* KISS data */
}
if (skb->len >= scc->stat.bufsize)
{
#ifdef notdef
printk(KERN_DEBUG "z8530drv: oops, scc_rxint() received huge frame...\n");
#endif
dev_kfree_skb_irq(skb);
scc->rx_buff = NULL;
Inb(scc->data);
or(scc, R3, ENT_HM);
return;
}
*(skb_put(skb, 1)) = Inb(scc->data);
}
/* Receive Special Condition interrupt handler */
static inline void scc_spint(struct scc_channel *scc)
{
unsigned char status;
struct sk_buff *skb;
scc->stat.spints++;
status = InReg(scc->ctrl,R1); /* read receiver status */
Inb(scc->data); /* throw away Rx byte */
skb = scc->rx_buff;
if(status & Rx_OVR) /* receiver overrun */
{
scc->stat.rx_over++; /* count them */
or(scc,R3,ENT_HM); /* enter hunt mode for next flag */
if (skb != NULL)
dev_kfree_skb_irq(skb);
scc->rx_buff = skb = NULL;
}
if(status & END_FR && skb != NULL) /* end of frame */
{
/* CRC okay, frame ends on 8 bit boundary and received something ? */
if (!(status & CRC_ERR) && (status & 0xe) == RES8 && skb->len > 0)
{
/* ignore last received byte (first of the CRC bytes) */
skb_trim(skb, skb->len-1);
scc_net_rx(scc, skb);
scc->rx_buff = NULL;
scc->stat.rxframes++;
} else { /* a bad frame */
dev_kfree_skb_irq(skb);
scc->rx_buff = NULL;
scc->stat.rxerrs++;
}
}
Outb(scc->ctrl,ERR_RES);
}
/* ----> interrupt service routine for the Z8530 <---- */
static void scc_isr_dispatch(struct scc_channel *scc, int vector)
{
spin_lock(&scc->lock);
switch (vector & VECTOR_MASK)
{
case TXINT: scc_txint(scc); break;
case EXINT: scc_exint(scc); break;
case RXINT: scc_rxint(scc); break;
case SPINT: scc_spint(scc); break;
}
spin_unlock(&scc->lock);
}
/* If the card has a latch for the interrupt vector (like the PA0HZP card)
use it to get the number of the chip that generated the int.
If not: poll all defined chips.
*/
#define SCC_IRQTIMEOUT 30000
static irqreturn_t scc_isr(int irq, void *dev_id)
{
int chip_irq = (long) dev_id;
unsigned char vector;
struct scc_channel *scc;
struct scc_ctrl *ctrl;
int k;
if (Vector_Latch)
{
for(k=0; k < SCC_IRQTIMEOUT; k++)
{
Outb(Vector_Latch, 0); /* Generate INTACK */
/* Read the vector */
if((vector=Inb(Vector_Latch)) >= 16 * Nchips) break;
if (vector & 0x01) break;
scc=&SCC_Info[vector >> 3 ^ 0x01];
if (!scc->dev) break;
scc_isr_dispatch(scc, vector);
OutReg(scc->ctrl,R0,RES_H_IUS); /* Reset Highest IUS */
}
if (k == SCC_IRQTIMEOUT)
printk(KERN_WARNING "z8530drv: endless loop in scc_isr()?\n");
return IRQ_HANDLED;
}
/* Find the SCC generating the interrupt by polling all attached SCCs
* reading RR3A (the interrupt pending register)
*/
ctrl = SCC_ctrl;
while (ctrl->chan_A)
{
if (ctrl->irq != chip_irq)
{
ctrl++;
continue;
}
scc = NULL;
for (k = 0; InReg(ctrl->chan_A,R3) && k < SCC_IRQTIMEOUT; k++)
{
vector=InReg(ctrl->chan_B,R2); /* Read the vector */
if (vector & 0x01) break;
scc = &SCC_Info[vector >> 3 ^ 0x01];
if (!scc->dev) break;
scc_isr_dispatch(scc, vector);
}
if (k == SCC_IRQTIMEOUT)
{
printk(KERN_WARNING "z8530drv: endless loop in scc_isr()?!\n");
break;
}
/* This looks weird and it is. At least the BayCom USCC doesn't
* use the Interrupt Daisy Chain, thus we'll have to start
* all over again to be sure not to miss an interrupt from
* (any of) the other chip(s)...
* Honestly, the situation *is* braindamaged...
*/
if (scc != NULL)
{
OutReg(scc->ctrl,R0,RES_H_IUS);
ctrl = SCC_ctrl;
} else
ctrl++;
}
return IRQ_HANDLED;
}
/* ******************************************************************** */
/* * Init Channel */
/* ******************************************************************** */
/* ----> set SCC channel speed <---- */
static inline void set_brg(struct scc_channel *scc, unsigned int tc)
{
cl(scc,R14,BRENABL); /* disable baudrate generator */
wr(scc,R12,tc & 255); /* brg rate LOW */
wr(scc,R13,tc >> 8); /* brg rate HIGH */
or(scc,R14,BRENABL); /* enable baudrate generator */
}
static inline void set_speed(struct scc_channel *scc)
{
unsigned long flags;
spin_lock_irqsave(&scc->lock, flags);
if (scc->modem.speed > 0) /* paranoia... */
set_brg(scc, (unsigned) (scc->clock / (scc->modem.speed * 64)) - 2);
spin_unlock_irqrestore(&scc->lock, flags);
}
/* ----> initialize a SCC channel <---- */
static inline void init_brg(struct scc_channel *scc)
{
wr(scc, R14, BRSRC); /* BRG source = PCLK */
OutReg(scc->ctrl, R14, SSBR|scc->wreg[R14]); /* DPLL source = BRG */
OutReg(scc->ctrl, R14, SNRZI|scc->wreg[R14]); /* DPLL NRZI mode */
}
/*
* Initialization according to the Z8530 manual (SGS-Thomson's version):
*
* 1. Modes and constants
*
* WR9 11000000 chip reset
* WR4 XXXXXXXX Tx/Rx control, async or sync mode
* WR1 0XX00X00 select W/REQ (optional)
* WR2 XXXXXXXX program interrupt vector
* WR3 XXXXXXX0 select Rx control
* WR5 XXXX0XXX select Tx control
* WR6 XXXXXXXX sync character
* WR7 XXXXXXXX sync character
* WR9 000X0XXX select interrupt control
* WR10 XXXXXXXX miscellaneous control (optional)
* WR11 XXXXXXXX clock control
* WR12 XXXXXXXX time constant lower byte (optional)
* WR13 XXXXXXXX time constant upper byte (optional)
* WR14 XXXXXXX0 miscellaneous control
* WR14 XXXSSSSS commands (optional)
*
* 2. Enables
*
* WR14 000SSSS1 baud rate enable
* WR3 SSSSSSS1 Rx enable
* WR5 SSSS1SSS Tx enable
* WR0 10000000 reset Tx CRG (optional)
* WR1 XSS00S00 DMA enable (optional)
*
* 3. Interrupt status
*
* WR15 XXXXXXXX enable external/status
* WR0 00010000 reset external status
* WR0 00010000 reset external status twice
* WR1 SSSXXSXX enable Rx, Tx and Ext/status
* WR9 000SXSSS enable master interrupt enable
*
* 1 = set to one, 0 = reset to zero
* X = user defined, S = same as previous init
*
*
* Note that the implementation differs in some points from above scheme.
*
*/
static void init_channel(struct scc_channel *scc)
{
del_timer(&scc->tx_t);
del_timer(&scc->tx_wdog);
disable_irq(scc->irq);
wr(scc,R4,X1CLK|SDLC); /* *1 clock, SDLC mode */
wr(scc,R1,0); /* no W/REQ operation */
wr(scc,R3,Rx8|RxCRC_ENAB); /* RX 8 bits/char, CRC, disabled */
wr(scc,R5,Tx8|DTR|TxCRC_ENAB); /* TX 8 bits/char, disabled, DTR */
wr(scc,R6,0); /* SDLC address zero (not used) */
wr(scc,R7,FLAG); /* SDLC flag value */
wr(scc,R9,VIS); /* vector includes status */
wr(scc,R10,(scc->modem.nrz? NRZ : NRZI)|CRCPS|ABUNDER); /* abort on underrun, preset CRC generator, NRZ(I) */
wr(scc,R14, 0);
/* set clock sources:
CLK_DPLL: normal halfduplex operation
RxClk: use DPLL
TxClk: use DPLL
TRxC mode DPLL output
CLK_EXTERNAL: external clocking (G3RUH or DF9IC modem)
BayCom: others:
TxClk = pin RTxC TxClk = pin TRxC
RxClk = pin TRxC RxClk = pin RTxC
CLK_DIVIDER:
RxClk = use DPLL
TxClk = pin RTxC
BayCom: others:
pin TRxC = DPLL pin TRxC = BRG
(RxClk * 1) (RxClk * 32)
*/
switch(scc->modem.clocksrc)
{
case CLK_DPLL:
wr(scc, R11, RCDPLL|TCDPLL|TRxCOI|TRxCDP);
init_brg(scc);
break;
case CLK_DIVIDER:
wr(scc, R11, ((scc->brand & BAYCOM)? TRxCDP : TRxCBR) | RCDPLL|TCRTxCP|TRxCOI);
init_brg(scc);
break;
case CLK_EXTERNAL:
wr(scc, R11, (scc->brand & BAYCOM)? RCTRxCP|TCRTxCP : RCRTxCP|TCTRxCP);
OutReg(scc->ctrl, R14, DISDPLL);
break;
}
set_speed(scc); /* set baudrate */
if(scc->enhanced)
{
or(scc,R15,SHDLCE|FIFOE); /* enable FIFO, SDLC/HDLC Enhancements (From now R7 is R7') */
wr(scc,R7,AUTOEOM);
}
if(scc->kiss.softdcd || (InReg(scc->ctrl,R0) & DCD))
/* DCD is now ON */
{
start_hunt(scc);
}
/* enable ABORT, DCD & SYNC/HUNT interrupts */
wr(scc,R15, BRKIE|TxUIE|(scc->kiss.softdcd? SYNCIE:DCDIE));
Outb(scc->ctrl,RES_EXT_INT); /* reset ext/status interrupts */
Outb(scc->ctrl,RES_EXT_INT); /* must be done twice */
or(scc,R1,INT_ALL_Rx|TxINT_ENAB|EXT_INT_ENAB); /* enable interrupts */
scc->status = InReg(scc->ctrl,R0); /* read initial status */
or(scc,R9,MIE); /* master interrupt enable */
scc_init_timer(scc);
enable_irq(scc->irq);
}
/* ******************************************************************** */
/* * SCC timer functions * */
/* ******************************************************************** */
/* ----> scc_key_trx sets the time constant for the baudrate
generator and keys the transmitter <---- */
static void scc_key_trx(struct scc_channel *scc, char tx)
{
unsigned int time_const;
if (scc->brand & PRIMUS)
Outb(scc->ctrl + 4, scc->option | (tx? 0x80 : 0));
if (scc->modem.speed < 300)
scc->modem.speed = 1200;
time_const = (unsigned) (scc->clock / (scc->modem.speed * (tx? 2:64))) - 2;
disable_irq(scc->irq);
if (tx)
{
or(scc, R1, TxINT_ENAB); /* t_maxkeyup may have reset these */
or(scc, R15, TxUIE);
}
if (scc->modem.clocksrc == CLK_DPLL)
{ /* force simplex operation */
if (tx)
{
#ifdef CONFIG_SCC_TRXECHO
cl(scc, R3, RxENABLE|ENT_HM); /* switch off receiver */
cl(scc, R15, DCDIE|SYNCIE); /* No DCD changes, please */
#endif
set_brg(scc, time_const); /* reprogram baudrate generator */
/* DPLL -> Rx clk, BRG -> Tx CLK, TRxC mode output, TRxC = BRG */
wr(scc, R11, RCDPLL|TCBR|TRxCOI|TRxCBR);
/* By popular demand: tx_inhibit */
if (scc->kiss.tx_inhibit)
{
or(scc,R5, TxENAB);
scc->wreg[R5] |= RTS;
} else {
or(scc,R5,RTS|TxENAB); /* set the RTS line and enable TX */
}
} else {
cl(scc,R5,RTS|TxENAB);
set_brg(scc, time_const); /* reprogram baudrate generator */
/* DPLL -> Rx clk, DPLL -> Tx CLK, TRxC mode output, TRxC = DPLL */
wr(scc, R11, RCDPLL|TCDPLL|TRxCOI|TRxCDP);
#ifndef CONFIG_SCC_TRXECHO
if (scc->kiss.softdcd)
#endif
{
or(scc,R15, scc->kiss.softdcd? SYNCIE:DCDIE);
start_hunt(scc);
}
}
} else {
if (tx)
{
#ifdef CONFIG_SCC_TRXECHO
if (scc->kiss.fulldup == KISS_DUPLEX_HALF)
{
cl(scc, R3, RxENABLE);
cl(scc, R15, DCDIE|SYNCIE);
}
#endif
if (scc->kiss.tx_inhibit)
{
or(scc,R5, TxENAB);
scc->wreg[R5] |= RTS;
} else {
or(scc,R5,RTS|TxENAB); /* enable tx */
}
} else {
cl(scc,R5,RTS|TxENAB); /* disable tx */
if ((scc->kiss.fulldup == KISS_DUPLEX_HALF) &&
#ifndef CONFIG_SCC_TRXECHO
scc->kiss.softdcd)
#else
1)
#endif
{
or(scc, R15, scc->kiss.softdcd? SYNCIE:DCDIE);
start_hunt(scc);
}
}
}
enable_irq(scc->irq);
}
/* ----> SCC timer interrupt handler and friends. <---- */
static void __scc_start_tx_timer(struct scc_channel *scc, void (*handler)(unsigned long), unsigned long when)
{
del_timer(&scc->tx_t);
if (when == 0)
{
handler((unsigned long) scc);
} else
if (when != TIMER_OFF)
{
scc->tx_t.data = (unsigned long) scc;
scc->tx_t.function = handler;
scc->tx_t.expires = jiffies + (when*HZ)/100;
add_timer(&scc->tx_t);
}
}
static void scc_start_tx_timer(struct scc_channel *scc, void (*handler)(unsigned long), unsigned long when)
{
unsigned long flags;
spin_lock_irqsave(&scc->lock, flags);
__scc_start_tx_timer(scc, handler, when);
spin_unlock_irqrestore(&scc->lock, flags);
}
static void scc_start_defer(struct scc_channel *scc)
{
unsigned long flags;
spin_lock_irqsave(&scc->lock, flags);
del_timer(&scc->tx_wdog);
if (scc->kiss.maxdefer != 0 && scc->kiss.maxdefer != TIMER_OFF)
{
scc->tx_wdog.data = (unsigned long) scc;
scc->tx_wdog.function = t_busy;
scc->tx_wdog.expires = jiffies + HZ*scc->kiss.maxdefer;
add_timer(&scc->tx_wdog);
}
spin_unlock_irqrestore(&scc->lock, flags);
}
static void scc_start_maxkeyup(struct scc_channel *scc)
{
unsigned long flags;
spin_lock_irqsave(&scc->lock, flags);
del_timer(&scc->tx_wdog);
if (scc->kiss.maxkeyup != 0 && scc->kiss.maxkeyup != TIMER_OFF)
{
scc->tx_wdog.data = (unsigned long) scc;
scc->tx_wdog.function = t_maxkeyup;
scc->tx_wdog.expires = jiffies + HZ*scc->kiss.maxkeyup;
add_timer(&scc->tx_wdog);
}
spin_unlock_irqrestore(&scc->lock, flags);
}
/*
* This is called from scc_txint() when there are no more frames to send.
* Not exactly a timer function, but it is a close friend of the family...
*/
static void scc_tx_done(struct scc_channel *scc)
{
/*
* trx remains keyed in fulldup mode 2 until t_idle expires.
*/
switch (scc->kiss.fulldup)
{
case KISS_DUPLEX_LINK:
scc->stat.tx_state = TXS_IDLE2;
if (scc->kiss.idletime != TIMER_OFF)
scc_start_tx_timer(scc, t_idle,
scc->kiss.idletime*100);
break;
case KISS_DUPLEX_OPTIMA:
scc_notify(scc, HWEV_ALL_SENT);
break;
default:
scc->stat.tx_state = TXS_BUSY;
scc_start_tx_timer(scc, t_tail, scc->kiss.tailtime);
}
netif_wake_queue(scc->dev);
}
static unsigned char Rand = 17;
static inline int is_grouped(struct scc_channel *scc)
{
int k;
struct scc_channel *scc2;
unsigned char grp1, grp2;
grp1 = scc->kiss.group;
for (k = 0; k < (Nchips * 2); k++)
{
scc2 = &SCC_Info[k];
grp2 = scc2->kiss.group;
if (scc2 == scc || !(scc2->dev && grp2))
continue;
if ((grp1 & 0x3f) == (grp2 & 0x3f))
{
if ( (grp1 & TXGROUP) && (scc2->wreg[R5] & RTS) )
return 1;
if ( (grp1 & RXGROUP) && scc2->dcd )
return 1;
}
}
return 0;
}
/* DWAIT and SLOTTIME expired
*
* fulldup == 0: DCD is active or Rand > P-persistence: start t_busy timer
* else key trx and start txdelay
* fulldup == 1: key trx and start txdelay
* fulldup == 2: mintime expired, reset status or key trx and start txdelay
*/
static void t_dwait(unsigned long channel)
{
struct scc_channel *scc = (struct scc_channel *) channel;
if (scc->stat.tx_state == TXS_WAIT) /* maxkeyup or idle timeout */
{
if (skb_queue_empty(&scc->tx_queue)) { /* nothing to send */
scc->stat.tx_state = TXS_IDLE;
netif_wake_queue(scc->dev); /* t_maxkeyup locked it. */
return;
}
scc->stat.tx_state = TXS_BUSY;
}
if (scc->kiss.fulldup == KISS_DUPLEX_HALF)
{
Rand = Rand * 17 + 31;
if (scc->dcd || (scc->kiss.persist) < Rand || (scc->kiss.group && is_grouped(scc)) )
{
scc_start_defer(scc);
scc_start_tx_timer(scc, t_dwait, scc->kiss.slottime);
return ;
}
}
if ( !(scc->wreg[R5] & RTS) )
{
scc_key_trx(scc, TX_ON);
scc_start_tx_timer(scc, t_txdelay, scc->kiss.txdelay);
} else {
scc_start_tx_timer(scc, t_txdelay, 0);
}
}
/* TXDELAY expired
*
* kick transmission by a fake scc_txint(scc), start 'maxkeyup' watchdog.
*/
static void t_txdelay(unsigned long channel)
{
struct scc_channel *scc = (struct scc_channel *) channel;
scc_start_maxkeyup(scc);
if (scc->tx_buff == NULL)
{
disable_irq(scc->irq);
scc_txint(scc);
enable_irq(scc->irq);
}
}
/* TAILTIME expired
*
* switch off transmitter. If we were stopped by Maxkeyup restart
* transmission after 'mintime' seconds
*/
static void t_tail(unsigned long channel)
{
struct scc_channel *scc = (struct scc_channel *) channel;
unsigned long flags;
spin_lock_irqsave(&scc->lock, flags);
del_timer(&scc->tx_wdog);
scc_key_trx(scc, TX_OFF);
spin_unlock_irqrestore(&scc->lock, flags);
if (scc->stat.tx_state == TXS_TIMEOUT) /* we had a timeout? */
{
scc->stat.tx_state = TXS_WAIT;
scc_start_tx_timer(scc, t_dwait, scc->kiss.mintime*100);
return;
}
scc->stat.tx_state = TXS_IDLE;
netif_wake_queue(scc->dev);
}
/* BUSY timeout
*
* throw away send buffers if DCD remains active too long.
*/
static void t_busy(unsigned long channel)
{
struct scc_channel *scc = (struct scc_channel *) channel;
del_timer(&scc->tx_t);
netif_stop_queue(scc->dev); /* don't pile on the wabbit! */
scc_discard_buffers(scc);
scc->stat.txerrs++;
scc->stat.tx_state = TXS_IDLE;
netif_wake_queue(scc->dev);
}
/* MAXKEYUP timeout
*
* this is our watchdog.
*/
static void t_maxkeyup(unsigned long channel)
{
struct scc_channel *scc = (struct scc_channel *) channel;
unsigned long flags;
spin_lock_irqsave(&scc->lock, flags);
/*
* let things settle down before we start to
* accept new data.
*/
netif_stop_queue(scc->dev);
scc_discard_buffers(scc);
del_timer(&scc->tx_t);
cl(scc, R1, TxINT_ENAB); /* force an ABORT, but don't */
cl(scc, R15, TxUIE); /* count it. */
OutReg(scc->ctrl, R0, RES_Tx_P);
spin_unlock_irqrestore(&scc->lock, flags);
scc->stat.txerrs++;
scc->stat.tx_state = TXS_TIMEOUT;
scc_start_tx_timer(scc, t_tail, scc->kiss.tailtime);
}
/* IDLE timeout
*
* in fulldup mode 2 it keys down the transmitter after 'idle' seconds
* of inactivity. We will not restart transmission before 'mintime'
* expires.
*/
static void t_idle(unsigned long channel)
{
struct scc_channel *scc = (struct scc_channel *) channel;
del_timer(&scc->tx_wdog);
scc_key_trx(scc, TX_OFF);
if(scc->kiss.mintime)
scc_start_tx_timer(scc, t_dwait, scc->kiss.mintime*100);
scc->stat.tx_state = TXS_WAIT;
}
static void scc_init_timer(struct scc_channel *scc)
{
unsigned long flags;
spin_lock_irqsave(&scc->lock, flags);
scc->stat.tx_state = TXS_IDLE;
spin_unlock_irqrestore(&scc->lock, flags);
}
/* ******************************************************************** */
/* * Set/get L1 parameters * */
/* ******************************************************************** */
/*
* this will set the "hardware" parameters through KISS commands or ioctl()
*/
#define CAST(x) (unsigned long)(x)
static unsigned int scc_set_param(struct scc_channel *scc, unsigned int cmd, unsigned int arg)
{
switch (cmd)
{
case PARAM_TXDELAY: scc->kiss.txdelay=arg; break;
case PARAM_PERSIST: scc->kiss.persist=arg; break;
case PARAM_SLOTTIME: scc->kiss.slottime=arg; break;
case PARAM_TXTAIL: scc->kiss.tailtime=arg; break;
case PARAM_FULLDUP: scc->kiss.fulldup=arg; break;
case PARAM_DTR: break; /* does someone need this? */
case PARAM_GROUP: scc->kiss.group=arg; break;
case PARAM_IDLE: scc->kiss.idletime=arg; break;
case PARAM_MIN: scc->kiss.mintime=arg; break;
case PARAM_MAXKEY: scc->kiss.maxkeyup=arg; break;
case PARAM_WAIT: scc->kiss.waittime=arg; break;
case PARAM_MAXDEFER: scc->kiss.maxdefer=arg; break;
case PARAM_TX: scc->kiss.tx_inhibit=arg; break;
case PARAM_SOFTDCD:
scc->kiss.softdcd=arg;
if (arg)
{
or(scc, R15, SYNCIE);
cl(scc, R15, DCDIE);
start_hunt(scc);
} else {
or(scc, R15, DCDIE);
cl(scc, R15, SYNCIE);
}
break;
case PARAM_SPEED:
if (arg < 256)
scc->modem.speed=arg*100;
else
scc->modem.speed=arg;
if (scc->stat.tx_state == 0) /* only switch baudrate on rx... ;-) */
set_speed(scc);
break;
case PARAM_RTS:
if ( !(scc->wreg[R5] & RTS) )
{
if (arg != TX_OFF) {
scc_key_trx(scc, TX_ON);
scc_start_tx_timer(scc, t_txdelay, scc->kiss.txdelay);
}
} else {
if (arg == TX_OFF)
{
scc->stat.tx_state = TXS_BUSY;
scc_start_tx_timer(scc, t_tail, scc->kiss.tailtime);
}
}
break;
case PARAM_HWEVENT:
scc_notify(scc, scc->dcd? HWEV_DCD_ON:HWEV_DCD_OFF);
break;
default: return -EINVAL;
}
return 0;
}
static unsigned long scc_get_param(struct scc_channel *scc, unsigned int cmd)
{
switch (cmd)
{
case PARAM_TXDELAY: return CAST(scc->kiss.txdelay);
case PARAM_PERSIST: return CAST(scc->kiss.persist);
case PARAM_SLOTTIME: return CAST(scc->kiss.slottime);
case PARAM_TXTAIL: return CAST(scc->kiss.tailtime);
case PARAM_FULLDUP: return CAST(scc->kiss.fulldup);
case PARAM_SOFTDCD: return CAST(scc->kiss.softdcd);
case PARAM_DTR: return CAST((scc->wreg[R5] & DTR)? 1:0);
case PARAM_RTS: return CAST((scc->wreg[R5] & RTS)? 1:0);
case PARAM_SPEED: return CAST(scc->modem.speed);
case PARAM_GROUP: return CAST(scc->kiss.group);
case PARAM_IDLE: return CAST(scc->kiss.idletime);
case PARAM_MIN: return CAST(scc->kiss.mintime);
case PARAM_MAXKEY: return CAST(scc->kiss.maxkeyup);
case PARAM_WAIT: return CAST(scc->kiss.waittime);
case PARAM_MAXDEFER: return CAST(scc->kiss.maxdefer);
case PARAM_TX: return CAST(scc->kiss.tx_inhibit);
default: return NO_SUCH_PARAM;
}
}
#undef CAST
/* ******************************************************************* */
/* * Send calibration pattern * */
/* ******************************************************************* */
static void scc_stop_calibrate(unsigned long channel)
{
struct scc_channel *scc = (struct scc_channel *) channel;
unsigned long flags;
spin_lock_irqsave(&scc->lock, flags);
del_timer(&scc->tx_wdog);
scc_key_trx(scc, TX_OFF);
wr(scc, R6, 0);
wr(scc, R7, FLAG);
Outb(scc->ctrl,RES_EXT_INT); /* reset ext/status interrupts */
Outb(scc->ctrl,RES_EXT_INT);
netif_wake_queue(scc->dev);
spin_unlock_irqrestore(&scc->lock, flags);
}
static void
scc_start_calibrate(struct scc_channel *scc, int duration, unsigned char pattern)
{
unsigned long flags;
spin_lock_irqsave(&scc->lock, flags);
netif_stop_queue(scc->dev);
scc_discard_buffers(scc);
del_timer(&scc->tx_wdog);
scc->tx_wdog.data = (unsigned long) scc;
scc->tx_wdog.function = scc_stop_calibrate;
scc->tx_wdog.expires = jiffies + HZ*duration;
add_timer(&scc->tx_wdog);
/* This doesn't seem to work. Why not? */
wr(scc, R6, 0);
wr(scc, R7, pattern);
/*
* Don't know if this works.
* Damn, where is my Z8530 programming manual...?
*/
Outb(scc->ctrl,RES_EXT_INT); /* reset ext/status interrupts */
Outb(scc->ctrl,RES_EXT_INT);
scc_key_trx(scc, TX_ON);
spin_unlock_irqrestore(&scc->lock, flags);
}
/* ******************************************************************* */
/* * Init channel structures, special HW, etc... * */
/* ******************************************************************* */
/*
* Reset the Z8530s and setup special hardware
*/
static void z8530_init(void)
{
struct scc_channel *scc;
int chip, k;
unsigned long flags;
char *flag;
printk(KERN_INFO "Init Z8530 driver: %u channels, IRQ", Nchips*2);
flag=" ";
for (k = 0; k < nr_irqs; k++)
if (Ivec[k].used)
{
printk("%s%d", flag, k);
flag=",";
}
printk("\n");
/* reset and pre-init all chips in the system */
for (chip = 0; chip < Nchips; chip++)
{
scc=&SCC_Info[2*chip];
if (!scc->ctrl) continue;
/* Special SCC cards */
if(scc->brand & EAGLE) /* this is an EAGLE card */
Outb(scc->special,0x08); /* enable interrupt on the board */
if(scc->brand & (PC100 | PRIMUS)) /* this is a PC100/PRIMUS card */
Outb(scc->special,scc->option); /* set the MODEM mode (0x22) */
/* Reset and pre-init Z8530 */
spin_lock_irqsave(&scc->lock, flags);
Outb(scc->ctrl, 0);
OutReg(scc->ctrl,R9,FHWRES); /* force hardware reset */
udelay(100); /* give it 'a bit' more time than required */
wr(scc, R2, chip*16); /* interrupt vector */
wr(scc, R9, VIS); /* vector includes status */
spin_unlock_irqrestore(&scc->lock, flags);
}
Driver_Initialized = 1;
}
/*
* Allocate device structure, err, instance, and register driver
*/
static int scc_net_alloc(const char *name, struct scc_channel *scc)
{
int err;
struct net_device *dev;
dev = alloc_netdev(0, name, scc_net_setup);
if (!dev)
return -ENOMEM;
dev->ml_priv = scc;
scc->dev = dev;
spin_lock_init(&scc->lock);
init_timer(&scc->tx_t);
init_timer(&scc->tx_wdog);
err = register_netdevice(dev);
if (err) {
printk(KERN_ERR "%s: can't register network device (%d)\n",
name, err);
free_netdev(dev);
scc->dev = NULL;
return err;
}
return 0;
}
/* ******************************************************************** */
/* * Network driver methods * */
/* ******************************************************************** */
static const struct net_device_ops scc_netdev_ops = {
.ndo_open = scc_net_open,
.ndo_stop = scc_net_close,
.ndo_start_xmit = scc_net_tx,
.ndo_set_mac_address = scc_net_set_mac_address,
.ndo_get_stats = scc_net_get_stats,
.ndo_do_ioctl = scc_net_ioctl,
};
/* ----> Initialize device <----- */
static void scc_net_setup(struct net_device *dev)
{
dev->tx_queue_len = 16; /* should be enough... */
dev->netdev_ops = &scc_netdev_ops;
dev->header_ops = &ax25_header_ops;
memcpy(dev->broadcast, &ax25_bcast, AX25_ADDR_LEN);
memcpy(dev->dev_addr, &ax25_defaddr, AX25_ADDR_LEN);
dev->flags = 0;
dev->type = ARPHRD_AX25;
dev->hard_header_len = AX25_MAX_HEADER_LEN + AX25_BPQ_HEADER_LEN;
dev->mtu = AX25_DEF_PACLEN;
dev->addr_len = AX25_ADDR_LEN;
}
/* ----> open network device <---- */
static int scc_net_open(struct net_device *dev)
{
struct scc_channel *scc = (struct scc_channel *) dev->ml_priv;
if (!scc->init)
return -EINVAL;
scc->tx_buff = NULL;
skb_queue_head_init(&scc->tx_queue);
init_channel(scc);
netif_start_queue(dev);
return 0;
}
/* ----> close network device <---- */
static int scc_net_close(struct net_device *dev)
{
struct scc_channel *scc = (struct scc_channel *) dev->ml_priv;
unsigned long flags;
netif_stop_queue(dev);
spin_lock_irqsave(&scc->lock, flags);
Outb(scc->ctrl,0); /* Make sure pointer is written */
wr(scc,R1,0); /* disable interrupts */
wr(scc,R3,0);
spin_unlock_irqrestore(&scc->lock, flags);
del_timer_sync(&scc->tx_t);
del_timer_sync(&scc->tx_wdog);
scc_discard_buffers(scc);
return 0;
}
/* ----> receive frame, called from scc_rxint() <---- */
static void scc_net_rx(struct scc_channel *scc, struct sk_buff *skb)
{
if (skb->len == 0) {
dev_kfree_skb_irq(skb);
return;
}
scc->dev_stat.rx_packets++;
scc->dev_stat.rx_bytes += skb->len;
skb->protocol = ax25_type_trans(skb, scc->dev);
netif_rx(skb);
}
/* ----> transmit frame <---- */
static netdev_tx_t scc_net_tx(struct sk_buff *skb, struct net_device *dev)
{
struct scc_channel *scc = (struct scc_channel *) dev->ml_priv;
unsigned long flags;
char kisscmd;
if (skb->len > scc->stat.bufsize || skb->len < 2) {
scc->dev_stat.tx_dropped++; /* bogus frame */
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
scc->dev_stat.tx_packets++;
scc->dev_stat.tx_bytes += skb->len;
scc->stat.txframes++;
kisscmd = *skb->data & 0x1f;
skb_pull(skb, 1);
if (kisscmd) {
scc_set_param(scc, kisscmd, *skb->data);
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
spin_lock_irqsave(&scc->lock, flags);
if (skb_queue_len(&scc->tx_queue) > scc->dev->tx_queue_len) {
struct sk_buff *skb_del;
skb_del = skb_dequeue(&scc->tx_queue);
dev_kfree_skb(skb_del);
}
skb_queue_tail(&scc->tx_queue, skb);
dev->trans_start = jiffies;
/*
* Start transmission if the trx state is idle or
* t_idle hasn't expired yet. Use dwait/persistence/slottime
* algorithm for normal halfduplex operation.
*/
if(scc->stat.tx_state == TXS_IDLE || scc->stat.tx_state == TXS_IDLE2) {
scc->stat.tx_state = TXS_BUSY;
if (scc->kiss.fulldup == KISS_DUPLEX_HALF)
__scc_start_tx_timer(scc, t_dwait, scc->kiss.waittime);
else
__scc_start_tx_timer(scc, t_dwait, 0);
}
spin_unlock_irqrestore(&scc->lock, flags);
return NETDEV_TX_OK;
}
/* ----> ioctl functions <---- */
/*
* SIOCSCCCFG - configure driver arg: (struct scc_hw_config *) arg
* SIOCSCCINI - initialize driver arg: ---
* SIOCSCCCHANINI - initialize channel arg: (struct scc_modem *) arg
* SIOCSCCSMEM - set memory arg: (struct scc_mem_config *) arg
* SIOCSCCGKISS - get level 1 parameter arg: (struct scc_kiss_cmd *) arg
* SIOCSCCSKISS - set level 1 parameter arg: (struct scc_kiss_cmd *) arg
* SIOCSCCGSTAT - get driver status arg: (struct scc_stat *) arg
* SIOCSCCCAL - send calib. pattern arg: (struct scc_calibrate *) arg
*/
static int scc_net_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct scc_kiss_cmd kiss_cmd;
struct scc_mem_config memcfg;
struct scc_hw_config hwcfg;
struct scc_calibrate cal;
struct scc_channel *scc = (struct scc_channel *) dev->ml_priv;
int chan;
unsigned char device_name[IFNAMSIZ];
void __user *arg = ifr->ifr_data;
if (!Driver_Initialized)
{
if (cmd == SIOCSCCCFG)
{
int found = 1;
if (!capable(CAP_SYS_RAWIO)) return -EPERM;
if (!arg) return -EFAULT;
if (Nchips >= SCC_MAXCHIPS)
return -EINVAL;
if (copy_from_user(&hwcfg, arg, sizeof(hwcfg)))
return -EFAULT;
if (hwcfg.irq == 2) hwcfg.irq = 9;
if (hwcfg.irq < 0 || hwcfg.irq >= nr_irqs)
return -EINVAL;
if (!Ivec[hwcfg.irq].used && hwcfg.irq)
{
if (request_irq(hwcfg.irq, scc_isr,
IRQF_DISABLED, "AX.25 SCC",
(void *)(long) hwcfg.irq))
printk(KERN_WARNING "z8530drv: warning, cannot get IRQ %d\n", hwcfg.irq);
else
Ivec[hwcfg.irq].used = 1;
}
if (hwcfg.vector_latch && !Vector_Latch) {
if (!request_region(hwcfg.vector_latch, 1, "scc vector latch"))
printk(KERN_WARNING "z8530drv: warning, cannot reserve vector latch port 0x%lx\n, disabled.", hwcfg.vector_latch);
else
Vector_Latch = hwcfg.vector_latch;
}
if (hwcfg.clock == 0)
hwcfg.clock = SCC_DEFAULT_CLOCK;
#ifndef SCC_DONT_CHECK
if(request_region(hwcfg.ctrl_a, 1, "scc-probe"))
{
disable_irq(hwcfg.irq);
Outb(hwcfg.ctrl_a, 0);
OutReg(hwcfg.ctrl_a, R9, FHWRES);
udelay(100);
OutReg(hwcfg.ctrl_a,R13,0x55); /* is this chip really there? */
udelay(5);
if (InReg(hwcfg.ctrl_a,R13) != 0x55)
found = 0;
enable_irq(hwcfg.irq);
release_region(hwcfg.ctrl_a, 1);
}
else
found = 0;
#endif
if (found)
{
SCC_Info[2*Nchips ].ctrl = hwcfg.ctrl_a;
SCC_Info[2*Nchips ].data = hwcfg.data_a;
SCC_Info[2*Nchips ].irq = hwcfg.irq;
SCC_Info[2*Nchips+1].ctrl = hwcfg.ctrl_b;
SCC_Info[2*Nchips+1].data = hwcfg.data_b;
SCC_Info[2*Nchips+1].irq = hwcfg.irq;
SCC_ctrl[Nchips].chan_A = hwcfg.ctrl_a;
SCC_ctrl[Nchips].chan_B = hwcfg.ctrl_b;
SCC_ctrl[Nchips].irq = hwcfg.irq;
}
for (chan = 0; chan < 2; chan++)
{
sprintf(device_name, "%s%i", SCC_DriverName, 2*Nchips+chan);
SCC_Info[2*Nchips+chan].special = hwcfg.special;
SCC_Info[2*Nchips+chan].clock = hwcfg.clock;
SCC_Info[2*Nchips+chan].brand = hwcfg.brand;
SCC_Info[2*Nchips+chan].option = hwcfg.option;
SCC_Info[2*Nchips+chan].enhanced = hwcfg.escc;
#ifdef SCC_DONT_CHECK
printk(KERN_INFO "%s: data port = 0x%3.3x control port = 0x%3.3x\n",
device_name,
SCC_Info[2*Nchips+chan].data,
SCC_Info[2*Nchips+chan].ctrl);
#else
printk(KERN_INFO "%s: data port = 0x%3.3lx control port = 0x%3.3lx -- %s\n",
device_name,
chan? hwcfg.data_b : hwcfg.data_a,
chan? hwcfg.ctrl_b : hwcfg.ctrl_a,
found? "found" : "missing");
#endif
if (found)
{
request_region(SCC_Info[2*Nchips+chan].ctrl, 1, "scc ctrl");
request_region(SCC_Info[2*Nchips+chan].data, 1, "scc data");
if (Nchips+chan != 0 &&
scc_net_alloc(device_name,
&SCC_Info[2*Nchips+chan]))
return -EINVAL;
}
}
if (found) Nchips++;
return 0;
}
if (cmd == SIOCSCCINI)
{
if (!capable(CAP_SYS_RAWIO))
return -EPERM;
if (Nchips == 0)
return -EINVAL;
z8530_init();
return 0;
}
return -EINVAL; /* confuse the user */
}
if (!scc->init)
{
if (cmd == SIOCSCCCHANINI)
{
if (!capable(CAP_NET_ADMIN)) return -EPERM;
if (!arg) return -EINVAL;
scc->stat.bufsize = SCC_BUFSIZE;
if (copy_from_user(&scc->modem, arg, sizeof(struct scc_modem)))
return -EINVAL;
/* default KISS Params */
if (scc->modem.speed < 4800)
{
scc->kiss.txdelay = 36; /* 360 ms */
scc->kiss.persist = 42; /* 25% persistence */ /* was 25 */
scc->kiss.slottime = 16; /* 160 ms */
scc->kiss.tailtime = 4; /* minimal reasonable value */
scc->kiss.fulldup = 0; /* CSMA */
scc->kiss.waittime = 50; /* 500 ms */
scc->kiss.maxkeyup = 10; /* 10 s */
scc->kiss.mintime = 3; /* 3 s */
scc->kiss.idletime = 30; /* 30 s */
scc->kiss.maxdefer = 120; /* 2 min */
scc->kiss.softdcd = 0; /* hardware dcd */
} else {
scc->kiss.txdelay = 10; /* 100 ms */
scc->kiss.persist = 64; /* 25% persistence */ /* was 25 */
scc->kiss.slottime = 8; /* 160 ms */
scc->kiss.tailtime = 1; /* minimal reasonable value */
scc->kiss.fulldup = 0; /* CSMA */
scc->kiss.waittime = 50; /* 500 ms */
scc->kiss.maxkeyup = 7; /* 7 s */
scc->kiss.mintime = 3; /* 3 s */
scc->kiss.idletime = 30; /* 30 s */
scc->kiss.maxdefer = 120; /* 2 min */
scc->kiss.softdcd = 0; /* hardware dcd */
}
scc->tx_buff = NULL;
skb_queue_head_init(&scc->tx_queue);
scc->init = 1;
return 0;
}
return -EINVAL;
}
switch(cmd)
{
case SIOCSCCRESERVED:
return -ENOIOCTLCMD;
case SIOCSCCSMEM:
if (!capable(CAP_SYS_RAWIO)) return -EPERM;
if (!arg || copy_from_user(&memcfg, arg, sizeof(memcfg)))
return -EINVAL;
scc->stat.bufsize = memcfg.bufsize;
return 0;
case SIOCSCCGSTAT:
if (!arg || copy_to_user(arg, &scc->stat, sizeof(scc->stat)))
return -EINVAL;
return 0;
case SIOCSCCGKISS:
if (!arg || copy_from_user(&kiss_cmd, arg, sizeof(kiss_cmd)))
return -EINVAL;
kiss_cmd.param = scc_get_param(scc, kiss_cmd.command);
if (copy_to_user(arg, &kiss_cmd, sizeof(kiss_cmd)))
return -EINVAL;
return 0;
case SIOCSCCSKISS:
if (!capable(CAP_NET_ADMIN)) return -EPERM;
if (!arg || copy_from_user(&kiss_cmd, arg, sizeof(kiss_cmd)))
return -EINVAL;
return scc_set_param(scc, kiss_cmd.command, kiss_cmd.param);
case SIOCSCCCAL:
if (!capable(CAP_SYS_RAWIO)) return -EPERM;
if (!arg || copy_from_user(&cal, arg, sizeof(cal)) || cal.time == 0)
return -EINVAL;
scc_start_calibrate(scc, cal.time, cal.pattern);
return 0;
default:
return -ENOIOCTLCMD;
}
return -EINVAL;
}
/* ----> set interface callsign <---- */
static int scc_net_set_mac_address(struct net_device *dev, void *addr)
{
struct sockaddr *sa = (struct sockaddr *) addr;
memcpy(dev->dev_addr, sa->sa_data, dev->addr_len);
return 0;
}
/* ----> get statistics <---- */
static struct net_device_stats *scc_net_get_stats(struct net_device *dev)
{
struct scc_channel *scc = (struct scc_channel *) dev->ml_priv;
scc->dev_stat.rx_errors = scc->stat.rxerrs + scc->stat.rx_over;
scc->dev_stat.tx_errors = scc->stat.txerrs + scc->stat.tx_under;
scc->dev_stat.rx_fifo_errors = scc->stat.rx_over;
scc->dev_stat.tx_fifo_errors = scc->stat.tx_under;
return &scc->dev_stat;
}
/* ******************************************************************** */
/* * dump statistics to /proc/net/z8530drv * */
/* ******************************************************************** */
#ifdef CONFIG_PROC_FS
static inline struct scc_channel *scc_net_seq_idx(loff_t pos)
{
int k;
for (k = 0; k < Nchips*2; ++k) {
if (!SCC_Info[k].init)
continue;
if (pos-- == 0)
return &SCC_Info[k];
}
return NULL;
}
static void *scc_net_seq_start(struct seq_file *seq, loff_t *pos)
{
return *pos ? scc_net_seq_idx(*pos - 1) : SEQ_START_TOKEN;
}
static void *scc_net_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
unsigned k;
struct scc_channel *scc = v;
++*pos;
for (k = (v == SEQ_START_TOKEN) ? 0 : (scc - SCC_Info)+1;
k < Nchips*2; ++k) {
if (SCC_Info[k].init)
return &SCC_Info[k];
}
return NULL;
}
static void scc_net_seq_stop(struct seq_file *seq, void *v)
{
}
static int scc_net_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN) {
seq_puts(seq, "z8530drv-"VERSION"\n");
} else if (!Driver_Initialized) {
seq_puts(seq, "not initialized\n");
} else if (!Nchips) {
seq_puts(seq, "chips missing\n");
} else {
const struct scc_channel *scc = v;
const struct scc_stat *stat = &scc->stat;
const struct scc_kiss *kiss = &scc->kiss;
/* dev data ctrl irq clock brand enh vector special option
* baud nrz clocksrc softdcd bufsize
* rxints txints exints spints
* rcvd rxerrs over / xmit txerrs under / nospace bufsize
* txd pers slot tail ful wait min maxk idl defr txof grp
* W ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
* R ## ## XX ## ## ## ## ## XX ## ## ## ## ## ## ##
*/
seq_printf(seq, "%s\t%3.3lx %3.3lx %d %lu %2.2x %d %3.3lx %3.3lx %d\n",
scc->dev->name,
scc->data, scc->ctrl, scc->irq, scc->clock, scc->brand,
scc->enhanced, Vector_Latch, scc->special,
scc->option);
seq_printf(seq, "\t%lu %d %d %d %d\n",
scc->modem.speed, scc->modem.nrz,
scc->modem.clocksrc, kiss->softdcd,
stat->bufsize);
seq_printf(seq, "\t%lu %lu %lu %lu\n",
stat->rxints, stat->txints, stat->exints, stat->spints);
seq_printf(seq, "\t%lu %lu %d / %lu %lu %d / %d %d\n",
stat->rxframes, stat->rxerrs, stat->rx_over,
stat->txframes, stat->txerrs, stat->tx_under,
stat->nospace, stat->tx_state);
#define K(x) kiss->x
seq_printf(seq, "\t%d %d %d %d %d %d %d %d %d %d %d %d\n",
K(txdelay), K(persist), K(slottime), K(tailtime),
K(fulldup), K(waittime), K(mintime), K(maxkeyup),
K(idletime), K(maxdefer), K(tx_inhibit), K(group));
#undef K
#ifdef SCC_DEBUG
{
int reg;
seq_printf(seq, "\tW ");
for (reg = 0; reg < 16; reg++)
seq_printf(seq, "%2.2x ", scc->wreg[reg]);
seq_printf(seq, "\n");
seq_printf(seq, "\tR %2.2x %2.2x XX ", InReg(scc->ctrl,R0), InReg(scc->ctrl,R1));
for (reg = 3; reg < 8; reg++)
seq_printf(seq, "%2.2x ", InReg(scc->ctrl, reg));
seq_printf(seq, "XX ");
for (reg = 9; reg < 16; reg++)
seq_printf(seq, "%2.2x ", InReg(scc->ctrl, reg));
seq_printf(seq, "\n");
}
#endif
seq_putc(seq, '\n');
}
return 0;
}
static const struct seq_operations scc_net_seq_ops = {
.start = scc_net_seq_start,
.next = scc_net_seq_next,
.stop = scc_net_seq_stop,
.show = scc_net_seq_show,
};
static int scc_net_seq_open(struct inode *inode, struct file *file)
{
return seq_open(file, &scc_net_seq_ops);
}
static const struct file_operations scc_net_seq_fops = {
.owner = THIS_MODULE,
.open = scc_net_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_private,
};
#endif /* CONFIG_PROC_FS */
/* ******************************************************************** */
/* * Init SCC driver * */
/* ******************************************************************** */
static int __init scc_init_driver (void)
{
char devname[IFNAMSIZ];
printk(banner);
sprintf(devname,"%s0", SCC_DriverName);
rtnl_lock();
if (scc_net_alloc(devname, SCC_Info)) {
rtnl_unlock();
printk(KERN_ERR "z8530drv: cannot initialize module\n");
return -EIO;
}
rtnl_unlock();
proc_create("z8530drv", 0, init_net.proc_net, &scc_net_seq_fops);
return 0;
}
static void __exit scc_cleanup_driver(void)
{
io_port ctrl;
int k;
struct scc_channel *scc;
struct net_device *dev;
if (Nchips == 0 && (dev = SCC_Info[0].dev))
{
unregister_netdev(dev);
free_netdev(dev);
}
/* Guard against chip prattle */
local_irq_disable();
for (k = 0; k < Nchips; k++)
if ( (ctrl = SCC_ctrl[k].chan_A) )
{
Outb(ctrl, 0);
OutReg(ctrl,R9,FHWRES); /* force hardware reset */
udelay(50);
}
/* To unload the port must be closed so no real IRQ pending */
for (k = 0; k < nr_irqs ; k++)
if (Ivec[k].used) free_irq(k, NULL);
local_irq_enable();
/* Now clean up */
for (k = 0; k < Nchips*2; k++)
{
scc = &SCC_Info[k];
if (scc->ctrl)
{
release_region(scc->ctrl, 1);
release_region(scc->data, 1);
}
if (scc->dev)
{
unregister_netdev(scc->dev);
free_netdev(scc->dev);
}
}
if (Vector_Latch)
release_region(Vector_Latch, 1);
remove_proc_entry("z8530drv", init_net.proc_net);
}
MODULE_AUTHOR("Joerg Reuter <jreuter@yaina.de>");
MODULE_DESCRIPTION("AX.25 Device Driver for Z8530 based HDLC cards");
MODULE_SUPPORTED_DEVICE("Z8530 based SCC cards for Amateur Radio");
MODULE_LICENSE("GPL");
module_init(scc_init_driver);
module_exit(scc_cleanup_driver);
| gpl-2.0 |
EmmanuelU/wild_kernel_htc_msm8660 | sound/soc/samsung/rx1950_uda1380.c | 2541 | 7406 | /*
* rx1950.c -- ALSA Soc Audio Layer
*
* Copyright (c) 2010 Vasily Khoruzhick <anarsoul@gmail.com>
*
* Based on smdk2440.c and magician.c
*
* Authors: Graeme Gregory graeme.gregory@wolfsonmicro.com
* Philipp Zabel <philipp.zabel@gmail.com>
* Denis Grigoriev <dgreenday@gmail.com>
* Vasily Khoruzhick <anarsoul@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 <linux/gpio.h>
#include <sound/soc.h>
#include <sound/jack.h>
#include <plat/regs-iis.h>
#include <asm/mach-types.h>
#include "s3c24xx-i2s.h"
static int rx1950_uda1380_init(struct snd_soc_pcm_runtime *rtd);
static int rx1950_startup(struct snd_pcm_substream *substream);
static int rx1950_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params);
static int rx1950_spk_power(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event);
static unsigned int rates[] = {
16000,
44100,
48000,
};
static struct snd_pcm_hw_constraint_list hw_rates = {
.count = ARRAY_SIZE(rates),
.list = rates,
.mask = 0,
};
static struct snd_soc_jack hp_jack;
static struct snd_soc_jack_pin hp_jack_pins[] = {
{
.pin = "Headphone Jack",
.mask = SND_JACK_HEADPHONE,
},
{
.pin = "Speaker",
.mask = SND_JACK_HEADPHONE,
.invert = 1,
},
};
static struct snd_soc_jack_gpio hp_jack_gpios[] = {
[0] = {
.gpio = S3C2410_GPG(12),
.name = "hp-gpio",
.report = SND_JACK_HEADPHONE,
.invert = 1,
.debounce_time = 200,
},
};
static struct snd_soc_ops rx1950_ops = {
.startup = rx1950_startup,
.hw_params = rx1950_hw_params,
};
/* s3c24xx digital audio interface glue - connects codec <--> CPU */
static struct snd_soc_dai_link rx1950_uda1380_dai[] = {
{
.name = "uda1380",
.stream_name = "UDA1380 Duplex",
.cpu_dai_name = "s3c24xx-iis",
.codec_dai_name = "uda1380-hifi",
.init = rx1950_uda1380_init,
.platform_name = "samsung-audio",
.codec_name = "uda1380-codec.0-001a",
.ops = &rx1950_ops,
},
};
static struct snd_soc_card rx1950_asoc = {
.name = "rx1950",
.dai_link = rx1950_uda1380_dai,
.num_links = ARRAY_SIZE(rx1950_uda1380_dai),
};
/* rx1950 machine dapm widgets */
static const struct snd_soc_dapm_widget uda1380_dapm_widgets[] = {
SND_SOC_DAPM_HP("Headphone Jack", NULL),
SND_SOC_DAPM_MIC("Mic Jack", NULL),
SND_SOC_DAPM_SPK("Speaker", rx1950_spk_power),
};
/* rx1950 machine audio_map */
static const struct snd_soc_dapm_route audio_map[] = {
/* headphone connected to VOUTLHP, VOUTRHP */
{"Headphone Jack", NULL, "VOUTLHP"},
{"Headphone Jack", NULL, "VOUTRHP"},
/* ext speaker connected to VOUTL, VOUTR */
{"Speaker", NULL, "VOUTL"},
{"Speaker", NULL, "VOUTR"},
/* mic is connected to VINM */
{"VINM", NULL, "Mic Jack"},
};
static struct platform_device *s3c24xx_snd_device;
static int rx1950_startup(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
runtime->hw.rate_min = hw_rates.list[0];
runtime->hw.rate_max = hw_rates.list[hw_rates.count - 1];
runtime->hw.rates = SNDRV_PCM_RATE_KNOT;
return snd_pcm_hw_constraint_list(runtime, 0,
SNDRV_PCM_HW_PARAM_RATE,
&hw_rates);
}
static int rx1950_spk_power(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
if (SND_SOC_DAPM_EVENT_ON(event))
gpio_set_value(S3C2410_GPA(1), 1);
else
gpio_set_value(S3C2410_GPA(1), 0);
return 0;
}
static int rx1950_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
int div;
int ret;
unsigned int rate = params_rate(params);
int clk_source, fs_mode;
switch (rate) {
case 16000:
case 48000:
clk_source = S3C24XX_CLKSRC_PCLK;
fs_mode = S3C2410_IISMOD_256FS;
div = s3c24xx_i2s_get_clockrate() / (256 * rate);
if (s3c24xx_i2s_get_clockrate() % (256 * rate) > (128 * rate))
div++;
break;
case 44100:
case 88200:
clk_source = S3C24XX_CLKSRC_MPLL;
fs_mode = S3C2410_IISMOD_384FS;
div = 1;
break;
default:
printk(KERN_ERR "%s: rate %d is not supported\n",
__func__, rate);
return -EINVAL;
}
/* set codec DAI configuration */
ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_I2S |
SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBS_CFS);
if (ret < 0)
return ret;
/* set cpu DAI configuration */
ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_I2S |
SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBS_CFS);
if (ret < 0)
return ret;
/* select clock source */
ret = snd_soc_dai_set_sysclk(cpu_dai, clk_source, rate,
SND_SOC_CLOCK_OUT);
if (ret < 0)
return ret;
/* set MCLK division for sample rate */
ret = snd_soc_dai_set_clkdiv(cpu_dai, S3C24XX_DIV_MCLK,
fs_mode);
if (ret < 0)
return ret;
/* set BCLK division for sample rate */
ret = snd_soc_dai_set_clkdiv(cpu_dai, S3C24XX_DIV_BCLK,
S3C2410_IISMOD_32FS);
if (ret < 0)
return ret;
/* set prescaler division for sample rate */
ret = snd_soc_dai_set_clkdiv(cpu_dai, S3C24XX_DIV_PRESCALER,
S3C24XX_PRESCALE(div, div));
if (ret < 0)
return ret;
return 0;
}
static int rx1950_uda1380_init(struct snd_soc_pcm_runtime *rtd)
{
struct snd_soc_codec *codec = rtd->codec;
struct snd_soc_dapm_context *dapm = &codec->dapm;
int err;
/* Add rx1950 specific widgets */
err = snd_soc_dapm_new_controls(dapm, uda1380_dapm_widgets,
ARRAY_SIZE(uda1380_dapm_widgets));
if (err)
return err;
/* Set up rx1950 specific audio path audio_mapnects */
err = snd_soc_dapm_add_routes(dapm, audio_map,
ARRAY_SIZE(audio_map));
if (err)
return err;
snd_soc_dapm_enable_pin(dapm, "Headphone Jack");
snd_soc_dapm_enable_pin(dapm, "Speaker");
snd_soc_dapm_enable_pin(dapm, "Mic Jack");
snd_soc_dapm_sync(dapm);
snd_soc_jack_new(codec, "Headphone Jack", SND_JACK_HEADPHONE,
&hp_jack);
snd_soc_jack_add_pins(&hp_jack, ARRAY_SIZE(hp_jack_pins),
hp_jack_pins);
snd_soc_jack_add_gpios(&hp_jack, ARRAY_SIZE(hp_jack_gpios),
hp_jack_gpios);
return 0;
}
static int __init rx1950_init(void)
{
int ret;
if (!machine_is_rx1950())
return -ENODEV;
/* configure some gpios */
ret = gpio_request(S3C2410_GPA(1), "speaker-power");
if (ret)
goto err_gpio;
ret = gpio_direction_output(S3C2410_GPA(1), 0);
if (ret)
goto err_gpio_conf;
s3c24xx_snd_device = platform_device_alloc("soc-audio", -1);
if (!s3c24xx_snd_device) {
ret = -ENOMEM;
goto err_plat_alloc;
}
platform_set_drvdata(s3c24xx_snd_device, &rx1950_asoc);
ret = platform_device_add(s3c24xx_snd_device);
if (ret) {
platform_device_put(s3c24xx_snd_device);
goto err_plat_add;
}
return 0;
err_plat_add:
err_plat_alloc:
err_gpio_conf:
gpio_free(S3C2410_GPA(1));
err_gpio:
return ret;
}
static void __exit rx1950_exit(void)
{
platform_device_unregister(s3c24xx_snd_device);
snd_soc_jack_free_gpios(&hp_jack, ARRAY_SIZE(hp_jack_gpios),
hp_jack_gpios);
gpio_free(S3C2410_GPA(1));
}
module_init(rx1950_init);
module_exit(rx1950_exit);
/* Module information */
MODULE_AUTHOR("Vasily Khoruzhick");
MODULE_DESCRIPTION("ALSA SoC RX1950");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Luquidtester/DirtyKernel-3.0.101 | drivers/s390/scsi/zfcp_unit.c | 2541 | 6529 | /*
* zfcp device driver
*
* Tracking of manually configured LUNs and helper functions to
* register the LUNs with the SCSI midlayer.
*
* Copyright IBM Corporation 2010
*/
#include "zfcp_def.h"
#include "zfcp_ext.h"
/**
* zfcp_unit_scsi_scan - Register LUN with SCSI midlayer
* @unit: The zfcp LUN/unit to register
*
* When the SCSI midlayer is not allowed to automatically scan and
* attach SCSI devices, zfcp has to register the single devices with
* the SCSI midlayer.
*/
void zfcp_unit_scsi_scan(struct zfcp_unit *unit)
{
struct fc_rport *rport = unit->port->rport;
unsigned int lun;
lun = scsilun_to_int((struct scsi_lun *) &unit->fcp_lun);
if (rport && rport->port_state == FC_PORTSTATE_ONLINE)
scsi_scan_target(&rport->dev, 0, rport->scsi_target_id, lun, 1);
}
static void zfcp_unit_scsi_scan_work(struct work_struct *work)
{
struct zfcp_unit *unit = container_of(work, struct zfcp_unit,
scsi_work);
zfcp_unit_scsi_scan(unit);
put_device(&unit->dev);
}
/**
* zfcp_unit_queue_scsi_scan - Register configured units on port
* @port: The zfcp_port where to register units
*
* After opening a port, all units configured on this port have to be
* registered with the SCSI midlayer. This function should be called
* after calling fc_remote_port_add, so that the fc_rport is already
* ONLINE and the call to scsi_scan_target runs the same way as the
* call in the FC transport class.
*/
void zfcp_unit_queue_scsi_scan(struct zfcp_port *port)
{
struct zfcp_unit *unit;
read_lock_irq(&port->unit_list_lock);
list_for_each_entry(unit, &port->unit_list, list) {
get_device(&unit->dev);
if (scsi_queue_work(port->adapter->scsi_host,
&unit->scsi_work) <= 0)
put_device(&unit->dev);
}
read_unlock_irq(&port->unit_list_lock);
}
static struct zfcp_unit *_zfcp_unit_find(struct zfcp_port *port, u64 fcp_lun)
{
struct zfcp_unit *unit;
list_for_each_entry(unit, &port->unit_list, list)
if (unit->fcp_lun == fcp_lun) {
get_device(&unit->dev);
return unit;
}
return NULL;
}
/**
* zfcp_unit_find - Find and return zfcp_unit with specified FCP LUN
* @port: zfcp_port where to look for the unit
* @fcp_lun: 64 Bit FCP LUN used to identify the zfcp_unit
*
* If zfcp_unit is found, a reference is acquired that has to be
* released later.
*
* Returns: Pointer to the zfcp_unit, or NULL if there is no zfcp_unit
* with the specified FCP LUN.
*/
struct zfcp_unit *zfcp_unit_find(struct zfcp_port *port, u64 fcp_lun)
{
struct zfcp_unit *unit;
read_lock_irq(&port->unit_list_lock);
unit = _zfcp_unit_find(port, fcp_lun);
read_unlock_irq(&port->unit_list_lock);
return unit;
}
/**
* zfcp_unit_release - Drop reference to zfcp_port and free memory of zfcp_unit.
* @dev: pointer to device in zfcp_unit
*/
static void zfcp_unit_release(struct device *dev)
{
struct zfcp_unit *unit = container_of(dev, struct zfcp_unit, dev);
atomic_dec(&unit->port->units);
kfree(unit);
}
/**
* zfcp_unit_enqueue - enqueue unit to unit list of a port.
* @port: pointer to port where unit is added
* @fcp_lun: FCP LUN of unit to be enqueued
* Returns: 0 success
*
* Sets up some unit internal structures and creates sysfs entry.
*/
int zfcp_unit_add(struct zfcp_port *port, u64 fcp_lun)
{
struct zfcp_unit *unit;
int retval = 0;
mutex_lock(&zfcp_sysfs_port_units_mutex);
if (atomic_read(&port->units) == -1) {
/* port is already gone */
retval = -ENODEV;
goto out;
}
unit = zfcp_unit_find(port, fcp_lun);
if (unit) {
put_device(&unit->dev);
retval = -EEXIST;
goto out;
}
unit = kzalloc(sizeof(struct zfcp_unit), GFP_KERNEL);
if (!unit) {
retval = -ENOMEM;
goto out;
}
unit->port = port;
unit->fcp_lun = fcp_lun;
unit->dev.parent = &port->dev;
unit->dev.release = zfcp_unit_release;
INIT_WORK(&unit->scsi_work, zfcp_unit_scsi_scan_work);
if (dev_set_name(&unit->dev, "0x%016llx",
(unsigned long long) fcp_lun)) {
kfree(unit);
retval = -ENOMEM;
goto out;
}
if (device_register(&unit->dev)) {
put_device(&unit->dev);
retval = -ENOMEM;
goto out;
}
if (sysfs_create_group(&unit->dev.kobj, &zfcp_sysfs_unit_attrs)) {
device_unregister(&unit->dev);
retval = -EINVAL;
goto out;
}
atomic_inc(&port->units); /* under zfcp_sysfs_port_units_mutex ! */
write_lock_irq(&port->unit_list_lock);
list_add_tail(&unit->list, &port->unit_list);
write_unlock_irq(&port->unit_list_lock);
zfcp_unit_scsi_scan(unit);
out:
mutex_unlock(&zfcp_sysfs_port_units_mutex);
return retval;
}
/**
* zfcp_unit_sdev - Return SCSI device for zfcp_unit
* @unit: The zfcp_unit where to get the SCSI device for
*
* Returns: scsi_device pointer on success, NULL if there is no SCSI
* device for this zfcp_unit
*
* On success, the caller also holds a reference to the SCSI device
* that must be released with scsi_device_put.
*/
struct scsi_device *zfcp_unit_sdev(struct zfcp_unit *unit)
{
struct Scsi_Host *shost;
struct zfcp_port *port;
unsigned int lun;
lun = scsilun_to_int((struct scsi_lun *) &unit->fcp_lun);
port = unit->port;
shost = port->adapter->scsi_host;
return scsi_device_lookup(shost, 0, port->starget_id, lun);
}
/**
* zfcp_unit_sdev_status - Return zfcp LUN status for SCSI device
* @unit: The unit to lookup the SCSI device for
*
* Returns the zfcp LUN status field of the SCSI device if the SCSI device
* for the zfcp_unit exists, 0 otherwise.
*/
unsigned int zfcp_unit_sdev_status(struct zfcp_unit *unit)
{
unsigned int status = 0;
struct scsi_device *sdev;
struct zfcp_scsi_dev *zfcp_sdev;
sdev = zfcp_unit_sdev(unit);
if (sdev) {
zfcp_sdev = sdev_to_zfcp(sdev);
status = atomic_read(&zfcp_sdev->status);
scsi_device_put(sdev);
}
return status;
}
/**
* zfcp_unit_remove - Remove entry from list of configured units
* @port: The port where to remove the unit from the configuration
* @fcp_lun: The 64 bit LUN of the unit to remove
*
* Returns: -EINVAL if a unit with the specified LUN does not exist,
* 0 on success.
*/
int zfcp_unit_remove(struct zfcp_port *port, u64 fcp_lun)
{
struct zfcp_unit *unit;
struct scsi_device *sdev;
write_lock_irq(&port->unit_list_lock);
unit = _zfcp_unit_find(port, fcp_lun);
if (unit)
list_del(&unit->list);
write_unlock_irq(&port->unit_list_lock);
if (!unit)
return -EINVAL;
sdev = zfcp_unit_sdev(unit);
if (sdev) {
scsi_remove_device(sdev);
scsi_device_put(sdev);
}
put_device(&unit->dev);
zfcp_device_unregister(&unit->dev, &zfcp_sysfs_unit_attrs);
return 0;
}
| gpl-2.0 |
viaembedded/springboard-kernel-bsp | net/core/secure_seq.c | 2797 | 4383 | #include <linux/kernel.h>
#include <linux/init.h>
#include <linux/cryptohash.h>
#include <linux/module.h>
#include <linux/cache.h>
#include <linux/random.h>
#include <linux/hrtimer.h>
#include <linux/ktime.h>
#include <linux/string.h>
#include <net/secure_seq.h>
static u32 net_secret[MD5_MESSAGE_BYTES / 4] ____cacheline_aligned;
static int __init net_secret_init(void)
{
get_random_bytes(net_secret, sizeof(net_secret));
return 0;
}
late_initcall(net_secret_init);
static u32 seq_scale(u32 seq)
{
/*
* As close as possible to RFC 793, which
* suggests using a 250 kHz clock.
* Further reading shows this assumes 2 Mb/s networks.
* For 10 Mb/s Ethernet, a 1 MHz clock is appropriate.
* For 10 Gb/s Ethernet, a 1 GHz clock should be ok, but
* we also need to limit the resolution so that the u32 seq
* overlaps less than one time per MSL (2 minutes).
* Choosing a clock of 64 ns period is OK. (period of 274 s)
*/
return seq + (ktime_to_ns(ktime_get_real()) >> 6);
}
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
__u32 secure_tcpv6_sequence_number(__be32 *saddr, __be32 *daddr,
__be16 sport, __be16 dport)
{
u32 secret[MD5_MESSAGE_BYTES / 4];
u32 hash[MD5_DIGEST_WORDS];
u32 i;
memcpy(hash, saddr, 16);
for (i = 0; i < 4; i++)
secret[i] = net_secret[i] + daddr[i];
secret[4] = net_secret[4] +
(((__force u16)sport << 16) + (__force u16)dport);
for (i = 5; i < MD5_MESSAGE_BYTES / 4; i++)
secret[i] = net_secret[i];
md5_transform(hash, secret);
return seq_scale(hash[0]);
}
EXPORT_SYMBOL(secure_tcpv6_sequence_number);
u32 secure_ipv6_port_ephemeral(const __be32 *saddr, const __be32 *daddr,
__be16 dport)
{
u32 secret[MD5_MESSAGE_BYTES / 4];
u32 hash[MD5_DIGEST_WORDS];
u32 i;
memcpy(hash, saddr, 16);
for (i = 0; i < 4; i++)
secret[i] = net_secret[i] + (__force u32) daddr[i];
secret[4] = net_secret[4] + (__force u32)dport;
for (i = 5; i < MD5_MESSAGE_BYTES / 4; i++)
secret[i] = net_secret[i];
md5_transform(hash, secret);
return hash[0];
}
#endif
#ifdef CONFIG_INET
__u32 secure_ip_id(__be32 daddr)
{
u32 hash[MD5_DIGEST_WORDS];
hash[0] = (__force __u32) daddr;
hash[1] = net_secret[13];
hash[2] = net_secret[14];
hash[3] = net_secret[15];
md5_transform(hash, net_secret);
return hash[0];
}
__u32 secure_ipv6_id(const __be32 daddr[4])
{
__u32 hash[4];
memcpy(hash, daddr, 16);
md5_transform(hash, net_secret);
return hash[0];
}
__u32 secure_tcp_sequence_number(__be32 saddr, __be32 daddr,
__be16 sport, __be16 dport)
{
u32 hash[MD5_DIGEST_WORDS];
hash[0] = (__force u32)saddr;
hash[1] = (__force u32)daddr;
hash[2] = ((__force u16)sport << 16) + (__force u16)dport;
hash[3] = net_secret[15];
md5_transform(hash, net_secret);
return seq_scale(hash[0]);
}
u32 secure_ipv4_port_ephemeral(__be32 saddr, __be32 daddr, __be16 dport)
{
u32 hash[MD5_DIGEST_WORDS];
hash[0] = (__force u32)saddr;
hash[1] = (__force u32)daddr;
hash[2] = (__force u32)dport ^ net_secret[14];
hash[3] = net_secret[15];
md5_transform(hash, net_secret);
return hash[0];
}
EXPORT_SYMBOL_GPL(secure_ipv4_port_ephemeral);
#endif
#if defined(CONFIG_IP_DCCP) || defined(CONFIG_IP_DCCP_MODULE)
u64 secure_dccp_sequence_number(__be32 saddr, __be32 daddr,
__be16 sport, __be16 dport)
{
u32 hash[MD5_DIGEST_WORDS];
u64 seq;
hash[0] = (__force u32)saddr;
hash[1] = (__force u32)daddr;
hash[2] = ((__force u16)sport << 16) + (__force u16)dport;
hash[3] = net_secret[15];
md5_transform(hash, net_secret);
seq = hash[0] | (((u64)hash[1]) << 32);
seq += ktime_to_ns(ktime_get_real());
seq &= (1ull << 48) - 1;
return seq;
}
EXPORT_SYMBOL(secure_dccp_sequence_number);
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
u64 secure_dccpv6_sequence_number(__be32 *saddr, __be32 *daddr,
__be16 sport, __be16 dport)
{
u32 secret[MD5_MESSAGE_BYTES / 4];
u32 hash[MD5_DIGEST_WORDS];
u64 seq;
u32 i;
memcpy(hash, saddr, 16);
for (i = 0; i < 4; i++)
secret[i] = net_secret[i] + daddr[i];
secret[4] = net_secret[4] +
(((__force u16)sport << 16) + (__force u16)dport);
for (i = 5; i < MD5_MESSAGE_BYTES / 4; i++)
secret[i] = net_secret[i];
md5_transform(hash, secret);
seq = hash[0] | (((u64)hash[1]) << 32);
seq += ktime_to_ns(ktime_get_real());
seq &= (1ull << 48) - 1;
return seq;
}
EXPORT_SYMBOL(secure_dccpv6_sequence_number);
#endif
#endif
| gpl-2.0 |
cnexus/kernel_d2spr_tw_422 | net/nfc/llcp/sock.c | 3565 | 15586 | /*
* Copyright (C) 2011 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#define pr_fmt(fmt) "llcp: %s: " fmt, __func__
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/nfc.h>
#include "../nfc.h"
#include "llcp.h"
static struct proto llcp_sock_proto = {
.name = "NFC_LLCP",
.owner = THIS_MODULE,
.obj_size = sizeof(struct nfc_llcp_sock),
};
static int llcp_sock_bind(struct socket *sock, struct sockaddr *addr, int alen)
{
struct sock *sk = sock->sk;
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
struct nfc_llcp_local *local;
struct nfc_dev *dev;
struct sockaddr_nfc_llcp llcp_addr;
int len, ret = 0;
pr_debug("sk %p addr %p family %d\n", sk, addr, addr->sa_family);
if (!addr || addr->sa_family != AF_NFC)
return -EINVAL;
memset(&llcp_addr, 0, sizeof(llcp_addr));
len = min_t(unsigned int, sizeof(llcp_addr), alen);
memcpy(&llcp_addr, addr, len);
/* This is going to be a listening socket, dsap must be 0 */
if (llcp_addr.dsap != 0)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state != LLCP_CLOSED) {
ret = -EBADFD;
goto error;
}
dev = nfc_get_device(llcp_addr.dev_idx);
if (dev == NULL) {
ret = -ENODEV;
goto error;
}
local = nfc_llcp_find_local(dev);
if (local == NULL) {
ret = -ENODEV;
goto put_dev;
}
llcp_sock->dev = dev;
llcp_sock->local = local;
llcp_sock->nfc_protocol = llcp_addr.nfc_protocol;
llcp_sock->service_name_len = min_t(unsigned int,
llcp_addr.service_name_len,
NFC_LLCP_MAX_SERVICE_NAME);
llcp_sock->service_name = kmemdup(llcp_addr.service_name,
llcp_sock->service_name_len,
GFP_KERNEL);
llcp_sock->ssap = nfc_llcp_get_sdp_ssap(local, llcp_sock);
if (llcp_sock->ssap == LLCP_MAX_SAP)
goto put_dev;
local->sockets[llcp_sock->ssap] = llcp_sock;
pr_debug("Socket bound to SAP %d\n", llcp_sock->ssap);
sk->sk_state = LLCP_BOUND;
put_dev:
nfc_put_device(dev);
error:
release_sock(sk);
return ret;
}
static int llcp_sock_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int ret = 0;
pr_debug("sk %p backlog %d\n", sk, backlog);
lock_sock(sk);
if ((sock->type != SOCK_SEQPACKET && sock->type != SOCK_STREAM)
|| sk->sk_state != LLCP_BOUND) {
ret = -EBADFD;
goto error;
}
sk->sk_max_ack_backlog = backlog;
sk->sk_ack_backlog = 0;
pr_debug("Socket listening\n");
sk->sk_state = LLCP_LISTEN;
error:
release_sock(sk);
return ret;
}
void nfc_llcp_accept_unlink(struct sock *sk)
{
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
pr_debug("state %d\n", sk->sk_state);
list_del_init(&llcp_sock->accept_queue);
sk_acceptq_removed(llcp_sock->parent);
llcp_sock->parent = NULL;
sock_put(sk);
}
void nfc_llcp_accept_enqueue(struct sock *parent, struct sock *sk)
{
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
struct nfc_llcp_sock *llcp_sock_parent = nfc_llcp_sock(parent);
/* Lock will be free from unlink */
sock_hold(sk);
list_add_tail(&llcp_sock->accept_queue,
&llcp_sock_parent->accept_queue);
llcp_sock->parent = parent;
sk_acceptq_added(parent);
}
struct sock *nfc_llcp_accept_dequeue(struct sock *parent,
struct socket *newsock)
{
struct nfc_llcp_sock *lsk, *n, *llcp_parent;
struct sock *sk;
llcp_parent = nfc_llcp_sock(parent);
list_for_each_entry_safe(lsk, n, &llcp_parent->accept_queue,
accept_queue) {
sk = &lsk->sk;
lock_sock(sk);
if (sk->sk_state == LLCP_CLOSED) {
release_sock(sk);
nfc_llcp_accept_unlink(sk);
continue;
}
if (sk->sk_state == LLCP_CONNECTED || !newsock) {
nfc_llcp_accept_unlink(sk);
if (newsock)
sock_graft(sk, newsock);
release_sock(sk);
pr_debug("Returning sk state %d\n", sk->sk_state);
return sk;
}
release_sock(sk);
}
return NULL;
}
static int llcp_sock_accept(struct socket *sock, struct socket *newsock,
int flags)
{
DECLARE_WAITQUEUE(wait, current);
struct sock *sk = sock->sk, *new_sk;
long timeo;
int ret = 0;
pr_debug("parent %p\n", sk);
lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
if (sk->sk_state != LLCP_LISTEN) {
ret = -EBADFD;
goto error;
}
timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
/* Wait for an incoming connection. */
add_wait_queue_exclusive(sk_sleep(sk), &wait);
while (!(new_sk = nfc_llcp_accept_dequeue(sk, newsock))) {
set_current_state(TASK_INTERRUPTIBLE);
if (!timeo) {
ret = -EAGAIN;
break;
}
if (signal_pending(current)) {
ret = sock_intr_errno(timeo);
break;
}
release_sock(sk);
timeo = schedule_timeout(timeo);
lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(sk_sleep(sk), &wait);
if (ret)
goto error;
newsock->state = SS_CONNECTED;
pr_debug("new socket %p\n", new_sk);
error:
release_sock(sk);
return ret;
}
static int llcp_sock_getname(struct socket *sock, struct sockaddr *addr,
int *len, int peer)
{
struct sockaddr_nfc_llcp *llcp_addr = (struct sockaddr_nfc_llcp *)addr;
struct sock *sk = sock->sk;
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
pr_debug("%p\n", sk);
addr->sa_family = AF_NFC;
*len = sizeof(struct sockaddr_nfc_llcp);
llcp_addr->dev_idx = llcp_sock->dev->idx;
llcp_addr->dsap = llcp_sock->dsap;
llcp_addr->ssap = llcp_sock->ssap;
llcp_addr->service_name_len = llcp_sock->service_name_len;
memcpy(llcp_addr->service_name, llcp_sock->service_name,
llcp_addr->service_name_len);
return 0;
}
static inline unsigned int llcp_accept_poll(struct sock *parent)
{
struct nfc_llcp_sock *llcp_sock, *n, *parent_sock;
struct sock *sk;
parent_sock = nfc_llcp_sock(parent);
list_for_each_entry_safe(llcp_sock, n, &parent_sock->accept_queue,
accept_queue) {
sk = &llcp_sock->sk;
if (sk->sk_state == LLCP_CONNECTED)
return POLLIN | POLLRDNORM;
}
return 0;
}
static unsigned int llcp_sock_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
unsigned int mask = 0;
pr_debug("%p\n", sk);
sock_poll_wait(file, sk_sleep(sk), wait);
if (sk->sk_state == LLCP_LISTEN)
return llcp_accept_poll(sk);
if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
mask |= POLLERR;
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN;
if (sk->sk_state == LLCP_CLOSED)
mask |= POLLHUP;
return mask;
}
static int llcp_sock_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct nfc_llcp_local *local;
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
int err = 0;
if (!sk)
return 0;
pr_debug("%p\n", sk);
local = llcp_sock->local;
if (local == NULL) {
err = -ENODEV;
goto out;
}
mutex_lock(&local->socket_lock);
if (llcp_sock == local->sockets[llcp_sock->ssap])
local->sockets[llcp_sock->ssap] = NULL;
else
list_del_init(&llcp_sock->list);
mutex_unlock(&local->socket_lock);
lock_sock(sk);
/* Send a DISC */
if (sk->sk_state == LLCP_CONNECTED)
nfc_llcp_disconnect(llcp_sock);
if (sk->sk_state == LLCP_LISTEN) {
struct nfc_llcp_sock *lsk, *n;
struct sock *accept_sk;
list_for_each_entry_safe(lsk, n, &llcp_sock->accept_queue,
accept_queue) {
accept_sk = &lsk->sk;
lock_sock(accept_sk);
nfc_llcp_disconnect(lsk);
nfc_llcp_accept_unlink(accept_sk);
release_sock(accept_sk);
sock_orphan(accept_sk);
}
}
/* Freeing the SAP */
if ((sk->sk_state == LLCP_CONNECTED
&& llcp_sock->ssap > LLCP_LOCAL_SAP_OFFSET) ||
sk->sk_state == LLCP_BOUND || sk->sk_state == LLCP_LISTEN)
nfc_llcp_put_ssap(llcp_sock->local, llcp_sock->ssap);
release_sock(sk);
out:
sock_orphan(sk);
sock_put(sk);
return err;
}
static int llcp_sock_connect(struct socket *sock, struct sockaddr *_addr,
int len, int flags)
{
struct sock *sk = sock->sk;
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
struct sockaddr_nfc_llcp *addr = (struct sockaddr_nfc_llcp *)_addr;
struct nfc_dev *dev;
struct nfc_llcp_local *local;
int ret = 0;
pr_debug("sock %p sk %p flags 0x%x\n", sock, sk, flags);
if (!addr || len < sizeof(struct sockaddr_nfc) ||
addr->sa_family != AF_NFC) {
pr_err("Invalid socket\n");
return -EINVAL;
}
if (addr->service_name_len == 0 && addr->dsap == 0) {
pr_err("Missing service name or dsap\n");
return -EINVAL;
}
pr_debug("addr dev_idx=%u target_idx=%u protocol=%u\n", addr->dev_idx,
addr->target_idx, addr->nfc_protocol);
lock_sock(sk);
if (sk->sk_state == LLCP_CONNECTED) {
ret = -EISCONN;
goto error;
}
dev = nfc_get_device(addr->dev_idx);
if (dev == NULL) {
ret = -ENODEV;
goto error;
}
local = nfc_llcp_find_local(dev);
if (local == NULL) {
ret = -ENODEV;
goto put_dev;
}
device_lock(&dev->dev);
if (dev->dep_link_up == false) {
ret = -ENOLINK;
device_unlock(&dev->dev);
goto put_dev;
}
device_unlock(&dev->dev);
if (local->rf_mode == NFC_RF_INITIATOR &&
addr->target_idx != local->target_idx) {
ret = -ENOLINK;
goto put_dev;
}
llcp_sock->dev = dev;
llcp_sock->local = local;
llcp_sock->ssap = nfc_llcp_get_local_ssap(local);
if (llcp_sock->ssap == LLCP_SAP_MAX) {
ret = -ENOMEM;
goto put_dev;
}
if (addr->service_name_len == 0)
llcp_sock->dsap = addr->dsap;
else
llcp_sock->dsap = LLCP_SAP_SDP;
llcp_sock->nfc_protocol = addr->nfc_protocol;
llcp_sock->service_name_len = min_t(unsigned int,
addr->service_name_len,
NFC_LLCP_MAX_SERVICE_NAME);
llcp_sock->service_name = kmemdup(addr->service_name,
llcp_sock->service_name_len,
GFP_KERNEL);
local->sockets[llcp_sock->ssap] = llcp_sock;
ret = nfc_llcp_send_connect(llcp_sock);
if (ret)
goto put_dev;
sk->sk_state = LLCP_CONNECTED;
release_sock(sk);
return 0;
put_dev:
nfc_put_device(dev);
error:
release_sock(sk);
return ret;
}
static int llcp_sock_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
int ret;
pr_debug("sock %p sk %p", sock, sk);
ret = sock_error(sk);
if (ret)
return ret;
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
lock_sock(sk);
if (sk->sk_state != LLCP_CONNECTED) {
release_sock(sk);
return -ENOTCONN;
}
release_sock(sk);
return nfc_llcp_send_i_frame(llcp_sock, msg, len);
}
static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
int noblock = flags & MSG_DONTWAIT;
struct sock *sk = sock->sk;
unsigned int copied, rlen;
struct sk_buff *skb, *cskb;
int err = 0;
pr_debug("%p %zu\n", sk, len);
lock_sock(sk);
if (sk->sk_state == LLCP_CLOSED &&
skb_queue_empty(&sk->sk_receive_queue)) {
release_sock(sk);
return 0;
}
release_sock(sk);
if (flags & (MSG_OOB))
return -EOPNOTSUPP;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb) {
pr_err("Recv datagram failed state %d %d %d",
sk->sk_state, err, sock_error(sk));
if (sk->sk_shutdown & RCV_SHUTDOWN)
return 0;
return err;
}
rlen = skb->len; /* real length of skb */
copied = min_t(unsigned int, rlen, len);
cskb = skb;
if (memcpy_toiovec(msg->msg_iov, cskb->data, copied)) {
if (!(flags & MSG_PEEK))
skb_queue_head(&sk->sk_receive_queue, skb);
return -EFAULT;
}
/* Mark read part of skb as used */
if (!(flags & MSG_PEEK)) {
/* SOCK_STREAM: re-queue skb if it contains unreceived data */
if (sk->sk_type == SOCK_STREAM) {
skb_pull(skb, copied);
if (skb->len) {
skb_queue_head(&sk->sk_receive_queue, skb);
goto done;
}
}
kfree_skb(skb);
}
/* XXX Queue backlogged skbs */
done:
/* SOCK_SEQPACKET: return real length if MSG_TRUNC is set */
if (sk->sk_type == SOCK_SEQPACKET && (flags & MSG_TRUNC))
copied = rlen;
return copied;
}
static const struct proto_ops llcp_sock_ops = {
.family = PF_NFC,
.owner = THIS_MODULE,
.bind = llcp_sock_bind,
.connect = llcp_sock_connect,
.release = llcp_sock_release,
.socketpair = sock_no_socketpair,
.accept = llcp_sock_accept,
.getname = llcp_sock_getname,
.poll = llcp_sock_poll,
.ioctl = sock_no_ioctl,
.listen = llcp_sock_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = llcp_sock_sendmsg,
.recvmsg = llcp_sock_recvmsg,
.mmap = sock_no_mmap,
};
static void llcp_sock_destruct(struct sock *sk)
{
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
pr_debug("%p\n", sk);
if (sk->sk_state == LLCP_CONNECTED)
nfc_put_device(llcp_sock->dev);
skb_queue_purge(&sk->sk_receive_queue);
nfc_llcp_sock_free(llcp_sock);
if (!sock_flag(sk, SOCK_DEAD)) {
pr_err("Freeing alive NFC LLCP socket %p\n", sk);
return;
}
}
struct sock *nfc_llcp_sock_alloc(struct socket *sock, int type, gfp_t gfp)
{
struct sock *sk;
struct nfc_llcp_sock *llcp_sock;
sk = sk_alloc(&init_net, PF_NFC, gfp, &llcp_sock_proto);
if (!sk)
return NULL;
llcp_sock = nfc_llcp_sock(sk);
sock_init_data(sock, sk);
sk->sk_state = LLCP_CLOSED;
sk->sk_protocol = NFC_SOCKPROTO_LLCP;
sk->sk_type = type;
sk->sk_destruct = llcp_sock_destruct;
llcp_sock->ssap = 0;
llcp_sock->dsap = LLCP_SAP_SDP;
llcp_sock->send_n = llcp_sock->send_ack_n = 0;
llcp_sock->recv_n = llcp_sock->recv_ack_n = 0;
llcp_sock->remote_ready = 1;
skb_queue_head_init(&llcp_sock->tx_queue);
skb_queue_head_init(&llcp_sock->tx_pending_queue);
skb_queue_head_init(&llcp_sock->tx_backlog_queue);
INIT_LIST_HEAD(&llcp_sock->list);
INIT_LIST_HEAD(&llcp_sock->accept_queue);
if (sock != NULL)
sock->state = SS_UNCONNECTED;
return sk;
}
void nfc_llcp_sock_free(struct nfc_llcp_sock *sock)
{
struct nfc_llcp_local *local = sock->local;
kfree(sock->service_name);
skb_queue_purge(&sock->tx_queue);
skb_queue_purge(&sock->tx_pending_queue);
skb_queue_purge(&sock->tx_backlog_queue);
list_del_init(&sock->accept_queue);
if (local != NULL && sock == local->sockets[sock->ssap])
local->sockets[sock->ssap] = NULL;
else
list_del_init(&sock->list);
sock->parent = NULL;
}
static int llcp_sock_create(struct net *net, struct socket *sock,
const struct nfc_protocol *nfc_proto)
{
struct sock *sk;
pr_debug("%p\n", sock);
if (sock->type != SOCK_STREAM && sock->type != SOCK_DGRAM)
return -ESOCKTNOSUPPORT;
sock->ops = &llcp_sock_ops;
sk = nfc_llcp_sock_alloc(sock, sock->type, GFP_ATOMIC);
if (sk == NULL)
return -ENOMEM;
return 0;
}
static const struct nfc_protocol llcp_nfc_proto = {
.id = NFC_SOCKPROTO_LLCP,
.proto = &llcp_sock_proto,
.owner = THIS_MODULE,
.create = llcp_sock_create
};
int __init nfc_llcp_sock_init(void)
{
return nfc_proto_register(&llcp_nfc_proto);
}
void nfc_llcp_sock_exit(void)
{
nfc_proto_unregister(&llcp_nfc_proto);
}
| gpl-2.0 |
kyasu/android_kernel_samsung_hltedcm | arch/arm/mach-omap2/mcbsp.c | 4845 | 5803 | /*
* linux/arch/arm/mach-omap2/mcbsp.c
*
* Copyright (C) 2008 Instituto Nokia de Tecnologia
* Contact: Eduardo Valentin <eduardo.valentin@indt.org.br>
*
* 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.
*
* Multichannel mode not supported.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <mach/irqs.h>
#include <plat/dma.h>
#include <plat/cpu.h>
#include <plat/mcbsp.h>
#include <plat/omap_device.h>
#include <linux/pm_runtime.h>
#include "control.h"
/*
* FIXME: Find a mechanism to enable/disable runtime the McBSP ICLK autoidle.
* Sidetone needs non-gated ICLK and sidetone autoidle is broken.
*/
#include "cm2xxx_3xxx.h"
#include "cm-regbits-34xx.h"
/* McBSP1 internal signal muxing function for OMAP2/3 */
static int omap2_mcbsp1_mux_rx_clk(struct device *dev, const char *signal,
const char *src)
{
u32 v;
v = omap_ctrl_readl(OMAP2_CONTROL_DEVCONF0);
if (!strcmp(signal, "clkr")) {
if (!strcmp(src, "clkr"))
v &= ~OMAP2_MCBSP1_CLKR_MASK;
else if (!strcmp(src, "clkx"))
v |= OMAP2_MCBSP1_CLKR_MASK;
else
return -EINVAL;
} else if (!strcmp(signal, "fsr")) {
if (!strcmp(src, "fsr"))
v &= ~OMAP2_MCBSP1_FSR_MASK;
else if (!strcmp(src, "fsx"))
v |= OMAP2_MCBSP1_FSR_MASK;
else
return -EINVAL;
} else {
return -EINVAL;
}
omap_ctrl_writel(v, OMAP2_CONTROL_DEVCONF0);
return 0;
}
/* McBSP4 internal signal muxing function for OMAP4 */
#define OMAP4_CONTROL_MCBSPLP_ALBCTRLRX_FSX (1 << 31)
#define OMAP4_CONTROL_MCBSPLP_ALBCTRLRX_CLKX (1 << 30)
static int omap4_mcbsp4_mux_rx_clk(struct device *dev, const char *signal,
const char *src)
{
u32 v;
/*
* In CONTROL_MCBSPLP register only bit 30 (CLKR mux), and bit 31 (FSR
* mux) is used */
v = omap4_ctrl_pad_readl(OMAP4_CTRL_MODULE_PAD_CORE_CONTROL_MCBSPLP);
if (!strcmp(signal, "clkr")) {
if (!strcmp(src, "clkr"))
v &= ~OMAP4_CONTROL_MCBSPLP_ALBCTRLRX_CLKX;
else if (!strcmp(src, "clkx"))
v |= OMAP4_CONTROL_MCBSPLP_ALBCTRLRX_CLKX;
else
return -EINVAL;
} else if (!strcmp(signal, "fsr")) {
if (!strcmp(src, "fsr"))
v &= ~OMAP4_CONTROL_MCBSPLP_ALBCTRLRX_FSX;
else if (!strcmp(src, "fsx"))
v |= OMAP4_CONTROL_MCBSPLP_ALBCTRLRX_FSX;
else
return -EINVAL;
} else {
return -EINVAL;
}
omap4_ctrl_pad_writel(v, OMAP4_CTRL_MODULE_PAD_CORE_CONTROL_MCBSPLP);
return 0;
}
/* McBSP CLKS source switching function */
static int omap2_mcbsp_set_clk_src(struct device *dev, struct clk *clk,
const char *src)
{
struct clk *fck_src;
char *fck_src_name;
int r;
if (!strcmp(src, "clks_ext"))
fck_src_name = "pad_fck";
else if (!strcmp(src, "clks_fclk"))
fck_src_name = "prcm_fck";
else
return -EINVAL;
fck_src = clk_get(dev, fck_src_name);
if (IS_ERR_OR_NULL(fck_src)) {
pr_err("omap-mcbsp: %s: could not clk_get() %s\n", "clks",
fck_src_name);
return -EINVAL;
}
pm_runtime_put_sync(dev);
r = clk_set_parent(clk, fck_src);
if (IS_ERR_VALUE(r)) {
pr_err("omap-mcbsp: %s: could not clk_set_parent() to %s\n",
"clks", fck_src_name);
clk_put(fck_src);
return -EINVAL;
}
pm_runtime_get_sync(dev);
clk_put(fck_src);
return 0;
}
static int omap3_enable_st_clock(unsigned int id, bool enable)
{
unsigned int w;
/*
* Sidetone uses McBSP ICLK - which must not idle when sidetones
* are enabled or sidetones start sounding ugly.
*/
w = omap2_cm_read_mod_reg(OMAP3430_PER_MOD, CM_AUTOIDLE);
if (enable)
w &= ~(1 << (id - 2));
else
w |= 1 << (id - 2);
omap2_cm_write_mod_reg(w, OMAP3430_PER_MOD, CM_AUTOIDLE);
return 0;
}
static int __init omap_init_mcbsp(struct omap_hwmod *oh, void *unused)
{
int id, count = 1;
char *name = "omap-mcbsp";
struct omap_hwmod *oh_device[2];
struct omap_mcbsp_platform_data *pdata = NULL;
struct platform_device *pdev;
sscanf(oh->name, "mcbsp%d", &id);
pdata = kzalloc(sizeof(struct omap_mcbsp_platform_data), GFP_KERNEL);
if (!pdata) {
pr_err("%s: No memory for mcbsp\n", __func__);
return -ENOMEM;
}
pdata->reg_step = 4;
if (oh->class->rev < MCBSP_CONFIG_TYPE2) {
pdata->reg_size = 2;
} else {
pdata->reg_size = 4;
pdata->has_ccr = true;
}
pdata->set_clk_src = omap2_mcbsp_set_clk_src;
/* On OMAP2/3 the McBSP1 port has 6 pin configuration */
if (id == 1 && oh->class->rev < MCBSP_CONFIG_TYPE4)
pdata->mux_signal = omap2_mcbsp1_mux_rx_clk;
/* On OMAP4 the McBSP4 port has 6 pin configuration */
if (id == 4 && oh->class->rev == MCBSP_CONFIG_TYPE4)
pdata->mux_signal = omap4_mcbsp4_mux_rx_clk;
if (oh->class->rev == MCBSP_CONFIG_TYPE3) {
if (id == 2)
/* The FIFO has 1024 + 256 locations */
pdata->buffer_size = 0x500;
else
/* The FIFO has 128 locations */
pdata->buffer_size = 0x80;
} else if (oh->class->rev == MCBSP_CONFIG_TYPE4) {
/* The FIFO has 128 locations for all instances */
pdata->buffer_size = 0x80;
}
if (oh->class->rev >= MCBSP_CONFIG_TYPE3)
pdata->has_wakeup = true;
oh_device[0] = oh;
if (oh->dev_attr) {
oh_device[1] = omap_hwmod_lookup((
(struct omap_mcbsp_dev_attr *)(oh->dev_attr))->sidetone);
pdata->enable_st_clock = omap3_enable_st_clock;
count++;
}
pdev = omap_device_build_ss(name, id, oh_device, count, pdata,
sizeof(*pdata), NULL, 0, false);
kfree(pdata);
if (IS_ERR(pdev)) {
pr_err("%s: Can't build omap_device for %s:%s.\n", __func__,
name, oh->name);
return PTR_ERR(pdev);
}
return 0;
}
static int __init omap2_mcbsp_init(void)
{
omap_hwmod_for_each_by_class("mcbsp", omap_init_mcbsp, NULL);
return 0;
}
arch_initcall(omap2_mcbsp_init);
| gpl-2.0 |
F4uzan/skernel_u0 | arch/arm/mach-omap2/mcbsp.c | 4845 | 5803 | /*
* linux/arch/arm/mach-omap2/mcbsp.c
*
* Copyright (C) 2008 Instituto Nokia de Tecnologia
* Contact: Eduardo Valentin <eduardo.valentin@indt.org.br>
*
* 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.
*
* Multichannel mode not supported.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <mach/irqs.h>
#include <plat/dma.h>
#include <plat/cpu.h>
#include <plat/mcbsp.h>
#include <plat/omap_device.h>
#include <linux/pm_runtime.h>
#include "control.h"
/*
* FIXME: Find a mechanism to enable/disable runtime the McBSP ICLK autoidle.
* Sidetone needs non-gated ICLK and sidetone autoidle is broken.
*/
#include "cm2xxx_3xxx.h"
#include "cm-regbits-34xx.h"
/* McBSP1 internal signal muxing function for OMAP2/3 */
static int omap2_mcbsp1_mux_rx_clk(struct device *dev, const char *signal,
const char *src)
{
u32 v;
v = omap_ctrl_readl(OMAP2_CONTROL_DEVCONF0);
if (!strcmp(signal, "clkr")) {
if (!strcmp(src, "clkr"))
v &= ~OMAP2_MCBSP1_CLKR_MASK;
else if (!strcmp(src, "clkx"))
v |= OMAP2_MCBSP1_CLKR_MASK;
else
return -EINVAL;
} else if (!strcmp(signal, "fsr")) {
if (!strcmp(src, "fsr"))
v &= ~OMAP2_MCBSP1_FSR_MASK;
else if (!strcmp(src, "fsx"))
v |= OMAP2_MCBSP1_FSR_MASK;
else
return -EINVAL;
} else {
return -EINVAL;
}
omap_ctrl_writel(v, OMAP2_CONTROL_DEVCONF0);
return 0;
}
/* McBSP4 internal signal muxing function for OMAP4 */
#define OMAP4_CONTROL_MCBSPLP_ALBCTRLRX_FSX (1 << 31)
#define OMAP4_CONTROL_MCBSPLP_ALBCTRLRX_CLKX (1 << 30)
static int omap4_mcbsp4_mux_rx_clk(struct device *dev, const char *signal,
const char *src)
{
u32 v;
/*
* In CONTROL_MCBSPLP register only bit 30 (CLKR mux), and bit 31 (FSR
* mux) is used */
v = omap4_ctrl_pad_readl(OMAP4_CTRL_MODULE_PAD_CORE_CONTROL_MCBSPLP);
if (!strcmp(signal, "clkr")) {
if (!strcmp(src, "clkr"))
v &= ~OMAP4_CONTROL_MCBSPLP_ALBCTRLRX_CLKX;
else if (!strcmp(src, "clkx"))
v |= OMAP4_CONTROL_MCBSPLP_ALBCTRLRX_CLKX;
else
return -EINVAL;
} else if (!strcmp(signal, "fsr")) {
if (!strcmp(src, "fsr"))
v &= ~OMAP4_CONTROL_MCBSPLP_ALBCTRLRX_FSX;
else if (!strcmp(src, "fsx"))
v |= OMAP4_CONTROL_MCBSPLP_ALBCTRLRX_FSX;
else
return -EINVAL;
} else {
return -EINVAL;
}
omap4_ctrl_pad_writel(v, OMAP4_CTRL_MODULE_PAD_CORE_CONTROL_MCBSPLP);
return 0;
}
/* McBSP CLKS source switching function */
static int omap2_mcbsp_set_clk_src(struct device *dev, struct clk *clk,
const char *src)
{
struct clk *fck_src;
char *fck_src_name;
int r;
if (!strcmp(src, "clks_ext"))
fck_src_name = "pad_fck";
else if (!strcmp(src, "clks_fclk"))
fck_src_name = "prcm_fck";
else
return -EINVAL;
fck_src = clk_get(dev, fck_src_name);
if (IS_ERR_OR_NULL(fck_src)) {
pr_err("omap-mcbsp: %s: could not clk_get() %s\n", "clks",
fck_src_name);
return -EINVAL;
}
pm_runtime_put_sync(dev);
r = clk_set_parent(clk, fck_src);
if (IS_ERR_VALUE(r)) {
pr_err("omap-mcbsp: %s: could not clk_set_parent() to %s\n",
"clks", fck_src_name);
clk_put(fck_src);
return -EINVAL;
}
pm_runtime_get_sync(dev);
clk_put(fck_src);
return 0;
}
static int omap3_enable_st_clock(unsigned int id, bool enable)
{
unsigned int w;
/*
* Sidetone uses McBSP ICLK - which must not idle when sidetones
* are enabled or sidetones start sounding ugly.
*/
w = omap2_cm_read_mod_reg(OMAP3430_PER_MOD, CM_AUTOIDLE);
if (enable)
w &= ~(1 << (id - 2));
else
w |= 1 << (id - 2);
omap2_cm_write_mod_reg(w, OMAP3430_PER_MOD, CM_AUTOIDLE);
return 0;
}
static int __init omap_init_mcbsp(struct omap_hwmod *oh, void *unused)
{
int id, count = 1;
char *name = "omap-mcbsp";
struct omap_hwmod *oh_device[2];
struct omap_mcbsp_platform_data *pdata = NULL;
struct platform_device *pdev;
sscanf(oh->name, "mcbsp%d", &id);
pdata = kzalloc(sizeof(struct omap_mcbsp_platform_data), GFP_KERNEL);
if (!pdata) {
pr_err("%s: No memory for mcbsp\n", __func__);
return -ENOMEM;
}
pdata->reg_step = 4;
if (oh->class->rev < MCBSP_CONFIG_TYPE2) {
pdata->reg_size = 2;
} else {
pdata->reg_size = 4;
pdata->has_ccr = true;
}
pdata->set_clk_src = omap2_mcbsp_set_clk_src;
/* On OMAP2/3 the McBSP1 port has 6 pin configuration */
if (id == 1 && oh->class->rev < MCBSP_CONFIG_TYPE4)
pdata->mux_signal = omap2_mcbsp1_mux_rx_clk;
/* On OMAP4 the McBSP4 port has 6 pin configuration */
if (id == 4 && oh->class->rev == MCBSP_CONFIG_TYPE4)
pdata->mux_signal = omap4_mcbsp4_mux_rx_clk;
if (oh->class->rev == MCBSP_CONFIG_TYPE3) {
if (id == 2)
/* The FIFO has 1024 + 256 locations */
pdata->buffer_size = 0x500;
else
/* The FIFO has 128 locations */
pdata->buffer_size = 0x80;
} else if (oh->class->rev == MCBSP_CONFIG_TYPE4) {
/* The FIFO has 128 locations for all instances */
pdata->buffer_size = 0x80;
}
if (oh->class->rev >= MCBSP_CONFIG_TYPE3)
pdata->has_wakeup = true;
oh_device[0] = oh;
if (oh->dev_attr) {
oh_device[1] = omap_hwmod_lookup((
(struct omap_mcbsp_dev_attr *)(oh->dev_attr))->sidetone);
pdata->enable_st_clock = omap3_enable_st_clock;
count++;
}
pdev = omap_device_build_ss(name, id, oh_device, count, pdata,
sizeof(*pdata), NULL, 0, false);
kfree(pdata);
if (IS_ERR(pdev)) {
pr_err("%s: Can't build omap_device for %s:%s.\n", __func__,
name, oh->name);
return PTR_ERR(pdev);
}
return 0;
}
static int __init omap2_mcbsp_init(void)
{
omap_hwmod_for_each_by_class("mcbsp", omap_init_mcbsp, NULL);
return 0;
}
arch_initcall(omap2_mcbsp_init);
| gpl-2.0 |
sicknemesis/kernel_lge_hammerhead | arch/arm/mach-h720x/h7201-eval.c | 5101 | 1065 | /*
* linux/arch/arm/mach-h720x/h7201-eval.c
*
* Copyright (C) 2003 Thomas Gleixner <tglx@linutronix.de>
* 2003 Robert Schwebel <r.schwebel@pengutronix.de>
* 2004 Sascha Hauer <s.hauer@pengutronix.de>
*
* Architecture specific stuff for Hynix GMS30C7201 development board
*
* 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/init.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/device.h>
#include <asm/setup.h>
#include <asm/types.h>
#include <asm/mach-types.h>
#include <asm/page.h>
#include <asm/mach/arch.h>
#include <mach/hardware.h>
#include "common.h"
MACHINE_START(H7201, "Hynix GMS30C7201")
/* Maintainer: Robert Schwebel, Pengutronix */
.atag_offset = 0x1000,
.map_io = h720x_map_io,
.init_irq = h720x_init_irq,
.timer = &h7201_timer,
.dma_zone_size = SZ_256M,
.restart = h720x_restart,
MACHINE_END
| gpl-2.0 |
tbalden/android_kernel_htc_m7-sense4.2 | net/netfilter/xt_cluster.c | 11501 | 5080 | /*
* (C) 2008-2009 Pablo Neira Ayuso <pablo@netfilter.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.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/jhash.h>
#include <linux/ip.h>
#include <net/ipv6.h>
#include <linux/netfilter/x_tables.h>
#include <net/netfilter/nf_conntrack.h>
#include <linux/netfilter/xt_cluster.h>
static inline u32 nf_ct_orig_ipv4_src(const struct nf_conn *ct)
{
return (__force u32)ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u3.ip;
}
static inline const u32 *nf_ct_orig_ipv6_src(const struct nf_conn *ct)
{
return (__force u32 *)ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u3.ip6;
}
static inline u_int32_t
xt_cluster_hash_ipv4(u_int32_t ip, const struct xt_cluster_match_info *info)
{
return jhash_1word(ip, info->hash_seed);
}
static inline u_int32_t
xt_cluster_hash_ipv6(const void *ip, const struct xt_cluster_match_info *info)
{
return jhash2(ip, NF_CT_TUPLE_L3SIZE / sizeof(__u32), info->hash_seed);
}
static inline u_int32_t
xt_cluster_hash(const struct nf_conn *ct,
const struct xt_cluster_match_info *info)
{
u_int32_t hash = 0;
switch(nf_ct_l3num(ct)) {
case AF_INET:
hash = xt_cluster_hash_ipv4(nf_ct_orig_ipv4_src(ct), info);
break;
case AF_INET6:
hash = xt_cluster_hash_ipv6(nf_ct_orig_ipv6_src(ct), info);
break;
default:
WARN_ON(1);
break;
}
return (((u64)hash * info->total_nodes) >> 32);
}
static inline bool
xt_cluster_ipv6_is_multicast(const struct in6_addr *addr)
{
__be32 st = addr->s6_addr32[0];
return ((st & htonl(0xFF000000)) == htonl(0xFF000000));
}
static inline bool
xt_cluster_is_multicast_addr(const struct sk_buff *skb, u_int8_t family)
{
bool is_multicast = false;
switch(family) {
case NFPROTO_IPV4:
is_multicast = ipv4_is_multicast(ip_hdr(skb)->daddr);
break;
case NFPROTO_IPV6:
is_multicast =
xt_cluster_ipv6_is_multicast(&ipv6_hdr(skb)->daddr);
break;
default:
WARN_ON(1);
break;
}
return is_multicast;
}
static bool
xt_cluster_mt(const struct sk_buff *skb, struct xt_action_param *par)
{
struct sk_buff *pskb = (struct sk_buff *)skb;
const struct xt_cluster_match_info *info = par->matchinfo;
const struct nf_conn *ct;
enum ip_conntrack_info ctinfo;
unsigned long hash;
/* This match assumes that all nodes see the same packets. This can be
* achieved if the switch that connects the cluster nodes support some
* sort of 'port mirroring'. However, if your switch does not support
* this, your cluster nodes can reply ARP request using a multicast MAC
* address. Thus, your switch will flood the same packets to the
* cluster nodes with the same multicast MAC address. Using a multicast
* link address is a RFC 1812 (section 3.3.2) violation, but this works
* fine in practise.
*
* Unfortunately, if you use the multicast MAC address, the link layer
* sets skbuff's pkt_type to PACKET_MULTICAST, which is not accepted
* by TCP and others for packets coming to this node. For that reason,
* this match mangles skbuff's pkt_type if it detects a packet
* addressed to a unicast address but using PACKET_MULTICAST. Yes, I
* know, matches should not alter packets, but we are doing this here
* because we would need to add a PKTTYPE target for this sole purpose.
*/
if (!xt_cluster_is_multicast_addr(skb, par->family) &&
skb->pkt_type == PACKET_MULTICAST) {
pskb->pkt_type = PACKET_HOST;
}
ct = nf_ct_get(skb, &ctinfo);
if (ct == NULL)
return false;
if (nf_ct_is_untracked(ct))
return false;
if (ct->master)
hash = xt_cluster_hash(ct->master, info);
else
hash = xt_cluster_hash(ct, info);
return !!((1 << hash) & info->node_mask) ^
!!(info->flags & XT_CLUSTER_F_INV);
}
static int xt_cluster_mt_checkentry(const struct xt_mtchk_param *par)
{
struct xt_cluster_match_info *info = par->matchinfo;
if (info->total_nodes > XT_CLUSTER_NODES_MAX) {
pr_info("you have exceeded the maximum "
"number of cluster nodes (%u > %u)\n",
info->total_nodes, XT_CLUSTER_NODES_MAX);
return -EINVAL;
}
if (info->node_mask >= (1ULL << info->total_nodes)) {
pr_info("this node mask cannot be "
"higher than the total number of nodes\n");
return -EDOM;
}
return 0;
}
static struct xt_match xt_cluster_match __read_mostly = {
.name = "cluster",
.family = NFPROTO_UNSPEC,
.match = xt_cluster_mt,
.checkentry = xt_cluster_mt_checkentry,
.matchsize = sizeof(struct xt_cluster_match_info),
.me = THIS_MODULE,
};
static int __init xt_cluster_mt_init(void)
{
return xt_register_match(&xt_cluster_match);
}
static void __exit xt_cluster_mt_fini(void)
{
xt_unregister_match(&xt_cluster_match);
}
MODULE_AUTHOR("Pablo Neira Ayuso <pablo@netfilter.org>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Xtables: hash-based cluster match");
MODULE_ALIAS("ipt_cluster");
MODULE_ALIAS("ip6t_cluster");
module_init(xt_cluster_mt_init);
module_exit(xt_cluster_mt_fini);
| gpl-2.0 |
javelinanddart/kernel_samsung_msm8660 | sound/pci/echoaudio/layla20_dsp.c | 12525 | 7501 | /****************************************************************************
Copyright Echo Digital Audio Corporation (c) 1998 - 2004
All rights reserved
www.echoaudio.com
This file is part of Echo Digital Audio's generic driver library.
Echo Digital Audio's generic driver library is free software;
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 will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU 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.
*************************************************************************
Translation from C++ and adaptation for use in ALSA-Driver
were made by Giuliano Pochini <pochini@shiny.it>
****************************************************************************/
static int read_dsp(struct echoaudio *chip, u32 *data);
static int set_professional_spdif(struct echoaudio *chip, char prof);
static int load_asic_generic(struct echoaudio *chip, u32 cmd, short asic);
static int check_asic_status(struct echoaudio *chip);
static int update_flags(struct echoaudio *chip);
static int init_hw(struct echoaudio *chip, u16 device_id, u16 subdevice_id)
{
int err;
DE_INIT(("init_hw() - Layla20\n"));
if (snd_BUG_ON((subdevice_id & 0xfff0) != LAYLA20))
return -ENODEV;
if ((err = init_dsp_comm_page(chip))) {
DE_INIT(("init_hw - could not initialize DSP comm page\n"));
return err;
}
chip->device_id = device_id;
chip->subdevice_id = subdevice_id;
chip->bad_board = TRUE;
chip->has_midi = TRUE;
chip->dsp_code_to_load = FW_LAYLA20_DSP;
chip->input_clock_types =
ECHO_CLOCK_BIT_INTERNAL | ECHO_CLOCK_BIT_SPDIF |
ECHO_CLOCK_BIT_WORD | ECHO_CLOCK_BIT_SUPER;
chip->output_clock_types =
ECHO_CLOCK_BIT_WORD | ECHO_CLOCK_BIT_SUPER;
if ((err = load_firmware(chip)) < 0)
return err;
chip->bad_board = FALSE;
DE_INIT(("init_hw done\n"));
return err;
}
static int set_mixer_defaults(struct echoaudio *chip)
{
chip->professional_spdif = FALSE;
return init_line_levels(chip);
}
static u32 detect_input_clocks(const struct echoaudio *chip)
{
u32 clocks_from_dsp, clock_bits;
/* Map the DSP clock detect bits to the generic driver clock detect bits */
clocks_from_dsp = le32_to_cpu(chip->comm_page->status_clocks);
clock_bits = ECHO_CLOCK_BIT_INTERNAL;
if (clocks_from_dsp & GLDM_CLOCK_DETECT_BIT_SPDIF)
clock_bits |= ECHO_CLOCK_BIT_SPDIF;
if (clocks_from_dsp & GLDM_CLOCK_DETECT_BIT_WORD) {
if (clocks_from_dsp & GLDM_CLOCK_DETECT_BIT_SUPER)
clock_bits |= ECHO_CLOCK_BIT_SUPER;
else
clock_bits |= ECHO_CLOCK_BIT_WORD;
}
return clock_bits;
}
/* ASIC status check - some cards have one or two ASICs that need to be
loaded. Once that load is complete, this function is called to see if
the load was successful.
If this load fails, it does not necessarily mean that the hardware is
defective - the external box may be disconnected or turned off.
This routine sometimes fails for Layla20; for Layla20, the loop runs
5 times and succeeds if it wins on three of the loops. */
static int check_asic_status(struct echoaudio *chip)
{
u32 asic_status;
int goodcnt, i;
chip->asic_loaded = FALSE;
for (i = goodcnt = 0; i < 5; i++) {
send_vector(chip, DSP_VC_TEST_ASIC);
/* The DSP will return a value to indicate whether or not
the ASIC is currently loaded */
if (read_dsp(chip, &asic_status) < 0) {
DE_ACT(("check_asic_status: failed on read_dsp\n"));
return -EIO;
}
if (asic_status == ASIC_ALREADY_LOADED) {
if (++goodcnt == 3) {
chip->asic_loaded = TRUE;
return 0;
}
}
}
return -EIO;
}
/* Layla20 has an ASIC in the external box */
static int load_asic(struct echoaudio *chip)
{
int err;
if (chip->asic_loaded)
return 0;
err = load_asic_generic(chip, DSP_FNC_LOAD_LAYLA_ASIC,
FW_LAYLA20_ASIC);
if (err < 0)
return err;
/* Check if ASIC is alive and well. */
return check_asic_status(chip);
}
static int set_sample_rate(struct echoaudio *chip, u32 rate)
{
if (snd_BUG_ON(rate < 8000 || rate > 50000))
return -EINVAL;
/* Only set the clock for internal mode. Do not return failure,
simply treat it as a non-event. */
if (chip->input_clock != ECHO_CLOCK_INTERNAL) {
DE_ACT(("set_sample_rate: Cannot set sample rate - "
"clock not set to CLK_CLOCKININTERNAL\n"));
chip->comm_page->sample_rate = cpu_to_le32(rate);
chip->sample_rate = rate;
return 0;
}
if (wait_handshake(chip))
return -EIO;
DE_ACT(("set_sample_rate(%d)\n", rate));
chip->sample_rate = rate;
chip->comm_page->sample_rate = cpu_to_le32(rate);
clear_handshake(chip);
return send_vector(chip, DSP_VC_SET_LAYLA_SAMPLE_RATE);
}
static int set_input_clock(struct echoaudio *chip, u16 clock_source)
{
u16 clock;
u32 rate;
DE_ACT(("set_input_clock:\n"));
rate = 0;
switch (clock_source) {
case ECHO_CLOCK_INTERNAL:
DE_ACT(("Set Layla20 clock to INTERNAL\n"));
rate = chip->sample_rate;
clock = LAYLA20_CLOCK_INTERNAL;
break;
case ECHO_CLOCK_SPDIF:
DE_ACT(("Set Layla20 clock to SPDIF\n"));
clock = LAYLA20_CLOCK_SPDIF;
break;
case ECHO_CLOCK_WORD:
DE_ACT(("Set Layla20 clock to WORD\n"));
clock = LAYLA20_CLOCK_WORD;
break;
case ECHO_CLOCK_SUPER:
DE_ACT(("Set Layla20 clock to SUPER\n"));
clock = LAYLA20_CLOCK_SUPER;
break;
default:
DE_ACT(("Input clock 0x%x not supported for Layla24\n",
clock_source));
return -EINVAL;
}
chip->input_clock = clock_source;
chip->comm_page->input_clock = cpu_to_le16(clock);
clear_handshake(chip);
send_vector(chip, DSP_VC_UPDATE_CLOCKS);
if (rate)
set_sample_rate(chip, rate);
return 0;
}
static int set_output_clock(struct echoaudio *chip, u16 clock)
{
DE_ACT(("set_output_clock: %d\n", clock));
switch (clock) {
case ECHO_CLOCK_SUPER:
clock = LAYLA20_OUTPUT_CLOCK_SUPER;
break;
case ECHO_CLOCK_WORD:
clock = LAYLA20_OUTPUT_CLOCK_WORD;
break;
default:
DE_ACT(("set_output_clock wrong clock\n"));
return -EINVAL;
}
if (wait_handshake(chip))
return -EIO;
chip->comm_page->output_clock = cpu_to_le16(clock);
chip->output_clock = clock;
clear_handshake(chip);
return send_vector(chip, DSP_VC_UPDATE_CLOCKS);
}
/* Set input bus gain (one unit is 0.5dB !) */
static int set_input_gain(struct echoaudio *chip, u16 input, int gain)
{
if (snd_BUG_ON(input >= num_busses_in(chip)))
return -EINVAL;
if (wait_handshake(chip))
return -EIO;
chip->input_gain[input] = gain;
gain += GL20_INPUT_GAIN_MAGIC_NUMBER;
chip->comm_page->line_in_level[input] = gain;
return 0;
}
/* Tell the DSP to reread the flags from the comm page */
static int update_flags(struct echoaudio *chip)
{
if (wait_handshake(chip))
return -EIO;
clear_handshake(chip);
return send_vector(chip, DSP_VC_UPDATE_FLAGS);
}
static int set_professional_spdif(struct echoaudio *chip, char prof)
{
DE_ACT(("set_professional_spdif %d\n", prof));
if (prof)
chip->comm_page->flags |=
cpu_to_le32(DSP_FLAG_PROFESSIONAL_SPDIF);
else
chip->comm_page->flags &=
~cpu_to_le32(DSP_FLAG_PROFESSIONAL_SPDIF);
chip->professional_spdif = prof;
return update_flags(chip);
}
| gpl-2.0 |
funky81/galaxy-2636 | arch/sh/drivers/pci/ops-dreamcast.c | 13805 | 2641 | /*
* PCI operations for the Sega Dreamcast
*
* Copyright (C) 2001, 2002 M. R. Brown
* Copyright (C) 2002, 2003 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/param.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/pci.h>
#include <linux/module.h>
#include <linux/io.h>
#include <mach/pci.h>
/*
* The !gapspci_config_access case really shouldn't happen, ever, unless
* someone implicitly messes around with the last devfn value.. otherwise we
* only support a single device anyways, and if we didn't have a BBA, we
* wouldn't make it terribly far through the PCI setup anyways.
*
* Also, we could very easily support both Type 0 and Type 1 configurations
* here, but since it doesn't seem that there is any such implementation in
* existence, we don't bother.
*
* I suppose if someone actually gets around to ripping the chip out of
* the BBA and hanging some more devices off of it, then this might be
* something to take into consideration. However, due to the cost of the BBA,
* and the general lack of activity by DC hardware hackers, this doesn't seem
* likely to happen anytime soon.
*/
static int gapspci_config_access(unsigned char bus, unsigned int devfn)
{
return (bus == 0) && (devfn == 0);
}
/*
* We can also actually read and write in b/w/l sizes! Thankfully this part
* was at least done right, and we don't have to do the stupid masking and
* shifting that we do on the 7751! Small wonders never cease to amaze.
*/
static int gapspci_read(struct pci_bus *bus, unsigned int devfn, int where, int size, u32 *val)
{
*val = 0xffffffff;
if (!gapspci_config_access(bus->number, devfn))
return PCIBIOS_DEVICE_NOT_FOUND;
switch (size) {
case 1: *val = inb(GAPSPCI_BBA_CONFIG+where); break;
case 2: *val = inw(GAPSPCI_BBA_CONFIG+where); break;
case 4: *val = inl(GAPSPCI_BBA_CONFIG+where); break;
}
return PCIBIOS_SUCCESSFUL;
}
static int gapspci_write(struct pci_bus *bus, unsigned int devfn, int where, int size, u32 val)
{
if (!gapspci_config_access(bus->number, devfn))
return PCIBIOS_DEVICE_NOT_FOUND;
switch (size) {
case 1: outb(( u8)val, GAPSPCI_BBA_CONFIG+where); break;
case 2: outw((u16)val, GAPSPCI_BBA_CONFIG+where); break;
case 4: outl((u32)val, GAPSPCI_BBA_CONFIG+where); break;
}
return PCIBIOS_SUCCESSFUL;
}
struct pci_ops gapspci_pci_ops = {
.read = gapspci_read,
.write = gapspci_write,
};
| gpl-2.0 |
jderrick/linux-blkdev | arch/arm/mach-spear/spear13xx.c | 494 | 3233 | /*
* arch/arm/mach-spear13xx/spear13xx.c
*
* SPEAr13XX machines common source file
*
* Copyright (C) 2012 ST Microelectronics
* Viresh Kumar <vireshk@kernel.org>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#define pr_fmt(fmt) "SPEAr13xx: " fmt
#include <linux/amba/pl022.h>
#include <linux/clk.h>
#include <linux/clocksource.h>
#include <linux/err.h>
#include <linux/of.h>
#include <asm/hardware/cache-l2x0.h>
#include <asm/mach/map.h>
#include <mach/spear.h>
#include "generic.h"
void __init spear13xx_l2x0_init(void)
{
/*
* 512KB (64KB/way), 8-way associativity, parity supported
*
* FIXME: 9th bit, of Auxillary Controller register must be set
* for some spear13xx devices for stable L2 operation.
*
* Enable Early BRESP, L2 prefetch for Instruction and Data,
* write alloc and 'Full line of zero' options
*
*/
if (!IS_ENABLED(CONFIG_CACHE_L2X0))
return;
writel_relaxed(0x06, VA_L2CC_BASE + L310_PREFETCH_CTRL);
/*
* Program following latencies in order to make
* SPEAr1340 work at 600 MHz
*/
writel_relaxed(0x221, VA_L2CC_BASE + L310_TAG_LATENCY_CTRL);
writel_relaxed(0x441, VA_L2CC_BASE + L310_DATA_LATENCY_CTRL);
l2x0_init(VA_L2CC_BASE, 0x30a00001, 0xfe0fffff);
}
/*
* Following will create 16MB static virtual/physical mappings
* PHYSICAL VIRTUAL
* 0xB3000000 0xF9000000
* 0xE0000000 0xFD000000
* 0xEC000000 0xFC000000
* 0xED000000 0xFB000000
*/
static struct map_desc spear13xx_io_desc[] __initdata = {
{
.virtual = (unsigned long)VA_PERIP_GRP2_BASE,
.pfn = __phys_to_pfn(PERIP_GRP2_BASE),
.length = SZ_16M,
.type = MT_DEVICE
}, {
.virtual = (unsigned long)VA_PERIP_GRP1_BASE,
.pfn = __phys_to_pfn(PERIP_GRP1_BASE),
.length = SZ_16M,
.type = MT_DEVICE
}, {
.virtual = (unsigned long)VA_A9SM_AND_MPMC_BASE,
.pfn = __phys_to_pfn(A9SM_AND_MPMC_BASE),
.length = SZ_16M,
.type = MT_DEVICE
}, {
.virtual = (unsigned long)VA_L2CC_BASE,
.pfn = __phys_to_pfn(L2CC_BASE),
.length = SZ_4K,
.type = MT_DEVICE
},
};
/* This will create static memory mapping for selected devices */
void __init spear13xx_map_io(void)
{
iotable_init(spear13xx_io_desc, ARRAY_SIZE(spear13xx_io_desc));
}
static void __init spear13xx_clk_init(void)
{
if (of_machine_is_compatible("st,spear1310"))
spear1310_clk_init(VA_MISC_BASE, VA_SPEAR1310_RAS_BASE);
else if (of_machine_is_compatible("st,spear1340"))
spear1340_clk_init(VA_MISC_BASE);
else
pr_err("%s: Unknown machine\n", __func__);
}
void __init spear13xx_timer_init(void)
{
char pclk_name[] = "osc_24m_clk";
struct clk *gpt_clk, *pclk;
spear13xx_clk_init();
/* get the system timer clock */
gpt_clk = clk_get_sys("gpt0", NULL);
if (IS_ERR(gpt_clk)) {
pr_err("%s:couldn't get clk for gpt\n", __func__);
BUG();
}
/* get the suitable parent clock for timer*/
pclk = clk_get(NULL, pclk_name);
if (IS_ERR(pclk)) {
pr_err("%s:couldn't get %s as parent for gpt\n", __func__,
pclk_name);
BUG();
}
clk_set_parent(gpt_clk, pclk);
clk_put(gpt_clk);
clk_put(pclk);
spear_setup_of_timer();
clocksource_probe();
}
| gpl-2.0 |
v3best/linux-v3best | drivers/input/keyboard/pxa27x_keypad.c | 494 | 23820 | /*
* linux/drivers/input/keyboard/pxa27x_keypad.c
*
* Driver for the pxa27x matrix keyboard controller.
*
* Created: Feb 22, 2007
* Author: Rodolfo Giometti <giometti@linux.it>
*
* Based on a previous implementations by Kevin O'Connor
* <kevin_at_koconnor.net> and Alex Osborne <bobofdoom@gmail.com> and
* on some suggestions by Nicolas Pitre <nico@fluxnic.net>.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/input/matrix_keypad.h>
#include <linux/slab.h>
#include <linux/of.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/hardware.h>
#include <linux/platform_data/keypad-pxa27x.h>
/*
* Keypad Controller registers
*/
#define KPC 0x0000 /* Keypad Control register */
#define KPDK 0x0008 /* Keypad Direct Key register */
#define KPREC 0x0010 /* Keypad Rotary Encoder register */
#define KPMK 0x0018 /* Keypad Matrix Key register */
#define KPAS 0x0020 /* Keypad Automatic Scan register */
/* Keypad Automatic Scan Multiple Key Presser register 0-3 */
#define KPASMKP0 0x0028
#define KPASMKP1 0x0030
#define KPASMKP2 0x0038
#define KPASMKP3 0x0040
#define KPKDI 0x0048
/* bit definitions */
#define KPC_MKRN(n) ((((n) - 1) & 0x7) << 26) /* matrix key row number */
#define KPC_MKCN(n) ((((n) - 1) & 0x7) << 23) /* matrix key column number */
#define KPC_DKN(n) ((((n) - 1) & 0x7) << 6) /* direct key number */
#define KPC_AS (0x1 << 30) /* Automatic Scan bit */
#define KPC_ASACT (0x1 << 29) /* Automatic Scan on Activity */
#define KPC_MI (0x1 << 22) /* Matrix interrupt bit */
#define KPC_IMKP (0x1 << 21) /* Ignore Multiple Key Press */
#define KPC_MS(n) (0x1 << (13 + (n))) /* Matrix scan line 'n' */
#define KPC_MS_ALL (0xff << 13)
#define KPC_ME (0x1 << 12) /* Matrix Keypad Enable */
#define KPC_MIE (0x1 << 11) /* Matrix Interrupt Enable */
#define KPC_DK_DEB_SEL (0x1 << 9) /* Direct Keypad Debounce Select */
#define KPC_DI (0x1 << 5) /* Direct key interrupt bit */
#define KPC_RE_ZERO_DEB (0x1 << 4) /* Rotary Encoder Zero Debounce */
#define KPC_REE1 (0x1 << 3) /* Rotary Encoder1 Enable */
#define KPC_REE0 (0x1 << 2) /* Rotary Encoder0 Enable */
#define KPC_DE (0x1 << 1) /* Direct Keypad Enable */
#define KPC_DIE (0x1 << 0) /* Direct Keypad interrupt Enable */
#define KPDK_DKP (0x1 << 31)
#define KPDK_DK(n) ((n) & 0xff)
#define KPREC_OF1 (0x1 << 31)
#define kPREC_UF1 (0x1 << 30)
#define KPREC_OF0 (0x1 << 15)
#define KPREC_UF0 (0x1 << 14)
#define KPREC_RECOUNT0(n) ((n) & 0xff)
#define KPREC_RECOUNT1(n) (((n) >> 16) & 0xff)
#define KPMK_MKP (0x1 << 31)
#define KPAS_SO (0x1 << 31)
#define KPASMKPx_SO (0x1 << 31)
#define KPAS_MUKP(n) (((n) >> 26) & 0x1f)
#define KPAS_RP(n) (((n) >> 4) & 0xf)
#define KPAS_CP(n) ((n) & 0xf)
#define KPASMKP_MKC_MASK (0xff)
#define keypad_readl(off) __raw_readl(keypad->mmio_base + (off))
#define keypad_writel(off, v) __raw_writel((v), keypad->mmio_base + (off))
#define MAX_MATRIX_KEY_NUM (MAX_MATRIX_KEY_ROWS * MAX_MATRIX_KEY_COLS)
#define MAX_KEYPAD_KEYS (MAX_MATRIX_KEY_NUM + MAX_DIRECT_KEY_NUM)
struct pxa27x_keypad {
const struct pxa27x_keypad_platform_data *pdata;
struct clk *clk;
struct input_dev *input_dev;
void __iomem *mmio_base;
int irq;
unsigned short keycodes[MAX_KEYPAD_KEYS];
int rotary_rel_code[2];
unsigned int row_shift;
/* state row bits of each column scan */
uint32_t matrix_key_state[MAX_MATRIX_KEY_COLS];
uint32_t direct_key_state;
unsigned int direct_key_mask;
};
#ifdef CONFIG_OF
static int pxa27x_keypad_matrix_key_parse_dt(struct pxa27x_keypad *keypad,
struct pxa27x_keypad_platform_data *pdata)
{
struct input_dev *input_dev = keypad->input_dev;
struct device *dev = input_dev->dev.parent;
u32 rows, cols;
int error;
error = matrix_keypad_parse_of_params(dev, &rows, &cols);
if (error)
return error;
if (rows > MAX_MATRIX_KEY_ROWS || cols > MAX_MATRIX_KEY_COLS) {
dev_err(dev, "rows or cols exceeds maximum value\n");
return -EINVAL;
}
pdata->matrix_key_rows = rows;
pdata->matrix_key_cols = cols;
error = matrix_keypad_build_keymap(NULL, NULL,
pdata->matrix_key_rows,
pdata->matrix_key_cols,
keypad->keycodes, input_dev);
if (error)
return error;
return 0;
}
static int pxa27x_keypad_direct_key_parse_dt(struct pxa27x_keypad *keypad,
struct pxa27x_keypad_platform_data *pdata)
{
struct input_dev *input_dev = keypad->input_dev;
struct device *dev = input_dev->dev.parent;
struct device_node *np = dev->of_node;
const __be16 *prop;
unsigned short code;
unsigned int proplen, size;
int i;
int error;
error = of_property_read_u32(np, "marvell,direct-key-count",
&pdata->direct_key_num);
if (error) {
/*
* If do not have marvel,direct-key-count defined,
* it means direct key is not supported.
*/
return error == -EINVAL ? 0 : error;
}
error = of_property_read_u32(np, "marvell,direct-key-mask",
&pdata->direct_key_mask);
if (error) {
if (error != -EINVAL)
return error;
/*
* If marvell,direct-key-mask is not defined, driver will use
* default value. Default value is set when configure the keypad.
*/
pdata->direct_key_mask = 0;
}
pdata->direct_key_low_active = of_property_read_bool(np,
"marvell,direct-key-low-active");
prop = of_get_property(np, "marvell,direct-key-map", &proplen);
if (!prop)
return -EINVAL;
if (proplen % sizeof(u16))
return -EINVAL;
size = proplen / sizeof(u16);
/* Only MAX_DIRECT_KEY_NUM is accepted.*/
if (size > MAX_DIRECT_KEY_NUM)
return -EINVAL;
for (i = 0; i < size; i++) {
code = be16_to_cpup(prop + i);
keypad->keycodes[MAX_MATRIX_KEY_NUM + i] = code;
__set_bit(code, input_dev->keybit);
}
return 0;
}
static int pxa27x_keypad_rotary_parse_dt(struct pxa27x_keypad *keypad,
struct pxa27x_keypad_platform_data *pdata)
{
const __be32 *prop;
int i, relkey_ret;
unsigned int code, proplen;
const char *rotaryname[2] = {
"marvell,rotary0", "marvell,rotary1"};
const char relkeyname[] = {"marvell,rotary-rel-key"};
struct input_dev *input_dev = keypad->input_dev;
struct device *dev = input_dev->dev.parent;
struct device_node *np = dev->of_node;
relkey_ret = of_property_read_u32(np, relkeyname, &code);
/* if can read correct rotary key-code, we do not need this. */
if (relkey_ret == 0) {
unsigned short relcode;
/* rotary0 taks lower half, rotary1 taks upper half. */
relcode = code & 0xffff;
pdata->rotary0_rel_code = (code & 0xffff);
__set_bit(relcode, input_dev->relbit);
relcode = code >> 16;
pdata->rotary1_rel_code = relcode;
__set_bit(relcode, input_dev->relbit);
}
for (i = 0; i < 2; i++) {
prop = of_get_property(np, rotaryname[i], &proplen);
/*
* If the prop is not set, it means keypad does not need
* initialize the rotaryX.
*/
if (!prop)
continue;
code = be32_to_cpup(prop);
/*
* Not all up/down key code are valid.
* Now we depends on direct-rel-code.
*/
if ((!(code & 0xffff) || !(code >> 16)) && relkey_ret) {
return relkey_ret;
} else {
unsigned int n = MAX_MATRIX_KEY_NUM + (i << 1);
unsigned short keycode;
keycode = code & 0xffff;
keypad->keycodes[n] = keycode;
__set_bit(keycode, input_dev->keybit);
keycode = code >> 16;
keypad->keycodes[n + 1] = keycode;
__set_bit(keycode, input_dev->keybit);
if (i == 0)
pdata->rotary0_rel_code = -1;
else
pdata->rotary1_rel_code = -1;
}
if (i == 0)
pdata->enable_rotary0 = 1;
else
pdata->enable_rotary1 = 1;
}
keypad->rotary_rel_code[0] = pdata->rotary0_rel_code;
keypad->rotary_rel_code[1] = pdata->rotary1_rel_code;
return 0;
}
static int pxa27x_keypad_build_keycode_from_dt(struct pxa27x_keypad *keypad)
{
struct input_dev *input_dev = keypad->input_dev;
struct device *dev = input_dev->dev.parent;
struct device_node *np = dev->of_node;
struct pxa27x_keypad_platform_data *pdata;
int error;
pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata) {
dev_err(dev, "failed to allocate memory for pdata\n");
return -ENOMEM;
}
error = pxa27x_keypad_matrix_key_parse_dt(keypad, pdata);
if (error) {
dev_err(dev, "failed to parse matrix key\n");
return error;
}
error = pxa27x_keypad_direct_key_parse_dt(keypad, pdata);
if (error) {
dev_err(dev, "failed to parse direct key\n");
return error;
}
error = pxa27x_keypad_rotary_parse_dt(keypad, pdata);
if (error) {
dev_err(dev, "failed to parse rotary key\n");
return error;
}
error = of_property_read_u32(np, "marvell,debounce-interval",
&pdata->debounce_interval);
if (error) {
dev_err(dev, "failed to parse debpunce-interval\n");
return error;
}
/*
* The keycodes may not only includes matrix key but also the direct
* key or rotary key.
*/
input_dev->keycodemax = ARRAY_SIZE(keypad->keycodes);
keypad->pdata = pdata;
return 0;
}
#else
static int pxa27x_keypad_build_keycode_from_dt(struct pxa27x_keypad *keypad)
{
dev_info(keypad->input_dev->dev.parent, "missing platform data\n");
return -EINVAL;
}
#endif
static int pxa27x_keypad_build_keycode(struct pxa27x_keypad *keypad)
{
const struct pxa27x_keypad_platform_data *pdata = keypad->pdata;
struct input_dev *input_dev = keypad->input_dev;
const struct matrix_keymap_data *keymap_data =
pdata ? pdata->matrix_keymap_data : NULL;
unsigned short keycode;
int i;
int error;
error = matrix_keypad_build_keymap(keymap_data, NULL,
pdata->matrix_key_rows,
pdata->matrix_key_cols,
keypad->keycodes, input_dev);
if (error)
return error;
/*
* The keycodes may not only include matrix keys but also the direct
* or rotary keys.
*/
input_dev->keycodemax = ARRAY_SIZE(keypad->keycodes);
/* For direct keys. */
for (i = 0; i < pdata->direct_key_num; i++) {
keycode = pdata->direct_key_map[i];
keypad->keycodes[MAX_MATRIX_KEY_NUM + i] = keycode;
__set_bit(keycode, input_dev->keybit);
}
if (pdata->enable_rotary0) {
if (pdata->rotary0_up_key && pdata->rotary0_down_key) {
keycode = pdata->rotary0_up_key;
keypad->keycodes[MAX_MATRIX_KEY_NUM + 0] = keycode;
__set_bit(keycode, input_dev->keybit);
keycode = pdata->rotary0_down_key;
keypad->keycodes[MAX_MATRIX_KEY_NUM + 1] = keycode;
__set_bit(keycode, input_dev->keybit);
keypad->rotary_rel_code[0] = -1;
} else {
keypad->rotary_rel_code[0] = pdata->rotary0_rel_code;
__set_bit(pdata->rotary0_rel_code, input_dev->relbit);
}
}
if (pdata->enable_rotary1) {
if (pdata->rotary1_up_key && pdata->rotary1_down_key) {
keycode = pdata->rotary1_up_key;
keypad->keycodes[MAX_MATRIX_KEY_NUM + 2] = keycode;
__set_bit(keycode, input_dev->keybit);
keycode = pdata->rotary1_down_key;
keypad->keycodes[MAX_MATRIX_KEY_NUM + 3] = keycode;
__set_bit(keycode, input_dev->keybit);
keypad->rotary_rel_code[1] = -1;
} else {
keypad->rotary_rel_code[1] = pdata->rotary1_rel_code;
__set_bit(pdata->rotary1_rel_code, input_dev->relbit);
}
}
__clear_bit(KEY_RESERVED, input_dev->keybit);
return 0;
}
static void pxa27x_keypad_scan_matrix(struct pxa27x_keypad *keypad)
{
const struct pxa27x_keypad_platform_data *pdata = keypad->pdata;
struct input_dev *input_dev = keypad->input_dev;
int row, col, num_keys_pressed = 0;
uint32_t new_state[MAX_MATRIX_KEY_COLS];
uint32_t kpas = keypad_readl(KPAS);
num_keys_pressed = KPAS_MUKP(kpas);
memset(new_state, 0, sizeof(new_state));
if (num_keys_pressed == 0)
goto scan;
if (num_keys_pressed == 1) {
col = KPAS_CP(kpas);
row = KPAS_RP(kpas);
/* if invalid row/col, treat as no key pressed */
if (col >= pdata->matrix_key_cols ||
row >= pdata->matrix_key_rows)
goto scan;
new_state[col] = (1 << row);
goto scan;
}
if (num_keys_pressed > 1) {
uint32_t kpasmkp0 = keypad_readl(KPASMKP0);
uint32_t kpasmkp1 = keypad_readl(KPASMKP1);
uint32_t kpasmkp2 = keypad_readl(KPASMKP2);
uint32_t kpasmkp3 = keypad_readl(KPASMKP3);
new_state[0] = kpasmkp0 & KPASMKP_MKC_MASK;
new_state[1] = (kpasmkp0 >> 16) & KPASMKP_MKC_MASK;
new_state[2] = kpasmkp1 & KPASMKP_MKC_MASK;
new_state[3] = (kpasmkp1 >> 16) & KPASMKP_MKC_MASK;
new_state[4] = kpasmkp2 & KPASMKP_MKC_MASK;
new_state[5] = (kpasmkp2 >> 16) & KPASMKP_MKC_MASK;
new_state[6] = kpasmkp3 & KPASMKP_MKC_MASK;
new_state[7] = (kpasmkp3 >> 16) & KPASMKP_MKC_MASK;
}
scan:
for (col = 0; col < pdata->matrix_key_cols; col++) {
uint32_t bits_changed;
int code;
bits_changed = keypad->matrix_key_state[col] ^ new_state[col];
if (bits_changed == 0)
continue;
for (row = 0; row < pdata->matrix_key_rows; row++) {
if ((bits_changed & (1 << row)) == 0)
continue;
code = MATRIX_SCAN_CODE(row, col, keypad->row_shift);
input_event(input_dev, EV_MSC, MSC_SCAN, code);
input_report_key(input_dev, keypad->keycodes[code],
new_state[col] & (1 << row));
}
}
input_sync(input_dev);
memcpy(keypad->matrix_key_state, new_state, sizeof(new_state));
}
#define DEFAULT_KPREC (0x007f007f)
static inline int rotary_delta(uint32_t kprec)
{
if (kprec & KPREC_OF0)
return (kprec & 0xff) + 0x7f;
else if (kprec & KPREC_UF0)
return (kprec & 0xff) - 0x7f - 0xff;
else
return (kprec & 0xff) - 0x7f;
}
static void report_rotary_event(struct pxa27x_keypad *keypad, int r, int delta)
{
struct input_dev *dev = keypad->input_dev;
if (delta == 0)
return;
if (keypad->rotary_rel_code[r] == -1) {
int code = MAX_MATRIX_KEY_NUM + 2 * r + (delta > 0 ? 0 : 1);
unsigned char keycode = keypad->keycodes[code];
/* simulate a press-n-release */
input_event(dev, EV_MSC, MSC_SCAN, code);
input_report_key(dev, keycode, 1);
input_sync(dev);
input_event(dev, EV_MSC, MSC_SCAN, code);
input_report_key(dev, keycode, 0);
input_sync(dev);
} else {
input_report_rel(dev, keypad->rotary_rel_code[r], delta);
input_sync(dev);
}
}
static void pxa27x_keypad_scan_rotary(struct pxa27x_keypad *keypad)
{
const struct pxa27x_keypad_platform_data *pdata = keypad->pdata;
uint32_t kprec;
/* read and reset to default count value */
kprec = keypad_readl(KPREC);
keypad_writel(KPREC, DEFAULT_KPREC);
if (pdata->enable_rotary0)
report_rotary_event(keypad, 0, rotary_delta(kprec));
if (pdata->enable_rotary1)
report_rotary_event(keypad, 1, rotary_delta(kprec >> 16));
}
static void pxa27x_keypad_scan_direct(struct pxa27x_keypad *keypad)
{
const struct pxa27x_keypad_platform_data *pdata = keypad->pdata;
struct input_dev *input_dev = keypad->input_dev;
unsigned int new_state;
uint32_t kpdk, bits_changed;
int i;
kpdk = keypad_readl(KPDK);
if (pdata->enable_rotary0 || pdata->enable_rotary1)
pxa27x_keypad_scan_rotary(keypad);
/*
* The KPDR_DK only output the key pin level, so it relates to board,
* and low level may be active.
*/
if (pdata->direct_key_low_active)
new_state = ~KPDK_DK(kpdk) & keypad->direct_key_mask;
else
new_state = KPDK_DK(kpdk) & keypad->direct_key_mask;
bits_changed = keypad->direct_key_state ^ new_state;
if (bits_changed == 0)
return;
for (i = 0; i < pdata->direct_key_num; i++) {
if (bits_changed & (1 << i)) {
int code = MAX_MATRIX_KEY_NUM + i;
input_event(input_dev, EV_MSC, MSC_SCAN, code);
input_report_key(input_dev, keypad->keycodes[code],
new_state & (1 << i));
}
}
input_sync(input_dev);
keypad->direct_key_state = new_state;
}
static void clear_wakeup_event(struct pxa27x_keypad *keypad)
{
const struct pxa27x_keypad_platform_data *pdata = keypad->pdata;
if (pdata->clear_wakeup_event)
(pdata->clear_wakeup_event)();
}
static irqreturn_t pxa27x_keypad_irq_handler(int irq, void *dev_id)
{
struct pxa27x_keypad *keypad = dev_id;
unsigned long kpc = keypad_readl(KPC);
clear_wakeup_event(keypad);
if (kpc & KPC_DI)
pxa27x_keypad_scan_direct(keypad);
if (kpc & KPC_MI)
pxa27x_keypad_scan_matrix(keypad);
return IRQ_HANDLED;
}
static void pxa27x_keypad_config(struct pxa27x_keypad *keypad)
{
const struct pxa27x_keypad_platform_data *pdata = keypad->pdata;
unsigned int mask = 0, direct_key_num = 0;
unsigned long kpc = 0;
/* clear pending interrupt bit */
keypad_readl(KPC);
/* enable matrix keys with automatic scan */
if (pdata->matrix_key_rows && pdata->matrix_key_cols) {
kpc |= KPC_ASACT | KPC_MIE | KPC_ME | KPC_MS_ALL;
kpc |= KPC_MKRN(pdata->matrix_key_rows) |
KPC_MKCN(pdata->matrix_key_cols);
}
/* enable rotary key, debounce interval same as direct keys */
if (pdata->enable_rotary0) {
mask |= 0x03;
direct_key_num = 2;
kpc |= KPC_REE0;
}
if (pdata->enable_rotary1) {
mask |= 0x0c;
direct_key_num = 4;
kpc |= KPC_REE1;
}
if (pdata->direct_key_num > direct_key_num)
direct_key_num = pdata->direct_key_num;
/*
* Direct keys usage may not start from KP_DKIN0, check the platfrom
* mask data to config the specific.
*/
if (pdata->direct_key_mask)
keypad->direct_key_mask = pdata->direct_key_mask;
else
keypad->direct_key_mask = ((1 << direct_key_num) - 1) & ~mask;
/* enable direct key */
if (direct_key_num)
kpc |= KPC_DE | KPC_DIE | KPC_DKN(direct_key_num);
keypad_writel(KPC, kpc | KPC_RE_ZERO_DEB);
keypad_writel(KPREC, DEFAULT_KPREC);
keypad_writel(KPKDI, pdata->debounce_interval);
}
static int pxa27x_keypad_open(struct input_dev *dev)
{
struct pxa27x_keypad *keypad = input_get_drvdata(dev);
/* Enable unit clock */
clk_prepare_enable(keypad->clk);
pxa27x_keypad_config(keypad);
return 0;
}
static void pxa27x_keypad_close(struct input_dev *dev)
{
struct pxa27x_keypad *keypad = input_get_drvdata(dev);
/* Disable clock unit */
clk_disable_unprepare(keypad->clk);
}
#ifdef CONFIG_PM_SLEEP
static int pxa27x_keypad_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct pxa27x_keypad *keypad = platform_get_drvdata(pdev);
/*
* If the keypad is used a wake up source, clock can not be disabled.
* Or it can not detect the key pressing.
*/
if (device_may_wakeup(&pdev->dev))
enable_irq_wake(keypad->irq);
else
clk_disable_unprepare(keypad->clk);
return 0;
}
static int pxa27x_keypad_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct pxa27x_keypad *keypad = platform_get_drvdata(pdev);
struct input_dev *input_dev = keypad->input_dev;
/*
* If the keypad is used as wake up source, the clock is not turned
* off. So do not need configure it again.
*/
if (device_may_wakeup(&pdev->dev)) {
disable_irq_wake(keypad->irq);
} else {
mutex_lock(&input_dev->mutex);
if (input_dev->users) {
/* Enable unit clock */
clk_prepare_enable(keypad->clk);
pxa27x_keypad_config(keypad);
}
mutex_unlock(&input_dev->mutex);
}
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(pxa27x_keypad_pm_ops,
pxa27x_keypad_suspend, pxa27x_keypad_resume);
static int pxa27x_keypad_probe(struct platform_device *pdev)
{
const struct pxa27x_keypad_platform_data *pdata =
dev_get_platdata(&pdev->dev);
struct device_node *np = pdev->dev.of_node;
struct pxa27x_keypad *keypad;
struct input_dev *input_dev;
struct resource *res;
int irq, error;
/* Driver need build keycode from device tree or pdata */
if (!np && !pdata)
return -EINVAL;
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
dev_err(&pdev->dev, "failed to get keypad irq\n");
return -ENXIO;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res == NULL) {
dev_err(&pdev->dev, "failed to get I/O memory\n");
return -ENXIO;
}
keypad = kzalloc(sizeof(struct pxa27x_keypad), GFP_KERNEL);
input_dev = input_allocate_device();
if (!keypad || !input_dev) {
dev_err(&pdev->dev, "failed to allocate memory\n");
error = -ENOMEM;
goto failed_free;
}
keypad->pdata = pdata;
keypad->input_dev = input_dev;
keypad->irq = irq;
res = request_mem_region(res->start, resource_size(res), pdev->name);
if (res == NULL) {
dev_err(&pdev->dev, "failed to request I/O memory\n");
error = -EBUSY;
goto failed_free;
}
keypad->mmio_base = ioremap(res->start, resource_size(res));
if (keypad->mmio_base == NULL) {
dev_err(&pdev->dev, "failed to remap I/O memory\n");
error = -ENXIO;
goto failed_free_mem;
}
keypad->clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(keypad->clk)) {
dev_err(&pdev->dev, "failed to get keypad clock\n");
error = PTR_ERR(keypad->clk);
goto failed_free_io;
}
input_dev->name = pdev->name;
input_dev->id.bustype = BUS_HOST;
input_dev->open = pxa27x_keypad_open;
input_dev->close = pxa27x_keypad_close;
input_dev->dev.parent = &pdev->dev;
input_dev->keycode = keypad->keycodes;
input_dev->keycodesize = sizeof(keypad->keycodes[0]);
input_dev->keycodemax = ARRAY_SIZE(keypad->keycodes);
input_set_drvdata(input_dev, keypad);
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP);
input_set_capability(input_dev, EV_MSC, MSC_SCAN);
if (pdata) {
error = pxa27x_keypad_build_keycode(keypad);
} else {
error = pxa27x_keypad_build_keycode_from_dt(keypad);
/*
* Data that we get from DT resides in dynamically
* allocated memory so we need to update our pdata
* pointer.
*/
pdata = keypad->pdata;
}
if (error) {
dev_err(&pdev->dev, "failed to build keycode\n");
goto failed_put_clk;
}
keypad->row_shift = get_count_order(pdata->matrix_key_cols);
if ((pdata->enable_rotary0 && keypad->rotary_rel_code[0] != -1) ||
(pdata->enable_rotary1 && keypad->rotary_rel_code[1] != -1)) {
input_dev->evbit[0] |= BIT_MASK(EV_REL);
}
error = request_irq(irq, pxa27x_keypad_irq_handler, 0,
pdev->name, keypad);
if (error) {
dev_err(&pdev->dev, "failed to request IRQ\n");
goto failed_put_clk;
}
/* Register the input device */
error = input_register_device(input_dev);
if (error) {
dev_err(&pdev->dev, "failed to register input device\n");
goto failed_free_irq;
}
platform_set_drvdata(pdev, keypad);
device_init_wakeup(&pdev->dev, 1);
return 0;
failed_free_irq:
free_irq(irq, keypad);
failed_put_clk:
clk_put(keypad->clk);
failed_free_io:
iounmap(keypad->mmio_base);
failed_free_mem:
release_mem_region(res->start, resource_size(res));
failed_free:
input_free_device(input_dev);
kfree(keypad);
return error;
}
static int pxa27x_keypad_remove(struct platform_device *pdev)
{
struct pxa27x_keypad *keypad = platform_get_drvdata(pdev);
struct resource *res;
free_irq(keypad->irq, keypad);
clk_put(keypad->clk);
input_unregister_device(keypad->input_dev);
iounmap(keypad->mmio_base);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(res->start, resource_size(res));
kfree(keypad);
return 0;
}
/* work with hotplug and coldplug */
MODULE_ALIAS("platform:pxa27x-keypad");
#ifdef CONFIG_OF
static const struct of_device_id pxa27x_keypad_dt_match[] = {
{ .compatible = "marvell,pxa27x-keypad" },
{},
};
MODULE_DEVICE_TABLE(of, pxa27x_keypad_dt_match);
#endif
static struct platform_driver pxa27x_keypad_driver = {
.probe = pxa27x_keypad_probe,
.remove = pxa27x_keypad_remove,
.driver = {
.name = "pxa27x-keypad",
.of_match_table = of_match_ptr(pxa27x_keypad_dt_match),
.owner = THIS_MODULE,
.pm = &pxa27x_keypad_pm_ops,
},
};
module_platform_driver(pxa27x_keypad_driver);
MODULE_DESCRIPTION("PXA27x Keypad Controller Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
einon/staging-et131x | drivers/misc/vmw_vmci/vmci_driver.c | 1006 | 3038 | /*
* VMware VMCI Driver
*
* Copyright (C) 2012 VMware, 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 version 2 and no 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/vmw_vmci_defs.h>
#include <linux/vmw_vmci_api.h>
#include <linux/atomic.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include "vmci_driver.h"
#include "vmci_event.h"
static bool vmci_disable_host;
module_param_named(disable_host, vmci_disable_host, bool, 0);
MODULE_PARM_DESC(disable_host,
"Disable driver host personality (default=enabled)");
static bool vmci_disable_guest;
module_param_named(disable_guest, vmci_disable_guest, bool, 0);
MODULE_PARM_DESC(disable_guest,
"Disable driver guest personality (default=enabled)");
static bool vmci_guest_personality_initialized;
static bool vmci_host_personality_initialized;
/*
* vmci_get_context_id() - Gets the current context ID.
*
* Returns the current context ID. Note that since this is accessed only
* from code running in the host, this always returns the host context ID.
*/
u32 vmci_get_context_id(void)
{
if (vmci_guest_code_active())
return vmci_get_vm_context_id();
else if (vmci_host_code_active())
return VMCI_HOST_CONTEXT_ID;
return VMCI_INVALID_ID;
}
EXPORT_SYMBOL_GPL(vmci_get_context_id);
static int __init vmci_drv_init(void)
{
int vmci_err;
int error;
vmci_err = vmci_event_init();
if (vmci_err < VMCI_SUCCESS) {
pr_err("Failed to initialize VMCIEvent (result=%d)\n",
vmci_err);
return -EINVAL;
}
if (!vmci_disable_guest) {
error = vmci_guest_init();
if (error) {
pr_warn("Failed to initialize guest personality (err=%d)\n",
error);
} else {
vmci_guest_personality_initialized = true;
pr_info("Guest personality initialized and is %s\n",
vmci_guest_code_active() ?
"active" : "inactive");
}
}
if (!vmci_disable_host) {
error = vmci_host_init();
if (error) {
pr_warn("Unable to initialize host personality (err=%d)\n",
error);
} else {
vmci_host_personality_initialized = true;
pr_info("Initialized host personality\n");
}
}
if (!vmci_guest_personality_initialized &&
!vmci_host_personality_initialized) {
vmci_event_exit();
return -ENODEV;
}
return 0;
}
module_init(vmci_drv_init);
static void __exit vmci_drv_exit(void)
{
if (vmci_guest_personality_initialized)
vmci_guest_exit();
if (vmci_host_personality_initialized)
vmci_host_exit();
vmci_event_exit();
}
module_exit(vmci_drv_exit);
MODULE_AUTHOR("VMware, Inc.");
MODULE_DESCRIPTION("VMware Virtual Machine Communication Interface.");
MODULE_VERSION("1.1.0.0-k");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
rogersb11/android_kernel_samsung_smdk4x12 | fs/proc/meminfo.c | 1518 | 4967 | #include <linux/fs.h>
#include <linux/hugetlb.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/mman.h>
#include <linux/mmzone.h>
#include <linux/proc_fs.h>
#include <linux/quicklist.h>
#include <linux/seq_file.h>
#include <linux/swap.h>
#include <linux/vmstat.h>
#include <asm/atomic.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include "internal.h"
void __attribute__((weak)) arch_report_meminfo(struct seq_file *m)
{
}
static int meminfo_proc_show(struct seq_file *m, void *v)
{
struct sysinfo i;
unsigned long committed;
unsigned long allowed;
struct vmalloc_info vmi;
long cached;
unsigned long pages[NR_LRU_LISTS];
int lru;
/*
* display in kilobytes.
*/
#define K(x) ((x) << (PAGE_SHIFT - 10))
si_meminfo(&i);
si_swapinfo(&i);
committed = percpu_counter_read_positive(&vm_committed_as);
allowed = ((totalram_pages - hugetlb_total_pages())
* sysctl_overcommit_ratio / 100) + total_swap_pages;
cached = global_page_state(NR_FILE_PAGES) -
total_swapcache_pages - i.bufferram;
if (cached < 0)
cached = 0;
get_vmalloc_info(&vmi);
for (lru = LRU_BASE; lru < NR_LRU_LISTS; lru++)
pages[lru] = global_page_state(NR_LRU_BASE + lru);
/*
* Tagged format, for easy grepping and expansion.
*/
seq_printf(m,
"MemTotal: %8lu kB\n"
"MemFree: %8lu kB\n"
"Buffers: %8lu kB\n"
"Cached: %8lu kB\n"
"SwapCached: %8lu kB\n"
"Active: %8lu kB\n"
"Inactive: %8lu kB\n"
"Active(anon): %8lu kB\n"
"Inactive(anon): %8lu kB\n"
"Active(file): %8lu kB\n"
"Inactive(file): %8lu kB\n"
"Unevictable: %8lu kB\n"
"Mlocked: %8lu kB\n"
#ifdef CONFIG_HIGHMEM
"HighTotal: %8lu kB\n"
"HighFree: %8lu kB\n"
"LowTotal: %8lu kB\n"
"LowFree: %8lu kB\n"
#endif
#ifndef CONFIG_MMU
"MmapCopy: %8lu kB\n"
#endif
"SwapTotal: %8lu kB\n"
"SwapFree: %8lu kB\n"
"Dirty: %8lu kB\n"
"Writeback: %8lu kB\n"
"AnonPages: %8lu kB\n"
"Mapped: %8lu kB\n"
"Shmem: %8lu kB\n"
"Slab: %8lu kB\n"
"SReclaimable: %8lu kB\n"
"SUnreclaim: %8lu kB\n"
"KernelStack: %8lu kB\n"
"PageTables: %8lu kB\n"
#ifdef CONFIG_QUICKLIST
"Quicklists: %8lu kB\n"
#endif
"NFS_Unstable: %8lu kB\n"
"Bounce: %8lu kB\n"
"WritebackTmp: %8lu kB\n"
"CommitLimit: %8lu kB\n"
"Committed_AS: %8lu kB\n"
"VmallocTotal: %8lu kB\n"
"VmallocUsed: %8lu kB\n"
"VmallocChunk: %8lu kB\n"
#ifdef CONFIG_MEMORY_FAILURE
"HardwareCorrupted: %5lu kB\n"
#endif
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
"AnonHugePages: %8lu kB\n"
#endif
,
K(i.totalram),
K(i.freeram),
K(i.bufferram),
K(cached),
K(total_swapcache_pages),
K(pages[LRU_ACTIVE_ANON] + pages[LRU_ACTIVE_FILE]),
K(pages[LRU_INACTIVE_ANON] + pages[LRU_INACTIVE_FILE]),
K(pages[LRU_ACTIVE_ANON]),
K(pages[LRU_INACTIVE_ANON]),
K(pages[LRU_ACTIVE_FILE]),
K(pages[LRU_INACTIVE_FILE]),
K(pages[LRU_UNEVICTABLE]),
K(global_page_state(NR_MLOCK)),
#ifdef CONFIG_HIGHMEM
K(i.totalhigh),
K(i.freehigh),
K(i.totalram-i.totalhigh),
K(i.freeram-i.freehigh),
#endif
#ifndef CONFIG_MMU
K((unsigned long) atomic_long_read(&mmap_pages_allocated)),
#endif
K(i.totalswap),
K(i.freeswap),
K(global_page_state(NR_FILE_DIRTY)),
K(global_page_state(NR_WRITEBACK)),
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
K(global_page_state(NR_ANON_PAGES)
+ global_page_state(NR_ANON_TRANSPARENT_HUGEPAGES) *
HPAGE_PMD_NR),
#else
K(global_page_state(NR_ANON_PAGES)),
#endif
K(global_page_state(NR_FILE_MAPPED)),
K(global_page_state(NR_SHMEM)),
K(global_page_state(NR_SLAB_RECLAIMABLE) +
global_page_state(NR_SLAB_UNRECLAIMABLE)),
K(global_page_state(NR_SLAB_RECLAIMABLE)),
K(global_page_state(NR_SLAB_UNRECLAIMABLE)),
global_page_state(NR_KERNEL_STACK) * THREAD_SIZE / 1024,
K(global_page_state(NR_PAGETABLE)),
#ifdef CONFIG_QUICKLIST
K(quicklist_total_size()),
#endif
K(global_page_state(NR_UNSTABLE_NFS)),
K(global_page_state(NR_BOUNCE)),
K(global_page_state(NR_WRITEBACK_TEMP)),
K(allowed),
K(committed),
(unsigned long)VMALLOC_TOTAL >> 10,
vmi.used >> 10,
vmi.largest_chunk >> 10
#ifdef CONFIG_MEMORY_FAILURE
,atomic_long_read(&mce_bad_pages) << (PAGE_SHIFT - 10)
#endif
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
,K(global_page_state(NR_ANON_TRANSPARENT_HUGEPAGES) *
HPAGE_PMD_NR)
#endif
);
hugetlb_report_meminfo(m);
arch_report_meminfo(m);
return 0;
#undef K
}
static int meminfo_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, meminfo_proc_show, NULL);
}
static const struct file_operations meminfo_proc_fops = {
.open = meminfo_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __init proc_meminfo_init(void)
{
proc_create("meminfo", 0, NULL, &meminfo_proc_fops);
return 0;
}
module_init(proc_meminfo_init);
| gpl-2.0 |
bedalus/moggy | drivers/video/msm/mdp4_overlay_writeback.c | 2030 | 19999 | /* Copyright (c) 2011-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/time.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/hrtimer.h>
#include <linux/delay.h>
#include <mach/hardware.h>
#include <linux/io.h>
#include <mach/iommu_domains.h>
#include <asm/system.h>
#include <asm/mach-types.h>
#include <linux/semaphore.h>
#include <linux/spinlock.h>
#include <linux/fb.h>
#include "mdp.h"
#include "msm_fb.h"
#include "mdp4.h"
enum {
WB_OPEN,
WB_START,
WB_STOPING,
WB_STOP
};
enum {
REGISTERED,
IN_FREE_QUEUE,
IN_BUSY_QUEUE,
WITH_CLIENT
};
#define MAX_CONTROLLER 1
#define VSYNC_EXPIRE_TICK 0
static struct vsycn_ctrl {
struct device *dev;
int inited;
int update_ndx;
u32 ov_koff;
u32 ov_done;
atomic_t suspend;
struct mutex update_lock;
struct completion ov_comp;
spinlock_t spin_lock;
struct msm_fb_data_type *mfd;
struct mdp4_overlay_pipe *base_pipe;
struct vsync_update vlist[2];
struct work_struct clk_work;
} vsync_ctrl_db[MAX_CONTROLLER];
static void vsync_irq_enable(int intr, int term)
{
unsigned long flag;
spin_lock_irqsave(&mdp_spin_lock, flag);
/* no need to clrear other interrupts for comamnd mode */
mdp_intr_mask |= intr;
outp32(MDP_INTR_ENABLE, mdp_intr_mask);
mdp_enable_irq(term);
spin_unlock_irqrestore(&mdp_spin_lock, flag);
}
static void vsync_irq_disable(int intr, int term)
{
unsigned long flag;
spin_lock_irqsave(&mdp_spin_lock, flag);
/* no need to clrear other interrupts for comamnd mode */
mdp_intr_mask &= ~intr;
outp32(MDP_INTR_ENABLE, mdp_intr_mask);
mdp_disable_irq_nosync(term);
spin_unlock_irqrestore(&mdp_spin_lock, flag);
}
static int mdp4_overlay_writeback_update(struct msm_fb_data_type *mfd);
static void mdp4_wfd_queue_wakeup(struct msm_fb_data_type *mfd,
struct msmfb_writeback_data_list *node);
static void mdp4_wfd_dequeue_update(struct msm_fb_data_type *mfd,
struct msmfb_writeback_data_list **wfdnode);
int mdp4_overlay_writeback_on(struct platform_device *pdev)
{
struct msm_fb_data_type *mfd;
struct fb_info *fbi;
uint8 *buf;
struct mdp4_overlay_pipe *pipe;
int bpp;
int ret;
uint32 data;
struct vsycn_ctrl *vctrl;
int cndx = 0;
mfd = (struct msm_fb_data_type *)platform_get_drvdata(pdev);
if (!mfd)
return -ENODEV;
if (mfd->key != MFD_KEY)
return -EINVAL;
vctrl = &vsync_ctrl_db[cndx];
vctrl->mfd = mfd;
vctrl->dev = mfd->fbi->dev;
fbi = mfd->fbi;
bpp = fbi->var.bits_per_pixel / 8;
buf = (uint8 *) fbi->fix.smem_start;
buf += fbi->var.xoffset * bpp +
fbi->var.yoffset * fbi->fix.line_length;
/* MDP cmd block enable */
mdp_clk_ctrl(1);
if (vctrl->base_pipe == NULL) {
pipe = mdp4_overlay_pipe_alloc(OVERLAY_TYPE_BF, MDP4_MIXER2);
if (pipe == NULL) {
pr_info("%s: pipe_alloc failed\n", __func__);
return -EIO;
}
pipe->pipe_used++;
pipe->mixer_stage = MDP4_MIXER_STAGE_BASE;
pipe->mixer_num = MDP4_MIXER2;
pipe->src_format = MDP_ARGB_8888;
mdp4_overlay_panel_mode(pipe->mixer_num, MDP4_PANEL_WRITEBACK);
ret = mdp4_overlay_format2pipe(pipe);
if (ret < 0)
pr_info("%s: format2type failed\n", __func__);
vctrl->base_pipe = pipe; /* keep it */
} else {
pipe = vctrl->base_pipe;
}
ret = panel_next_on(pdev);
/* MDP_LAYERMIXER_WB_MUX_SEL to use mixer1 axi for mixer2 writeback */
if (hdmi_prim_display)
data = 0x01;
else
data = 0x02;
outpdw(MDP_BASE + 0x100F4, data);
MDP_OUTP(MDP_BASE + MDP4_OVERLAYPROC1_BASE + 0x5004,
((0x0 & 0xFFF) << 16) | /* 12-bit B */
(0x0 & 0xFFF)); /* 12-bit G */
/* MSP_BORDER_COLOR */
MDP_OUTP(MDP_BASE + MDP4_OVERLAYPROC1_BASE + 0x5008,
(0x0 & 0xFFF)); /* 12-bit R */
mdp_clk_ctrl(0);
return ret;
}
int mdp4_overlay_writeback_off(struct platform_device *pdev)
{
int cndx = 0;
struct msm_fb_data_type *mfd;
struct vsycn_ctrl *vctrl;
struct mdp4_overlay_pipe *pipe;
int ret = 0;
int undx;
struct vsync_update *vp;
pr_debug("%s+:\n", __func__);
mfd = (struct msm_fb_data_type *)platform_get_drvdata(pdev);
vctrl = &vsync_ctrl_db[cndx];
pipe = vctrl->base_pipe;
if (pipe == NULL) {
pr_err("%s: NO base pipe\n", __func__);
return ret;
}
/* sanity check, free pipes besides base layer */
mdp4_overlay_unset_mixer(pipe->mixer_num);
mdp4_mixer_stage_down(pipe, 1);
mdp4_overlay_pipe_free(pipe);
vctrl->base_pipe = NULL;
undx = vctrl->update_ndx;
vp = &vctrl->vlist[undx];
if (vp->update_cnt) {
/*
* pipe's iommu will be freed at next overlay play
* and iommu_drop statistic will be increased by one
*/
vp->update_cnt = 0; /* empty queue */
}
ret = panel_next_off(pdev);
mdp_clk_ctrl(1);
/* MDP_LAYERMIXER_WB_MUX_SEL to restore to default cfg*/
outpdw(MDP_BASE + 0x100F4, 0x0);
mdp_clk_ctrl(0);
pr_debug("%s-:\n", __func__);
return ret;
}
static int mdp4_overlay_writeback_update(struct msm_fb_data_type *mfd)
{
struct fb_info *fbi;
uint8 *buf;
unsigned int buf_offset;
struct mdp4_overlay_pipe *pipe;
int bpp;
int cndx = 0;
struct vsycn_ctrl *vctrl;
if (mfd->key != MFD_KEY)
return -ENODEV;
fbi = mfd->fbi;
vctrl = &vsync_ctrl_db[cndx];
pipe = vctrl->base_pipe;
if (!pipe) {
pr_err("%s: no base layer pipe\n", __func__);
return -EINVAL;
}
bpp = fbi->var.bits_per_pixel / 8;
buf = (uint8 *) fbi->fix.smem_start;
buf_offset = fbi->var.xoffset * bpp +
fbi->var.yoffset * fbi->fix.line_length;
/* MDP cmd block enable */
mdp_clk_ctrl(1);
pipe->src_height = fbi->var.yres;
pipe->src_width = fbi->var.xres;
pipe->src_h = fbi->var.yres;
pipe->src_w = fbi->var.xres;
pipe->dst_h = fbi->var.yres;
pipe->dst_w = fbi->var.xres;
pipe->srcp0_ystride = fbi->fix.line_length;
pipe->src_y = 0;
pipe->src_x = 0;
pipe->dst_y = 0;
pipe->dst_x = 0;
mdp4_overlay_mdp_pipe_req(pipe, mfd);
mdp4_calc_blt_mdp_bw(mfd, pipe);
if (mfd->display_iova)
pipe->srcp0_addr = mfd->display_iova + buf_offset;
else
pipe->srcp0_addr = (uint32)(buf + buf_offset);
mdp4_mixer_stage_up(pipe, 0);
mdp4_overlayproc_cfg(pipe);
if (hdmi_prim_display)
outpdw(MDP_BASE + 0x100F4, 0x01);
else
outpdw(MDP_BASE + 0x100F4, 0x02);
/* MDP cmd block disable */
mdp_clk_ctrl(0);
wmb();
return 0;
}
/*
* mdp4_wfd_piep_queue:
* called from thread context
*/
void mdp4_wfd_pipe_queue(int cndx, struct mdp4_overlay_pipe *pipe)
{
struct vsycn_ctrl *vctrl;
struct vsync_update *vp;
struct mdp4_overlay_pipe *pp;
int undx;
if (cndx >= MAX_CONTROLLER) {
pr_err("%s: out or range: cndx=%d\n", __func__, cndx);
return;
}
vctrl = &vsync_ctrl_db[cndx];
if (atomic_read(&vctrl->suspend) > 0)
return;
mutex_lock(&vctrl->update_lock);
undx = vctrl->update_ndx;
vp = &vctrl->vlist[undx];
pp = &vp->plist[pipe->pipe_ndx - 1]; /* ndx start form 1 */
pr_debug("%s: vndx=%d pipe_ndx=%d pid=%d\n", __func__,
undx, pipe->pipe_ndx, current->pid);
*pp = *pipe; /* clone it */
vp->update_cnt++;
mutex_unlock(&vctrl->update_lock);
mdp4_stat.overlay_play[pipe->mixer_num]++;
}
static void mdp4_wfd_wait4ov(int cndx);
int mdp4_wfd_pipe_commit(struct msm_fb_data_type *mfd,
int cndx, int wait)
{
int i, undx;
int mixer = 0;
struct vsycn_ctrl *vctrl;
struct vsync_update *vp;
struct mdp4_overlay_pipe *pipe;
struct mdp4_overlay_pipe *real_pipe;
unsigned long flags;
int cnt = 0;
struct msmfb_writeback_data_list *node = NULL;
vctrl = &vsync_ctrl_db[cndx];
mutex_lock(&vctrl->update_lock);
undx = vctrl->update_ndx;
vp = &vctrl->vlist[undx];
pipe = vctrl->base_pipe;
mixer = pipe->mixer_num;
if (vp->update_cnt == 0) {
mutex_unlock(&vctrl->update_lock);
return cnt;
}
vctrl->update_ndx++;
vctrl->update_ndx &= 0x01;
vp->update_cnt = 0; /* reset */
mutex_unlock(&vctrl->update_lock);
mdp4_wfd_dequeue_update(mfd, &node);
/* free previous committed iommu back to pool */
mdp4_overlay_iommu_unmap_freelist(mixer);
pipe = vp->plist;
for (i = 0; i < OVERLAY_PIPE_MAX; i++, pipe++) {
if (pipe->pipe_used) {
cnt++;
real_pipe = mdp4_overlay_ndx2pipe(pipe->pipe_ndx);
if (real_pipe && real_pipe->pipe_used) {
/* pipe not unset */
mdp4_overlay_vsync_commit(pipe);
}
/* free previous iommu to freelist
* which will be freed at next
* pipe_commit
*/
mdp4_overlay_iommu_pipe_free(pipe->pipe_ndx, 0);
pipe->pipe_used = 0; /* clear */
}
}
mdp_clk_ctrl(1);
mdp4_mixer_stage_commit(mixer);
pipe = vctrl->base_pipe;
spin_lock_irqsave(&vctrl->spin_lock, flags);
vctrl->ov_koff++;
INIT_COMPLETION(vctrl->ov_comp);
vsync_irq_enable(INTR_OVERLAY2_DONE, MDP_OVERLAY2_TERM);
pr_debug("%s: kickoff\n", __func__);
/* kickoff overlay engine */
mdp4_stat.kickoff_ov2++;
outpdw(MDP_BASE + 0x00D0, 0);
mb(); /* make sure kickoff executed */
spin_unlock_irqrestore(&vctrl->spin_lock, flags);
mdp4_stat.overlay_commit[pipe->mixer_num]++;
if (wait)
mdp4_wfd_wait4ov(cndx);
mdp4_wfd_queue_wakeup(mfd, node);
return cnt;
}
static void clk_ctrl_work(struct work_struct *work)
{
struct vsycn_ctrl *vctrl =
container_of(work, typeof(*vctrl), clk_work);
mdp_clk_ctrl(0);
}
void mdp4_wfd_init(int cndx)
{
struct vsycn_ctrl *vctrl;
if (cndx >= MAX_CONTROLLER) {
pr_err("%s: out or range: cndx=%d\n", __func__, cndx);
return;
}
vctrl = &vsync_ctrl_db[cndx];
if (vctrl->inited)
return;
vctrl->inited = 1;
vctrl->update_ndx = 0;
mutex_init(&vctrl->update_lock);
init_completion(&vctrl->ov_comp);
spin_lock_init(&vctrl->spin_lock);
INIT_WORK(&vctrl->clk_work, clk_ctrl_work);
}
static void mdp4_wfd_wait4ov(int cndx)
{
struct vsycn_ctrl *vctrl;
if (cndx >= MAX_CONTROLLER) {
pr_err("%s: out or range: cndx=%d\n", __func__, cndx);
return;
}
vctrl = &vsync_ctrl_db[cndx];
if (atomic_read(&vctrl->suspend) > 0)
return;
wait_for_completion(&vctrl->ov_comp);
}
void mdp4_overlay2_done_wfd(struct mdp_dma_data *dma)
{
struct vsycn_ctrl *vctrl;
struct mdp4_overlay_pipe *pipe;
int cndx = 0;
vctrl = &vsync_ctrl_db[cndx];
pipe = vctrl->base_pipe;
spin_lock(&vctrl->spin_lock);
vsync_irq_disable(INTR_OVERLAY2_DONE, MDP_OVERLAY2_TERM);
vctrl->ov_done++;
complete(&vctrl->ov_comp);
schedule_work(&vctrl->clk_work);
pr_debug("%s ovdone interrupt\n", __func__);
spin_unlock(&vctrl->spin_lock);
}
void mdp4_writeback_overlay(struct msm_fb_data_type *mfd)
{
struct vsycn_ctrl *vctrl;
struct mdp4_overlay_pipe *pipe;
if (mfd && !mfd->panel_power_on)
return;
pr_debug("%s:+ mfd=%x\n", __func__, (int)mfd);
vctrl = &vsync_ctrl_db[0];
pipe = vctrl->base_pipe;
mutex_lock(&mfd->dma->ov_mutex);
if (pipe->pipe_type == OVERLAY_TYPE_RGB)
mdp4_wfd_pipe_queue(0, pipe);
mdp4_overlay_mdp_perf_upd(mfd, 1);
mdp4_wfd_pipe_commit(mfd, 0, 1);
mdp4_overlay_mdp_perf_upd(mfd, 0);
mutex_unlock(&mfd->dma->ov_mutex);
}
static int mdp4_overlay_writeback_register_buffer(
struct msm_fb_data_type *mfd, struct msmfb_writeback_data_list *node)
{
if (!node) {
pr_err("Cannot register a NULL node\n");
return -EINVAL;
}
node->state = REGISTERED;
list_add_tail(&node->registered_entry, &mfd->writeback_register_queue);
return 0;
}
static struct msmfb_writeback_data_list *get_if_registered(
struct msm_fb_data_type *mfd, struct msmfb_data *data)
{
struct msmfb_writeback_data_list *temp;
bool found = false;
int domain;
if (!list_empty(&mfd->writeback_register_queue)) {
list_for_each_entry(temp,
&mfd->writeback_register_queue,
registered_entry) {
if (temp && temp->buf_info.iova == data->iova) {
found = true;
break;
}
}
}
if (!found) {
temp = kzalloc(sizeof(struct msmfb_writeback_data_list),
GFP_KERNEL);
if (temp == NULL) {
pr_err("%s: out of memory\n", __func__);
goto register_alloc_fail;
}
temp->ihdl = NULL;
if (data->iova)
temp->addr = (void *)(data->iova + data->offset);
else if (mfd->iclient) {
struct ion_handle *srcp_ihdl;
ulong len;
srcp_ihdl = ion_import_dma_buf(mfd->iclient,
data->memory_id);
if (IS_ERR_OR_NULL(srcp_ihdl)) {
pr_err("%s: ion import fd failed\n", __func__);
goto register_ion_fail;
}
if (mdp_iommu_split_domain)
domain = DISPLAY_WRITE_DOMAIN;
else
domain = DISPLAY_READ_DOMAIN;
if (ion_map_iommu(mfd->iclient,
srcp_ihdl,
domain,
GEN_POOL,
SZ_4K,
0,
(ulong *)&temp->addr,
(ulong *)&len,
0,
ION_IOMMU_UNMAP_DELAYED)) {
ion_free(mfd->iclient, srcp_ihdl);
pr_err("%s: unable to get ion mapping addr\n",
__func__);
goto register_ion_fail;
}
temp->addr += data->offset;
temp->ihdl = srcp_ihdl;
}
else {
pr_err("%s: only support ion memory\n", __func__);
goto register_ion_fail;
}
memcpy(&temp->buf_info, data, sizeof(struct msmfb_data));
if (mdp4_overlay_writeback_register_buffer(mfd, temp)) {
pr_err("%s: error registering node\n", __func__);
goto register_ion_fail;
}
}
return temp;
register_ion_fail:
kfree(temp);
register_alloc_fail:
return NULL;
}
int mdp4_writeback_start(
struct fb_info *info)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
mutex_lock(&mfd->writeback_mutex);
mfd->writeback_state = WB_START;
mutex_unlock(&mfd->writeback_mutex);
wake_up(&mfd->wait_q);
return 0;
}
int mdp4_writeback_queue_buffer(struct fb_info *info, struct msmfb_data *data)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
struct msmfb_writeback_data_list *node = NULL;
int rv = 0;
mutex_lock(&mfd->writeback_mutex);
node = get_if_registered(mfd, data);
if (!node || node->state == IN_BUSY_QUEUE ||
node->state == IN_FREE_QUEUE) {
pr_err("memory not registered or Buffer already with us\n");
rv = -EINVAL;
goto exit;
}
list_add_tail(&node->active_entry, &mfd->writeback_free_queue);
node->state = IN_FREE_QUEUE;
exit:
mutex_unlock(&mfd->writeback_mutex);
return rv;
}
static int is_buffer_ready(struct msm_fb_data_type *mfd)
{
int rc;
mutex_lock(&mfd->writeback_mutex);
rc = !list_empty(&mfd->writeback_busy_queue) ||
(mfd->writeback_state == WB_STOPING);
mutex_unlock(&mfd->writeback_mutex);
return rc;
}
int mdp4_writeback_dequeue_buffer(struct fb_info *info, struct msmfb_data *data)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
struct msmfb_writeback_data_list *node = NULL;
int rc = 0, domain;
rc = wait_event_interruptible(mfd->wait_q, is_buffer_ready(mfd));
if (rc) {
pr_err("failed to get dequeued buffer\n");
return -ENOBUFS;
}
mutex_lock(&mfd->writeback_mutex);
if (mfd->writeback_state == WB_STOPING) {
mfd->writeback_state = WB_STOP;
mutex_unlock(&mfd->writeback_mutex);
return -ENOBUFS;
} else if (!list_empty(&mfd->writeback_busy_queue)) {
node = list_first_entry(&mfd->writeback_busy_queue,
struct msmfb_writeback_data_list, active_entry);
}
if (node) {
list_del(&node->active_entry);
node->state = WITH_CLIENT;
memcpy(data, &node->buf_info, sizeof(struct msmfb_data));
if (!data->iova)
if (mfd->iclient && node->ihdl) {
if (mdp_iommu_split_domain)
domain = DISPLAY_WRITE_DOMAIN;
else
domain = DISPLAY_READ_DOMAIN;
ion_unmap_iommu(mfd->iclient,
node->ihdl,
domain,
GEN_POOL);
ion_free(mfd->iclient,
node->ihdl);
}
} else {
pr_err("node is NULL. Somebody else dequeued?\n");
rc = -ENOBUFS;
}
mutex_unlock(&mfd->writeback_mutex);
return rc;
}
static bool is_writeback_inactive(struct msm_fb_data_type *mfd)
{
bool active;
mutex_lock(&mfd->writeback_mutex);
active = !mfd->writeback_active_cnt;
mutex_unlock(&mfd->writeback_mutex);
return active;
}
int mdp4_writeback_stop(struct fb_info *info)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
mutex_lock(&mfd->writeback_mutex);
mfd->writeback_state = WB_STOPING;
mutex_unlock(&mfd->writeback_mutex);
/* Wait for all pending writebacks to finish */
wait_event_interruptible(mfd->wait_q, is_writeback_inactive(mfd));
/* Wake up dequeue thread in case of no UI update*/
wake_up(&mfd->wait_q);
return 0;
}
int mdp4_writeback_init(struct fb_info *info)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
mutex_init(&mfd->writeback_mutex);
mutex_init(&mfd->unregister_mutex);
INIT_LIST_HEAD(&mfd->writeback_free_queue);
INIT_LIST_HEAD(&mfd->writeback_busy_queue);
INIT_LIST_HEAD(&mfd->writeback_register_queue);
mfd->writeback_state = WB_OPEN;
init_waitqueue_head(&mfd->wait_q);
return 0;
}
int mdp4_writeback_terminate(struct fb_info *info)
{
struct list_head *ptr, *next;
struct msmfb_writeback_data_list *temp;
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
int rc = 0;
mutex_lock(&mfd->unregister_mutex);
mutex_lock(&mfd->writeback_mutex);
if (mfd->writeback_state != WB_STOPING &&
mfd->writeback_state != WB_STOP) {
pr_err("%s called without stopping\n", __func__);
rc = -EPERM;
goto terminate_err;
}
if (!list_empty(&mfd->writeback_register_queue)) {
list_for_each_safe(ptr, next,
&mfd->writeback_register_queue) {
temp = list_entry(ptr,
struct msmfb_writeback_data_list,
registered_entry);
list_del(&temp->registered_entry);
kfree(temp);
}
}
INIT_LIST_HEAD(&mfd->writeback_register_queue);
INIT_LIST_HEAD(&mfd->writeback_busy_queue);
INIT_LIST_HEAD(&mfd->writeback_free_queue);
terminate_err:
mutex_unlock(&mfd->writeback_mutex);
mutex_unlock(&mfd->unregister_mutex);
return rc;
}
static void mdp4_wfd_dequeue_update(struct msm_fb_data_type *mfd,
struct msmfb_writeback_data_list **wfdnode)
{
struct vsycn_ctrl *vctrl;
struct mdp4_overlay_pipe *pipe;
struct msmfb_writeback_data_list *node = NULL;
if (mfd && !mfd->panel_power_on)
return;
pr_debug("%s:+ mfd=%x\n", __func__, (int)mfd);
vctrl = &vsync_ctrl_db[0];
pipe = vctrl->base_pipe;
mutex_lock(&mfd->unregister_mutex);
mutex_lock(&mfd->writeback_mutex);
if (!list_empty(&mfd->writeback_free_queue)
&& mfd->writeback_state != WB_STOPING
&& mfd->writeback_state != WB_STOP) {
node = list_first_entry(&mfd->writeback_free_queue,
struct msmfb_writeback_data_list, active_entry);
}
if (node) {
list_del(&(node->active_entry));
node->state = IN_BUSY_QUEUE;
mfd->writeback_active_cnt++;
}
mutex_unlock(&mfd->writeback_mutex);
pipe->ov_blt_addr = (ulong) (node ? node->addr : NULL);
if (!pipe->ov_blt_addr) {
pr_err("%s: no writeback buffer 0x%x, %p\n", __func__,
(unsigned int)pipe->ov_blt_addr, node);
mutex_unlock(&mfd->unregister_mutex);
return;
}
mdp4_overlay_writeback_update(mfd);
*wfdnode = node;
mutex_unlock(&mfd->unregister_mutex);
}
static void mdp4_wfd_queue_wakeup(struct msm_fb_data_type *mfd,
struct msmfb_writeback_data_list *node)
{
if (mfd && !mfd->panel_power_on)
return;
if (node == NULL)
return;
pr_debug("%s: mfd=%x node: %p", __func__, (int)mfd, node);
mutex_lock(&mfd->writeback_mutex);
list_add_tail(&node->active_entry, &mfd->writeback_busy_queue);
mfd->writeback_active_cnt--;
mutex_unlock(&mfd->writeback_mutex);
wake_up(&mfd->wait_q);
}
int mdp4_writeback_set_mirroring_hint(struct fb_info *info, int hint)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
if (mfd->panel.type != WRITEBACK_PANEL)
return -ENOTSUPP;
switch (hint) {
case MDP_WRITEBACK_MIRROR_ON:
case MDP_WRITEBACK_MIRROR_PAUSE:
case MDP_WRITEBACK_MIRROR_RESUME:
case MDP_WRITEBACK_MIRROR_OFF:
pr_info("wfd state switched to %d\n", hint);
switch_set_state(&mfd->writeback_sdev, hint);
return 0;
default:
return -EINVAL;
}
}
| gpl-2.0 |
desaishivam26/android_kernel_motorola_msm8916 | drivers/thermal/intel_powerclamp.c | 2286 | 20992 | /*
* intel_powerclamp.c - package c-state idle injection
*
* Copyright (c) 2012, Intel Corporation.
*
* Authors:
* Arjan van de Ven <arjan@linux.intel.com>
* Jacob Pan <jacob.jun.pan@linux.intel.com>
*
* 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.
*
*
* TODO:
* 1. better handle wakeup from external interrupts, currently a fixed
* compensation is added to clamping duration when excessive amount
* of wakeups are observed during idle time. the reason is that in
* case of external interrupts without need for ack, clamping down
* cpu in non-irq context does not reduce irq. for majority of the
* cases, clamping down cpu does help reduce irq as well, we should
* be able to differenciate the two cases and give a quantitative
* solution for the irqs that we can control. perhaps based on
* get_cpu_iowait_time_us()
*
* 2. synchronization with other hw blocks
*
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/cpu.h>
#include <linux/thermal.h>
#include <linux/slab.h>
#include <linux/tick.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/sched/rt.h>
#include <asm/nmi.h>
#include <asm/msr.h>
#include <asm/mwait.h>
#include <asm/cpu_device_id.h>
#include <asm/idle.h>
#include <asm/hardirq.h>
#define MAX_TARGET_RATIO (50U)
/* For each undisturbed clamping period (no extra wake ups during idle time),
* we increment the confidence counter for the given target ratio.
* CONFIDENCE_OK defines the level where runtime calibration results are
* valid.
*/
#define CONFIDENCE_OK (3)
/* Default idle injection duration, driver adjust sleep time to meet target
* idle ratio. Similar to frequency modulation.
*/
#define DEFAULT_DURATION_JIFFIES (6)
static unsigned int target_mwait;
static struct dentry *debug_dir;
/* user selected target */
static unsigned int set_target_ratio;
static unsigned int current_ratio;
static bool should_skip;
static bool reduce_irq;
static atomic_t idle_wakeup_counter;
static unsigned int control_cpu; /* The cpu assigned to collect stat and update
* control parameters. default to BSP but BSP
* can be offlined.
*/
static bool clamping;
static struct task_struct * __percpu *powerclamp_thread;
static struct thermal_cooling_device *cooling_dev;
static unsigned long *cpu_clamping_mask; /* bit map for tracking per cpu
* clamping thread
*/
static unsigned int duration;
static unsigned int pkg_cstate_ratio_cur;
static unsigned int window_size;
static int duration_set(const char *arg, const struct kernel_param *kp)
{
int ret = 0;
unsigned long new_duration;
ret = kstrtoul(arg, 10, &new_duration);
if (ret)
goto exit;
if (new_duration > 25 || new_duration < 6) {
pr_err("Out of recommended range %lu, between 6-25ms\n",
new_duration);
ret = -EINVAL;
}
duration = clamp(new_duration, 6ul, 25ul);
smp_mb();
exit:
return ret;
}
static struct kernel_param_ops duration_ops = {
.set = duration_set,
.get = param_get_int,
};
module_param_cb(duration, &duration_ops, &duration, 0644);
MODULE_PARM_DESC(duration, "forced idle time for each attempt in msec.");
struct powerclamp_calibration_data {
unsigned long confidence; /* used for calibration, basically a counter
* gets incremented each time a clamping
* period is completed without extra wakeups
* once that counter is reached given level,
* compensation is deemed usable.
*/
unsigned long steady_comp; /* steady state compensation used when
* no extra wakeups occurred.
*/
unsigned long dynamic_comp; /* compensate excessive wakeup from idle
* mostly from external interrupts.
*/
};
static struct powerclamp_calibration_data cal_data[MAX_TARGET_RATIO];
static int window_size_set(const char *arg, const struct kernel_param *kp)
{
int ret = 0;
unsigned long new_window_size;
ret = kstrtoul(arg, 10, &new_window_size);
if (ret)
goto exit_win;
if (new_window_size > 10 || new_window_size < 2) {
pr_err("Out of recommended window size %lu, between 2-10\n",
new_window_size);
ret = -EINVAL;
}
window_size = clamp(new_window_size, 2ul, 10ul);
smp_mb();
exit_win:
return ret;
}
static struct kernel_param_ops window_size_ops = {
.set = window_size_set,
.get = param_get_int,
};
module_param_cb(window_size, &window_size_ops, &window_size, 0644);
MODULE_PARM_DESC(window_size, "sliding window in number of clamping cycles\n"
"\tpowerclamp controls idle ratio within this window. larger\n"
"\twindow size results in slower response time but more smooth\n"
"\tclamping results. default to 2.");
static void find_target_mwait(void)
{
unsigned int eax, ebx, ecx, edx;
unsigned int highest_cstate = 0;
unsigned int highest_subcstate = 0;
int i;
if (boot_cpu_data.cpuid_level < CPUID_MWAIT_LEAF)
return;
cpuid(CPUID_MWAIT_LEAF, &eax, &ebx, &ecx, &edx);
if (!(ecx & CPUID5_ECX_EXTENSIONS_SUPPORTED) ||
!(ecx & CPUID5_ECX_INTERRUPT_BREAK))
return;
edx >>= MWAIT_SUBSTATE_SIZE;
for (i = 0; i < 7 && edx; i++, edx >>= MWAIT_SUBSTATE_SIZE) {
if (edx & MWAIT_SUBSTATE_MASK) {
highest_cstate = i;
highest_subcstate = edx & MWAIT_SUBSTATE_MASK;
}
}
target_mwait = (highest_cstate << MWAIT_SUBSTATE_SIZE) |
(highest_subcstate - 1);
}
static u64 pkg_state_counter(void)
{
u64 val;
u64 count = 0;
static bool skip_c2;
static bool skip_c3;
static bool skip_c6;
static bool skip_c7;
if (!skip_c2) {
if (!rdmsrl_safe(MSR_PKG_C2_RESIDENCY, &val))
count += val;
else
skip_c2 = true;
}
if (!skip_c3) {
if (!rdmsrl_safe(MSR_PKG_C3_RESIDENCY, &val))
count += val;
else
skip_c3 = true;
}
if (!skip_c6) {
if (!rdmsrl_safe(MSR_PKG_C6_RESIDENCY, &val))
count += val;
else
skip_c6 = true;
}
if (!skip_c7) {
if (!rdmsrl_safe(MSR_PKG_C7_RESIDENCY, &val))
count += val;
else
skip_c7 = true;
}
return count;
}
static void noop_timer(unsigned long foo)
{
/* empty... just the fact that we get the interrupt wakes us up */
}
static unsigned int get_compensation(int ratio)
{
unsigned int comp = 0;
/* we only use compensation if all adjacent ones are good */
if (ratio == 1 &&
cal_data[ratio].confidence >= CONFIDENCE_OK &&
cal_data[ratio + 1].confidence >= CONFIDENCE_OK &&
cal_data[ratio + 2].confidence >= CONFIDENCE_OK) {
comp = (cal_data[ratio].steady_comp +
cal_data[ratio + 1].steady_comp +
cal_data[ratio + 2].steady_comp) / 3;
} else if (ratio == MAX_TARGET_RATIO - 1 &&
cal_data[ratio].confidence >= CONFIDENCE_OK &&
cal_data[ratio - 1].confidence >= CONFIDENCE_OK &&
cal_data[ratio - 2].confidence >= CONFIDENCE_OK) {
comp = (cal_data[ratio].steady_comp +
cal_data[ratio - 1].steady_comp +
cal_data[ratio - 2].steady_comp) / 3;
} else if (cal_data[ratio].confidence >= CONFIDENCE_OK &&
cal_data[ratio - 1].confidence >= CONFIDENCE_OK &&
cal_data[ratio + 1].confidence >= CONFIDENCE_OK) {
comp = (cal_data[ratio].steady_comp +
cal_data[ratio - 1].steady_comp +
cal_data[ratio + 1].steady_comp) / 3;
}
/* REVISIT: simple penalty of double idle injection */
if (reduce_irq)
comp = ratio;
/* do not exceed limit */
if (comp + ratio >= MAX_TARGET_RATIO)
comp = MAX_TARGET_RATIO - ratio - 1;
return comp;
}
static void adjust_compensation(int target_ratio, unsigned int win)
{
int delta;
struct powerclamp_calibration_data *d = &cal_data[target_ratio];
/*
* adjust compensations if confidence level has not been reached or
* there are too many wakeups during the last idle injection period, we
* cannot trust the data for compensation.
*/
if (d->confidence >= CONFIDENCE_OK ||
atomic_read(&idle_wakeup_counter) >
win * num_online_cpus())
return;
delta = set_target_ratio - current_ratio;
/* filter out bad data */
if (delta >= 0 && delta <= (1+target_ratio/10)) {
if (d->steady_comp)
d->steady_comp =
roundup(delta+d->steady_comp, 2)/2;
else
d->steady_comp = delta;
d->confidence++;
}
}
static bool powerclamp_adjust_controls(unsigned int target_ratio,
unsigned int guard, unsigned int win)
{
static u64 msr_last, tsc_last;
u64 msr_now, tsc_now;
u64 val64;
/* check result for the last window */
msr_now = pkg_state_counter();
rdtscll(tsc_now);
/* calculate pkg cstate vs tsc ratio */
if (!msr_last || !tsc_last)
current_ratio = 1;
else if (tsc_now-tsc_last) {
val64 = 100*(msr_now-msr_last);
do_div(val64, (tsc_now-tsc_last));
current_ratio = val64;
}
/* update record */
msr_last = msr_now;
tsc_last = tsc_now;
adjust_compensation(target_ratio, win);
/*
* too many external interrupts, set flag such
* that we can take measure later.
*/
reduce_irq = atomic_read(&idle_wakeup_counter) >=
2 * win * num_online_cpus();
atomic_set(&idle_wakeup_counter, 0);
/* if we are above target+guard, skip */
return set_target_ratio + guard <= current_ratio;
}
static int clamp_thread(void *arg)
{
int cpunr = (unsigned long)arg;
DEFINE_TIMER(wakeup_timer, noop_timer, 0, 0);
static const struct sched_param param = {
.sched_priority = MAX_USER_RT_PRIO/2,
};
unsigned int count = 0;
unsigned int target_ratio;
set_bit(cpunr, cpu_clamping_mask);
set_freezable();
init_timer_on_stack(&wakeup_timer);
sched_setscheduler(current, SCHED_FIFO, ¶m);
while (true == clamping && !kthread_should_stop() &&
cpu_online(cpunr)) {
int sleeptime;
unsigned long target_jiffies;
unsigned int guard;
unsigned int compensation = 0;
int interval; /* jiffies to sleep for each attempt */
unsigned int duration_jiffies = msecs_to_jiffies(duration);
unsigned int window_size_now;
try_to_freeze();
/*
* make sure user selected ratio does not take effect until
* the next round. adjust target_ratio if user has changed
* target such that we can converge quickly.
*/
target_ratio = set_target_ratio;
guard = 1 + target_ratio/20;
window_size_now = window_size;
count++;
/*
* systems may have different ability to enter package level
* c-states, thus we need to compensate the injected idle ratio
* to achieve the actual target reported by the HW.
*/
compensation = get_compensation(target_ratio);
interval = duration_jiffies*100/(target_ratio+compensation);
/* align idle time */
target_jiffies = roundup(jiffies, interval);
sleeptime = target_jiffies - jiffies;
if (sleeptime <= 0)
sleeptime = 1;
schedule_timeout_interruptible(sleeptime);
/*
* only elected controlling cpu can collect stats and update
* control parameters.
*/
if (cpunr == control_cpu && !(count%window_size_now)) {
should_skip =
powerclamp_adjust_controls(target_ratio,
guard, window_size_now);
smp_mb();
}
if (should_skip)
continue;
target_jiffies = jiffies + duration_jiffies;
mod_timer(&wakeup_timer, target_jiffies);
if (unlikely(local_softirq_pending()))
continue;
/*
* stop tick sched during idle time, interrupts are still
* allowed. thus jiffies are updated properly.
*/
preempt_disable();
tick_nohz_idle_enter();
/* mwait until target jiffies is reached */
while (time_before(jiffies, target_jiffies)) {
unsigned long ecx = 1;
unsigned long eax = target_mwait;
/*
* REVISIT: may call enter_idle() to notify drivers who
* can save power during cpu idle. same for exit_idle()
*/
local_touch_nmi();
stop_critical_timings();
__monitor((void *)¤t_thread_info()->flags, 0, 0);
cpu_relax(); /* allow HT sibling to run */
__mwait(eax, ecx);
start_critical_timings();
atomic_inc(&idle_wakeup_counter);
}
tick_nohz_idle_exit();
preempt_enable_no_resched();
}
del_timer_sync(&wakeup_timer);
clear_bit(cpunr, cpu_clamping_mask);
return 0;
}
/*
* 1 HZ polling while clamping is active, useful for userspace
* to monitor actual idle ratio.
*/
static void poll_pkg_cstate(struct work_struct *dummy);
static DECLARE_DELAYED_WORK(poll_pkg_cstate_work, poll_pkg_cstate);
static void poll_pkg_cstate(struct work_struct *dummy)
{
static u64 msr_last;
static u64 tsc_last;
static unsigned long jiffies_last;
u64 msr_now;
unsigned long jiffies_now;
u64 tsc_now;
u64 val64;
msr_now = pkg_state_counter();
rdtscll(tsc_now);
jiffies_now = jiffies;
/* calculate pkg cstate vs tsc ratio */
if (!msr_last || !tsc_last)
pkg_cstate_ratio_cur = 1;
else {
if (tsc_now - tsc_last) {
val64 = 100 * (msr_now - msr_last);
do_div(val64, (tsc_now - tsc_last));
pkg_cstate_ratio_cur = val64;
}
}
/* update record */
msr_last = msr_now;
jiffies_last = jiffies_now;
tsc_last = tsc_now;
if (true == clamping)
schedule_delayed_work(&poll_pkg_cstate_work, HZ);
}
static int start_power_clamp(void)
{
unsigned long cpu;
struct task_struct *thread;
/* check if pkg cstate counter is completely 0, abort in this case */
if (!pkg_state_counter()) {
pr_err("pkg cstate counter not functional, abort\n");
return -EINVAL;
}
set_target_ratio = clamp(set_target_ratio, 0U, MAX_TARGET_RATIO - 1);
/* prevent cpu hotplug */
get_online_cpus();
/* prefer BSP */
control_cpu = 0;
if (!cpu_online(control_cpu))
control_cpu = smp_processor_id();
clamping = true;
schedule_delayed_work(&poll_pkg_cstate_work, 0);
/* start one thread per online cpu */
for_each_online_cpu(cpu) {
struct task_struct **p =
per_cpu_ptr(powerclamp_thread, cpu);
thread = kthread_create_on_node(clamp_thread,
(void *) cpu,
cpu_to_node(cpu),
"kidle_inject/%ld", cpu);
/* bind to cpu here */
if (likely(!IS_ERR(thread))) {
kthread_bind(thread, cpu);
wake_up_process(thread);
*p = thread;
}
}
put_online_cpus();
return 0;
}
static void end_power_clamp(void)
{
int i;
struct task_struct *thread;
clamping = false;
/*
* make clamping visible to other cpus and give per cpu clamping threads
* sometime to exit, or gets killed later.
*/
smp_mb();
msleep(20);
if (bitmap_weight(cpu_clamping_mask, num_possible_cpus())) {
for_each_set_bit(i, cpu_clamping_mask, num_possible_cpus()) {
pr_debug("clamping thread for cpu %d alive, kill\n", i);
thread = *per_cpu_ptr(powerclamp_thread, i);
kthread_stop(thread);
}
}
}
static int powerclamp_cpu_callback(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
unsigned long cpu = (unsigned long)hcpu;
struct task_struct *thread;
struct task_struct **percpu_thread =
per_cpu_ptr(powerclamp_thread, cpu);
if (false == clamping)
goto exit_ok;
switch (action) {
case CPU_ONLINE:
thread = kthread_create_on_node(clamp_thread,
(void *) cpu,
cpu_to_node(cpu),
"kidle_inject/%lu", cpu);
if (likely(!IS_ERR(thread))) {
kthread_bind(thread, cpu);
wake_up_process(thread);
*percpu_thread = thread;
}
/* prefer BSP as controlling CPU */
if (cpu == 0) {
control_cpu = 0;
smp_mb();
}
break;
case CPU_DEAD:
if (test_bit(cpu, cpu_clamping_mask)) {
pr_err("cpu %lu dead but powerclamping thread is not\n",
cpu);
kthread_stop(*percpu_thread);
}
if (cpu == control_cpu) {
control_cpu = smp_processor_id();
smp_mb();
}
}
exit_ok:
return NOTIFY_OK;
}
static struct notifier_block powerclamp_cpu_notifier = {
.notifier_call = powerclamp_cpu_callback,
};
static int powerclamp_get_max_state(struct thermal_cooling_device *cdev,
unsigned long *state)
{
*state = MAX_TARGET_RATIO;
return 0;
}
static int powerclamp_get_cur_state(struct thermal_cooling_device *cdev,
unsigned long *state)
{
if (true == clamping)
*state = pkg_cstate_ratio_cur;
else
/* to save power, do not poll idle ratio while not clamping */
*state = -1; /* indicates invalid state */
return 0;
}
static int powerclamp_set_cur_state(struct thermal_cooling_device *cdev,
unsigned long new_target_ratio)
{
int ret = 0;
new_target_ratio = clamp(new_target_ratio, 0UL,
(unsigned long) (MAX_TARGET_RATIO-1));
if (set_target_ratio == 0 && new_target_ratio > 0) {
pr_info("Start idle injection to reduce power\n");
set_target_ratio = new_target_ratio;
ret = start_power_clamp();
goto exit_set;
} else if (set_target_ratio > 0 && new_target_ratio == 0) {
pr_info("Stop forced idle injection\n");
set_target_ratio = 0;
end_power_clamp();
} else /* adjust currently running */ {
set_target_ratio = new_target_ratio;
/* make new set_target_ratio visible to other cpus */
smp_mb();
}
exit_set:
return ret;
}
/* bind to generic thermal layer as cooling device*/
static struct thermal_cooling_device_ops powerclamp_cooling_ops = {
.get_max_state = powerclamp_get_max_state,
.get_cur_state = powerclamp_get_cur_state,
.set_cur_state = powerclamp_set_cur_state,
};
/* runs on Nehalem and later */
static const struct x86_cpu_id intel_powerclamp_ids[] = {
{ X86_VENDOR_INTEL, 6, 0x1a},
{ X86_VENDOR_INTEL, 6, 0x1c},
{ X86_VENDOR_INTEL, 6, 0x1e},
{ X86_VENDOR_INTEL, 6, 0x1f},
{ X86_VENDOR_INTEL, 6, 0x25},
{ X86_VENDOR_INTEL, 6, 0x26},
{ X86_VENDOR_INTEL, 6, 0x2a},
{ X86_VENDOR_INTEL, 6, 0x2c},
{ X86_VENDOR_INTEL, 6, 0x2d},
{ X86_VENDOR_INTEL, 6, 0x2e},
{ X86_VENDOR_INTEL, 6, 0x2f},
{ X86_VENDOR_INTEL, 6, 0x3a},
{}
};
MODULE_DEVICE_TABLE(x86cpu, intel_powerclamp_ids);
static int powerclamp_probe(void)
{
if (!x86_match_cpu(intel_powerclamp_ids)) {
pr_err("Intel powerclamp does not run on family %d model %d\n",
boot_cpu_data.x86, boot_cpu_data.x86_model);
return -ENODEV;
}
if (!boot_cpu_has(X86_FEATURE_NONSTOP_TSC) ||
!boot_cpu_has(X86_FEATURE_CONSTANT_TSC) ||
!boot_cpu_has(X86_FEATURE_MWAIT) ||
!boot_cpu_has(X86_FEATURE_ARAT))
return -ENODEV;
/* find the deepest mwait value */
find_target_mwait();
return 0;
}
static int powerclamp_debug_show(struct seq_file *m, void *unused)
{
int i = 0;
seq_printf(m, "controlling cpu: %d\n", control_cpu);
seq_printf(m, "pct confidence steady dynamic (compensation)\n");
for (i = 0; i < MAX_TARGET_RATIO; i++) {
seq_printf(m, "%d\t%lu\t%lu\t%lu\n",
i,
cal_data[i].confidence,
cal_data[i].steady_comp,
cal_data[i].dynamic_comp);
}
return 0;
}
static int powerclamp_debug_open(struct inode *inode,
struct file *file)
{
return single_open(file, powerclamp_debug_show, inode->i_private);
}
static const struct file_operations powerclamp_debug_fops = {
.open = powerclamp_debug_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static inline void powerclamp_create_debug_files(void)
{
debug_dir = debugfs_create_dir("intel_powerclamp", NULL);
if (!debug_dir)
return;
if (!debugfs_create_file("powerclamp_calib", S_IRUGO, debug_dir,
cal_data, &powerclamp_debug_fops))
goto file_error;
return;
file_error:
debugfs_remove_recursive(debug_dir);
}
static int powerclamp_init(void)
{
int retval;
int bitmap_size;
bitmap_size = BITS_TO_LONGS(num_possible_cpus()) * sizeof(long);
cpu_clamping_mask = kzalloc(bitmap_size, GFP_KERNEL);
if (!cpu_clamping_mask)
return -ENOMEM;
/* probe cpu features and ids here */
retval = powerclamp_probe();
if (retval)
return retval;
/* set default limit, maybe adjusted during runtime based on feedback */
window_size = 2;
register_hotcpu_notifier(&powerclamp_cpu_notifier);
powerclamp_thread = alloc_percpu(struct task_struct *);
cooling_dev = thermal_cooling_device_register("intel_powerclamp", NULL,
&powerclamp_cooling_ops);
if (IS_ERR(cooling_dev))
return -ENODEV;
if (!duration)
duration = jiffies_to_msecs(DEFAULT_DURATION_JIFFIES);
powerclamp_create_debug_files();
return 0;
}
module_init(powerclamp_init);
static void powerclamp_exit(void)
{
unregister_hotcpu_notifier(&powerclamp_cpu_notifier);
end_power_clamp();
free_percpu(powerclamp_thread);
thermal_cooling_device_unregister(cooling_dev);
kfree(cpu_clamping_mask);
cancel_delayed_work_sync(&poll_pkg_cstate_work);
debugfs_remove_recursive(debug_dir);
}
module_exit(powerclamp_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Arjan van de Ven <arjan@linux.intel.com>");
MODULE_AUTHOR("Jacob Pan <jacob.jun.pan@linux.intel.com>");
MODULE_DESCRIPTION("Package Level C-state Idle Injection for Intel CPUs");
| gpl-2.0 |
droidroidz/d2usc-tw-jb | net/tipc/name_distr.c | 2542 | 9032 | /*
* net/tipc/name_distr.c: TIPC name distribution code
*
* Copyright (c) 2000-2006, Ericsson AB
* Copyright (c) 2005, 2010-2011, Wind River Systems
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the names of the copyright holders nor the names of its
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "core.h"
#include "link.h"
#include "name_distr.h"
#define ITEM_SIZE sizeof(struct distr_item)
/**
* struct distr_item - publication info distributed to other nodes
* @type: name sequence type
* @lower: name sequence lower bound
* @upper: name sequence upper bound
* @ref: publishing port reference
* @key: publication key
*
* ===> All fields are stored in network byte order. <===
*
* First 3 fields identify (name or) name sequence being published.
* Reference field uniquely identifies port that published name sequence.
* Key field uniquely identifies publication, in the event a port has
* multiple publications of the same name sequence.
*
* Note: There is no field that identifies the publishing node because it is
* the same for all items contained within a publication message.
*/
struct distr_item {
__be32 type;
__be32 lower;
__be32 upper;
__be32 ref;
__be32 key;
};
/**
* List of externally visible publications by this node --
* that is, all publications having scope > TIPC_NODE_SCOPE.
*/
static LIST_HEAD(publ_root);
static u32 publ_cnt;
/**
* publ_to_item - add publication info to a publication message
*/
static void publ_to_item(struct distr_item *i, struct publication *p)
{
i->type = htonl(p->type);
i->lower = htonl(p->lower);
i->upper = htonl(p->upper);
i->ref = htonl(p->ref);
i->key = htonl(p->key);
}
/**
* named_prepare_buf - allocate & initialize a publication message
*/
static struct sk_buff *named_prepare_buf(u32 type, u32 size, u32 dest)
{
struct sk_buff *buf = tipc_buf_acquire(LONG_H_SIZE + size);
struct tipc_msg *msg;
if (buf != NULL) {
msg = buf_msg(buf);
tipc_msg_init(msg, NAME_DISTRIBUTOR, type, LONG_H_SIZE, dest);
msg_set_size(msg, LONG_H_SIZE + size);
}
return buf;
}
static void named_cluster_distribute(struct sk_buff *buf)
{
struct sk_buff *buf_copy;
struct tipc_node *n_ptr;
list_for_each_entry(n_ptr, &tipc_node_list, list) {
if (tipc_node_active_links(n_ptr)) {
buf_copy = skb_copy(buf, GFP_ATOMIC);
if (!buf_copy)
break;
msg_set_destnode(buf_msg(buf_copy), n_ptr->addr);
tipc_link_send(buf_copy, n_ptr->addr, n_ptr->addr);
}
}
buf_discard(buf);
}
/**
* tipc_named_publish - tell other nodes about a new publication by this node
*/
void tipc_named_publish(struct publication *publ)
{
struct sk_buff *buf;
struct distr_item *item;
list_add_tail(&publ->local_list, &publ_root);
publ_cnt++;
buf = named_prepare_buf(PUBLICATION, ITEM_SIZE, 0);
if (!buf) {
warn("Publication distribution failure\n");
return;
}
item = (struct distr_item *)msg_data(buf_msg(buf));
publ_to_item(item, publ);
named_cluster_distribute(buf);
}
/**
* tipc_named_withdraw - tell other nodes about a withdrawn publication by this node
*/
void tipc_named_withdraw(struct publication *publ)
{
struct sk_buff *buf;
struct distr_item *item;
list_del(&publ->local_list);
publ_cnt--;
buf = named_prepare_buf(WITHDRAWAL, ITEM_SIZE, 0);
if (!buf) {
warn("Withdrawal distribution failure\n");
return;
}
item = (struct distr_item *)msg_data(buf_msg(buf));
publ_to_item(item, publ);
named_cluster_distribute(buf);
}
/**
* tipc_named_node_up - tell specified node about all publications by this node
*/
void tipc_named_node_up(unsigned long node)
{
struct publication *publ;
struct distr_item *item = NULL;
struct sk_buff *buf = NULL;
u32 left = 0;
u32 rest;
u32 max_item_buf;
read_lock_bh(&tipc_nametbl_lock);
max_item_buf = TIPC_MAX_USER_MSG_SIZE / ITEM_SIZE;
max_item_buf *= ITEM_SIZE;
rest = publ_cnt * ITEM_SIZE;
list_for_each_entry(publ, &publ_root, local_list) {
if (!buf) {
left = (rest <= max_item_buf) ? rest : max_item_buf;
rest -= left;
buf = named_prepare_buf(PUBLICATION, left, node);
if (!buf) {
warn("Bulk publication distribution failure\n");
goto exit;
}
item = (struct distr_item *)msg_data(buf_msg(buf));
}
publ_to_item(item, publ);
item++;
left -= ITEM_SIZE;
if (!left) {
msg_set_link_selector(buf_msg(buf), node);
tipc_link_send(buf, node, node);
buf = NULL;
}
}
exit:
read_unlock_bh(&tipc_nametbl_lock);
}
/**
* named_purge_publ - remove publication associated with a failed node
*
* Invoked for each publication issued by a newly failed node.
* Removes publication structure from name table & deletes it.
* In rare cases the link may have come back up again when this
* function is called, and we have two items representing the same
* publication. Nudge this item's key to distinguish it from the other.
*/
static void named_purge_publ(struct publication *publ)
{
struct publication *p;
write_lock_bh(&tipc_nametbl_lock);
publ->key += 1222345;
p = tipc_nametbl_remove_publ(publ->type, publ->lower,
publ->node, publ->ref, publ->key);
if (p)
tipc_nodesub_unsubscribe(&p->subscr);
write_unlock_bh(&tipc_nametbl_lock);
if (p != publ) {
err("Unable to remove publication from failed node\n"
"(type=%u, lower=%u, node=0x%x, ref=%u, key=%u)\n",
publ->type, publ->lower, publ->node, publ->ref, publ->key);
}
kfree(p);
}
/**
* tipc_named_recv - process name table update message sent by another node
*/
void tipc_named_recv(struct sk_buff *buf)
{
struct publication *publ;
struct tipc_msg *msg = buf_msg(buf);
struct distr_item *item = (struct distr_item *)msg_data(msg);
u32 count = msg_data_sz(msg) / ITEM_SIZE;
write_lock_bh(&tipc_nametbl_lock);
while (count--) {
if (msg_type(msg) == PUBLICATION) {
publ = tipc_nametbl_insert_publ(ntohl(item->type),
ntohl(item->lower),
ntohl(item->upper),
TIPC_CLUSTER_SCOPE,
msg_orignode(msg),
ntohl(item->ref),
ntohl(item->key));
if (publ) {
tipc_nodesub_subscribe(&publ->subscr,
msg_orignode(msg),
publ,
(net_ev_handler)
named_purge_publ);
}
} else if (msg_type(msg) == WITHDRAWAL) {
publ = tipc_nametbl_remove_publ(ntohl(item->type),
ntohl(item->lower),
msg_orignode(msg),
ntohl(item->ref),
ntohl(item->key));
if (publ) {
tipc_nodesub_unsubscribe(&publ->subscr);
kfree(publ);
} else {
err("Unable to remove publication by node 0x%x\n"
"(type=%u, lower=%u, ref=%u, key=%u)\n",
msg_orignode(msg),
ntohl(item->type), ntohl(item->lower),
ntohl(item->ref), ntohl(item->key));
}
} else {
warn("Unrecognized name table message received\n");
}
item++;
}
write_unlock_bh(&tipc_nametbl_lock);
buf_discard(buf);
}
/**
* tipc_named_reinit - re-initialize local publication list
*
* This routine is called whenever TIPC networking is (re)enabled.
* All existing publications by this node that have "cluster" or "zone" scope
* are updated to reflect the node's current network address.
* (If the node's address is unchanged, the update loop terminates immediately.)
*/
void tipc_named_reinit(void)
{
struct publication *publ;
write_lock_bh(&tipc_nametbl_lock);
list_for_each_entry(publ, &publ_root, local_list) {
if (publ->node == tipc_own_addr)
break;
publ->node = tipc_own_addr;
}
write_unlock_bh(&tipc_nametbl_lock);
}
| gpl-2.0 |
codename13/kernel_samsung_kylessopen | net/sched/cls_route.c | 2542 | 12506 | /*
* net/sched/cls_route.c ROUTE4 classifier.
*
* This program is free software; you can redistribute 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.
*
* Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/skbuff.h>
#include <net/dst.h>
#include <net/route.h>
#include <net/netlink.h>
#include <net/act_api.h>
#include <net/pkt_cls.h>
/*
* 1. For now we assume that route tags < 256.
* It allows to use direct table lookups, instead of hash tables.
* 2. For now we assume that "from TAG" and "fromdev DEV" statements
* are mutually exclusive.
* 3. "to TAG from ANY" has higher priority, than "to ANY from XXX"
*/
struct route4_fastmap {
struct route4_filter *filter;
u32 id;
int iif;
};
struct route4_head {
struct route4_fastmap fastmap[16];
struct route4_bucket *table[256 + 1];
};
struct route4_bucket {
/* 16 FROM buckets + 16 IIF buckets + 1 wildcard bucket */
struct route4_filter *ht[16 + 16 + 1];
};
struct route4_filter {
struct route4_filter *next;
u32 id;
int iif;
struct tcf_result res;
struct tcf_exts exts;
u32 handle;
struct route4_bucket *bkt;
};
#define ROUTE4_FAILURE ((struct route4_filter *)(-1L))
static const struct tcf_ext_map route_ext_map = {
.police = TCA_ROUTE4_POLICE,
.action = TCA_ROUTE4_ACT
};
static inline int route4_fastmap_hash(u32 id, int iif)
{
return id & 0xF;
}
static void
route4_reset_fastmap(struct Qdisc *q, struct route4_head *head, u32 id)
{
spinlock_t *root_lock = qdisc_root_sleeping_lock(q);
spin_lock_bh(root_lock);
memset(head->fastmap, 0, sizeof(head->fastmap));
spin_unlock_bh(root_lock);
}
static void
route4_set_fastmap(struct route4_head *head, u32 id, int iif,
struct route4_filter *f)
{
int h = route4_fastmap_hash(id, iif);
head->fastmap[h].id = id;
head->fastmap[h].iif = iif;
head->fastmap[h].filter = f;
}
static inline int route4_hash_to(u32 id)
{
return id & 0xFF;
}
static inline int route4_hash_from(u32 id)
{
return (id >> 16) & 0xF;
}
static inline int route4_hash_iif(int iif)
{
return 16 + ((iif >> 16) & 0xF);
}
static inline int route4_hash_wild(void)
{
return 32;
}
#define ROUTE4_APPLY_RESULT() \
{ \
*res = f->res; \
if (tcf_exts_is_available(&f->exts)) { \
int r = tcf_exts_exec(skb, &f->exts, res); \
if (r < 0) { \
dont_cache = 1; \
continue; \
} \
return r; \
} else if (!dont_cache) \
route4_set_fastmap(head, id, iif, f); \
return 0; \
}
static int route4_classify(struct sk_buff *skb, struct tcf_proto *tp,
struct tcf_result *res)
{
struct route4_head *head = (struct route4_head *)tp->root;
struct dst_entry *dst;
struct route4_bucket *b;
struct route4_filter *f;
u32 id, h;
int iif, dont_cache = 0;
dst = skb_dst(skb);
if (!dst)
goto failure;
id = dst->tclassid;
if (head == NULL)
goto old_method;
iif = ((struct rtable *)dst)->rt_iif;
h = route4_fastmap_hash(id, iif);
if (id == head->fastmap[h].id &&
iif == head->fastmap[h].iif &&
(f = head->fastmap[h].filter) != NULL) {
if (f == ROUTE4_FAILURE)
goto failure;
*res = f->res;
return 0;
}
h = route4_hash_to(id);
restart:
b = head->table[h];
if (b) {
for (f = b->ht[route4_hash_from(id)]; f; f = f->next)
if (f->id == id)
ROUTE4_APPLY_RESULT();
for (f = b->ht[route4_hash_iif(iif)]; f; f = f->next)
if (f->iif == iif)
ROUTE4_APPLY_RESULT();
for (f = b->ht[route4_hash_wild()]; f; f = f->next)
ROUTE4_APPLY_RESULT();
}
if (h < 256) {
h = 256;
id &= ~0xFFFF;
goto restart;
}
if (!dont_cache)
route4_set_fastmap(head, id, iif, ROUTE4_FAILURE);
failure:
return -1;
old_method:
if (id && (TC_H_MAJ(id) == 0 ||
!(TC_H_MAJ(id^tp->q->handle)))) {
res->classid = id;
res->class = 0;
return 0;
}
return -1;
}
static inline u32 to_hash(u32 id)
{
u32 h = id & 0xFF;
if (id & 0x8000)
h += 256;
return h;
}
static inline u32 from_hash(u32 id)
{
id &= 0xFFFF;
if (id == 0xFFFF)
return 32;
if (!(id & 0x8000)) {
if (id > 255)
return 256;
return id & 0xF;
}
return 16 + (id & 0xF);
}
static unsigned long route4_get(struct tcf_proto *tp, u32 handle)
{
struct route4_head *head = (struct route4_head *)tp->root;
struct route4_bucket *b;
struct route4_filter *f;
unsigned int h1, h2;
if (!head)
return 0;
h1 = to_hash(handle);
if (h1 > 256)
return 0;
h2 = from_hash(handle >> 16);
if (h2 > 32)
return 0;
b = head->table[h1];
if (b) {
for (f = b->ht[h2]; f; f = f->next)
if (f->handle == handle)
return (unsigned long)f;
}
return 0;
}
static void route4_put(struct tcf_proto *tp, unsigned long f)
{
}
static int route4_init(struct tcf_proto *tp)
{
return 0;
}
static void
route4_delete_filter(struct tcf_proto *tp, struct route4_filter *f)
{
tcf_unbind_filter(tp, &f->res);
tcf_exts_destroy(tp, &f->exts);
kfree(f);
}
static void route4_destroy(struct tcf_proto *tp)
{
struct route4_head *head = tp->root;
int h1, h2;
if (head == NULL)
return;
for (h1 = 0; h1 <= 256; h1++) {
struct route4_bucket *b;
b = head->table[h1];
if (b) {
for (h2 = 0; h2 <= 32; h2++) {
struct route4_filter *f;
while ((f = b->ht[h2]) != NULL) {
b->ht[h2] = f->next;
route4_delete_filter(tp, f);
}
}
kfree(b);
}
}
kfree(head);
}
static int route4_delete(struct tcf_proto *tp, unsigned long arg)
{
struct route4_head *head = (struct route4_head *)tp->root;
struct route4_filter **fp, *f = (struct route4_filter *)arg;
unsigned int h = 0;
struct route4_bucket *b;
int i;
if (!head || !f)
return -EINVAL;
h = f->handle;
b = f->bkt;
for (fp = &b->ht[from_hash(h >> 16)]; *fp; fp = &(*fp)->next) {
if (*fp == f) {
tcf_tree_lock(tp);
*fp = f->next;
tcf_tree_unlock(tp);
route4_reset_fastmap(tp->q, head, f->id);
route4_delete_filter(tp, f);
/* Strip tree */
for (i = 0; i <= 32; i++)
if (b->ht[i])
return 0;
/* OK, session has no flows */
tcf_tree_lock(tp);
head->table[to_hash(h)] = NULL;
tcf_tree_unlock(tp);
kfree(b);
return 0;
}
}
return 0;
}
static const struct nla_policy route4_policy[TCA_ROUTE4_MAX + 1] = {
[TCA_ROUTE4_CLASSID] = { .type = NLA_U32 },
[TCA_ROUTE4_TO] = { .type = NLA_U32 },
[TCA_ROUTE4_FROM] = { .type = NLA_U32 },
[TCA_ROUTE4_IIF] = { .type = NLA_U32 },
};
static int route4_set_parms(struct tcf_proto *tp, unsigned long base,
struct route4_filter *f, u32 handle, struct route4_head *head,
struct nlattr **tb, struct nlattr *est, int new)
{
int err;
u32 id = 0, to = 0, nhandle = 0x8000;
struct route4_filter *fp;
unsigned int h1;
struct route4_bucket *b;
struct tcf_exts e;
err = tcf_exts_validate(tp, tb, est, &e, &route_ext_map);
if (err < 0)
return err;
err = -EINVAL;
if (tb[TCA_ROUTE4_TO]) {
if (new && handle & 0x8000)
goto errout;
to = nla_get_u32(tb[TCA_ROUTE4_TO]);
if (to > 0xFF)
goto errout;
nhandle = to;
}
if (tb[TCA_ROUTE4_FROM]) {
if (tb[TCA_ROUTE4_IIF])
goto errout;
id = nla_get_u32(tb[TCA_ROUTE4_FROM]);
if (id > 0xFF)
goto errout;
nhandle |= id << 16;
} else if (tb[TCA_ROUTE4_IIF]) {
id = nla_get_u32(tb[TCA_ROUTE4_IIF]);
if (id > 0x7FFF)
goto errout;
nhandle |= (id | 0x8000) << 16;
} else
nhandle |= 0xFFFF << 16;
if (handle && new) {
nhandle |= handle & 0x7F00;
if (nhandle != handle)
goto errout;
}
h1 = to_hash(nhandle);
b = head->table[h1];
if (!b) {
err = -ENOBUFS;
b = kzalloc(sizeof(struct route4_bucket), GFP_KERNEL);
if (b == NULL)
goto errout;
tcf_tree_lock(tp);
head->table[h1] = b;
tcf_tree_unlock(tp);
} else {
unsigned int h2 = from_hash(nhandle >> 16);
err = -EEXIST;
for (fp = b->ht[h2]; fp; fp = fp->next)
if (fp->handle == f->handle)
goto errout;
}
tcf_tree_lock(tp);
if (tb[TCA_ROUTE4_TO])
f->id = to;
if (tb[TCA_ROUTE4_FROM])
f->id = to | id<<16;
else if (tb[TCA_ROUTE4_IIF])
f->iif = id;
f->handle = nhandle;
f->bkt = b;
tcf_tree_unlock(tp);
if (tb[TCA_ROUTE4_CLASSID]) {
f->res.classid = nla_get_u32(tb[TCA_ROUTE4_CLASSID]);
tcf_bind_filter(tp, &f->res, base);
}
tcf_exts_change(tp, &f->exts, &e);
return 0;
errout:
tcf_exts_destroy(tp, &e);
return err;
}
static int route4_change(struct tcf_proto *tp, unsigned long base,
u32 handle,
struct nlattr **tca,
unsigned long *arg)
{
struct route4_head *head = tp->root;
struct route4_filter *f, *f1, **fp;
struct route4_bucket *b;
struct nlattr *opt = tca[TCA_OPTIONS];
struct nlattr *tb[TCA_ROUTE4_MAX + 1];
unsigned int h, th;
u32 old_handle = 0;
int err;
if (opt == NULL)
return handle ? -EINVAL : 0;
err = nla_parse_nested(tb, TCA_ROUTE4_MAX, opt, route4_policy);
if (err < 0)
return err;
f = (struct route4_filter *)*arg;
if (f) {
if (f->handle != handle && handle)
return -EINVAL;
if (f->bkt)
old_handle = f->handle;
err = route4_set_parms(tp, base, f, handle, head, tb,
tca[TCA_RATE], 0);
if (err < 0)
return err;
goto reinsert;
}
err = -ENOBUFS;
if (head == NULL) {
head = kzalloc(sizeof(struct route4_head), GFP_KERNEL);
if (head == NULL)
goto errout;
tcf_tree_lock(tp);
tp->root = head;
tcf_tree_unlock(tp);
}
f = kzalloc(sizeof(struct route4_filter), GFP_KERNEL);
if (f == NULL)
goto errout;
err = route4_set_parms(tp, base, f, handle, head, tb,
tca[TCA_RATE], 1);
if (err < 0)
goto errout;
reinsert:
h = from_hash(f->handle >> 16);
for (fp = &f->bkt->ht[h]; (f1 = *fp) != NULL; fp = &f1->next)
if (f->handle < f1->handle)
break;
f->next = f1;
tcf_tree_lock(tp);
*fp = f;
if (old_handle && f->handle != old_handle) {
th = to_hash(old_handle);
h = from_hash(old_handle >> 16);
b = head->table[th];
if (b) {
for (fp = &b->ht[h]; *fp; fp = &(*fp)->next) {
if (*fp == f) {
*fp = f->next;
break;
}
}
}
}
tcf_tree_unlock(tp);
route4_reset_fastmap(tp->q, head, f->id);
*arg = (unsigned long)f;
return 0;
errout:
kfree(f);
return err;
}
static void route4_walk(struct tcf_proto *tp, struct tcf_walker *arg)
{
struct route4_head *head = tp->root;
unsigned int h, h1;
if (head == NULL)
arg->stop = 1;
if (arg->stop)
return;
for (h = 0; h <= 256; h++) {
struct route4_bucket *b = head->table[h];
if (b) {
for (h1 = 0; h1 <= 32; h1++) {
struct route4_filter *f;
for (f = b->ht[h1]; f; f = f->next) {
if (arg->count < arg->skip) {
arg->count++;
continue;
}
if (arg->fn(tp, (unsigned long)f, arg) < 0) {
arg->stop = 1;
return;
}
arg->count++;
}
}
}
}
}
static int route4_dump(struct tcf_proto *tp, unsigned long fh,
struct sk_buff *skb, struct tcmsg *t)
{
struct route4_filter *f = (struct route4_filter *)fh;
unsigned char *b = skb_tail_pointer(skb);
struct nlattr *nest;
u32 id;
if (f == NULL)
return skb->len;
t->tcm_handle = f->handle;
nest = nla_nest_start(skb, TCA_OPTIONS);
if (nest == NULL)
goto nla_put_failure;
if (!(f->handle & 0x8000)) {
id = f->id & 0xFF;
NLA_PUT_U32(skb, TCA_ROUTE4_TO, id);
}
if (f->handle & 0x80000000) {
if ((f->handle >> 16) != 0xFFFF)
NLA_PUT_U32(skb, TCA_ROUTE4_IIF, f->iif);
} else {
id = f->id >> 16;
NLA_PUT_U32(skb, TCA_ROUTE4_FROM, id);
}
if (f->res.classid)
NLA_PUT_U32(skb, TCA_ROUTE4_CLASSID, f->res.classid);
if (tcf_exts_dump(skb, &f->exts, &route_ext_map) < 0)
goto nla_put_failure;
nla_nest_end(skb, nest);
if (tcf_exts_dump_stats(skb, &f->exts, &route_ext_map) < 0)
goto nla_put_failure;
return skb->len;
nla_put_failure:
nlmsg_trim(skb, b);
return -1;
}
static struct tcf_proto_ops cls_route4_ops __read_mostly = {
.kind = "route",
.classify = route4_classify,
.init = route4_init,
.destroy = route4_destroy,
.get = route4_get,
.put = route4_put,
.change = route4_change,
.delete = route4_delete,
.walk = route4_walk,
.dump = route4_dump,
.owner = THIS_MODULE,
};
static int __init init_route4(void)
{
return register_tcf_proto_ops(&cls_route4_ops);
}
static void __exit exit_route4(void)
{
unregister_tcf_proto_ops(&cls_route4_ops);
}
module_init(init_route4)
module_exit(exit_route4)
MODULE_LICENSE("GPL");
| gpl-2.0 |
Nothing-Dev/Samsung_STE_Kernel-exp | arch/mn10300/unit-asb2305/pci-asb2305.c | 3054 | 7539 | /* ASB2305 PCI resource stuff
*
* Copyright (C) 2001 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
* - Derived from arch/i386/pci-i386.c
* - Copyright 1997--2000 Martin Mares <mj@suse.cz>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/errno.h>
#include "pci-asb2305.h"
/*
* We need to avoid collisions with `mirrored' VGA ports
* and other strange ISA hardware, so we always want the
* addresses to be allocated in the 0x000-0x0ff region
* modulo 0x400.
*
* Why? Because some silly external IO cards only decode
* the low 10 bits of the IO address. The 0x00-0xff region
* is reserved for motherboard devices that decode all 16
* bits, so it's ok to allocate at, say, 0x2800-0x28ff,
* but we want to try to avoid allocating at 0x2900-0x2bff
* which might have be mirrored at 0x0100-0x03ff..
*/
resource_size_t pcibios_align_resource(void *data, const struct resource *res,
resource_size_t size, resource_size_t align)
{
resource_size_t start = res->start;
#if 0
struct pci_dev *dev = data;
printk(KERN_DEBUG
"### PCIBIOS_ALIGN_RESOURCE(%s,,{%08lx-%08lx,%08lx},%lx)\n",
pci_name(dev),
res->start,
res->end,
res->flags,
size
);
#endif
if ((res->flags & IORESOURCE_IO) && (start & 0x300))
start = (start + 0x3ff) & ~0x3ff;
return start;
}
/*
* Handle resources of PCI devices. If the world were perfect, we could
* just allocate all the resource regions and do nothing more. It isn't.
* On the other hand, we cannot just re-allocate all devices, as it would
* require us to know lots of host bridge internals. So we attempt to
* keep as much of the original configuration as possible, but tweak it
* when it's found to be wrong.
*
* Known BIOS problems we have to work around:
* - I/O or memory regions not configured
* - regions configured, but not enabled in the command register
* - bogus I/O addresses above 64K used
* - expansion ROMs left enabled (this may sound harmless, but given
* the fact the PCI specs explicitly allow address decoders to be
* shared between expansion ROMs and other resource regions, it's
* at least dangerous)
*
* Our solution:
* (1) Allocate resources for all buses behind PCI-to-PCI bridges.
* This gives us fixed barriers on where we can allocate.
* (2) Allocate resources for all enabled devices. If there is
* a collision, just mark the resource as unallocated. Also
* disable expansion ROMs during this step.
* (3) Try to allocate resources for disabled devices. If the
* resources were assigned correctly, everything goes well,
* if they weren't, they won't disturb allocation of other
* resources.
* (4) Assign new addresses to resources which were either
* not configured at all or misconfigured. If explicitly
* requested by the user, configure expansion ROM address
* as well.
*/
static void __init pcibios_allocate_bus_resources(struct list_head *bus_list)
{
struct pci_bus *bus;
struct pci_dev *dev;
int idx;
struct resource *r;
/* Depth-First Search on bus tree */
list_for_each_entry(bus, bus_list, node) {
dev = bus->self;
if (dev) {
for (idx = PCI_BRIDGE_RESOURCES;
idx < PCI_NUM_RESOURCES;
idx++) {
r = &dev->resource[idx];
if (!r->flags)
continue;
if (!r->start ||
pci_claim_resource(dev, idx) < 0) {
printk(KERN_ERR "PCI:"
" Cannot allocate resource"
" region %d of bridge %s\n",
idx, pci_name(dev));
/* Something is wrong with the region.
* Invalidate the resource to prevent
* child resource allocations in this
* range. */
r->start = r->end = 0;
r->flags = 0;
}
}
}
pcibios_allocate_bus_resources(&bus->children);
}
}
static void __init pcibios_allocate_resources(int pass)
{
struct pci_dev *dev = NULL;
int idx, disabled;
u16 command;
struct resource *r;
for_each_pci_dev(dev) {
pci_read_config_word(dev, PCI_COMMAND, &command);
for (idx = 0; idx < 6; idx++) {
r = &dev->resource[idx];
if (r->parent) /* Already allocated */
continue;
if (!r->start) /* Address not assigned */
continue;
if (r->flags & IORESOURCE_IO)
disabled = !(command & PCI_COMMAND_IO);
else
disabled = !(command & PCI_COMMAND_MEMORY);
if (pass == disabled) {
DBG("PCI[%s]: Resource %08lx-%08lx"
" (f=%lx, d=%d, p=%d)\n",
pci_name(dev), r->start, r->end, r->flags,
disabled, pass);
if (pci_claim_resource(dev, idx) < 0) {
printk(KERN_ERR "PCI:"
" Cannot allocate resource"
" region %d of device %s\n",
idx, pci_name(dev));
/* We'll assign a new address later */
r->end -= r->start;
r->start = 0;
}
}
}
if (!pass) {
r = &dev->resource[PCI_ROM_RESOURCE];
if (r->flags & IORESOURCE_ROM_ENABLE) {
/* Turn the ROM off, leave the resource region,
* but keep it unregistered. */
u32 reg;
DBG("PCI: Switching off ROM of %s\n",
pci_name(dev));
r->flags &= ~IORESOURCE_ROM_ENABLE;
pci_read_config_dword(
dev, dev->rom_base_reg, ®);
pci_write_config_dword(
dev, dev->rom_base_reg,
reg & ~PCI_ROM_ADDRESS_ENABLE);
}
}
}
}
static int __init pcibios_assign_resources(void)
{
struct pci_dev *dev = NULL;
struct resource *r;
if (!(pci_probe & PCI_ASSIGN_ROMS)) {
/* Try to use BIOS settings for ROMs, otherwise let
pci_assign_unassigned_resources() allocate the new
addresses. */
for_each_pci_dev(dev) {
r = &dev->resource[PCI_ROM_RESOURCE];
if (!r->flags || !r->start)
continue;
if (pci_claim_resource(dev, PCI_ROM_RESOURCE) < 0) {
r->end -= r->start;
r->start = 0;
}
}
}
pci_assign_unassigned_resources();
return 0;
}
fs_initcall(pcibios_assign_resources);
void __init pcibios_resource_survey(void)
{
DBG("PCI: Allocating resources\n");
pcibios_allocate_bus_resources(&pci_root_buses);
pcibios_allocate_resources(0);
pcibios_allocate_resources(1);
}
/*
* If we set up a device for bus mastering, we need to check the latency
* timer as certain crappy BIOSes forget to set it properly.
*/
unsigned int pcibios_max_latency = 255;
void pcibios_set_master(struct pci_dev *dev)
{
u8 lat;
pci_read_config_byte(dev, PCI_LATENCY_TIMER, &lat);
if (lat < 16)
lat = (64 <= pcibios_max_latency) ? 64 : pcibios_max_latency;
else if (lat > pcibios_max_latency)
lat = pcibios_max_latency;
else
return;
pci_write_config_byte(dev, PCI_LATENCY_TIMER, lat);
}
int pci_mmap_page_range(struct pci_dev *dev, struct vm_area_struct *vma,
enum pci_mmap_state mmap_state, int write_combine)
{
unsigned long prot;
/* Leave vm_pgoff as-is, the PCI space address is the physical
* address on this platform.
*/
vma->vm_flags |= VM_LOCKED | VM_IO;
prot = pgprot_val(vma->vm_page_prot);
prot &= ~_PAGE_CACHE;
vma->vm_page_prot = __pgprot(prot);
/* Write-combine setting is ignored */
if (io_remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
vma->vm_end - vma->vm_start,
vma->vm_page_prot))
return -EAGAIN;
return 0;
}
| gpl-2.0 |
sktjdgns1189/android_kernel_samsung_kccat6 | drivers/input/keyboard/hilkbd.c | 4590 | 8751 | /*
* linux/drivers/hil/hilkbd.c
*
* Copyright (C) 1998 Philip Blundell <philb@gnu.org>
* Copyright (C) 1999 Matthew Wilcox <willy@bofh.ai>
* Copyright (C) 1999-2007 Helge Deller <deller@gmx.de>
*
* Very basic HP Human Interface Loop (HIL) driver.
* This driver handles the keyboard on HP300 (m68k) and on some
* HP700 (parisc) series machines.
*
*
* This file is subject to the terms and conditions of the GNU General Public
* License version 2. See the file COPYING in the main directory of this
* archive for more details.
*/
#include <linux/pci_ids.h>
#include <linux/ioport.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/input.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/hil.h>
#include <linux/io.h>
#include <linux/sched.h>
#include <linux/spinlock.h>
#include <asm/irq.h>
#ifdef CONFIG_HP300
#include <asm/hwtest.h>
#endif
MODULE_AUTHOR("Philip Blundell, Matthew Wilcox, Helge Deller");
MODULE_DESCRIPTION("HIL keyboard driver (basic functionality)");
MODULE_LICENSE("GPL v2");
#if defined(CONFIG_PARISC)
#include <asm/io.h>
#include <asm/hardware.h>
#include <asm/parisc-device.h>
static unsigned long hil_base; /* HPA for the HIL device */
static unsigned int hil_irq;
#define HILBASE hil_base /* HPPA (parisc) port address */
#define HIL_DATA 0x800
#define HIL_CMD 0x801
#define HIL_IRQ hil_irq
#define hil_readb(p) gsc_readb(p)
#define hil_writeb(v,p) gsc_writeb((v),(p))
#elif defined(CONFIG_HP300)
#define HILBASE 0xf0428000UL /* HP300 (m68k) port address */
#define HIL_DATA 0x1
#define HIL_CMD 0x3
#define HIL_IRQ 2
#define hil_readb(p) readb(p)
#define hil_writeb(v,p) writeb((v),(p))
#else
#error "HIL is not supported on this platform"
#endif
/* HIL helper functions */
#define hil_busy() (hil_readb(HILBASE + HIL_CMD) & HIL_BUSY)
#define hil_data_available() (hil_readb(HILBASE + HIL_CMD) & HIL_DATA_RDY)
#define hil_status() (hil_readb(HILBASE + HIL_CMD))
#define hil_command(x) do { hil_writeb((x), HILBASE + HIL_CMD); } while (0)
#define hil_read_data() (hil_readb(HILBASE + HIL_DATA))
#define hil_write_data(x) do { hil_writeb((x), HILBASE + HIL_DATA); } while (0)
/* HIL constants */
#define HIL_BUSY 0x02
#define HIL_DATA_RDY 0x01
#define HIL_SETARD 0xA0 /* set auto-repeat delay */
#define HIL_SETARR 0xA2 /* set auto-repeat rate */
#define HIL_SETTONE 0xA3 /* set tone generator */
#define HIL_CNMT 0xB2 /* clear nmi */
#define HIL_INTON 0x5C /* Turn on interrupts. */
#define HIL_INTOFF 0x5D /* Turn off interrupts. */
#define HIL_READKBDSADR 0xF9
#define HIL_WRITEKBDSADR 0xE9
static unsigned int hphilkeyb_keycode[HIL_KEYCODES_SET1_TBLSIZE] __read_mostly =
{ HIL_KEYCODES_SET1 };
/* HIL structure */
static struct {
struct input_dev *dev;
unsigned int curdev;
unsigned char s;
unsigned char c;
int valid;
unsigned char data[16];
unsigned int ptr;
spinlock_t lock;
void *dev_id; /* native bus device */
} hil_dev;
static void poll_finished(void)
{
int down;
int key;
unsigned char scode;
switch (hil_dev.data[0]) {
case 0x40:
down = (hil_dev.data[1] & 1) == 0;
scode = hil_dev.data[1] >> 1;
key = hphilkeyb_keycode[scode];
input_report_key(hil_dev.dev, key, down);
break;
}
hil_dev.curdev = 0;
}
static inline void handle_status(unsigned char s, unsigned char c)
{
if (c & 0x8) {
/* End of block */
if (c & 0x10)
poll_finished();
} else {
if (c & 0x10) {
if (hil_dev.curdev)
poll_finished(); /* just in case */
hil_dev.curdev = c & 7;
hil_dev.ptr = 0;
}
}
}
static inline void handle_data(unsigned char s, unsigned char c)
{
if (hil_dev.curdev) {
hil_dev.data[hil_dev.ptr++] = c;
hil_dev.ptr &= 15;
}
}
/* handle HIL interrupts */
static irqreturn_t hil_interrupt(int irq, void *handle)
{
unsigned char s, c;
s = hil_status();
c = hil_read_data();
switch (s >> 4) {
case 0x5:
handle_status(s, c);
break;
case 0x6:
handle_data(s, c);
break;
case 0x4:
hil_dev.s = s;
hil_dev.c = c;
mb();
hil_dev.valid = 1;
break;
}
return IRQ_HANDLED;
}
/* send a command to the HIL */
static void hil_do(unsigned char cmd, unsigned char *data, unsigned int len)
{
unsigned long flags;
spin_lock_irqsave(&hil_dev.lock, flags);
while (hil_busy())
/* wait */;
hil_command(cmd);
while (len--) {
while (hil_busy())
/* wait */;
hil_write_data(*(data++));
}
spin_unlock_irqrestore(&hil_dev.lock, flags);
}
/* initialize HIL */
static int hil_keyb_init(void)
{
unsigned char c;
unsigned int i, kbid;
wait_queue_head_t hil_wait;
int err;
if (hil_dev.dev)
return -ENODEV; /* already initialized */
init_waitqueue_head(&hil_wait);
spin_lock_init(&hil_dev.lock);
hil_dev.dev = input_allocate_device();
if (!hil_dev.dev)
return -ENOMEM;
err = request_irq(HIL_IRQ, hil_interrupt, 0, "hil", hil_dev.dev_id);
if (err) {
printk(KERN_ERR "HIL: Can't get IRQ\n");
goto err1;
}
/* Turn on interrupts */
hil_do(HIL_INTON, NULL, 0);
/* Look for keyboards */
hil_dev.valid = 0; /* clear any pending data */
hil_do(HIL_READKBDSADR, NULL, 0);
wait_event_interruptible_timeout(hil_wait, hil_dev.valid, 3 * HZ);
if (!hil_dev.valid)
printk(KERN_WARNING "HIL: timed out, assuming no keyboard present\n");
c = hil_dev.c;
hil_dev.valid = 0;
if (c == 0) {
kbid = -1;
printk(KERN_WARNING "HIL: no keyboard present\n");
} else {
kbid = ffz(~c);
printk(KERN_INFO "HIL: keyboard found at id %d\n", kbid);
}
/* set it to raw mode */
c = 0;
hil_do(HIL_WRITEKBDSADR, &c, 1);
for (i = 0; i < HIL_KEYCODES_SET1_TBLSIZE; i++)
if (hphilkeyb_keycode[i] != KEY_RESERVED)
__set_bit(hphilkeyb_keycode[i], hil_dev.dev->keybit);
hil_dev.dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP);
hil_dev.dev->ledbit[0] = BIT_MASK(LED_NUML) | BIT_MASK(LED_CAPSL) |
BIT_MASK(LED_SCROLLL);
hil_dev.dev->keycodemax = HIL_KEYCODES_SET1_TBLSIZE;
hil_dev.dev->keycodesize= sizeof(hphilkeyb_keycode[0]);
hil_dev.dev->keycode = hphilkeyb_keycode;
hil_dev.dev->name = "HIL keyboard";
hil_dev.dev->phys = "hpkbd/input0";
hil_dev.dev->id.bustype = BUS_HIL;
hil_dev.dev->id.vendor = PCI_VENDOR_ID_HP;
hil_dev.dev->id.product = 0x0001;
hil_dev.dev->id.version = 0x0010;
err = input_register_device(hil_dev.dev);
if (err) {
printk(KERN_ERR "HIL: Can't register device\n");
goto err2;
}
printk(KERN_INFO "input: %s, ID %d at 0x%08lx (irq %d) found and attached\n",
hil_dev.dev->name, kbid, HILBASE, HIL_IRQ);
return 0;
err2:
hil_do(HIL_INTOFF, NULL, 0);
free_irq(HIL_IRQ, hil_dev.dev_id);
err1:
input_free_device(hil_dev.dev);
hil_dev.dev = NULL;
return err;
}
static void hil_keyb_exit(void)
{
if (HIL_IRQ)
free_irq(HIL_IRQ, hil_dev.dev_id);
/* Turn off interrupts */
hil_do(HIL_INTOFF, NULL, 0);
input_unregister_device(hil_dev.dev);
hil_dev.dev = NULL;
}
#if defined(CONFIG_PARISC)
static int hil_probe_chip(struct parisc_device *dev)
{
/* Only allow one HIL keyboard */
if (hil_dev.dev)
return -ENODEV;
if (!dev->irq) {
printk(KERN_WARNING "HIL: IRQ not found for HIL bus at 0x%p\n",
(void *)dev->hpa.start);
return -ENODEV;
}
hil_base = dev->hpa.start;
hil_irq = dev->irq;
hil_dev.dev_id = dev;
printk(KERN_INFO "Found HIL bus at 0x%08lx, IRQ %d\n", hil_base, hil_irq);
return hil_keyb_init();
}
static int hil_remove_chip(struct parisc_device *dev)
{
hil_keyb_exit();
return 0;
}
static struct parisc_device_id hil_tbl[] = {
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x00073 },
{ 0, }
};
#if 0
/* Disabled to avoid conflicts with the HP SDC HIL drivers */
MODULE_DEVICE_TABLE(parisc, hil_tbl);
#endif
static struct parisc_driver hil_driver = {
.name = "hil",
.id_table = hil_tbl,
.probe = hil_probe_chip,
.remove = hil_remove_chip,
};
static int __init hil_init(void)
{
return register_parisc_driver(&hil_driver);
}
static void __exit hil_exit(void)
{
unregister_parisc_driver(&hil_driver);
}
#else /* !CONFIG_PARISC */
static int __init hil_init(void)
{
int error;
/* Only allow one HIL keyboard */
if (hil_dev.dev)
return -EBUSY;
if (!MACH_IS_HP300)
return -ENODEV;
if (!hwreg_present((void *)(HILBASE + HIL_DATA))) {
printk(KERN_ERR "HIL: hardware register was not found\n");
return -ENODEV;
}
if (!request_region(HILBASE + HIL_DATA, 2, "hil")) {
printk(KERN_ERR "HIL: IOPORT region already used\n");
return -EIO;
}
error = hil_keyb_init();
if (error) {
release_region(HILBASE + HIL_DATA, 2);
return error;
}
return 0;
}
static void __exit hil_exit(void)
{
hil_keyb_exit();
release_region(HILBASE + HIL_DATA, 2);
}
#endif /* CONFIG_PARISC */
module_init(hil_init);
module_exit(hil_exit);
| gpl-2.0 |
SlimKat-U8950/chil360-kernel | arch/arm/mach-tegra/irq.c | 4846 | 3518 | /*
* Copyright (C) 2011 Google, Inc.
*
* Author:
* Colin Cross <ccross@android.com>
*
* Copyright (C) 2010, NVIDIA Corporation
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/of.h>
#include <asm/hardware/gic.h>
#include <mach/iomap.h>
#include "board.h"
#define ICTLR_CPU_IEP_VFIQ 0x08
#define ICTLR_CPU_IEP_FIR 0x14
#define ICTLR_CPU_IEP_FIR_SET 0x18
#define ICTLR_CPU_IEP_FIR_CLR 0x1c
#define ICTLR_CPU_IER 0x20
#define ICTLR_CPU_IER_SET 0x24
#define ICTLR_CPU_IER_CLR 0x28
#define ICTLR_CPU_IEP_CLASS 0x2C
#define ICTLR_COP_IER 0x30
#define ICTLR_COP_IER_SET 0x34
#define ICTLR_COP_IER_CLR 0x38
#define ICTLR_COP_IEP_CLASS 0x3c
#define FIRST_LEGACY_IRQ 32
static int num_ictlrs;
static void __iomem *ictlr_reg_base[] = {
IO_ADDRESS(TEGRA_PRIMARY_ICTLR_BASE),
IO_ADDRESS(TEGRA_SECONDARY_ICTLR_BASE),
IO_ADDRESS(TEGRA_TERTIARY_ICTLR_BASE),
IO_ADDRESS(TEGRA_QUATERNARY_ICTLR_BASE),
IO_ADDRESS(TEGRA_QUINARY_ICTLR_BASE),
};
static inline void tegra_irq_write_mask(unsigned int irq, unsigned long reg)
{
void __iomem *base;
u32 mask;
BUG_ON(irq < FIRST_LEGACY_IRQ ||
irq >= FIRST_LEGACY_IRQ + num_ictlrs * 32);
base = ictlr_reg_base[(irq - FIRST_LEGACY_IRQ) / 32];
mask = BIT((irq - FIRST_LEGACY_IRQ) % 32);
__raw_writel(mask, base + reg);
}
static void tegra_mask(struct irq_data *d)
{
if (d->irq < FIRST_LEGACY_IRQ)
return;
tegra_irq_write_mask(d->irq, ICTLR_CPU_IER_CLR);
}
static void tegra_unmask(struct irq_data *d)
{
if (d->irq < FIRST_LEGACY_IRQ)
return;
tegra_irq_write_mask(d->irq, ICTLR_CPU_IER_SET);
}
static void tegra_ack(struct irq_data *d)
{
if (d->irq < FIRST_LEGACY_IRQ)
return;
tegra_irq_write_mask(d->irq, ICTLR_CPU_IEP_FIR_CLR);
}
static void tegra_eoi(struct irq_data *d)
{
if (d->irq < FIRST_LEGACY_IRQ)
return;
tegra_irq_write_mask(d->irq, ICTLR_CPU_IEP_FIR_CLR);
}
static int tegra_retrigger(struct irq_data *d)
{
if (d->irq < FIRST_LEGACY_IRQ)
return 0;
tegra_irq_write_mask(d->irq, ICTLR_CPU_IEP_FIR_SET);
return 1;
}
void __init tegra_init_irq(void)
{
int i;
void __iomem *distbase;
distbase = IO_ADDRESS(TEGRA_ARM_INT_DIST_BASE);
num_ictlrs = readl_relaxed(distbase + GIC_DIST_CTR) & 0x1f;
if (num_ictlrs > ARRAY_SIZE(ictlr_reg_base)) {
WARN(1, "Too many (%d) interrupt controllers found. Maximum is %d.",
num_ictlrs, ARRAY_SIZE(ictlr_reg_base));
num_ictlrs = ARRAY_SIZE(ictlr_reg_base);
}
for (i = 0; i < num_ictlrs; i++) {
void __iomem *ictlr = ictlr_reg_base[i];
writel(~0, ictlr + ICTLR_CPU_IER_CLR);
writel(0, ictlr + ICTLR_CPU_IEP_CLASS);
}
gic_arch_extn.irq_ack = tegra_ack;
gic_arch_extn.irq_eoi = tegra_eoi;
gic_arch_extn.irq_mask = tegra_mask;
gic_arch_extn.irq_unmask = tegra_unmask;
gic_arch_extn.irq_retrigger = tegra_retrigger;
/*
* Check if there is a devicetree present, since the GIC will be
* initialized elsewhere under DT.
*/
if (!of_have_populated_dt())
gic_init(0, 29, distbase,
IO_ADDRESS(TEGRA_ARM_PERIF_BASE + 0x100));
}
| gpl-2.0 |
slawr/linux-stable | drivers/mfd/da9052-core.c | 4846 | 15426 | /*
* Device access for Dialog DA9052 PMICs.
*
* Copyright(c) 2011 Dialog Semiconductor Ltd.
*
* Author: David Dajun Chen <dchen@diasemi.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 <linux/device.h>
#include <linux/delay.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/mfd/core.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/mfd/da9052/da9052.h>
#include <linux/mfd/da9052/pdata.h>
#include <linux/mfd/da9052/reg.h>
#define DA9052_NUM_IRQ_REGS 4
#define DA9052_IRQ_MASK_POS_1 0x01
#define DA9052_IRQ_MASK_POS_2 0x02
#define DA9052_IRQ_MASK_POS_3 0x04
#define DA9052_IRQ_MASK_POS_4 0x08
#define DA9052_IRQ_MASK_POS_5 0x10
#define DA9052_IRQ_MASK_POS_6 0x20
#define DA9052_IRQ_MASK_POS_7 0x40
#define DA9052_IRQ_MASK_POS_8 0x80
static bool da9052_reg_readable(struct device *dev, unsigned int reg)
{
switch (reg) {
case DA9052_PAGE0_CON_REG:
case DA9052_STATUS_A_REG:
case DA9052_STATUS_B_REG:
case DA9052_STATUS_C_REG:
case DA9052_STATUS_D_REG:
case DA9052_EVENT_A_REG:
case DA9052_EVENT_B_REG:
case DA9052_EVENT_C_REG:
case DA9052_EVENT_D_REG:
case DA9052_FAULTLOG_REG:
case DA9052_IRQ_MASK_A_REG:
case DA9052_IRQ_MASK_B_REG:
case DA9052_IRQ_MASK_C_REG:
case DA9052_IRQ_MASK_D_REG:
case DA9052_CONTROL_A_REG:
case DA9052_CONTROL_B_REG:
case DA9052_CONTROL_C_REG:
case DA9052_CONTROL_D_REG:
case DA9052_PDDIS_REG:
case DA9052_INTERFACE_REG:
case DA9052_RESET_REG:
case DA9052_GPIO_0_1_REG:
case DA9052_GPIO_2_3_REG:
case DA9052_GPIO_4_5_REG:
case DA9052_GPIO_6_7_REG:
case DA9052_GPIO_14_15_REG:
case DA9052_ID_0_1_REG:
case DA9052_ID_2_3_REG:
case DA9052_ID_4_5_REG:
case DA9052_ID_6_7_REG:
case DA9052_ID_8_9_REG:
case DA9052_ID_10_11_REG:
case DA9052_ID_12_13_REG:
case DA9052_ID_14_15_REG:
case DA9052_ID_16_17_REG:
case DA9052_ID_18_19_REG:
case DA9052_ID_20_21_REG:
case DA9052_SEQ_STATUS_REG:
case DA9052_SEQ_A_REG:
case DA9052_SEQ_B_REG:
case DA9052_SEQ_TIMER_REG:
case DA9052_BUCKA_REG:
case DA9052_BUCKB_REG:
case DA9052_BUCKCORE_REG:
case DA9052_BUCKPRO_REG:
case DA9052_BUCKMEM_REG:
case DA9052_BUCKPERI_REG:
case DA9052_LDO1_REG:
case DA9052_LDO2_REG:
case DA9052_LDO3_REG:
case DA9052_LDO4_REG:
case DA9052_LDO5_REG:
case DA9052_LDO6_REG:
case DA9052_LDO7_REG:
case DA9052_LDO8_REG:
case DA9052_LDO9_REG:
case DA9052_LDO10_REG:
case DA9052_SUPPLY_REG:
case DA9052_PULLDOWN_REG:
case DA9052_CHGBUCK_REG:
case DA9052_WAITCONT_REG:
case DA9052_ISET_REG:
case DA9052_BATCHG_REG:
case DA9052_CHG_CONT_REG:
case DA9052_INPUT_CONT_REG:
case DA9052_CHG_TIME_REG:
case DA9052_BBAT_CONT_REG:
case DA9052_BOOST_REG:
case DA9052_LED_CONT_REG:
case DA9052_LEDMIN123_REG:
case DA9052_LED1_CONF_REG:
case DA9052_LED2_CONF_REG:
case DA9052_LED3_CONF_REG:
case DA9052_LED1CONT_REG:
case DA9052_LED2CONT_REG:
case DA9052_LED3CONT_REG:
case DA9052_LED_CONT_4_REG:
case DA9052_LED_CONT_5_REG:
case DA9052_ADC_MAN_REG:
case DA9052_ADC_CONT_REG:
case DA9052_ADC_RES_L_REG:
case DA9052_ADC_RES_H_REG:
case DA9052_VDD_RES_REG:
case DA9052_VDD_MON_REG:
case DA9052_ICHG_AV_REG:
case DA9052_ICHG_THD_REG:
case DA9052_ICHG_END_REG:
case DA9052_TBAT_RES_REG:
case DA9052_TBAT_HIGHP_REG:
case DA9052_TBAT_HIGHN_REG:
case DA9052_TBAT_LOW_REG:
case DA9052_T_OFFSET_REG:
case DA9052_ADCIN4_RES_REG:
case DA9052_AUTO4_HIGH_REG:
case DA9052_AUTO4_LOW_REG:
case DA9052_ADCIN5_RES_REG:
case DA9052_AUTO5_HIGH_REG:
case DA9052_AUTO5_LOW_REG:
case DA9052_ADCIN6_RES_REG:
case DA9052_AUTO6_HIGH_REG:
case DA9052_AUTO6_LOW_REG:
case DA9052_TJUNC_RES_REG:
case DA9052_TSI_CONT_A_REG:
case DA9052_TSI_CONT_B_REG:
case DA9052_TSI_X_MSB_REG:
case DA9052_TSI_Y_MSB_REG:
case DA9052_TSI_LSB_REG:
case DA9052_TSI_Z_MSB_REG:
case DA9052_COUNT_S_REG:
case DA9052_COUNT_MI_REG:
case DA9052_COUNT_H_REG:
case DA9052_COUNT_D_REG:
case DA9052_COUNT_MO_REG:
case DA9052_COUNT_Y_REG:
case DA9052_ALARM_MI_REG:
case DA9052_ALARM_H_REG:
case DA9052_ALARM_D_REG:
case DA9052_ALARM_MO_REG:
case DA9052_ALARM_Y_REG:
case DA9052_SECOND_A_REG:
case DA9052_SECOND_B_REG:
case DA9052_SECOND_C_REG:
case DA9052_SECOND_D_REG:
case DA9052_PAGE1_CON_REG:
return true;
default:
return false;
}
}
static bool da9052_reg_writeable(struct device *dev, unsigned int reg)
{
switch (reg) {
case DA9052_PAGE0_CON_REG:
case DA9052_EVENT_A_REG:
case DA9052_EVENT_B_REG:
case DA9052_EVENT_C_REG:
case DA9052_EVENT_D_REG:
case DA9052_IRQ_MASK_A_REG:
case DA9052_IRQ_MASK_B_REG:
case DA9052_IRQ_MASK_C_REG:
case DA9052_IRQ_MASK_D_REG:
case DA9052_CONTROL_A_REG:
case DA9052_CONTROL_B_REG:
case DA9052_CONTROL_C_REG:
case DA9052_CONTROL_D_REG:
case DA9052_PDDIS_REG:
case DA9052_RESET_REG:
case DA9052_GPIO_0_1_REG:
case DA9052_GPIO_2_3_REG:
case DA9052_GPIO_4_5_REG:
case DA9052_GPIO_6_7_REG:
case DA9052_GPIO_14_15_REG:
case DA9052_ID_0_1_REG:
case DA9052_ID_2_3_REG:
case DA9052_ID_4_5_REG:
case DA9052_ID_6_7_REG:
case DA9052_ID_8_9_REG:
case DA9052_ID_10_11_REG:
case DA9052_ID_12_13_REG:
case DA9052_ID_14_15_REG:
case DA9052_ID_16_17_REG:
case DA9052_ID_18_19_REG:
case DA9052_ID_20_21_REG:
case DA9052_SEQ_STATUS_REG:
case DA9052_SEQ_A_REG:
case DA9052_SEQ_B_REG:
case DA9052_SEQ_TIMER_REG:
case DA9052_BUCKA_REG:
case DA9052_BUCKB_REG:
case DA9052_BUCKCORE_REG:
case DA9052_BUCKPRO_REG:
case DA9052_BUCKMEM_REG:
case DA9052_BUCKPERI_REG:
case DA9052_LDO1_REG:
case DA9052_LDO2_REG:
case DA9052_LDO3_REG:
case DA9052_LDO4_REG:
case DA9052_LDO5_REG:
case DA9052_LDO6_REG:
case DA9052_LDO7_REG:
case DA9052_LDO8_REG:
case DA9052_LDO9_REG:
case DA9052_LDO10_REG:
case DA9052_SUPPLY_REG:
case DA9052_PULLDOWN_REG:
case DA9052_CHGBUCK_REG:
case DA9052_WAITCONT_REG:
case DA9052_ISET_REG:
case DA9052_BATCHG_REG:
case DA9052_CHG_CONT_REG:
case DA9052_INPUT_CONT_REG:
case DA9052_BBAT_CONT_REG:
case DA9052_BOOST_REG:
case DA9052_LED_CONT_REG:
case DA9052_LEDMIN123_REG:
case DA9052_LED1_CONF_REG:
case DA9052_LED2_CONF_REG:
case DA9052_LED3_CONF_REG:
case DA9052_LED1CONT_REG:
case DA9052_LED2CONT_REG:
case DA9052_LED3CONT_REG:
case DA9052_LED_CONT_4_REG:
case DA9052_LED_CONT_5_REG:
case DA9052_ADC_MAN_REG:
case DA9052_ADC_CONT_REG:
case DA9052_ADC_RES_L_REG:
case DA9052_ADC_RES_H_REG:
case DA9052_VDD_RES_REG:
case DA9052_VDD_MON_REG:
case DA9052_ICHG_THD_REG:
case DA9052_ICHG_END_REG:
case DA9052_TBAT_HIGHP_REG:
case DA9052_TBAT_HIGHN_REG:
case DA9052_TBAT_LOW_REG:
case DA9052_T_OFFSET_REG:
case DA9052_AUTO4_HIGH_REG:
case DA9052_AUTO4_LOW_REG:
case DA9052_AUTO5_HIGH_REG:
case DA9052_AUTO5_LOW_REG:
case DA9052_AUTO6_HIGH_REG:
case DA9052_AUTO6_LOW_REG:
case DA9052_TSI_CONT_A_REG:
case DA9052_TSI_CONT_B_REG:
case DA9052_COUNT_S_REG:
case DA9052_COUNT_MI_REG:
case DA9052_COUNT_H_REG:
case DA9052_COUNT_D_REG:
case DA9052_COUNT_MO_REG:
case DA9052_COUNT_Y_REG:
case DA9052_ALARM_MI_REG:
case DA9052_ALARM_H_REG:
case DA9052_ALARM_D_REG:
case DA9052_ALARM_MO_REG:
case DA9052_ALARM_Y_REG:
case DA9052_PAGE1_CON_REG:
return true;
default:
return false;
}
}
static bool da9052_reg_volatile(struct device *dev, unsigned int reg)
{
switch (reg) {
case DA9052_STATUS_A_REG:
case DA9052_STATUS_B_REG:
case DA9052_STATUS_C_REG:
case DA9052_STATUS_D_REG:
case DA9052_EVENT_A_REG:
case DA9052_EVENT_B_REG:
case DA9052_EVENT_C_REG:
case DA9052_EVENT_D_REG:
case DA9052_FAULTLOG_REG:
case DA9052_CHG_TIME_REG:
case DA9052_ADC_RES_L_REG:
case DA9052_ADC_RES_H_REG:
case DA9052_VDD_RES_REG:
case DA9052_ICHG_AV_REG:
case DA9052_TBAT_RES_REG:
case DA9052_ADCIN4_RES_REG:
case DA9052_ADCIN5_RES_REG:
case DA9052_ADCIN6_RES_REG:
case DA9052_TJUNC_RES_REG:
case DA9052_TSI_X_MSB_REG:
case DA9052_TSI_Y_MSB_REG:
case DA9052_TSI_LSB_REG:
case DA9052_TSI_Z_MSB_REG:
case DA9052_COUNT_S_REG:
case DA9052_COUNT_MI_REG:
case DA9052_COUNT_H_REG:
case DA9052_COUNT_D_REG:
case DA9052_COUNT_MO_REG:
case DA9052_COUNT_Y_REG:
case DA9052_ALARM_MI_REG:
return true;
default:
return false;
}
}
static struct resource da9052_rtc_resource = {
.name = "ALM",
.start = DA9052_IRQ_ALARM,
.end = DA9052_IRQ_ALARM,
.flags = IORESOURCE_IRQ,
};
static struct resource da9052_onkey_resource = {
.name = "ONKEY",
.start = DA9052_IRQ_NONKEY,
.end = DA9052_IRQ_NONKEY,
.flags = IORESOURCE_IRQ,
};
static struct resource da9052_bat_resources[] = {
{
.name = "BATT TEMP",
.start = DA9052_IRQ_TBAT,
.end = DA9052_IRQ_TBAT,
.flags = IORESOURCE_IRQ,
},
{
.name = "DCIN DET",
.start = DA9052_IRQ_DCIN,
.end = DA9052_IRQ_DCIN,
.flags = IORESOURCE_IRQ,
},
{
.name = "DCIN REM",
.start = DA9052_IRQ_DCINREM,
.end = DA9052_IRQ_DCINREM,
.flags = IORESOURCE_IRQ,
},
{
.name = "VBUS DET",
.start = DA9052_IRQ_VBUS,
.end = DA9052_IRQ_VBUS,
.flags = IORESOURCE_IRQ,
},
{
.name = "VBUS REM",
.start = DA9052_IRQ_VBUSREM,
.end = DA9052_IRQ_VBUSREM,
.flags = IORESOURCE_IRQ,
},
{
.name = "CHG END",
.start = DA9052_IRQ_CHGEND,
.end = DA9052_IRQ_CHGEND,
.flags = IORESOURCE_IRQ,
},
};
static struct resource da9052_tsi_resources[] = {
{
.name = "PENDWN",
.start = DA9052_IRQ_PENDOWN,
.end = DA9052_IRQ_PENDOWN,
.flags = IORESOURCE_IRQ,
},
{
.name = "TSIRDY",
.start = DA9052_IRQ_TSIREADY,
.end = DA9052_IRQ_TSIREADY,
.flags = IORESOURCE_IRQ,
},
};
static struct mfd_cell __devinitdata da9052_subdev_info[] = {
{
.name = "da9052-regulator",
.id = 1,
},
{
.name = "da9052-regulator",
.id = 2,
},
{
.name = "da9052-regulator",
.id = 3,
},
{
.name = "da9052-regulator",
.id = 4,
},
{
.name = "da9052-regulator",
.id = 5,
},
{
.name = "da9052-regulator",
.id = 6,
},
{
.name = "da9052-regulator",
.id = 7,
},
{
.name = "da9052-regulator",
.id = 8,
},
{
.name = "da9052-regulator",
.id = 9,
},
{
.name = "da9052-regulator",
.id = 10,
},
{
.name = "da9052-regulator",
.id = 11,
},
{
.name = "da9052-regulator",
.id = 12,
},
{
.name = "da9052-regulator",
.id = 13,
},
{
.name = "da9052-regulator",
.id = 14,
},
{
.name = "da9052-onkey",
.resources = &da9052_onkey_resource,
.num_resources = 1,
},
{
.name = "da9052-rtc",
.resources = &da9052_rtc_resource,
.num_resources = 1,
},
{
.name = "da9052-gpio",
},
{
.name = "da9052-hwmon",
},
{
.name = "da9052-leds",
},
{
.name = "da9052-wled1",
},
{
.name = "da9052-wled2",
},
{
.name = "da9052-wled3",
},
{
.name = "da9052-tsi",
.resources = da9052_tsi_resources,
.num_resources = ARRAY_SIZE(da9052_tsi_resources),
},
{
.name = "da9052-bat",
.resources = da9052_bat_resources,
.num_resources = ARRAY_SIZE(da9052_bat_resources),
},
{
.name = "da9052-watchdog",
},
};
static struct regmap_irq da9052_irqs[] = {
[DA9052_IRQ_DCIN] = {
.reg_offset = 0,
.mask = DA9052_IRQ_MASK_POS_1,
},
[DA9052_IRQ_VBUS] = {
.reg_offset = 0,
.mask = DA9052_IRQ_MASK_POS_2,
},
[DA9052_IRQ_DCINREM] = {
.reg_offset = 0,
.mask = DA9052_IRQ_MASK_POS_3,
},
[DA9052_IRQ_VBUSREM] = {
.reg_offset = 0,
.mask = DA9052_IRQ_MASK_POS_4,
},
[DA9052_IRQ_VDDLOW] = {
.reg_offset = 0,
.mask = DA9052_IRQ_MASK_POS_5,
},
[DA9052_IRQ_ALARM] = {
.reg_offset = 0,
.mask = DA9052_IRQ_MASK_POS_6,
},
[DA9052_IRQ_SEQRDY] = {
.reg_offset = 0,
.mask = DA9052_IRQ_MASK_POS_7,
},
[DA9052_IRQ_COMP1V2] = {
.reg_offset = 0,
.mask = DA9052_IRQ_MASK_POS_8,
},
[DA9052_IRQ_NONKEY] = {
.reg_offset = 1,
.mask = DA9052_IRQ_MASK_POS_1,
},
[DA9052_IRQ_IDFLOAT] = {
.reg_offset = 1,
.mask = DA9052_IRQ_MASK_POS_2,
},
[DA9052_IRQ_IDGND] = {
.reg_offset = 1,
.mask = DA9052_IRQ_MASK_POS_3,
},
[DA9052_IRQ_CHGEND] = {
.reg_offset = 1,
.mask = DA9052_IRQ_MASK_POS_4,
},
[DA9052_IRQ_TBAT] = {
.reg_offset = 1,
.mask = DA9052_IRQ_MASK_POS_5,
},
[DA9052_IRQ_ADC_EOM] = {
.reg_offset = 1,
.mask = DA9052_IRQ_MASK_POS_6,
},
[DA9052_IRQ_PENDOWN] = {
.reg_offset = 1,
.mask = DA9052_IRQ_MASK_POS_7,
},
[DA9052_IRQ_TSIREADY] = {
.reg_offset = 1,
.mask = DA9052_IRQ_MASK_POS_8,
},
[DA9052_IRQ_GPI0] = {
.reg_offset = 2,
.mask = DA9052_IRQ_MASK_POS_1,
},
[DA9052_IRQ_GPI1] = {
.reg_offset = 2,
.mask = DA9052_IRQ_MASK_POS_2,
},
[DA9052_IRQ_GPI2] = {
.reg_offset = 2,
.mask = DA9052_IRQ_MASK_POS_3,
},
[DA9052_IRQ_GPI3] = {
.reg_offset = 2,
.mask = DA9052_IRQ_MASK_POS_4,
},
[DA9052_IRQ_GPI4] = {
.reg_offset = 2,
.mask = DA9052_IRQ_MASK_POS_5,
},
[DA9052_IRQ_GPI5] = {
.reg_offset = 2,
.mask = DA9052_IRQ_MASK_POS_6,
},
[DA9052_IRQ_GPI6] = {
.reg_offset = 2,
.mask = DA9052_IRQ_MASK_POS_7,
},
[DA9052_IRQ_GPI7] = {
.reg_offset = 2,
.mask = DA9052_IRQ_MASK_POS_8,
},
[DA9052_IRQ_GPI8] = {
.reg_offset = 3,
.mask = DA9052_IRQ_MASK_POS_1,
},
[DA9052_IRQ_GPI9] = {
.reg_offset = 3,
.mask = DA9052_IRQ_MASK_POS_2,
},
[DA9052_IRQ_GPI10] = {
.reg_offset = 3,
.mask = DA9052_IRQ_MASK_POS_3,
},
[DA9052_IRQ_GPI11] = {
.reg_offset = 3,
.mask = DA9052_IRQ_MASK_POS_4,
},
[DA9052_IRQ_GPI12] = {
.reg_offset = 3,
.mask = DA9052_IRQ_MASK_POS_5,
},
[DA9052_IRQ_GPI13] = {
.reg_offset = 3,
.mask = DA9052_IRQ_MASK_POS_6,
},
[DA9052_IRQ_GPI14] = {
.reg_offset = 3,
.mask = DA9052_IRQ_MASK_POS_7,
},
[DA9052_IRQ_GPI15] = {
.reg_offset = 3,
.mask = DA9052_IRQ_MASK_POS_8,
},
};
static struct regmap_irq_chip da9052_regmap_irq_chip = {
.name = "da9052_irq",
.status_base = DA9052_EVENT_A_REG,
.mask_base = DA9052_IRQ_MASK_A_REG,
.ack_base = DA9052_EVENT_A_REG,
.num_regs = DA9052_NUM_IRQ_REGS,
.irqs = da9052_irqs,
.num_irqs = ARRAY_SIZE(da9052_irqs),
};
struct regmap_config da9052_regmap_config = {
.reg_bits = 8,
.val_bits = 8,
.cache_type = REGCACHE_RBTREE,
.max_register = DA9052_PAGE1_CON_REG,
.readable_reg = da9052_reg_readable,
.writeable_reg = da9052_reg_writeable,
.volatile_reg = da9052_reg_volatile,
};
EXPORT_SYMBOL_GPL(da9052_regmap_config);
int __devinit da9052_device_init(struct da9052 *da9052, u8 chip_id)
{
struct da9052_pdata *pdata = da9052->dev->platform_data;
struct irq_desc *desc;
int ret;
if (pdata && pdata->init != NULL)
pdata->init(da9052);
da9052->chip_id = chip_id;
if (!pdata || !pdata->irq_base)
da9052->irq_base = -1;
else
da9052->irq_base = pdata->irq_base;
ret = regmap_add_irq_chip(da9052->regmap, da9052->chip_irq,
IRQF_TRIGGER_LOW | IRQF_ONESHOT,
da9052->irq_base, &da9052_regmap_irq_chip,
NULL);
if (ret < 0)
goto regmap_err;
desc = irq_to_desc(da9052->chip_irq);
da9052->irq_base = regmap_irq_chip_get_base(desc->action->dev_id);
ret = mfd_add_devices(da9052->dev, -1, da9052_subdev_info,
ARRAY_SIZE(da9052_subdev_info), NULL, 0);
if (ret)
goto err;
return 0;
err:
mfd_remove_devices(da9052->dev);
regmap_err:
return ret;
}
void da9052_device_exit(struct da9052 *da9052)
{
regmap_del_irq_chip(da9052->chip_irq,
irq_get_irq_data(da9052->irq_base)->chip_data);
mfd_remove_devices(da9052->dev);
}
MODULE_AUTHOR("David Dajun Chen <dchen@diasemi.com>");
MODULE_DESCRIPTION("DA9052 MFD Core");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Tesla-Redux-Devices/android_kernel_samsung_lt02ltespr | arch/s390/kernel/module.c | 5102 | 12744 | /*
* arch/s390/kernel/module.c - Kernel module help for s390.
*
* S390 version
* Copyright (C) 2002, 2003 IBM Deutschland Entwicklung GmbH,
* IBM Corporation
* Author(s): Arnd Bergmann (arndb@de.ibm.com)
* Martin Schwidefsky (schwidefsky@de.ibm.com)
*
* based on i386 version
* Copyright (C) 2001 Rusty Russell.
*
* This program is free software; you can redistribute 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/elf.h>
#include <linux/vmalloc.h>
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/moduleloader.h>
#include <linux/bug.h>
#if 0
#define DEBUGP printk
#else
#define DEBUGP(fmt , ...)
#endif
#ifndef CONFIG_64BIT
#define PLT_ENTRY_SIZE 12
#else /* CONFIG_64BIT */
#define PLT_ENTRY_SIZE 20
#endif /* CONFIG_64BIT */
/* Free memory returned from module_alloc */
void module_free(struct module *mod, void *module_region)
{
if (mod) {
vfree(mod->arch.syminfo);
mod->arch.syminfo = NULL;
}
vfree(module_region);
}
static void
check_rela(Elf_Rela *rela, struct module *me)
{
struct mod_arch_syminfo *info;
info = me->arch.syminfo + ELF_R_SYM (rela->r_info);
switch (ELF_R_TYPE (rela->r_info)) {
case R_390_GOT12: /* 12 bit GOT offset. */
case R_390_GOT16: /* 16 bit GOT offset. */
case R_390_GOT20: /* 20 bit GOT offset. */
case R_390_GOT32: /* 32 bit GOT offset. */
case R_390_GOT64: /* 64 bit GOT offset. */
case R_390_GOTENT: /* 32 bit PC rel. to GOT entry shifted by 1. */
case R_390_GOTPLT12: /* 12 bit offset to jump slot. */
case R_390_GOTPLT16: /* 16 bit offset to jump slot. */
case R_390_GOTPLT20: /* 20 bit offset to jump slot. */
case R_390_GOTPLT32: /* 32 bit offset to jump slot. */
case R_390_GOTPLT64: /* 64 bit offset to jump slot. */
case R_390_GOTPLTENT: /* 32 bit rel. offset to jump slot >> 1. */
if (info->got_offset == -1UL) {
info->got_offset = me->arch.got_size;
me->arch.got_size += sizeof(void*);
}
break;
case R_390_PLT16DBL: /* 16 bit PC rel. PLT shifted by 1. */
case R_390_PLT32DBL: /* 32 bit PC rel. PLT shifted by 1. */
case R_390_PLT32: /* 32 bit PC relative PLT address. */
case R_390_PLT64: /* 64 bit PC relative PLT address. */
case R_390_PLTOFF16: /* 16 bit offset from GOT to PLT. */
case R_390_PLTOFF32: /* 32 bit offset from GOT to PLT. */
case R_390_PLTOFF64: /* 16 bit offset from GOT to PLT. */
if (info->plt_offset == -1UL) {
info->plt_offset = me->arch.plt_size;
me->arch.plt_size += PLT_ENTRY_SIZE;
}
break;
case R_390_COPY:
case R_390_GLOB_DAT:
case R_390_JMP_SLOT:
case R_390_RELATIVE:
/* Only needed if we want to support loading of
modules linked with -shared. */
break;
}
}
/*
* Account for GOT and PLT relocations. We can't add sections for
* got and plt but we can increase the core module size.
*/
int
module_frob_arch_sections(Elf_Ehdr *hdr, Elf_Shdr *sechdrs,
char *secstrings, struct module *me)
{
Elf_Shdr *symtab;
Elf_Sym *symbols;
Elf_Rela *rela;
char *strings;
int nrela, i, j;
/* Find symbol table and string table. */
symtab = NULL;
for (i = 0; i < hdr->e_shnum; i++)
switch (sechdrs[i].sh_type) {
case SHT_SYMTAB:
symtab = sechdrs + i;
break;
}
if (!symtab) {
printk(KERN_ERR "module %s: no symbol table\n", me->name);
return -ENOEXEC;
}
/* Allocate one syminfo structure per symbol. */
me->arch.nsyms = symtab->sh_size / sizeof(Elf_Sym);
me->arch.syminfo = vmalloc(me->arch.nsyms *
sizeof(struct mod_arch_syminfo));
if (!me->arch.syminfo)
return -ENOMEM;
symbols = (void *) hdr + symtab->sh_offset;
strings = (void *) hdr + sechdrs[symtab->sh_link].sh_offset;
for (i = 0; i < me->arch.nsyms; i++) {
if (symbols[i].st_shndx == SHN_UNDEF &&
strcmp(strings + symbols[i].st_name,
"_GLOBAL_OFFSET_TABLE_") == 0)
/* "Define" it as absolute. */
symbols[i].st_shndx = SHN_ABS;
me->arch.syminfo[i].got_offset = -1UL;
me->arch.syminfo[i].plt_offset = -1UL;
me->arch.syminfo[i].got_initialized = 0;
me->arch.syminfo[i].plt_initialized = 0;
}
/* Search for got/plt relocations. */
me->arch.got_size = me->arch.plt_size = 0;
for (i = 0; i < hdr->e_shnum; i++) {
if (sechdrs[i].sh_type != SHT_RELA)
continue;
nrela = sechdrs[i].sh_size / sizeof(Elf_Rela);
rela = (void *) hdr + sechdrs[i].sh_offset;
for (j = 0; j < nrela; j++)
check_rela(rela + j, me);
}
/* Increase core size by size of got & plt and set start
offsets for got and plt. */
me->core_size = ALIGN(me->core_size, 4);
me->arch.got_offset = me->core_size;
me->core_size += me->arch.got_size;
me->arch.plt_offset = me->core_size;
me->core_size += me->arch.plt_size;
return 0;
}
static int
apply_rela(Elf_Rela *rela, Elf_Addr base, Elf_Sym *symtab,
struct module *me)
{
struct mod_arch_syminfo *info;
Elf_Addr loc, val;
int r_type, r_sym;
/* This is where to make the change */
loc = base + rela->r_offset;
/* This is the symbol it is referring to. Note that all
undefined symbols have been resolved. */
r_sym = ELF_R_SYM(rela->r_info);
r_type = ELF_R_TYPE(rela->r_info);
info = me->arch.syminfo + r_sym;
val = symtab[r_sym].st_value;
switch (r_type) {
case R_390_8: /* Direct 8 bit. */
case R_390_12: /* Direct 12 bit. */
case R_390_16: /* Direct 16 bit. */
case R_390_20: /* Direct 20 bit. */
case R_390_32: /* Direct 32 bit. */
case R_390_64: /* Direct 64 bit. */
val += rela->r_addend;
if (r_type == R_390_8)
*(unsigned char *) loc = val;
else if (r_type == R_390_12)
*(unsigned short *) loc = (val & 0xfff) |
(*(unsigned short *) loc & 0xf000);
else if (r_type == R_390_16)
*(unsigned short *) loc = val;
else if (r_type == R_390_20)
*(unsigned int *) loc =
(*(unsigned int *) loc & 0xf00000ff) |
(val & 0xfff) << 16 | (val & 0xff000) >> 4;
else if (r_type == R_390_32)
*(unsigned int *) loc = val;
else if (r_type == R_390_64)
*(unsigned long *) loc = val;
break;
case R_390_PC16: /* PC relative 16 bit. */
case R_390_PC16DBL: /* PC relative 16 bit shifted by 1. */
case R_390_PC32DBL: /* PC relative 32 bit shifted by 1. */
case R_390_PC32: /* PC relative 32 bit. */
case R_390_PC64: /* PC relative 64 bit. */
val += rela->r_addend - loc;
if (r_type == R_390_PC16)
*(unsigned short *) loc = val;
else if (r_type == R_390_PC16DBL)
*(unsigned short *) loc = val >> 1;
else if (r_type == R_390_PC32DBL)
*(unsigned int *) loc = val >> 1;
else if (r_type == R_390_PC32)
*(unsigned int *) loc = val;
else if (r_type == R_390_PC64)
*(unsigned long *) loc = val;
break;
case R_390_GOT12: /* 12 bit GOT offset. */
case R_390_GOT16: /* 16 bit GOT offset. */
case R_390_GOT20: /* 20 bit GOT offset. */
case R_390_GOT32: /* 32 bit GOT offset. */
case R_390_GOT64: /* 64 bit GOT offset. */
case R_390_GOTENT: /* 32 bit PC rel. to GOT entry shifted by 1. */
case R_390_GOTPLT12: /* 12 bit offset to jump slot. */
case R_390_GOTPLT20: /* 20 bit offset to jump slot. */
case R_390_GOTPLT16: /* 16 bit offset to jump slot. */
case R_390_GOTPLT32: /* 32 bit offset to jump slot. */
case R_390_GOTPLT64: /* 64 bit offset to jump slot. */
case R_390_GOTPLTENT: /* 32 bit rel. offset to jump slot >> 1. */
if (info->got_initialized == 0) {
Elf_Addr *gotent;
gotent = me->module_core + me->arch.got_offset +
info->got_offset;
*gotent = val;
info->got_initialized = 1;
}
val = info->got_offset + rela->r_addend;
if (r_type == R_390_GOT12 ||
r_type == R_390_GOTPLT12)
*(unsigned short *) loc = (val & 0xfff) |
(*(unsigned short *) loc & 0xf000);
else if (r_type == R_390_GOT16 ||
r_type == R_390_GOTPLT16)
*(unsigned short *) loc = val;
else if (r_type == R_390_GOT20 ||
r_type == R_390_GOTPLT20)
*(unsigned int *) loc =
(*(unsigned int *) loc & 0xf00000ff) |
(val & 0xfff) << 16 | (val & 0xff000) >> 4;
else if (r_type == R_390_GOT32 ||
r_type == R_390_GOTPLT32)
*(unsigned int *) loc = val;
else if (r_type == R_390_GOTENT ||
r_type == R_390_GOTPLTENT)
*(unsigned int *) loc =
(val + (Elf_Addr) me->module_core - loc) >> 1;
else if (r_type == R_390_GOT64 ||
r_type == R_390_GOTPLT64)
*(unsigned long *) loc = val;
break;
case R_390_PLT16DBL: /* 16 bit PC rel. PLT shifted by 1. */
case R_390_PLT32DBL: /* 32 bit PC rel. PLT shifted by 1. */
case R_390_PLT32: /* 32 bit PC relative PLT address. */
case R_390_PLT64: /* 64 bit PC relative PLT address. */
case R_390_PLTOFF16: /* 16 bit offset from GOT to PLT. */
case R_390_PLTOFF32: /* 32 bit offset from GOT to PLT. */
case R_390_PLTOFF64: /* 16 bit offset from GOT to PLT. */
if (info->plt_initialized == 0) {
unsigned int *ip;
ip = me->module_core + me->arch.plt_offset +
info->plt_offset;
#ifndef CONFIG_64BIT
ip[0] = 0x0d105810; /* basr 1,0; l 1,6(1); br 1 */
ip[1] = 0x100607f1;
ip[2] = val;
#else /* CONFIG_64BIT */
ip[0] = 0x0d10e310; /* basr 1,0; lg 1,10(1); br 1 */
ip[1] = 0x100a0004;
ip[2] = 0x07f10000;
ip[3] = (unsigned int) (val >> 32);
ip[4] = (unsigned int) val;
#endif /* CONFIG_64BIT */
info->plt_initialized = 1;
}
if (r_type == R_390_PLTOFF16 ||
r_type == R_390_PLTOFF32 ||
r_type == R_390_PLTOFF64)
val = me->arch.plt_offset - me->arch.got_offset +
info->plt_offset + rela->r_addend;
else {
if (!((r_type == R_390_PLT16DBL &&
val - loc + 0xffffUL < 0x1ffffeUL) ||
(r_type == R_390_PLT32DBL &&
val - loc + 0xffffffffULL < 0x1fffffffeULL)))
val = (Elf_Addr) me->module_core +
me->arch.plt_offset +
info->plt_offset;
val += rela->r_addend - loc;
}
if (r_type == R_390_PLT16DBL)
*(unsigned short *) loc = val >> 1;
else if (r_type == R_390_PLTOFF16)
*(unsigned short *) loc = val;
else if (r_type == R_390_PLT32DBL)
*(unsigned int *) loc = val >> 1;
else if (r_type == R_390_PLT32 ||
r_type == R_390_PLTOFF32)
*(unsigned int *) loc = val;
else if (r_type == R_390_PLT64 ||
r_type == R_390_PLTOFF64)
*(unsigned long *) loc = val;
break;
case R_390_GOTOFF16: /* 16 bit offset to GOT. */
case R_390_GOTOFF32: /* 32 bit offset to GOT. */
case R_390_GOTOFF64: /* 64 bit offset to GOT. */
val = val + rela->r_addend -
((Elf_Addr) me->module_core + me->arch.got_offset);
if (r_type == R_390_GOTOFF16)
*(unsigned short *) loc = val;
else if (r_type == R_390_GOTOFF32)
*(unsigned int *) loc = val;
else if (r_type == R_390_GOTOFF64)
*(unsigned long *) loc = val;
break;
case R_390_GOTPC: /* 32 bit PC relative offset to GOT. */
case R_390_GOTPCDBL: /* 32 bit PC rel. off. to GOT shifted by 1. */
val = (Elf_Addr) me->module_core + me->arch.got_offset +
rela->r_addend - loc;
if (r_type == R_390_GOTPC)
*(unsigned int *) loc = val;
else if (r_type == R_390_GOTPCDBL)
*(unsigned int *) loc = val >> 1;
break;
case R_390_COPY:
case R_390_GLOB_DAT: /* Create GOT entry. */
case R_390_JMP_SLOT: /* Create PLT entry. */
case R_390_RELATIVE: /* Adjust by program base. */
/* Only needed if we want to support loading of
modules linked with -shared. */
break;
default:
printk(KERN_ERR "module %s: Unknown relocation: %u\n",
me->name, r_type);
return -ENOEXEC;
}
return 0;
}
int
apply_relocate_add(Elf_Shdr *sechdrs, const char *strtab,
unsigned int symindex, unsigned int relsec,
struct module *me)
{
Elf_Addr base;
Elf_Sym *symtab;
Elf_Rela *rela;
unsigned long i, n;
int rc;
DEBUGP("Applying relocate section %u to %u\n",
relsec, sechdrs[relsec].sh_info);
base = sechdrs[sechdrs[relsec].sh_info].sh_addr;
symtab = (Elf_Sym *) sechdrs[symindex].sh_addr;
rela = (Elf_Rela *) sechdrs[relsec].sh_addr;
n = sechdrs[relsec].sh_size / sizeof(Elf_Rela);
for (i = 0; i < n; i++, rela++) {
rc = apply_rela(rela, base, symtab, me);
if (rc)
return rc;
}
return 0;
}
int module_finalize(const Elf_Ehdr *hdr,
const Elf_Shdr *sechdrs,
struct module *me)
{
vfree(me->arch.syminfo);
me->arch.syminfo = NULL;
return 0;
}
| gpl-2.0 |
zarboz/Ville-5.0.1 | drivers/scsi/libsas/sas_dump.c | 8174 | 2318 | /*
* Serial Attached SCSI (SAS) Dump/Debugging routines
*
* Copyright (C) 2005 Adaptec, Inc. All rights reserved.
* Copyright (C) 2005 Luben Tuikov <luben_tuikov@adaptec.com>
*
* This file is licensed under GPLv2.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "sas_dump.h"
static const char *sas_hae_str[] = {
[0] = "HAE_RESET",
};
static const char *sas_porte_str[] = {
[0] = "PORTE_BYTES_DMAED",
[1] = "PORTE_BROADCAST_RCVD",
[2] = "PORTE_LINK_RESET_ERR",
[3] = "PORTE_TIMER_EVENT",
[4] = "PORTE_HARD_RESET",
};
static const char *sas_phye_str[] = {
[0] = "PHYE_LOSS_OF_SIGNAL",
[1] = "PHYE_OOB_DONE",
[2] = "PHYE_OOB_ERROR",
[3] = "PHYE_SPINUP_HOLD",
};
void sas_dprint_porte(int phyid, enum port_event pe)
{
SAS_DPRINTK("phy%d: port event: %s\n", phyid, sas_porte_str[pe]);
}
void sas_dprint_phye(int phyid, enum phy_event pe)
{
SAS_DPRINTK("phy%d: phy event: %s\n", phyid, sas_phye_str[pe]);
}
void sas_dprint_hae(struct sas_ha_struct *sas_ha, enum ha_event he)
{
SAS_DPRINTK("ha %s: %s event\n", dev_name(sas_ha->dev),
sas_hae_str[he]);
}
void sas_dump_port(struct asd_sas_port *port)
{
SAS_DPRINTK("port%d: class:0x%x\n", port->id, port->class);
SAS_DPRINTK("port%d: sas_addr:%llx\n", port->id,
SAS_ADDR(port->sas_addr));
SAS_DPRINTK("port%d: attached_sas_addr:%llx\n", port->id,
SAS_ADDR(port->attached_sas_addr));
SAS_DPRINTK("port%d: iproto:0x%x\n", port->id, port->iproto);
SAS_DPRINTK("port%d: tproto:0x%x\n", port->id, port->tproto);
SAS_DPRINTK("port%d: oob_mode:0x%x\n", port->id, port->oob_mode);
SAS_DPRINTK("port%d: num_phys:%d\n", port->id, port->num_phys);
}
| gpl-2.0 |
bigbiff/android_kernel_samsung_hlte | drivers/mfd/wm8350-regmap.c | 9198 | 126729 | /*
* wm8350-regmap.c -- Wolfson Microelectronics WM8350 register map
*
* This file splits out the tables describing the defaults and access
* status of the WM8350 registers since they are rather large.
*
* Copyright 2007, 2008 Wolfson Microelectronics PLC.
*
* This program is free software; you can redistribute 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/mfd/wm8350/core.h>
#ifdef CONFIG_MFD_WM8350_CONFIG_MODE_0
#undef WM8350_HAVE_CONFIG_MODE
#define WM8350_HAVE_CONFIG_MODE
const u16 wm8350_mode0_defaults[] = {
0x17FF, /* R0 - Reset/ID */
0x1000, /* R1 - ID */
0x0000, /* R2 */
0x1002, /* R3 - System Control 1 */
0x0004, /* R4 - System Control 2 */
0x0000, /* R5 - System Hibernate */
0x8A00, /* R6 - Interface Control */
0x0000, /* R7 */
0x8000, /* R8 - Power mgmt (1) */
0x0000, /* R9 - Power mgmt (2) */
0x0000, /* R10 - Power mgmt (3) */
0x2000, /* R11 - Power mgmt (4) */
0x0E00, /* R12 - Power mgmt (5) */
0x0000, /* R13 - Power mgmt (6) */
0x0000, /* R14 - Power mgmt (7) */
0x0000, /* R15 */
0x0000, /* R16 - RTC Seconds/Minutes */
0x0100, /* R17 - RTC Hours/Day */
0x0101, /* R18 - RTC Date/Month */
0x1400, /* R19 - RTC Year */
0x0000, /* R20 - Alarm Seconds/Minutes */
0x0000, /* R21 - Alarm Hours/Day */
0x0000, /* R22 - Alarm Date/Month */
0x0320, /* R23 - RTC Time Control */
0x0000, /* R24 - System Interrupts */
0x0000, /* R25 - Interrupt Status 1 */
0x0000, /* R26 - Interrupt Status 2 */
0x0000, /* R27 - Power Up Interrupt Status */
0x0000, /* R28 - Under Voltage Interrupt status */
0x0000, /* R29 - Over Current Interrupt status */
0x0000, /* R30 - GPIO Interrupt Status */
0x0000, /* R31 - Comparator Interrupt Status */
0x3FFF, /* R32 - System Interrupts Mask */
0x0000, /* R33 - Interrupt Status 1 Mask */
0x0000, /* R34 - Interrupt Status 2 Mask */
0x0000, /* R35 - Power Up Interrupt Status Mask */
0x0000, /* R36 - Under Voltage Interrupt status Mask */
0x0000, /* R37 - Over Current Interrupt status Mask */
0x0000, /* R38 - GPIO Interrupt Status Mask */
0x0000, /* R39 - Comparator Interrupt Status Mask */
0x0040, /* R40 - Clock Control 1 */
0x0000, /* R41 - Clock Control 2 */
0x3B00, /* R42 - FLL Control 1 */
0x7086, /* R43 - FLL Control 2 */
0xC226, /* R44 - FLL Control 3 */
0x0000, /* R45 - FLL Control 4 */
0x0000, /* R46 */
0x0000, /* R47 */
0x0000, /* R48 - DAC Control */
0x0000, /* R49 */
0x00C0, /* R50 - DAC Digital Volume L */
0x00C0, /* R51 - DAC Digital Volume R */
0x0000, /* R52 */
0x0040, /* R53 - DAC LR Rate */
0x0000, /* R54 - DAC Clock Control */
0x0000, /* R55 */
0x0000, /* R56 */
0x0000, /* R57 */
0x4000, /* R58 - DAC Mute */
0x0000, /* R59 - DAC Mute Volume */
0x0000, /* R60 - DAC Side */
0x0000, /* R61 */
0x0000, /* R62 */
0x0000, /* R63 */
0x8000, /* R64 - ADC Control */
0x0000, /* R65 */
0x00C0, /* R66 - ADC Digital Volume L */
0x00C0, /* R67 - ADC Digital Volume R */
0x0000, /* R68 - ADC Divider */
0x0000, /* R69 */
0x0040, /* R70 - ADC LR Rate */
0x0000, /* R71 */
0x0303, /* R72 - Input Control */
0x0000, /* R73 - IN3 Input Control */
0x0000, /* R74 - Mic Bias Control */
0x0000, /* R75 */
0x0000, /* R76 - Output Control */
0x0000, /* R77 - Jack Detect */
0x0000, /* R78 - Anti Pop Control */
0x0000, /* R79 */
0x0040, /* R80 - Left Input Volume */
0x0040, /* R81 - Right Input Volume */
0x0000, /* R82 */
0x0000, /* R83 */
0x0000, /* R84 */
0x0000, /* R85 */
0x0000, /* R86 */
0x0000, /* R87 */
0x0800, /* R88 - Left Mixer Control */
0x1000, /* R89 - Right Mixer Control */
0x0000, /* R90 */
0x0000, /* R91 */
0x0000, /* R92 - OUT3 Mixer Control */
0x0000, /* R93 - OUT4 Mixer Control */
0x0000, /* R94 */
0x0000, /* R95 */
0x0000, /* R96 - Output Left Mixer Volume */
0x0000, /* R97 - Output Right Mixer Volume */
0x0000, /* R98 - Input Mixer Volume L */
0x0000, /* R99 - Input Mixer Volume R */
0x0000, /* R100 - Input Mixer Volume */
0x0000, /* R101 */
0x0000, /* R102 */
0x0000, /* R103 */
0x00E4, /* R104 - LOUT1 Volume */
0x00E4, /* R105 - ROUT1 Volume */
0x00E4, /* R106 - LOUT2 Volume */
0x02E4, /* R107 - ROUT2 Volume */
0x0000, /* R108 */
0x0000, /* R109 */
0x0000, /* R110 */
0x0000, /* R111 - BEEP Volume */
0x0A00, /* R112 - AI Formating */
0x0000, /* R113 - ADC DAC COMP */
0x0020, /* R114 - AI ADC Control */
0x0020, /* R115 - AI DAC Control */
0x0000, /* R116 - AIF Test */
0x0000, /* R117 */
0x0000, /* R118 */
0x0000, /* R119 */
0x0000, /* R120 */
0x0000, /* R121 */
0x0000, /* R122 */
0x0000, /* R123 */
0x0000, /* R124 */
0x0000, /* R125 */
0x0000, /* R126 */
0x0000, /* R127 */
0x1FFF, /* R128 - GPIO Debounce */
0x0000, /* R129 - GPIO Pin pull up Control */
0x03FC, /* R130 - GPIO Pull down Control */
0x0000, /* R131 - GPIO Interrupt Mode */
0x0000, /* R132 */
0x0000, /* R133 - GPIO Control */
0x0FFC, /* R134 - GPIO Configuration (i/o) */
0x0FFC, /* R135 - GPIO Pin Polarity / Type */
0x0000, /* R136 */
0x0000, /* R137 */
0x0000, /* R138 */
0x0000, /* R139 */
0x0013, /* R140 - GPIO Function Select 1 */
0x0000, /* R141 - GPIO Function Select 2 */
0x0000, /* R142 - GPIO Function Select 3 */
0x0003, /* R143 - GPIO Function Select 4 */
0x0000, /* R144 - Digitiser Control (1) */
0x0002, /* R145 - Digitiser Control (2) */
0x0000, /* R146 */
0x0000, /* R147 */
0x0000, /* R148 */
0x0000, /* R149 */
0x0000, /* R150 */
0x0000, /* R151 */
0x7000, /* R152 - AUX1 Readback */
0x7000, /* R153 - AUX2 Readback */
0x7000, /* R154 - AUX3 Readback */
0x7000, /* R155 - AUX4 Readback */
0x0000, /* R156 - USB Voltage Readback */
0x0000, /* R157 - LINE Voltage Readback */
0x0000, /* R158 - BATT Voltage Readback */
0x0000, /* R159 - Chip Temp Readback */
0x0000, /* R160 */
0x0000, /* R161 */
0x0000, /* R162 */
0x0000, /* R163 - Generic Comparator Control */
0x0000, /* R164 - Generic comparator 1 */
0x0000, /* R165 - Generic comparator 2 */
0x0000, /* R166 - Generic comparator 3 */
0x0000, /* R167 - Generic comparator 4 */
0xA00F, /* R168 - Battery Charger Control 1 */
0x0B06, /* R169 - Battery Charger Control 2 */
0x0000, /* R170 - Battery Charger Control 3 */
0x0000, /* R171 */
0x0000, /* R172 - Current Sink Driver A */
0x0000, /* R173 - CSA Flash control */
0x0000, /* R174 - Current Sink Driver B */
0x0000, /* R175 - CSB Flash control */
0x0000, /* R176 - DCDC/LDO requested */
0x002D, /* R177 - DCDC Active options */
0x0000, /* R178 - DCDC Sleep options */
0x0025, /* R179 - Power-check comparator */
0x000E, /* R180 - DCDC1 Control */
0x0000, /* R181 - DCDC1 Timeouts */
0x1006, /* R182 - DCDC1 Low Power */
0x0018, /* R183 - DCDC2 Control */
0x0000, /* R184 - DCDC2 Timeouts */
0x0000, /* R185 */
0x0000, /* R186 - DCDC3 Control */
0x0000, /* R187 - DCDC3 Timeouts */
0x0006, /* R188 - DCDC3 Low Power */
0x0000, /* R189 - DCDC4 Control */
0x0000, /* R190 - DCDC4 Timeouts */
0x0006, /* R191 - DCDC4 Low Power */
0x0008, /* R192 - DCDC5 Control */
0x0000, /* R193 - DCDC5 Timeouts */
0x0000, /* R194 */
0x0000, /* R195 - DCDC6 Control */
0x0000, /* R196 - DCDC6 Timeouts */
0x0006, /* R197 - DCDC6 Low Power */
0x0000, /* R198 */
0x0003, /* R199 - Limit Switch Control */
0x001C, /* R200 - LDO1 Control */
0x0000, /* R201 - LDO1 Timeouts */
0x001C, /* R202 - LDO1 Low Power */
0x001B, /* R203 - LDO2 Control */
0x0000, /* R204 - LDO2 Timeouts */
0x001C, /* R205 - LDO2 Low Power */
0x001B, /* R206 - LDO3 Control */
0x0000, /* R207 - LDO3 Timeouts */
0x001C, /* R208 - LDO3 Low Power */
0x001B, /* R209 - LDO4 Control */
0x0000, /* R210 - LDO4 Timeouts */
0x001C, /* R211 - LDO4 Low Power */
0x0000, /* R212 */
0x0000, /* R213 */
0x0000, /* R214 */
0x0000, /* R215 - VCC_FAULT Masks */
0x001F, /* R216 - Main Bandgap Control */
0x0000, /* R217 - OSC Control */
0x9000, /* R218 - RTC Tick Control */
0x0000, /* R219 */
0x4000, /* R220 - RAM BIST 1 */
0x0000, /* R221 */
0x0000, /* R222 */
0x0000, /* R223 */
0x0000, /* R224 */
0x0000, /* R225 - DCDC/LDO status */
0x0000, /* R226 */
0x0000, /* R227 */
0x0000, /* R228 */
0x0000, /* R229 */
0xE000, /* R230 - GPIO Pin Status */
0x0000, /* R231 */
0x0000, /* R232 */
0x0000, /* R233 */
0x0000, /* R234 */
0x0000, /* R235 */
0x0000, /* R236 */
0x0000, /* R237 */
0x0000, /* R238 */
0x0000, /* R239 */
0x0000, /* R240 */
0x0000, /* R241 */
0x0000, /* R242 */
0x0000, /* R243 */
0x0000, /* R244 */
0x0000, /* R245 */
0x0000, /* R246 */
0x0000, /* R247 */
0x0000, /* R248 */
0x0000, /* R249 */
0x0000, /* R250 */
0x0000, /* R251 */
0x0000, /* R252 */
0x0000, /* R253 */
0x0000, /* R254 */
0x0000, /* R255 */
};
#endif
#ifdef CONFIG_MFD_WM8350_CONFIG_MODE_1
#undef WM8350_HAVE_CONFIG_MODE
#define WM8350_HAVE_CONFIG_MODE
const u16 wm8350_mode1_defaults[] = {
0x17FF, /* R0 - Reset/ID */
0x1000, /* R1 - ID */
0x0000, /* R2 */
0x1002, /* R3 - System Control 1 */
0x0014, /* R4 - System Control 2 */
0x0000, /* R5 - System Hibernate */
0x8A00, /* R6 - Interface Control */
0x0000, /* R7 */
0x8000, /* R8 - Power mgmt (1) */
0x0000, /* R9 - Power mgmt (2) */
0x0000, /* R10 - Power mgmt (3) */
0x2000, /* R11 - Power mgmt (4) */
0x0E00, /* R12 - Power mgmt (5) */
0x0000, /* R13 - Power mgmt (6) */
0x0000, /* R14 - Power mgmt (7) */
0x0000, /* R15 */
0x0000, /* R16 - RTC Seconds/Minutes */
0x0100, /* R17 - RTC Hours/Day */
0x0101, /* R18 - RTC Date/Month */
0x1400, /* R19 - RTC Year */
0x0000, /* R20 - Alarm Seconds/Minutes */
0x0000, /* R21 - Alarm Hours/Day */
0x0000, /* R22 - Alarm Date/Month */
0x0320, /* R23 - RTC Time Control */
0x0000, /* R24 - System Interrupts */
0x0000, /* R25 - Interrupt Status 1 */
0x0000, /* R26 - Interrupt Status 2 */
0x0000, /* R27 - Power Up Interrupt Status */
0x0000, /* R28 - Under Voltage Interrupt status */
0x0000, /* R29 - Over Current Interrupt status */
0x0000, /* R30 - GPIO Interrupt Status */
0x0000, /* R31 - Comparator Interrupt Status */
0x3FFF, /* R32 - System Interrupts Mask */
0x0000, /* R33 - Interrupt Status 1 Mask */
0x0000, /* R34 - Interrupt Status 2 Mask */
0x0000, /* R35 - Power Up Interrupt Status Mask */
0x0000, /* R36 - Under Voltage Interrupt status Mask */
0x0000, /* R37 - Over Current Interrupt status Mask */
0x0000, /* R38 - GPIO Interrupt Status Mask */
0x0000, /* R39 - Comparator Interrupt Status Mask */
0x0040, /* R40 - Clock Control 1 */
0x0000, /* R41 - Clock Control 2 */
0x3B00, /* R42 - FLL Control 1 */
0x7086, /* R43 - FLL Control 2 */
0xC226, /* R44 - FLL Control 3 */
0x0000, /* R45 - FLL Control 4 */
0x0000, /* R46 */
0x0000, /* R47 */
0x0000, /* R48 - DAC Control */
0x0000, /* R49 */
0x00C0, /* R50 - DAC Digital Volume L */
0x00C0, /* R51 - DAC Digital Volume R */
0x0000, /* R52 */
0x0040, /* R53 - DAC LR Rate */
0x0000, /* R54 - DAC Clock Control */
0x0000, /* R55 */
0x0000, /* R56 */
0x0000, /* R57 */
0x4000, /* R58 - DAC Mute */
0x0000, /* R59 - DAC Mute Volume */
0x0000, /* R60 - DAC Side */
0x0000, /* R61 */
0x0000, /* R62 */
0x0000, /* R63 */
0x8000, /* R64 - ADC Control */
0x0000, /* R65 */
0x00C0, /* R66 - ADC Digital Volume L */
0x00C0, /* R67 - ADC Digital Volume R */
0x0000, /* R68 - ADC Divider */
0x0000, /* R69 */
0x0040, /* R70 - ADC LR Rate */
0x0000, /* R71 */
0x0303, /* R72 - Input Control */
0x0000, /* R73 - IN3 Input Control */
0x0000, /* R74 - Mic Bias Control */
0x0000, /* R75 */
0x0000, /* R76 - Output Control */
0x0000, /* R77 - Jack Detect */
0x0000, /* R78 - Anti Pop Control */
0x0000, /* R79 */
0x0040, /* R80 - Left Input Volume */
0x0040, /* R81 - Right Input Volume */
0x0000, /* R82 */
0x0000, /* R83 */
0x0000, /* R84 */
0x0000, /* R85 */
0x0000, /* R86 */
0x0000, /* R87 */
0x0800, /* R88 - Left Mixer Control */
0x1000, /* R89 - Right Mixer Control */
0x0000, /* R90 */
0x0000, /* R91 */
0x0000, /* R92 - OUT3 Mixer Control */
0x0000, /* R93 - OUT4 Mixer Control */
0x0000, /* R94 */
0x0000, /* R95 */
0x0000, /* R96 - Output Left Mixer Volume */
0x0000, /* R97 - Output Right Mixer Volume */
0x0000, /* R98 - Input Mixer Volume L */
0x0000, /* R99 - Input Mixer Volume R */
0x0000, /* R100 - Input Mixer Volume */
0x0000, /* R101 */
0x0000, /* R102 */
0x0000, /* R103 */
0x00E4, /* R104 - LOUT1 Volume */
0x00E4, /* R105 - ROUT1 Volume */
0x00E4, /* R106 - LOUT2 Volume */
0x02E4, /* R107 - ROUT2 Volume */
0x0000, /* R108 */
0x0000, /* R109 */
0x0000, /* R110 */
0x0000, /* R111 - BEEP Volume */
0x0A00, /* R112 - AI Formating */
0x0000, /* R113 - ADC DAC COMP */
0x0020, /* R114 - AI ADC Control */
0x0020, /* R115 - AI DAC Control */
0x0000, /* R116 - AIF Test */
0x0000, /* R117 */
0x0000, /* R118 */
0x0000, /* R119 */
0x0000, /* R120 */
0x0000, /* R121 */
0x0000, /* R122 */
0x0000, /* R123 */
0x0000, /* R124 */
0x0000, /* R125 */
0x0000, /* R126 */
0x0000, /* R127 */
0x1FFF, /* R128 - GPIO Debounce */
0x0000, /* R129 - GPIO Pin pull up Control */
0x03FC, /* R130 - GPIO Pull down Control */
0x0000, /* R131 - GPIO Interrupt Mode */
0x0000, /* R132 */
0x0000, /* R133 - GPIO Control */
0x00FB, /* R134 - GPIO Configuration (i/o) */
0x04FE, /* R135 - GPIO Pin Polarity / Type */
0x0000, /* R136 */
0x0000, /* R137 */
0x0000, /* R138 */
0x0000, /* R139 */
0x0312, /* R140 - GPIO Function Select 1 */
0x1003, /* R141 - GPIO Function Select 2 */
0x1331, /* R142 - GPIO Function Select 3 */
0x0003, /* R143 - GPIO Function Select 4 */
0x0000, /* R144 - Digitiser Control (1) */
0x0002, /* R145 - Digitiser Control (2) */
0x0000, /* R146 */
0x0000, /* R147 */
0x0000, /* R148 */
0x0000, /* R149 */
0x0000, /* R150 */
0x0000, /* R151 */
0x7000, /* R152 - AUX1 Readback */
0x7000, /* R153 - AUX2 Readback */
0x7000, /* R154 - AUX3 Readback */
0x7000, /* R155 - AUX4 Readback */
0x0000, /* R156 - USB Voltage Readback */
0x0000, /* R157 - LINE Voltage Readback */
0x0000, /* R158 - BATT Voltage Readback */
0x0000, /* R159 - Chip Temp Readback */
0x0000, /* R160 */
0x0000, /* R161 */
0x0000, /* R162 */
0x0000, /* R163 - Generic Comparator Control */
0x0000, /* R164 - Generic comparator 1 */
0x0000, /* R165 - Generic comparator 2 */
0x0000, /* R166 - Generic comparator 3 */
0x0000, /* R167 - Generic comparator 4 */
0xA00F, /* R168 - Battery Charger Control 1 */
0x0B06, /* R169 - Battery Charger Control 2 */
0x0000, /* R170 - Battery Charger Control 3 */
0x0000, /* R171 */
0x0000, /* R172 - Current Sink Driver A */
0x0000, /* R173 - CSA Flash control */
0x0000, /* R174 - Current Sink Driver B */
0x0000, /* R175 - CSB Flash control */
0x0000, /* R176 - DCDC/LDO requested */
0x002D, /* R177 - DCDC Active options */
0x0000, /* R178 - DCDC Sleep options */
0x0025, /* R179 - Power-check comparator */
0x0062, /* R180 - DCDC1 Control */
0x0400, /* R181 - DCDC1 Timeouts */
0x1006, /* R182 - DCDC1 Low Power */
0x0018, /* R183 - DCDC2 Control */
0x0000, /* R184 - DCDC2 Timeouts */
0x0000, /* R185 */
0x0026, /* R186 - DCDC3 Control */
0x0400, /* R187 - DCDC3 Timeouts */
0x0006, /* R188 - DCDC3 Low Power */
0x0062, /* R189 - DCDC4 Control */
0x0400, /* R190 - DCDC4 Timeouts */
0x0006, /* R191 - DCDC4 Low Power */
0x0008, /* R192 - DCDC5 Control */
0x0000, /* R193 - DCDC5 Timeouts */
0x0000, /* R194 */
0x0026, /* R195 - DCDC6 Control */
0x0800, /* R196 - DCDC6 Timeouts */
0x0006, /* R197 - DCDC6 Low Power */
0x0000, /* R198 */
0x0003, /* R199 - Limit Switch Control */
0x0006, /* R200 - LDO1 Control */
0x0400, /* R201 - LDO1 Timeouts */
0x001C, /* R202 - LDO1 Low Power */
0x0006, /* R203 - LDO2 Control */
0x0400, /* R204 - LDO2 Timeouts */
0x001C, /* R205 - LDO2 Low Power */
0x001B, /* R206 - LDO3 Control */
0x0000, /* R207 - LDO3 Timeouts */
0x001C, /* R208 - LDO3 Low Power */
0x001B, /* R209 - LDO4 Control */
0x0000, /* R210 - LDO4 Timeouts */
0x001C, /* R211 - LDO4 Low Power */
0x0000, /* R212 */
0x0000, /* R213 */
0x0000, /* R214 */
0x0000, /* R215 - VCC_FAULT Masks */
0x001F, /* R216 - Main Bandgap Control */
0x0000, /* R217 - OSC Control */
0x9000, /* R218 - RTC Tick Control */
0x0000, /* R219 */
0x4000, /* R220 - RAM BIST 1 */
0x0000, /* R221 */
0x0000, /* R222 */
0x0000, /* R223 */
0x0000, /* R224 */
0x0000, /* R225 - DCDC/LDO status */
0x0000, /* R226 */
0x0000, /* R227 */
0x0000, /* R228 */
0x0000, /* R229 */
0xE000, /* R230 - GPIO Pin Status */
0x0000, /* R231 */
0x0000, /* R232 */
0x0000, /* R233 */
0x0000, /* R234 */
0x0000, /* R235 */
0x0000, /* R236 */
0x0000, /* R237 */
0x0000, /* R238 */
0x0000, /* R239 */
0x0000, /* R240 */
0x0000, /* R241 */
0x0000, /* R242 */
0x0000, /* R243 */
0x0000, /* R244 */
0x0000, /* R245 */
0x0000, /* R246 */
0x0000, /* R247 */
0x0000, /* R248 */
0x0000, /* R249 */
0x0000, /* R250 */
0x0000, /* R251 */
0x0000, /* R252 */
0x0000, /* R253 */
0x0000, /* R254 */
0x0000, /* R255 */
};
#endif
#ifdef CONFIG_MFD_WM8350_CONFIG_MODE_2
#undef WM8350_HAVE_CONFIG_MODE
#define WM8350_HAVE_CONFIG_MODE
const u16 wm8350_mode2_defaults[] = {
0x17FF, /* R0 - Reset/ID */
0x1000, /* R1 - ID */
0x0000, /* R2 */
0x1002, /* R3 - System Control 1 */
0x0014, /* R4 - System Control 2 */
0x0000, /* R5 - System Hibernate */
0x8A00, /* R6 - Interface Control */
0x0000, /* R7 */
0x8000, /* R8 - Power mgmt (1) */
0x0000, /* R9 - Power mgmt (2) */
0x0000, /* R10 - Power mgmt (3) */
0x2000, /* R11 - Power mgmt (4) */
0x0E00, /* R12 - Power mgmt (5) */
0x0000, /* R13 - Power mgmt (6) */
0x0000, /* R14 - Power mgmt (7) */
0x0000, /* R15 */
0x0000, /* R16 - RTC Seconds/Minutes */
0x0100, /* R17 - RTC Hours/Day */
0x0101, /* R18 - RTC Date/Month */
0x1400, /* R19 - RTC Year */
0x0000, /* R20 - Alarm Seconds/Minutes */
0x0000, /* R21 - Alarm Hours/Day */
0x0000, /* R22 - Alarm Date/Month */
0x0320, /* R23 - RTC Time Control */
0x0000, /* R24 - System Interrupts */
0x0000, /* R25 - Interrupt Status 1 */
0x0000, /* R26 - Interrupt Status 2 */
0x0000, /* R27 - Power Up Interrupt Status */
0x0000, /* R28 - Under Voltage Interrupt status */
0x0000, /* R29 - Over Current Interrupt status */
0x0000, /* R30 - GPIO Interrupt Status */
0x0000, /* R31 - Comparator Interrupt Status */
0x3FFF, /* R32 - System Interrupts Mask */
0x0000, /* R33 - Interrupt Status 1 Mask */
0x0000, /* R34 - Interrupt Status 2 Mask */
0x0000, /* R35 - Power Up Interrupt Status Mask */
0x0000, /* R36 - Under Voltage Interrupt status Mask */
0x0000, /* R37 - Over Current Interrupt status Mask */
0x0000, /* R38 - GPIO Interrupt Status Mask */
0x0000, /* R39 - Comparator Interrupt Status Mask */
0x0040, /* R40 - Clock Control 1 */
0x0000, /* R41 - Clock Control 2 */
0x3B00, /* R42 - FLL Control 1 */
0x7086, /* R43 - FLL Control 2 */
0xC226, /* R44 - FLL Control 3 */
0x0000, /* R45 - FLL Control 4 */
0x0000, /* R46 */
0x0000, /* R47 */
0x0000, /* R48 - DAC Control */
0x0000, /* R49 */
0x00C0, /* R50 - DAC Digital Volume L */
0x00C0, /* R51 - DAC Digital Volume R */
0x0000, /* R52 */
0x0040, /* R53 - DAC LR Rate */
0x0000, /* R54 - DAC Clock Control */
0x0000, /* R55 */
0x0000, /* R56 */
0x0000, /* R57 */
0x4000, /* R58 - DAC Mute */
0x0000, /* R59 - DAC Mute Volume */
0x0000, /* R60 - DAC Side */
0x0000, /* R61 */
0x0000, /* R62 */
0x0000, /* R63 */
0x8000, /* R64 - ADC Control */
0x0000, /* R65 */
0x00C0, /* R66 - ADC Digital Volume L */
0x00C0, /* R67 - ADC Digital Volume R */
0x0000, /* R68 - ADC Divider */
0x0000, /* R69 */
0x0040, /* R70 - ADC LR Rate */
0x0000, /* R71 */
0x0303, /* R72 - Input Control */
0x0000, /* R73 - IN3 Input Control */
0x0000, /* R74 - Mic Bias Control */
0x0000, /* R75 */
0x0000, /* R76 - Output Control */
0x0000, /* R77 - Jack Detect */
0x0000, /* R78 - Anti Pop Control */
0x0000, /* R79 */
0x0040, /* R80 - Left Input Volume */
0x0040, /* R81 - Right Input Volume */
0x0000, /* R82 */
0x0000, /* R83 */
0x0000, /* R84 */
0x0000, /* R85 */
0x0000, /* R86 */
0x0000, /* R87 */
0x0800, /* R88 - Left Mixer Control */
0x1000, /* R89 - Right Mixer Control */
0x0000, /* R90 */
0x0000, /* R91 */
0x0000, /* R92 - OUT3 Mixer Control */
0x0000, /* R93 - OUT4 Mixer Control */
0x0000, /* R94 */
0x0000, /* R95 */
0x0000, /* R96 - Output Left Mixer Volume */
0x0000, /* R97 - Output Right Mixer Volume */
0x0000, /* R98 - Input Mixer Volume L */
0x0000, /* R99 - Input Mixer Volume R */
0x0000, /* R100 - Input Mixer Volume */
0x0000, /* R101 */
0x0000, /* R102 */
0x0000, /* R103 */
0x00E4, /* R104 - LOUT1 Volume */
0x00E4, /* R105 - ROUT1 Volume */
0x00E4, /* R106 - LOUT2 Volume */
0x02E4, /* R107 - ROUT2 Volume */
0x0000, /* R108 */
0x0000, /* R109 */
0x0000, /* R110 */
0x0000, /* R111 - BEEP Volume */
0x0A00, /* R112 - AI Formating */
0x0000, /* R113 - ADC DAC COMP */
0x0020, /* R114 - AI ADC Control */
0x0020, /* R115 - AI DAC Control */
0x0000, /* R116 - AIF Test */
0x0000, /* R117 */
0x0000, /* R118 */
0x0000, /* R119 */
0x0000, /* R120 */
0x0000, /* R121 */
0x0000, /* R122 */
0x0000, /* R123 */
0x0000, /* R124 */
0x0000, /* R125 */
0x0000, /* R126 */
0x0000, /* R127 */
0x1FFF, /* R128 - GPIO Debounce */
0x0000, /* R129 - GPIO Pin pull up Control */
0x03FC, /* R130 - GPIO Pull down Control */
0x0000, /* R131 - GPIO Interrupt Mode */
0x0000, /* R132 */
0x0000, /* R133 - GPIO Control */
0x08FB, /* R134 - GPIO Configuration (i/o) */
0x0CFE, /* R135 - GPIO Pin Polarity / Type */
0x0000, /* R136 */
0x0000, /* R137 */
0x0000, /* R138 */
0x0000, /* R139 */
0x0312, /* R140 - GPIO Function Select 1 */
0x0003, /* R141 - GPIO Function Select 2 */
0x2331, /* R142 - GPIO Function Select 3 */
0x0003, /* R143 - GPIO Function Select 4 */
0x0000, /* R144 - Digitiser Control (1) */
0x0002, /* R145 - Digitiser Control (2) */
0x0000, /* R146 */
0x0000, /* R147 */
0x0000, /* R148 */
0x0000, /* R149 */
0x0000, /* R150 */
0x0000, /* R151 */
0x7000, /* R152 - AUX1 Readback */
0x7000, /* R153 - AUX2 Readback */
0x7000, /* R154 - AUX3 Readback */
0x7000, /* R155 - AUX4 Readback */
0x0000, /* R156 - USB Voltage Readback */
0x0000, /* R157 - LINE Voltage Readback */
0x0000, /* R158 - BATT Voltage Readback */
0x0000, /* R159 - Chip Temp Readback */
0x0000, /* R160 */
0x0000, /* R161 */
0x0000, /* R162 */
0x0000, /* R163 - Generic Comparator Control */
0x0000, /* R164 - Generic comparator 1 */
0x0000, /* R165 - Generic comparator 2 */
0x0000, /* R166 - Generic comparator 3 */
0x0000, /* R167 - Generic comparator 4 */
0xA00F, /* R168 - Battery Charger Control 1 */
0x0B06, /* R169 - Battery Charger Control 2 */
0x0000, /* R170 - Battery Charger Control 3 */
0x0000, /* R171 */
0x0000, /* R172 - Current Sink Driver A */
0x0000, /* R173 - CSA Flash control */
0x0000, /* R174 - Current Sink Driver B */
0x0000, /* R175 - CSB Flash control */
0x0000, /* R176 - DCDC/LDO requested */
0x002D, /* R177 - DCDC Active options */
0x0000, /* R178 - DCDC Sleep options */
0x0025, /* R179 - Power-check comparator */
0x000E, /* R180 - DCDC1 Control */
0x0400, /* R181 - DCDC1 Timeouts */
0x1006, /* R182 - DCDC1 Low Power */
0x0018, /* R183 - DCDC2 Control */
0x0000, /* R184 - DCDC2 Timeouts */
0x0000, /* R185 */
0x002E, /* R186 - DCDC3 Control */
0x0800, /* R187 - DCDC3 Timeouts */
0x0006, /* R188 - DCDC3 Low Power */
0x000E, /* R189 - DCDC4 Control */
0x0800, /* R190 - DCDC4 Timeouts */
0x0006, /* R191 - DCDC4 Low Power */
0x0008, /* R192 - DCDC5 Control */
0x0000, /* R193 - DCDC5 Timeouts */
0x0000, /* R194 */
0x0026, /* R195 - DCDC6 Control */
0x0C00, /* R196 - DCDC6 Timeouts */
0x0006, /* R197 - DCDC6 Low Power */
0x0000, /* R198 */
0x0003, /* R199 - Limit Switch Control */
0x001A, /* R200 - LDO1 Control */
0x0800, /* R201 - LDO1 Timeouts */
0x001C, /* R202 - LDO1 Low Power */
0x0010, /* R203 - LDO2 Control */
0x0800, /* R204 - LDO2 Timeouts */
0x001C, /* R205 - LDO2 Low Power */
0x000A, /* R206 - LDO3 Control */
0x0C00, /* R207 - LDO3 Timeouts */
0x001C, /* R208 - LDO3 Low Power */
0x001A, /* R209 - LDO4 Control */
0x0800, /* R210 - LDO4 Timeouts */
0x001C, /* R211 - LDO4 Low Power */
0x0000, /* R212 */
0x0000, /* R213 */
0x0000, /* R214 */
0x0000, /* R215 - VCC_FAULT Masks */
0x001F, /* R216 - Main Bandgap Control */
0x0000, /* R217 - OSC Control */
0x9000, /* R218 - RTC Tick Control */
0x0000, /* R219 */
0x4000, /* R220 - RAM BIST 1 */
0x0000, /* R221 */
0x0000, /* R222 */
0x0000, /* R223 */
0x0000, /* R224 */
0x0000, /* R225 - DCDC/LDO status */
0x0000, /* R226 */
0x0000, /* R227 */
0x0000, /* R228 */
0x0000, /* R229 */
0xE000, /* R230 - GPIO Pin Status */
0x0000, /* R231 */
0x0000, /* R232 */
0x0000, /* R233 */
0x0000, /* R234 */
0x0000, /* R235 */
0x0000, /* R236 */
0x0000, /* R237 */
0x0000, /* R238 */
0x0000, /* R239 */
0x0000, /* R240 */
0x0000, /* R241 */
0x0000, /* R242 */
0x0000, /* R243 */
0x0000, /* R244 */
0x0000, /* R245 */
0x0000, /* R246 */
0x0000, /* R247 */
0x0000, /* R248 */
0x0000, /* R249 */
0x0000, /* R250 */
0x0000, /* R251 */
0x0000, /* R252 */
0x0000, /* R253 */
0x0000, /* R254 */
0x0000, /* R255 */
};
#endif
#ifdef CONFIG_MFD_WM8350_CONFIG_MODE_3
#undef WM8350_HAVE_CONFIG_MODE
#define WM8350_HAVE_CONFIG_MODE
const u16 wm8350_mode3_defaults[] = {
0x17FF, /* R0 - Reset/ID */
0x1000, /* R1 - ID */
0x0000, /* R2 */
0x1000, /* R3 - System Control 1 */
0x0004, /* R4 - System Control 2 */
0x0000, /* R5 - System Hibernate */
0x8A00, /* R6 - Interface Control */
0x0000, /* R7 */
0x8000, /* R8 - Power mgmt (1) */
0x0000, /* R9 - Power mgmt (2) */
0x0000, /* R10 - Power mgmt (3) */
0x2000, /* R11 - Power mgmt (4) */
0x0E00, /* R12 - Power mgmt (5) */
0x0000, /* R13 - Power mgmt (6) */
0x0000, /* R14 - Power mgmt (7) */
0x0000, /* R15 */
0x0000, /* R16 - RTC Seconds/Minutes */
0x0100, /* R17 - RTC Hours/Day */
0x0101, /* R18 - RTC Date/Month */
0x1400, /* R19 - RTC Year */
0x0000, /* R20 - Alarm Seconds/Minutes */
0x0000, /* R21 - Alarm Hours/Day */
0x0000, /* R22 - Alarm Date/Month */
0x0320, /* R23 - RTC Time Control */
0x0000, /* R24 - System Interrupts */
0x0000, /* R25 - Interrupt Status 1 */
0x0000, /* R26 - Interrupt Status 2 */
0x0000, /* R27 - Power Up Interrupt Status */
0x0000, /* R28 - Under Voltage Interrupt status */
0x0000, /* R29 - Over Current Interrupt status */
0x0000, /* R30 - GPIO Interrupt Status */
0x0000, /* R31 - Comparator Interrupt Status */
0x3FFF, /* R32 - System Interrupts Mask */
0x0000, /* R33 - Interrupt Status 1 Mask */
0x0000, /* R34 - Interrupt Status 2 Mask */
0x0000, /* R35 - Power Up Interrupt Status Mask */
0x0000, /* R36 - Under Voltage Interrupt status Mask */
0x0000, /* R37 - Over Current Interrupt status Mask */
0x0000, /* R38 - GPIO Interrupt Status Mask */
0x0000, /* R39 - Comparator Interrupt Status Mask */
0x0040, /* R40 - Clock Control 1 */
0x0000, /* R41 - Clock Control 2 */
0x3B00, /* R42 - FLL Control 1 */
0x7086, /* R43 - FLL Control 2 */
0xC226, /* R44 - FLL Control 3 */
0x0000, /* R45 - FLL Control 4 */
0x0000, /* R46 */
0x0000, /* R47 */
0x0000, /* R48 - DAC Control */
0x0000, /* R49 */
0x00C0, /* R50 - DAC Digital Volume L */
0x00C0, /* R51 - DAC Digital Volume R */
0x0000, /* R52 */
0x0040, /* R53 - DAC LR Rate */
0x0000, /* R54 - DAC Clock Control */
0x0000, /* R55 */
0x0000, /* R56 */
0x0000, /* R57 */
0x4000, /* R58 - DAC Mute */
0x0000, /* R59 - DAC Mute Volume */
0x0000, /* R60 - DAC Side */
0x0000, /* R61 */
0x0000, /* R62 */
0x0000, /* R63 */
0x8000, /* R64 - ADC Control */
0x0000, /* R65 */
0x00C0, /* R66 - ADC Digital Volume L */
0x00C0, /* R67 - ADC Digital Volume R */
0x0000, /* R68 - ADC Divider */
0x0000, /* R69 */
0x0040, /* R70 - ADC LR Rate */
0x0000, /* R71 */
0x0303, /* R72 - Input Control */
0x0000, /* R73 - IN3 Input Control */
0x0000, /* R74 - Mic Bias Control */
0x0000, /* R75 */
0x0000, /* R76 - Output Control */
0x0000, /* R77 - Jack Detect */
0x0000, /* R78 - Anti Pop Control */
0x0000, /* R79 */
0x0040, /* R80 - Left Input Volume */
0x0040, /* R81 - Right Input Volume */
0x0000, /* R82 */
0x0000, /* R83 */
0x0000, /* R84 */
0x0000, /* R85 */
0x0000, /* R86 */
0x0000, /* R87 */
0x0800, /* R88 - Left Mixer Control */
0x1000, /* R89 - Right Mixer Control */
0x0000, /* R90 */
0x0000, /* R91 */
0x0000, /* R92 - OUT3 Mixer Control */
0x0000, /* R93 - OUT4 Mixer Control */
0x0000, /* R94 */
0x0000, /* R95 */
0x0000, /* R96 - Output Left Mixer Volume */
0x0000, /* R97 - Output Right Mixer Volume */
0x0000, /* R98 - Input Mixer Volume L */
0x0000, /* R99 - Input Mixer Volume R */
0x0000, /* R100 - Input Mixer Volume */
0x0000, /* R101 */
0x0000, /* R102 */
0x0000, /* R103 */
0x00E4, /* R104 - LOUT1 Volume */
0x00E4, /* R105 - ROUT1 Volume */
0x00E4, /* R106 - LOUT2 Volume */
0x02E4, /* R107 - ROUT2 Volume */
0x0000, /* R108 */
0x0000, /* R109 */
0x0000, /* R110 */
0x0000, /* R111 - BEEP Volume */
0x0A00, /* R112 - AI Formating */
0x0000, /* R113 - ADC DAC COMP */
0x0020, /* R114 - AI ADC Control */
0x0020, /* R115 - AI DAC Control */
0x0000, /* R116 - AIF Test */
0x0000, /* R117 */
0x0000, /* R118 */
0x0000, /* R119 */
0x0000, /* R120 */
0x0000, /* R121 */
0x0000, /* R122 */
0x0000, /* R123 */
0x0000, /* R124 */
0x0000, /* R125 */
0x0000, /* R126 */
0x0000, /* R127 */
0x1FFF, /* R128 - GPIO Debounce */
0x0000, /* R129 - GPIO Pin pull up Control */
0x03FC, /* R130 - GPIO Pull down Control */
0x0000, /* R131 - GPIO Interrupt Mode */
0x0000, /* R132 */
0x0000, /* R133 - GPIO Control */
0x0A7B, /* R134 - GPIO Configuration (i/o) */
0x06FE, /* R135 - GPIO Pin Polarity / Type */
0x0000, /* R136 */
0x0000, /* R137 */
0x0000, /* R138 */
0x0000, /* R139 */
0x1312, /* R140 - GPIO Function Select 1 */
0x1030, /* R141 - GPIO Function Select 2 */
0x2231, /* R142 - GPIO Function Select 3 */
0x0003, /* R143 - GPIO Function Select 4 */
0x0000, /* R144 - Digitiser Control (1) */
0x0002, /* R145 - Digitiser Control (2) */
0x0000, /* R146 */
0x0000, /* R147 */
0x0000, /* R148 */
0x0000, /* R149 */
0x0000, /* R150 */
0x0000, /* R151 */
0x7000, /* R152 - AUX1 Readback */
0x7000, /* R153 - AUX2 Readback */
0x7000, /* R154 - AUX3 Readback */
0x7000, /* R155 - AUX4 Readback */
0x0000, /* R156 - USB Voltage Readback */
0x0000, /* R157 - LINE Voltage Readback */
0x0000, /* R158 - BATT Voltage Readback */
0x0000, /* R159 - Chip Temp Readback */
0x0000, /* R160 */
0x0000, /* R161 */
0x0000, /* R162 */
0x0000, /* R163 - Generic Comparator Control */
0x0000, /* R164 - Generic comparator 1 */
0x0000, /* R165 - Generic comparator 2 */
0x0000, /* R166 - Generic comparator 3 */
0x0000, /* R167 - Generic comparator 4 */
0xA00F, /* R168 - Battery Charger Control 1 */
0x0B06, /* R169 - Battery Charger Control 2 */
0x0000, /* R170 - Battery Charger Control 3 */
0x0000, /* R171 */
0x0000, /* R172 - Current Sink Driver A */
0x0000, /* R173 - CSA Flash control */
0x0000, /* R174 - Current Sink Driver B */
0x0000, /* R175 - CSB Flash control */
0x0000, /* R176 - DCDC/LDO requested */
0x002D, /* R177 - DCDC Active options */
0x0000, /* R178 - DCDC Sleep options */
0x0025, /* R179 - Power-check comparator */
0x000E, /* R180 - DCDC1 Control */
0x0400, /* R181 - DCDC1 Timeouts */
0x1006, /* R182 - DCDC1 Low Power */
0x0018, /* R183 - DCDC2 Control */
0x0000, /* R184 - DCDC2 Timeouts */
0x0000, /* R185 */
0x000E, /* R186 - DCDC3 Control */
0x0400, /* R187 - DCDC3 Timeouts */
0x0006, /* R188 - DCDC3 Low Power */
0x0026, /* R189 - DCDC4 Control */
0x0400, /* R190 - DCDC4 Timeouts */
0x0006, /* R191 - DCDC4 Low Power */
0x0008, /* R192 - DCDC5 Control */
0x0000, /* R193 - DCDC5 Timeouts */
0x0000, /* R194 */
0x0026, /* R195 - DCDC6 Control */
0x0400, /* R196 - DCDC6 Timeouts */
0x0006, /* R197 - DCDC6 Low Power */
0x0000, /* R198 */
0x0003, /* R199 - Limit Switch Control */
0x001C, /* R200 - LDO1 Control */
0x0000, /* R201 - LDO1 Timeouts */
0x001C, /* R202 - LDO1 Low Power */
0x001C, /* R203 - LDO2 Control */
0x0400, /* R204 - LDO2 Timeouts */
0x001C, /* R205 - LDO2 Low Power */
0x001C, /* R206 - LDO3 Control */
0x0400, /* R207 - LDO3 Timeouts */
0x001C, /* R208 - LDO3 Low Power */
0x001F, /* R209 - LDO4 Control */
0x0400, /* R210 - LDO4 Timeouts */
0x001C, /* R211 - LDO4 Low Power */
0x0000, /* R212 */
0x0000, /* R213 */
0x0000, /* R214 */
0x0000, /* R215 - VCC_FAULT Masks */
0x001F, /* R216 - Main Bandgap Control */
0x0000, /* R217 - OSC Control */
0x9000, /* R218 - RTC Tick Control */
0x0000, /* R219 */
0x4000, /* R220 - RAM BIST 1 */
0x0000, /* R221 */
0x0000, /* R222 */
0x0000, /* R223 */
0x0000, /* R224 */
0x0000, /* R225 - DCDC/LDO status */
0x0000, /* R226 */
0x0000, /* R227 */
0x0000, /* R228 */
0x0000, /* R229 */
0xE000, /* R230 - GPIO Pin Status */
0x0000, /* R231 */
0x0000, /* R232 */
0x0000, /* R233 */
0x0000, /* R234 */
0x0000, /* R235 */
0x0000, /* R236 */
0x0000, /* R237 */
0x0000, /* R238 */
0x0000, /* R239 */
0x0000, /* R240 */
0x0000, /* R241 */
0x0000, /* R242 */
0x0000, /* R243 */
0x0000, /* R244 */
0x0000, /* R245 */
0x0000, /* R246 */
0x0000, /* R247 */
0x0000, /* R248 */
0x0000, /* R249 */
0x0000, /* R250 */
0x0000, /* R251 */
0x0000, /* R252 */
0x0000, /* R253 */
0x0000, /* R254 */
0x0000, /* R255 */
};
#endif
#ifdef CONFIG_MFD_WM8351_CONFIG_MODE_0
#undef WM8350_HAVE_CONFIG_MODE
#define WM8350_HAVE_CONFIG_MODE
const u16 wm8351_mode0_defaults[] = {
0x6143, /* R0 - Reset/ID */
0x0000, /* R1 - ID */
0x0001, /* R2 - Revision */
0x1C02, /* R3 - System Control 1 */
0x0004, /* R4 - System Control 2 */
0x0000, /* R5 - System Hibernate */
0x8A00, /* R6 - Interface Control */
0x0000, /* R7 */
0x8000, /* R8 - Power mgmt (1) */
0x0000, /* R9 - Power mgmt (2) */
0x0000, /* R10 - Power mgmt (3) */
0x2000, /* R11 - Power mgmt (4) */
0x0E00, /* R12 - Power mgmt (5) */
0x0000, /* R13 - Power mgmt (6) */
0x0000, /* R14 - Power mgmt (7) */
0x0000, /* R15 */
0x0000, /* R16 - RTC Seconds/Minutes */
0x0100, /* R17 - RTC Hours/Day */
0x0101, /* R18 - RTC Date/Month */
0x1400, /* R19 - RTC Year */
0x0000, /* R20 - Alarm Seconds/Minutes */
0x0000, /* R21 - Alarm Hours/Day */
0x0000, /* R22 - Alarm Date/Month */
0x0320, /* R23 - RTC Time Control */
0x0000, /* R24 - System Interrupts */
0x0000, /* R25 - Interrupt Status 1 */
0x0000, /* R26 - Interrupt Status 2 */
0x0000, /* R27 */
0x0000, /* R28 - Under Voltage Interrupt status */
0x0000, /* R29 - Over Current Interrupt status */
0x0000, /* R30 - GPIO Interrupt Status */
0x0000, /* R31 - Comparator Interrupt Status */
0x3FFF, /* R32 - System Interrupts Mask */
0x0000, /* R33 - Interrupt Status 1 Mask */
0x0000, /* R34 - Interrupt Status 2 Mask */
0x0000, /* R35 */
0x0000, /* R36 - Under Voltage Interrupt status Mask */
0x0000, /* R37 - Over Current Interrupt status Mask */
0x0000, /* R38 - GPIO Interrupt Status Mask */
0x0000, /* R39 - Comparator Interrupt Status Mask */
0x0040, /* R40 - Clock Control 1 */
0x0000, /* R41 - Clock Control 2 */
0x3A00, /* R42 - FLL Control 1 */
0x7086, /* R43 - FLL Control 2 */
0xC226, /* R44 - FLL Control 3 */
0x0000, /* R45 - FLL Control 4 */
0x0000, /* R46 */
0x0000, /* R47 */
0x0000, /* R48 - DAC Control */
0x0000, /* R49 */
0x00C0, /* R50 - DAC Digital Volume L */
0x00C0, /* R51 - DAC Digital Volume R */
0x0000, /* R52 */
0x0040, /* R53 - DAC LR Rate */
0x0000, /* R54 - DAC Clock Control */
0x0000, /* R55 */
0x0000, /* R56 */
0x0000, /* R57 */
0x4000, /* R58 - DAC Mute */
0x0000, /* R59 - DAC Mute Volume */
0x0000, /* R60 - DAC Side */
0x0000, /* R61 */
0x0000, /* R62 */
0x0000, /* R63 */
0x8000, /* R64 - ADC Control */
0x0000, /* R65 */
0x00C0, /* R66 - ADC Digital Volume L */
0x00C0, /* R67 - ADC Digital Volume R */
0x0000, /* R68 - ADC Divider */
0x0000, /* R69 */
0x0040, /* R70 - ADC LR Rate */
0x0000, /* R71 */
0x0303, /* R72 - Input Control */
0x0000, /* R73 - IN3 Input Control */
0x0000, /* R74 - Mic Bias Control */
0x0000, /* R75 */
0x0000, /* R76 - Output Control */
0x0000, /* R77 - Jack Detect */
0x0000, /* R78 - Anti Pop Control */
0x0000, /* R79 */
0x0040, /* R80 - Left Input Volume */
0x0040, /* R81 - Right Input Volume */
0x0000, /* R82 */
0x0000, /* R83 */
0x0000, /* R84 */
0x0000, /* R85 */
0x0000, /* R86 */
0x0000, /* R87 */
0x0800, /* R88 - Left Mixer Control */
0x1000, /* R89 - Right Mixer Control */
0x0000, /* R90 */
0x0000, /* R91 */
0x0000, /* R92 - OUT3 Mixer Control */
0x0000, /* R93 - OUT4 Mixer Control */
0x0000, /* R94 */
0x0000, /* R95 */
0x0000, /* R96 - Output Left Mixer Volume */
0x0000, /* R97 - Output Right Mixer Volume */
0x0000, /* R98 - Input Mixer Volume L */
0x0000, /* R99 - Input Mixer Volume R */
0x0000, /* R100 - Input Mixer Volume */
0x0000, /* R101 */
0x0000, /* R102 */
0x0000, /* R103 */
0x00E4, /* R104 - OUT1L Volume */
0x00E4, /* R105 - OUT1R Volume */
0x00E4, /* R106 - OUT2L Volume */
0x02E4, /* R107 - OUT2R Volume */
0x0000, /* R108 */
0x0000, /* R109 */
0x0000, /* R110 */
0x0000, /* R111 - BEEP Volume */
0x0A00, /* R112 - AI Formating */
0x0000, /* R113 - ADC DAC COMP */
0x0020, /* R114 - AI ADC Control */
0x0020, /* R115 - AI DAC Control */
0x0000, /* R116 */
0x0000, /* R117 */
0x0000, /* R118 */
0x0000, /* R119 */
0x0000, /* R120 */
0x0000, /* R121 */
0x0000, /* R122 */
0x0000, /* R123 */
0x0000, /* R124 */
0x0000, /* R125 */
0x0000, /* R126 */
0x0000, /* R127 */
0x1FFF, /* R128 - GPIO Debounce */
0x0000, /* R129 - GPIO Pin pull up Control */
0x0000, /* R130 - GPIO Pull down Control */
0x0000, /* R131 - GPIO Interrupt Mode */
0x0000, /* R132 */
0x0000, /* R133 - GPIO Control */
0x0FFC, /* R134 - GPIO Configuration (i/o) */
0x0FFC, /* R135 - GPIO Pin Polarity / Type */
0x0000, /* R136 */
0x0000, /* R137 */
0x0000, /* R138 */
0x0000, /* R139 */
0x0013, /* R140 - GPIO Function Select 1 */
0x0000, /* R141 - GPIO Function Select 2 */
0x0000, /* R142 - GPIO Function Select 3 */
0x0003, /* R143 - GPIO Function Select 4 */
0x0000, /* R144 - Digitiser Control (1) */
0x0002, /* R145 - Digitiser Control (2) */
0x0000, /* R146 */
0x0000, /* R147 */
0x0000, /* R148 */
0x0000, /* R149 */
0x0000, /* R150 */
0x0000, /* R151 */
0x7000, /* R152 - AUX1 Readback */
0x7000, /* R153 - AUX2 Readback */
0x7000, /* R154 - AUX3 Readback */
0x7000, /* R155 - AUX4 Readback */
0x0000, /* R156 - USB Voltage Readback */
0x0000, /* R157 - LINE Voltage Readback */
0x0000, /* R158 - BATT Voltage Readback */
0x0000, /* R159 - Chip Temp Readback */
0x0000, /* R160 */
0x0000, /* R161 */
0x0000, /* R162 */
0x0000, /* R163 - Generic Comparator Control */
0x0000, /* R164 - Generic comparator 1 */
0x0000, /* R165 - Generic comparator 2 */
0x0000, /* R166 - Generic comparator 3 */
0x0000, /* R167 - Generic comparator 4 */
0xA00F, /* R168 - Battery Charger Control 1 */
0x0B06, /* R169 - Battery Charger Control 2 */
0x0000, /* R170 - Battery Charger Control 3 */
0x0000, /* R171 */
0x0000, /* R172 - Current Sink Driver A */
0x0000, /* R173 - CSA Flash control */
0x0000, /* R174 */
0x0000, /* R175 */
0x0000, /* R176 - DCDC/LDO requested */
0x032D, /* R177 - DCDC Active options */
0x0000, /* R178 - DCDC Sleep options */
0x0025, /* R179 - Power-check comparator */
0x000E, /* R180 - DCDC1 Control */
0x0000, /* R181 - DCDC1 Timeouts */
0x1006, /* R182 - DCDC1 Low Power */
0x0018, /* R183 - DCDC2 Control */
0x0000, /* R184 - DCDC2 Timeouts */
0x0000, /* R185 */
0x0000, /* R186 - DCDC3 Control */
0x0000, /* R187 - DCDC3 Timeouts */
0x0006, /* R188 - DCDC3 Low Power */
0x0000, /* R189 - DCDC4 Control */
0x0000, /* R190 - DCDC4 Timeouts */
0x0006, /* R191 - DCDC4 Low Power */
0x0008, /* R192 */
0x0000, /* R193 */
0x0000, /* R194 */
0x0000, /* R195 */
0x0000, /* R196 */
0x0006, /* R197 */
0x0000, /* R198 */
0x0003, /* R199 - Limit Switch Control */
0x001C, /* R200 - LDO1 Control */
0x0000, /* R201 - LDO1 Timeouts */
0x001C, /* R202 - LDO1 Low Power */
0x001B, /* R203 - LDO2 Control */
0x0000, /* R204 - LDO2 Timeouts */
0x001C, /* R205 - LDO2 Low Power */
0x001B, /* R206 - LDO3 Control */
0x0000, /* R207 - LDO3 Timeouts */
0x001C, /* R208 - LDO3 Low Power */
0x001B, /* R209 - LDO4 Control */
0x0000, /* R210 - LDO4 Timeouts */
0x001C, /* R211 - LDO4 Low Power */
0x0000, /* R212 */
0x0000, /* R213 */
0x0000, /* R214 */
0x0000, /* R215 - VCC_FAULT Masks */
0x001F, /* R216 - Main Bandgap Control */
0x0000, /* R217 - OSC Control */
0x9000, /* R218 - RTC Tick Control */
0x0000, /* R219 - Security1 */
0x4000, /* R220 */
0x0000, /* R221 */
0x0000, /* R222 */
0x0000, /* R223 */
0x0000, /* R224 - Signal overrides */
0x0000, /* R225 - DCDC/LDO status */
0x0000, /* R226 - Charger Overides/status */
0x0000, /* R227 - misc overrides */
0x0000, /* R228 - Supply overrides/status 1 */
0x0000, /* R229 - Supply overrides/status 2 */
0xE000, /* R230 - GPIO Pin Status */
0x0000, /* R231 - comparotor overrides */
0x0000, /* R232 */
0x0000, /* R233 - State Machine status */
0x1200, /* R234 - FLL Test 1 */
0x0000, /* R235 */
0x8000, /* R236 */
0x0000, /* R237 */
0x0000, /* R238 */
0x0000, /* R239 */
0x0003, /* R240 */
0x0000, /* R241 */
0x0000, /* R242 */
0x0004, /* R243 */
0x0300, /* R244 */
0x0000, /* R245 */
0x0200, /* R246 */
0x0000, /* R247 */
0x1000, /* R248 - DCDC1 Test Controls */
0x1000, /* R249 */
0x1000, /* R250 - DCDC3 Test Controls */
0x1000, /* R251 - DCDC4 Test Controls */
};
#endif
#ifdef CONFIG_MFD_WM8351_CONFIG_MODE_1
#undef WM8350_HAVE_CONFIG_MODE
#define WM8350_HAVE_CONFIG_MODE
const u16 wm8351_mode1_defaults[] = {
0x6143, /* R0 - Reset/ID */
0x0000, /* R1 - ID */
0x0001, /* R2 - Revision */
0x1C02, /* R3 - System Control 1 */
0x0204, /* R4 - System Control 2 */
0x0000, /* R5 - System Hibernate */
0x8A00, /* R6 - Interface Control */
0x0000, /* R7 */
0x8000, /* R8 - Power mgmt (1) */
0x0000, /* R9 - Power mgmt (2) */
0x0000, /* R10 - Power mgmt (3) */
0x2000, /* R11 - Power mgmt (4) */
0x0E00, /* R12 - Power mgmt (5) */
0x0000, /* R13 - Power mgmt (6) */
0x0000, /* R14 - Power mgmt (7) */
0x0000, /* R15 */
0x0000, /* R16 - RTC Seconds/Minutes */
0x0100, /* R17 - RTC Hours/Day */
0x0101, /* R18 - RTC Date/Month */
0x1400, /* R19 - RTC Year */
0x0000, /* R20 - Alarm Seconds/Minutes */
0x0000, /* R21 - Alarm Hours/Day */
0x0000, /* R22 - Alarm Date/Month */
0x0320, /* R23 - RTC Time Control */
0x0000, /* R24 - System Interrupts */
0x0000, /* R25 - Interrupt Status 1 */
0x0000, /* R26 - Interrupt Status 2 */
0x0000, /* R27 */
0x0000, /* R28 - Under Voltage Interrupt status */
0x0000, /* R29 - Over Current Interrupt status */
0x0000, /* R30 - GPIO Interrupt Status */
0x0000, /* R31 - Comparator Interrupt Status */
0x3FFF, /* R32 - System Interrupts Mask */
0x0000, /* R33 - Interrupt Status 1 Mask */
0x0000, /* R34 - Interrupt Status 2 Mask */
0x0000, /* R35 */
0x0000, /* R36 - Under Voltage Interrupt status Mask */
0x0000, /* R37 - Over Current Interrupt status Mask */
0x0000, /* R38 - GPIO Interrupt Status Mask */
0x0000, /* R39 - Comparator Interrupt Status Mask */
0x0040, /* R40 - Clock Control 1 */
0x0000, /* R41 - Clock Control 2 */
0x3A00, /* R42 - FLL Control 1 */
0x7086, /* R43 - FLL Control 2 */
0xC226, /* R44 - FLL Control 3 */
0x0000, /* R45 - FLL Control 4 */
0x0000, /* R46 */
0x0000, /* R47 */
0x0000, /* R48 - DAC Control */
0x0000, /* R49 */
0x00C0, /* R50 - DAC Digital Volume L */
0x00C0, /* R51 - DAC Digital Volume R */
0x0000, /* R52 */
0x0040, /* R53 - DAC LR Rate */
0x0000, /* R54 - DAC Clock Control */
0x0000, /* R55 */
0x0000, /* R56 */
0x0000, /* R57 */
0x4000, /* R58 - DAC Mute */
0x0000, /* R59 - DAC Mute Volume */
0x0000, /* R60 - DAC Side */
0x0000, /* R61 */
0x0000, /* R62 */
0x0000, /* R63 */
0x8000, /* R64 - ADC Control */
0x0000, /* R65 */
0x00C0, /* R66 - ADC Digital Volume L */
0x00C0, /* R67 - ADC Digital Volume R */
0x0000, /* R68 - ADC Divider */
0x0000, /* R69 */
0x0040, /* R70 - ADC LR Rate */
0x0000, /* R71 */
0x0303, /* R72 - Input Control */
0x0000, /* R73 - IN3 Input Control */
0x0000, /* R74 - Mic Bias Control */
0x0000, /* R75 */
0x0000, /* R76 - Output Control */
0x0000, /* R77 - Jack Detect */
0x0000, /* R78 - Anti Pop Control */
0x0000, /* R79 */
0x0040, /* R80 - Left Input Volume */
0x0040, /* R81 - Right Input Volume */
0x0000, /* R82 */
0x0000, /* R83 */
0x0000, /* R84 */
0x0000, /* R85 */
0x0000, /* R86 */
0x0000, /* R87 */
0x0800, /* R88 - Left Mixer Control */
0x1000, /* R89 - Right Mixer Control */
0x0000, /* R90 */
0x0000, /* R91 */
0x0000, /* R92 - OUT3 Mixer Control */
0x0000, /* R93 - OUT4 Mixer Control */
0x0000, /* R94 */
0x0000, /* R95 */
0x0000, /* R96 - Output Left Mixer Volume */
0x0000, /* R97 - Output Right Mixer Volume */
0x0000, /* R98 - Input Mixer Volume L */
0x0000, /* R99 - Input Mixer Volume R */
0x0000, /* R100 - Input Mixer Volume */
0x0000, /* R101 */
0x0000, /* R102 */
0x0000, /* R103 */
0x00E4, /* R104 - OUT1L Volume */
0x00E4, /* R105 - OUT1R Volume */
0x00E4, /* R106 - OUT2L Volume */
0x02E4, /* R107 - OUT2R Volume */
0x0000, /* R108 */
0x0000, /* R109 */
0x0000, /* R110 */
0x0000, /* R111 - BEEP Volume */
0x0A00, /* R112 - AI Formating */
0x0000, /* R113 - ADC DAC COMP */
0x0020, /* R114 - AI ADC Control */
0x0020, /* R115 - AI DAC Control */
0x0000, /* R116 */
0x0000, /* R117 */
0x0000, /* R118 */
0x0000, /* R119 */
0x0000, /* R120 */
0x0000, /* R121 */
0x0000, /* R122 */
0x0000, /* R123 */
0x0000, /* R124 */
0x0000, /* R125 */
0x0000, /* R126 */
0x0000, /* R127 */
0x1FFF, /* R128 - GPIO Debounce */
0x0000, /* R129 - GPIO Pin pull up Control */
0x0000, /* R130 - GPIO Pull down Control */
0x0000, /* R131 - GPIO Interrupt Mode */
0x0000, /* R132 */
0x0000, /* R133 - GPIO Control */
0x0CFB, /* R134 - GPIO Configuration (i/o) */
0x0C1F, /* R135 - GPIO Pin Polarity / Type */
0x0000, /* R136 */
0x0000, /* R137 */
0x0000, /* R138 */
0x0000, /* R139 */
0x0300, /* R140 - GPIO Function Select 1 */
0x1110, /* R141 - GPIO Function Select 2 */
0x0013, /* R142 - GPIO Function Select 3 */
0x0003, /* R143 - GPIO Function Select 4 */
0x0000, /* R144 - Digitiser Control (1) */
0x0002, /* R145 - Digitiser Control (2) */
0x0000, /* R146 */
0x0000, /* R147 */
0x0000, /* R148 */
0x0000, /* R149 */
0x0000, /* R150 */
0x0000, /* R151 */
0x7000, /* R152 - AUX1 Readback */
0x7000, /* R153 - AUX2 Readback */
0x7000, /* R154 - AUX3 Readback */
0x7000, /* R155 - AUX4 Readback */
0x0000, /* R156 - USB Voltage Readback */
0x0000, /* R157 - LINE Voltage Readback */
0x0000, /* R158 - BATT Voltage Readback */
0x0000, /* R159 - Chip Temp Readback */
0x0000, /* R160 */
0x0000, /* R161 */
0x0000, /* R162 */
0x0000, /* R163 - Generic Comparator Control */
0x0000, /* R164 - Generic comparator 1 */
0x0000, /* R165 - Generic comparator 2 */
0x0000, /* R166 - Generic comparator 3 */
0x0000, /* R167 - Generic comparator 4 */
0xA00F, /* R168 - Battery Charger Control 1 */
0x0B06, /* R169 - Battery Charger Control 2 */
0x0000, /* R170 - Battery Charger Control 3 */
0x0000, /* R171 */
0x0000, /* R172 - Current Sink Driver A */
0x0000, /* R173 - CSA Flash control */
0x0000, /* R174 */
0x0000, /* R175 */
0x0000, /* R176 - DCDC/LDO requested */
0x032D, /* R177 - DCDC Active options */
0x0000, /* R178 - DCDC Sleep options */
0x0025, /* R179 - Power-check comparator */
0x000E, /* R180 - DCDC1 Control */
0x0C00, /* R181 - DCDC1 Timeouts */
0x1006, /* R182 - DCDC1 Low Power */
0x0018, /* R183 - DCDC2 Control */
0x0000, /* R184 - DCDC2 Timeouts */
0x0000, /* R185 */
0x0026, /* R186 - DCDC3 Control */
0x0400, /* R187 - DCDC3 Timeouts */
0x0006, /* R188 - DCDC3 Low Power */
0x0062, /* R189 - DCDC4 Control */
0x0800, /* R190 - DCDC4 Timeouts */
0x0006, /* R191 - DCDC4 Low Power */
0x0008, /* R192 */
0x0000, /* R193 */
0x0000, /* R194 */
0x000A, /* R195 */
0x1000, /* R196 */
0x0006, /* R197 */
0x0000, /* R198 */
0x0003, /* R199 - Limit Switch Control */
0x0006, /* R200 - LDO1 Control */
0x0000, /* R201 - LDO1 Timeouts */
0x001C, /* R202 - LDO1 Low Power */
0x0010, /* R203 - LDO2 Control */
0x0C00, /* R204 - LDO2 Timeouts */
0x001C, /* R205 - LDO2 Low Power */
0x001F, /* R206 - LDO3 Control */
0x0800, /* R207 - LDO3 Timeouts */
0x001C, /* R208 - LDO3 Low Power */
0x000A, /* R209 - LDO4 Control */
0x0800, /* R210 - LDO4 Timeouts */
0x001C, /* R211 - LDO4 Low Power */
0x0000, /* R212 */
0x0000, /* R213 */
0x0000, /* R214 */
0x0000, /* R215 - VCC_FAULT Masks */
0x001F, /* R216 - Main Bandgap Control */
0x0000, /* R217 - OSC Control */
0x9000, /* R218 - RTC Tick Control */
0x0000, /* R219 - Security1 */
0x4000, /* R220 */
0x0000, /* R221 */
0x0000, /* R222 */
0x0000, /* R223 */
0x0000, /* R224 - Signal overrides */
0x0000, /* R225 - DCDC/LDO status */
0x0000, /* R226 - Charger Overides/status */
0x0000, /* R227 - misc overrides */
0x0000, /* R228 - Supply overrides/status 1 */
0x0000, /* R229 - Supply overrides/status 2 */
0xE000, /* R230 - GPIO Pin Status */
0x0000, /* R231 - comparotor overrides */
0x0000, /* R232 */
0x0000, /* R233 - State Machine status */
0x1200, /* R234 - FLL Test 1 */
0x0000, /* R235 */
0x8000, /* R236 */
0x0000, /* R237 */
0x0000, /* R238 */
0x0000, /* R239 */
0x0003, /* R240 */
0x0000, /* R241 */
0x0000, /* R242 */
0x0004, /* R243 */
0x0300, /* R244 */
0x0000, /* R245 */
0x0200, /* R246 */
0x1000, /* R247 */
0x1000, /* R248 - DCDC1 Test Controls */
0x1000, /* R249 */
0x1000, /* R250 - DCDC3 Test Controls */
0x1000, /* R251 - DCDC4 Test Controls */
};
#endif
#ifdef CONFIG_MFD_WM8351_CONFIG_MODE_2
#undef WM8350_HAVE_CONFIG_MODE
#define WM8350_HAVE_CONFIG_MODE
const u16 wm8351_mode2_defaults[] = {
0x6143, /* R0 - Reset/ID */
0x0000, /* R1 - ID */
0x0001, /* R2 - Revision */
0x1C02, /* R3 - System Control 1 */
0x0214, /* R4 - System Control 2 */
0x0000, /* R5 - System Hibernate */
0x8A00, /* R6 - Interface Control */
0x0000, /* R7 */
0x8000, /* R8 - Power mgmt (1) */
0x0000, /* R9 - Power mgmt (2) */
0x0000, /* R10 - Power mgmt (3) */
0x2000, /* R11 - Power mgmt (4) */
0x0E00, /* R12 - Power mgmt (5) */
0x0000, /* R13 - Power mgmt (6) */
0x0000, /* R14 - Power mgmt (7) */
0x0000, /* R15 */
0x0000, /* R16 - RTC Seconds/Minutes */
0x0100, /* R17 - RTC Hours/Day */
0x0101, /* R18 - RTC Date/Month */
0x1400, /* R19 - RTC Year */
0x0000, /* R20 - Alarm Seconds/Minutes */
0x0000, /* R21 - Alarm Hours/Day */
0x0000, /* R22 - Alarm Date/Month */
0x0320, /* R23 - RTC Time Control */
0x0000, /* R24 - System Interrupts */
0x0000, /* R25 - Interrupt Status 1 */
0x0000, /* R26 - Interrupt Status 2 */
0x0000, /* R27 */
0x0000, /* R28 - Under Voltage Interrupt status */
0x0000, /* R29 - Over Current Interrupt status */
0x0000, /* R30 - GPIO Interrupt Status */
0x0000, /* R31 - Comparator Interrupt Status */
0x3FFF, /* R32 - System Interrupts Mask */
0x0000, /* R33 - Interrupt Status 1 Mask */
0x0000, /* R34 - Interrupt Status 2 Mask */
0x0000, /* R35 */
0x0000, /* R36 - Under Voltage Interrupt status Mask */
0x0000, /* R37 - Over Current Interrupt status Mask */
0x0000, /* R38 - GPIO Interrupt Status Mask */
0x0000, /* R39 - Comparator Interrupt Status Mask */
0x0040, /* R40 - Clock Control 1 */
0x0000, /* R41 - Clock Control 2 */
0x3A00, /* R42 - FLL Control 1 */
0x7086, /* R43 - FLL Control 2 */
0xC226, /* R44 - FLL Control 3 */
0x0000, /* R45 - FLL Control 4 */
0x0000, /* R46 */
0x0000, /* R47 */
0x0000, /* R48 - DAC Control */
0x0000, /* R49 */
0x00C0, /* R50 - DAC Digital Volume L */
0x00C0, /* R51 - DAC Digital Volume R */
0x0000, /* R52 */
0x0040, /* R53 - DAC LR Rate */
0x0000, /* R54 - DAC Clock Control */
0x0000, /* R55 */
0x0000, /* R56 */
0x0000, /* R57 */
0x4000, /* R58 - DAC Mute */
0x0000, /* R59 - DAC Mute Volume */
0x0000, /* R60 - DAC Side */
0x0000, /* R61 */
0x0000, /* R62 */
0x0000, /* R63 */
0x8000, /* R64 - ADC Control */
0x0000, /* R65 */
0x00C0, /* R66 - ADC Digital Volume L */
0x00C0, /* R67 - ADC Digital Volume R */
0x0000, /* R68 - ADC Divider */
0x0000, /* R69 */
0x0040, /* R70 - ADC LR Rate */
0x0000, /* R71 */
0x0303, /* R72 - Input Control */
0x0000, /* R73 - IN3 Input Control */
0x0000, /* R74 - Mic Bias Control */
0x0000, /* R75 */
0x0000, /* R76 - Output Control */
0x0000, /* R77 - Jack Detect */
0x0000, /* R78 - Anti Pop Control */
0x0000, /* R79 */
0x0040, /* R80 - Left Input Volume */
0x0040, /* R81 - Right Input Volume */
0x0000, /* R82 */
0x0000, /* R83 */
0x0000, /* R84 */
0x0000, /* R85 */
0x0000, /* R86 */
0x0000, /* R87 */
0x0800, /* R88 - Left Mixer Control */
0x1000, /* R89 - Right Mixer Control */
0x0000, /* R90 */
0x0000, /* R91 */
0x0000, /* R92 - OUT3 Mixer Control */
0x0000, /* R93 - OUT4 Mixer Control */
0x0000, /* R94 */
0x0000, /* R95 */
0x0000, /* R96 - Output Left Mixer Volume */
0x0000, /* R97 - Output Right Mixer Volume */
0x0000, /* R98 - Input Mixer Volume L */
0x0000, /* R99 - Input Mixer Volume R */
0x0000, /* R100 - Input Mixer Volume */
0x0000, /* R101 */
0x0000, /* R102 */
0x0000, /* R103 */
0x00E4, /* R104 - OUT1L Volume */
0x00E4, /* R105 - OUT1R Volume */
0x00E4, /* R106 - OUT2L Volume */
0x02E4, /* R107 - OUT2R Volume */
0x0000, /* R108 */
0x0000, /* R109 */
0x0000, /* R110 */
0x0000, /* R111 - BEEP Volume */
0x0A00, /* R112 - AI Formating */
0x0000, /* R113 - ADC DAC COMP */
0x0020, /* R114 - AI ADC Control */
0x0020, /* R115 - AI DAC Control */
0x0000, /* R116 */
0x0000, /* R117 */
0x0000, /* R118 */
0x0000, /* R119 */
0x0000, /* R120 */
0x0000, /* R121 */
0x0000, /* R122 */
0x0000, /* R123 */
0x0000, /* R124 */
0x0000, /* R125 */
0x0000, /* R126 */
0x0000, /* R127 */
0x1FFF, /* R128 - GPIO Debounce */
0x0000, /* R129 - GPIO Pin pull up Control */
0x0110, /* R130 - GPIO Pull down Control */
0x0000, /* R131 - GPIO Interrupt Mode */
0x0000, /* R132 */
0x0000, /* R133 - GPIO Control */
0x09FA, /* R134 - GPIO Configuration (i/o) */
0x0DF6, /* R135 - GPIO Pin Polarity / Type */
0x0000, /* R136 */
0x0000, /* R137 */
0x0000, /* R138 */
0x0000, /* R139 */
0x1310, /* R140 - GPIO Function Select 1 */
0x0003, /* R141 - GPIO Function Select 2 */
0x2000, /* R142 - GPIO Function Select 3 */
0x0000, /* R143 - GPIO Function Select 4 */
0x0000, /* R144 - Digitiser Control (1) */
0x0002, /* R145 - Digitiser Control (2) */
0x0000, /* R146 */
0x0000, /* R147 */
0x0000, /* R148 */
0x0000, /* R149 */
0x0000, /* R150 */
0x0000, /* R151 */
0x7000, /* R152 - AUX1 Readback */
0x7000, /* R153 - AUX2 Readback */
0x7000, /* R154 - AUX3 Readback */
0x7000, /* R155 - AUX4 Readback */
0x0000, /* R156 - USB Voltage Readback */
0x0000, /* R157 - LINE Voltage Readback */
0x0000, /* R158 - BATT Voltage Readback */
0x0000, /* R159 - Chip Temp Readback */
0x0000, /* R160 */
0x0000, /* R161 */
0x0000, /* R162 */
0x0000, /* R163 - Generic Comparator Control */
0x0000, /* R164 - Generic comparator 1 */
0x0000, /* R165 - Generic comparator 2 */
0x0000, /* R166 - Generic comparator 3 */
0x0000, /* R167 - Generic comparator 4 */
0xA00F, /* R168 - Battery Charger Control 1 */
0x0B06, /* R169 - Battery Charger Control 2 */
0x0000, /* R170 - Battery Charger Control 3 */
0x0000, /* R171 */
0x0000, /* R172 - Current Sink Driver A */
0x0000, /* R173 - CSA Flash control */
0x0000, /* R174 */
0x0000, /* R175 */
0x0000, /* R176 - DCDC/LDO requested */
0x032D, /* R177 - DCDC Active options */
0x0000, /* R178 - DCDC Sleep options */
0x0025, /* R179 - Power-check comparator */
0x001A, /* R180 - DCDC1 Control */
0x0800, /* R181 - DCDC1 Timeouts */
0x1006, /* R182 - DCDC1 Low Power */
0x0018, /* R183 - DCDC2 Control */
0x0000, /* R184 - DCDC2 Timeouts */
0x0000, /* R185 */
0x0056, /* R186 - DCDC3 Control */
0x0400, /* R187 - DCDC3 Timeouts */
0x0006, /* R188 - DCDC3 Low Power */
0x0026, /* R189 - DCDC4 Control */
0x0C00, /* R190 - DCDC4 Timeouts */
0x0006, /* R191 - DCDC4 Low Power */
0x0008, /* R192 */
0x0000, /* R193 */
0x0000, /* R194 */
0x0026, /* R195 */
0x0C00, /* R196 */
0x0006, /* R197 */
0x0000, /* R198 */
0x0003, /* R199 - Limit Switch Control */
0x001C, /* R200 - LDO1 Control */
0x0400, /* R201 - LDO1 Timeouts */
0x001C, /* R202 - LDO1 Low Power */
0x0010, /* R203 - LDO2 Control */
0x0C00, /* R204 - LDO2 Timeouts */
0x001C, /* R205 - LDO2 Low Power */
0x0015, /* R206 - LDO3 Control */
0x0000, /* R207 - LDO3 Timeouts */
0x001C, /* R208 - LDO3 Low Power */
0x001A, /* R209 - LDO4 Control */
0x0000, /* R210 - LDO4 Timeouts */
0x001C, /* R211 - LDO4 Low Power */
0x0000, /* R212 */
0x0000, /* R213 */
0x0000, /* R214 */
0x0000, /* R215 - VCC_FAULT Masks */
0x001F, /* R216 - Main Bandgap Control */
0x0000, /* R217 - OSC Control */
0x9000, /* R218 - RTC Tick Control */
0x0000, /* R219 - Security1 */
0x4000, /* R220 */
0x0000, /* R221 */
0x0000, /* R222 */
0x0000, /* R223 */
0x0000, /* R224 - Signal overrides */
0x0000, /* R225 - DCDC/LDO status */
0x0000, /* R226 - Charger Overides/status */
0x0000, /* R227 - misc overrides */
0x0000, /* R228 - Supply overrides/status 1 */
0x0000, /* R229 - Supply overrides/status 2 */
0xE000, /* R230 - GPIO Pin Status */
0x0000, /* R231 - comparotor overrides */
0x0000, /* R232 */
0x0000, /* R233 - State Machine status */
0x1200, /* R234 - FLL Test 1 */
0x0000, /* R235 */
0x8000, /* R236 */
0x0000, /* R237 */
0x0000, /* R238 */
0x0000, /* R239 */
0x0003, /* R240 */
0x0000, /* R241 */
0x0000, /* R242 */
0x0004, /* R243 */
0x0300, /* R244 */
0x0000, /* R245 */
0x0200, /* R246 */
0x0000, /* R247 */
0x1000, /* R248 - DCDC1 Test Controls */
0x1000, /* R249 */
0x1000, /* R250 - DCDC3 Test Controls */
0x1000, /* R251 - DCDC4 Test Controls */
};
#endif
#ifdef CONFIG_MFD_WM8351_CONFIG_MODE_3
#undef WM8350_HAVE_CONFIG_MODE
#define WM8350_HAVE_CONFIG_MODE
const u16 wm8351_mode3_defaults[] = {
0x6143, /* R0 - Reset/ID */
0x0000, /* R1 - ID */
0x0001, /* R2 - Revision */
0x1C02, /* R3 - System Control 1 */
0x0204, /* R4 - System Control 2 */
0x0000, /* R5 - System Hibernate */
0x8A00, /* R6 - Interface Control */
0x0000, /* R7 */
0x8000, /* R8 - Power mgmt (1) */
0x0000, /* R9 - Power mgmt (2) */
0x0000, /* R10 - Power mgmt (3) */
0x2000, /* R11 - Power mgmt (4) */
0x0E00, /* R12 - Power mgmt (5) */
0x0000, /* R13 - Power mgmt (6) */
0x0000, /* R14 - Power mgmt (7) */
0x0000, /* R15 */
0x0000, /* R16 - RTC Seconds/Minutes */
0x0100, /* R17 - RTC Hours/Day */
0x0101, /* R18 - RTC Date/Month */
0x1400, /* R19 - RTC Year */
0x0000, /* R20 - Alarm Seconds/Minutes */
0x0000, /* R21 - Alarm Hours/Day */
0x0000, /* R22 - Alarm Date/Month */
0x0320, /* R23 - RTC Time Control */
0x0000, /* R24 - System Interrupts */
0x0000, /* R25 - Interrupt Status 1 */
0x0000, /* R26 - Interrupt Status 2 */
0x0000, /* R27 */
0x0000, /* R28 - Under Voltage Interrupt status */
0x0000, /* R29 - Over Current Interrupt status */
0x0000, /* R30 - GPIO Interrupt Status */
0x0000, /* R31 - Comparator Interrupt Status */
0x3FFF, /* R32 - System Interrupts Mask */
0x0000, /* R33 - Interrupt Status 1 Mask */
0x0000, /* R34 - Interrupt Status 2 Mask */
0x0000, /* R35 */
0x0000, /* R36 - Under Voltage Interrupt status Mask */
0x0000, /* R37 - Over Current Interrupt status Mask */
0x0000, /* R38 - GPIO Interrupt Status Mask */
0x0000, /* R39 - Comparator Interrupt Status Mask */
0x0040, /* R40 - Clock Control 1 */
0x0000, /* R41 - Clock Control 2 */
0x3A00, /* R42 - FLL Control 1 */
0x7086, /* R43 - FLL Control 2 */
0xC226, /* R44 - FLL Control 3 */
0x0000, /* R45 - FLL Control 4 */
0x0000, /* R46 */
0x0000, /* R47 */
0x0000, /* R48 - DAC Control */
0x0000, /* R49 */
0x00C0, /* R50 - DAC Digital Volume L */
0x00C0, /* R51 - DAC Digital Volume R */
0x0000, /* R52 */
0x0040, /* R53 - DAC LR Rate */
0x0000, /* R54 - DAC Clock Control */
0x0000, /* R55 */
0x0000, /* R56 */
0x0000, /* R57 */
0x4000, /* R58 - DAC Mute */
0x0000, /* R59 - DAC Mute Volume */
0x0000, /* R60 - DAC Side */
0x0000, /* R61 */
0x0000, /* R62 */
0x0000, /* R63 */
0x8000, /* R64 - ADC Control */
0x0000, /* R65 */
0x00C0, /* R66 - ADC Digital Volume L */
0x00C0, /* R67 - ADC Digital Volume R */
0x0000, /* R68 - ADC Divider */
0x0000, /* R69 */
0x0040, /* R70 - ADC LR Rate */
0x0000, /* R71 */
0x0303, /* R72 - Input Control */
0x0000, /* R73 - IN3 Input Control */
0x0000, /* R74 - Mic Bias Control */
0x0000, /* R75 */
0x0000, /* R76 - Output Control */
0x0000, /* R77 - Jack Detect */
0x0000, /* R78 - Anti Pop Control */
0x0000, /* R79 */
0x0040, /* R80 - Left Input Volume */
0x0040, /* R81 - Right Input Volume */
0x0000, /* R82 */
0x0000, /* R83 */
0x0000, /* R84 */
0x0000, /* R85 */
0x0000, /* R86 */
0x0000, /* R87 */
0x0800, /* R88 - Left Mixer Control */
0x1000, /* R89 - Right Mixer Control */
0x0000, /* R90 */
0x0000, /* R91 */
0x0000, /* R92 - OUT3 Mixer Control */
0x0000, /* R93 - OUT4 Mixer Control */
0x0000, /* R94 */
0x0000, /* R95 */
0x0000, /* R96 - Output Left Mixer Volume */
0x0000, /* R97 - Output Right Mixer Volume */
0x0000, /* R98 - Input Mixer Volume L */
0x0000, /* R99 - Input Mixer Volume R */
0x0000, /* R100 - Input Mixer Volume */
0x0000, /* R101 */
0x0000, /* R102 */
0x0000, /* R103 */
0x00E4, /* R104 - OUT1L Volume */
0x00E4, /* R105 - OUT1R Volume */
0x00E4, /* R106 - OUT2L Volume */
0x02E4, /* R107 - OUT2R Volume */
0x0000, /* R108 */
0x0000, /* R109 */
0x0000, /* R110 */
0x0000, /* R111 - BEEP Volume */
0x0A00, /* R112 - AI Formating */
0x0000, /* R113 - ADC DAC COMP */
0x0020, /* R114 - AI ADC Control */
0x0020, /* R115 - AI DAC Control */
0x0000, /* R116 */
0x0000, /* R117 */
0x0000, /* R118 */
0x0000, /* R119 */
0x0000, /* R120 */
0x0000, /* R121 */
0x0000, /* R122 */
0x0000, /* R123 */
0x0000, /* R124 */
0x0000, /* R125 */
0x0000, /* R126 */
0x0000, /* R127 */
0x1FFF, /* R128 - GPIO Debounce */
0x0010, /* R129 - GPIO Pin pull up Control */
0x0000, /* R130 - GPIO Pull down Control */
0x0000, /* R131 - GPIO Interrupt Mode */
0x0000, /* R132 */
0x0000, /* R133 - GPIO Control */
0x0BFB, /* R134 - GPIO Configuration (i/o) */
0x0FFD, /* R135 - GPIO Pin Polarity / Type */
0x0000, /* R136 */
0x0000, /* R137 */
0x0000, /* R138 */
0x0000, /* R139 */
0x0310, /* R140 - GPIO Function Select 1 */
0x0001, /* R141 - GPIO Function Select 2 */
0x2300, /* R142 - GPIO Function Select 3 */
0x0003, /* R143 - GPIO Function Select 4 */
0x0000, /* R144 - Digitiser Control (1) */
0x0002, /* R145 - Digitiser Control (2) */
0x0000, /* R146 */
0x0000, /* R147 */
0x0000, /* R148 */
0x0000, /* R149 */
0x0000, /* R150 */
0x0000, /* R151 */
0x7000, /* R152 - AUX1 Readback */
0x7000, /* R153 - AUX2 Readback */
0x7000, /* R154 - AUX3 Readback */
0x7000, /* R155 - AUX4 Readback */
0x0000, /* R156 - USB Voltage Readback */
0x0000, /* R157 - LINE Voltage Readback */
0x0000, /* R158 - BATT Voltage Readback */
0x0000, /* R159 - Chip Temp Readback */
0x0000, /* R160 */
0x0000, /* R161 */
0x0000, /* R162 */
0x0000, /* R163 - Generic Comparator Control */
0x0000, /* R164 - Generic comparator 1 */
0x0000, /* R165 - Generic comparator 2 */
0x0000, /* R166 - Generic comparator 3 */
0x0000, /* R167 - Generic comparator 4 */
0xA00F, /* R168 - Battery Charger Control 1 */
0x0B06, /* R169 - Battery Charger Control 2 */
0x0000, /* R170 - Battery Charger Control 3 */
0x0000, /* R171 */
0x0000, /* R172 - Current Sink Driver A */
0x0000, /* R173 - CSA Flash control */
0x0000, /* R174 */
0x0000, /* R175 */
0x0000, /* R176 - DCDC/LDO requested */
0x032D, /* R177 - DCDC Active options */
0x0000, /* R178 - DCDC Sleep options */
0x0025, /* R179 - Power-check comparator */
0x000E, /* R180 - DCDC1 Control */
0x0400, /* R181 - DCDC1 Timeouts */
0x1006, /* R182 - DCDC1 Low Power */
0x0018, /* R183 - DCDC2 Control */
0x0000, /* R184 - DCDC2 Timeouts */
0x0000, /* R185 */
0x0026, /* R186 - DCDC3 Control */
0x0800, /* R187 - DCDC3 Timeouts */
0x0006, /* R188 - DCDC3 Low Power */
0x0062, /* R189 - DCDC4 Control */
0x1400, /* R190 - DCDC4 Timeouts */
0x0006, /* R191 - DCDC4 Low Power */
0x0008, /* R192 */
0x0000, /* R193 */
0x0000, /* R194 */
0x0026, /* R195 */
0x0400, /* R196 */
0x0006, /* R197 */
0x0000, /* R198 */
0x0003, /* R199 - Limit Switch Control */
0x0006, /* R200 - LDO1 Control */
0x0C00, /* R201 - LDO1 Timeouts */
0x001C, /* R202 - LDO1 Low Power */
0x0016, /* R203 - LDO2 Control */
0x0000, /* R204 - LDO2 Timeouts */
0x001C, /* R205 - LDO2 Low Power */
0x0019, /* R206 - LDO3 Control */
0x0000, /* R207 - LDO3 Timeouts */
0x001C, /* R208 - LDO3 Low Power */
0x001A, /* R209 - LDO4 Control */
0x1000, /* R210 - LDO4 Timeouts */
0x001C, /* R211 - LDO4 Low Power */
0x0000, /* R212 */
0x0000, /* R213 */
0x0000, /* R214 */
0x0000, /* R215 - VCC_FAULT Masks */
0x001F, /* R216 - Main Bandgap Control */
0x0000, /* R217 - OSC Control */
0x9000, /* R218 - RTC Tick Control */
0x0000, /* R219 - Security1 */
0x4000, /* R220 */
0x0000, /* R221 */
0x0000, /* R222 */
0x0000, /* R223 */
0x0000, /* R224 - Signal overrides */
0x0000, /* R225 - DCDC/LDO status */
0x0000, /* R226 - Charger Overides/status */
0x0000, /* R227 - misc overrides */
0x0000, /* R228 - Supply overrides/status 1 */
0x0000, /* R229 - Supply overrides/status 2 */
0xE000, /* R230 - GPIO Pin Status */
0x0000, /* R231 - comparotor overrides */
0x0000, /* R232 */
0x0000, /* R233 - State Machine status */
0x1200, /* R234 - FLL Test 1 */
0x0000, /* R235 */
0x8000, /* R236 */
0x0000, /* R237 */
0x0000, /* R238 */
0x0000, /* R239 */
0x0003, /* R240 */
0x0000, /* R241 */
0x0000, /* R242 */
0x0004, /* R243 */
0x0300, /* R244 */
0x0000, /* R245 */
0x0200, /* R246 */
0x0000, /* R247 */
0x1000, /* R248 - DCDC1 Test Controls */
0x1000, /* R249 */
0x1000, /* R250 - DCDC3 Test Controls */
0x1000, /* R251 - DCDC4 Test Controls */
};
#endif
#ifdef CONFIG_MFD_WM8352_CONFIG_MODE_0
#undef WM8350_HAVE_CONFIG_MODE
#define WM8350_HAVE_CONFIG_MODE
const u16 wm8352_mode0_defaults[] = {
0x6143, /* R0 - Reset/ID */
0x0000, /* R1 - ID */
0x0002, /* R2 - Revision */
0x1C02, /* R3 - System Control 1 */
0x0004, /* R4 - System Control 2 */
0x0000, /* R5 - System Hibernate */
0x8A00, /* R6 - Interface Control */
0x0000, /* R7 */
0x8000, /* R8 - Power mgmt (1) */
0x0000, /* R9 - Power mgmt (2) */
0x0000, /* R10 - Power mgmt (3) */
0x2000, /* R11 - Power mgmt (4) */
0x0E00, /* R12 - Power mgmt (5) */
0x0000, /* R13 - Power mgmt (6) */
0x0000, /* R14 - Power mgmt (7) */
0x0000, /* R15 */
0x0000, /* R16 - RTC Seconds/Minutes */
0x0100, /* R17 - RTC Hours/Day */
0x0101, /* R18 - RTC Date/Month */
0x1400, /* R19 - RTC Year */
0x0000, /* R20 - Alarm Seconds/Minutes */
0x0000, /* R21 - Alarm Hours/Day */
0x0000, /* R22 - Alarm Date/Month */
0x0320, /* R23 - RTC Time Control */
0x0000, /* R24 - System Interrupts */
0x0000, /* R25 - Interrupt Status 1 */
0x0000, /* R26 - Interrupt Status 2 */
0x0000, /* R27 */
0x0000, /* R28 - Under Voltage Interrupt status */
0x0000, /* R29 - Over Current Interrupt status */
0x0000, /* R30 - GPIO Interrupt Status */
0x0000, /* R31 - Comparator Interrupt Status */
0x3FFF, /* R32 - System Interrupts Mask */
0x0000, /* R33 - Interrupt Status 1 Mask */
0x0000, /* R34 - Interrupt Status 2 Mask */
0x0000, /* R35 */
0x0000, /* R36 - Under Voltage Interrupt status Mask */
0x0000, /* R37 - Over Current Interrupt status Mask */
0x0000, /* R38 - GPIO Interrupt Status Mask */
0x0000, /* R39 - Comparator Interrupt Status Mask */
0x0040, /* R40 - Clock Control 1 */
0x0000, /* R41 - Clock Control 2 */
0x3A00, /* R42 - FLL Control 1 */
0x7086, /* R43 - FLL Control 2 */
0xC226, /* R44 - FLL Control 3 */
0x0000, /* R45 - FLL Control 4 */
0x0000, /* R46 */
0x0000, /* R47 */
0x0000, /* R48 - DAC Control */
0x0000, /* R49 */
0x00C0, /* R50 - DAC Digital Volume L */
0x00C0, /* R51 - DAC Digital Volume R */
0x0000, /* R52 */
0x0040, /* R53 - DAC LR Rate */
0x0000, /* R54 - DAC Clock Control */
0x0000, /* R55 */
0x0000, /* R56 */
0x0000, /* R57 */
0x4000, /* R58 - DAC Mute */
0x0000, /* R59 - DAC Mute Volume */
0x0000, /* R60 - DAC Side */
0x0000, /* R61 */
0x0000, /* R62 */
0x0000, /* R63 */
0x8000, /* R64 - ADC Control */
0x0000, /* R65 */
0x00C0, /* R66 - ADC Digital Volume L */
0x00C0, /* R67 - ADC Digital Volume R */
0x0000, /* R68 - ADC Divider */
0x0000, /* R69 */
0x0040, /* R70 - ADC LR Rate */
0x0000, /* R71 */
0x0303, /* R72 - Input Control */
0x0000, /* R73 - IN3 Input Control */
0x0000, /* R74 - Mic Bias Control */
0x0000, /* R75 */
0x0000, /* R76 - Output Control */
0x0000, /* R77 - Jack Detect */
0x0000, /* R78 - Anti Pop Control */
0x0000, /* R79 */
0x0040, /* R80 - Left Input Volume */
0x0040, /* R81 - Right Input Volume */
0x0000, /* R82 */
0x0000, /* R83 */
0x0000, /* R84 */
0x0000, /* R85 */
0x0000, /* R86 */
0x0000, /* R87 */
0x0800, /* R88 - Left Mixer Control */
0x1000, /* R89 - Right Mixer Control */
0x0000, /* R90 */
0x0000, /* R91 */
0x0000, /* R92 - OUT3 Mixer Control */
0x0000, /* R93 - OUT4 Mixer Control */
0x0000, /* R94 */
0x0000, /* R95 */
0x0000, /* R96 - Output Left Mixer Volume */
0x0000, /* R97 - Output Right Mixer Volume */
0x0000, /* R98 - Input Mixer Volume L */
0x0000, /* R99 - Input Mixer Volume R */
0x0000, /* R100 - Input Mixer Volume */
0x0000, /* R101 */
0x0000, /* R102 */
0x0000, /* R103 */
0x00E4, /* R104 - OUT1L Volume */
0x00E4, /* R105 - OUT1R Volume */
0x00E4, /* R106 - OUT2L Volume */
0x02E4, /* R107 - OUT2R Volume */
0x0000, /* R108 */
0x0000, /* R109 */
0x0000, /* R110 */
0x0000, /* R111 - BEEP Volume */
0x0A00, /* R112 - AI Formating */
0x0000, /* R113 - ADC DAC COMP */
0x0020, /* R114 - AI ADC Control */
0x0020, /* R115 - AI DAC Control */
0x0000, /* R116 */
0x0000, /* R117 */
0x0000, /* R118 */
0x0000, /* R119 */
0x0000, /* R120 */
0x0000, /* R121 */
0x0000, /* R122 */
0x0000, /* R123 */
0x0000, /* R124 */
0x0000, /* R125 */
0x0000, /* R126 */
0x0000, /* R127 */
0x1FFF, /* R128 - GPIO Debounce */
0x0000, /* R129 - GPIO Pin pull up Control */
0x0000, /* R130 - GPIO Pull down Control */
0x0000, /* R131 - GPIO Interrupt Mode */
0x0000, /* R132 */
0x0000, /* R133 - GPIO Control */
0x0FFC, /* R134 - GPIO Configuration (i/o) */
0x0FFC, /* R135 - GPIO Pin Polarity / Type */
0x0000, /* R136 */
0x0000, /* R137 */
0x0000, /* R138 */
0x0000, /* R139 */
0x0013, /* R140 - GPIO Function Select 1 */
0x0000, /* R141 - GPIO Function Select 2 */
0x0000, /* R142 - GPIO Function Select 3 */
0x0003, /* R143 - GPIO Function Select 4 */
0x0000, /* R144 - Digitiser Control (1) */
0x0002, /* R145 - Digitiser Control (2) */
0x0000, /* R146 */
0x0000, /* R147 */
0x0000, /* R148 */
0x0000, /* R149 */
0x0000, /* R150 */
0x0000, /* R151 */
0x7000, /* R152 - AUX1 Readback */
0x7000, /* R153 - AUX2 Readback */
0x7000, /* R154 - AUX3 Readback */
0x7000, /* R155 - AUX4 Readback */
0x0000, /* R156 - USB Voltage Readback */
0x0000, /* R157 - LINE Voltage Readback */
0x0000, /* R158 - BATT Voltage Readback */
0x0000, /* R159 - Chip Temp Readback */
0x0000, /* R160 */
0x0000, /* R161 */
0x0000, /* R162 */
0x0000, /* R163 - Generic Comparator Control */
0x0000, /* R164 - Generic comparator 1 */
0x0000, /* R165 - Generic comparator 2 */
0x0000, /* R166 - Generic comparator 3 */
0x0000, /* R167 - Generic comparator 4 */
0xA00F, /* R168 - Battery Charger Control 1 */
0x0B06, /* R169 - Battery Charger Control 2 */
0x0000, /* R170 - Battery Charger Control 3 */
0x0000, /* R171 */
0x0000, /* R172 - Current Sink Driver A */
0x0000, /* R173 - CSA Flash control */
0x0000, /* R174 - Current Sink Driver B */
0x0000, /* R175 - CSB Flash control */
0x0000, /* R176 - DCDC/LDO requested */
0x032D, /* R177 - DCDC Active options */
0x0000, /* R178 - DCDC Sleep options */
0x0025, /* R179 - Power-check comparator */
0x000E, /* R180 - DCDC1 Control */
0x0000, /* R181 - DCDC1 Timeouts */
0x1006, /* R182 - DCDC1 Low Power */
0x0018, /* R183 - DCDC2 Control */
0x0000, /* R184 - DCDC2 Timeouts */
0x0000, /* R185 */
0x0000, /* R186 - DCDC3 Control */
0x0000, /* R187 - DCDC3 Timeouts */
0x0006, /* R188 - DCDC3 Low Power */
0x0000, /* R189 - DCDC4 Control */
0x0000, /* R190 - DCDC4 Timeouts */
0x0006, /* R191 - DCDC4 Low Power */
0x0008, /* R192 - DCDC5 Control */
0x0000, /* R193 - DCDC5 Timeouts */
0x0000, /* R194 */
0x0000, /* R195 - DCDC6 Control */
0x0000, /* R196 - DCDC6 Timeouts */
0x0006, /* R197 - DCDC6 Low Power */
0x0000, /* R198 */
0x0003, /* R199 - Limit Switch Control */
0x001C, /* R200 - LDO1 Control */
0x0000, /* R201 - LDO1 Timeouts */
0x001C, /* R202 - LDO1 Low Power */
0x001B, /* R203 - LDO2 Control */
0x0000, /* R204 - LDO2 Timeouts */
0x001C, /* R205 - LDO2 Low Power */
0x001B, /* R206 - LDO3 Control */
0x0000, /* R207 - LDO3 Timeouts */
0x001C, /* R208 - LDO3 Low Power */
0x001B, /* R209 - LDO4 Control */
0x0000, /* R210 - LDO4 Timeouts */
0x001C, /* R211 - LDO4 Low Power */
0x0000, /* R212 */
0x0000, /* R213 */
0x0000, /* R214 */
0x0000, /* R215 - VCC_FAULT Masks */
0x001F, /* R216 - Main Bandgap Control */
0x0000, /* R217 - OSC Control */
0x9000, /* R218 - RTC Tick Control */
0x0000, /* R219 - Security1 */
0x4000, /* R220 */
0x0000, /* R221 */
0x0000, /* R222 */
0x0000, /* R223 */
0x0000, /* R224 - Signal overrides */
0x0000, /* R225 - DCDC/LDO status */
0x0000, /* R226 - Charger Overides/status */
0x0000, /* R227 - misc overrides */
0x0000, /* R228 - Supply overrides/status 1 */
0x0000, /* R229 - Supply overrides/status 2 */
0xE000, /* R230 - GPIO Pin Status */
0x0000, /* R231 - comparotor overrides */
0x0000, /* R232 */
0x0000, /* R233 - State Machine status */
0x1200, /* R234 */
0x0000, /* R235 */
0x8000, /* R236 */
0x0000, /* R237 */
0x0000, /* R238 */
0x0000, /* R239 */
0x0003, /* R240 */
0x0000, /* R241 */
0x0000, /* R242 */
0x0004, /* R243 */
0x0300, /* R244 */
0x0000, /* R245 */
0x0200, /* R246 */
0x0000, /* R247 */
0x1000, /* R248 - DCDC1 Test Controls */
0x5000, /* R249 */
0x1000, /* R250 - DCDC3 Test Controls */
0x1000, /* R251 - DCDC4 Test Controls */
0x5100, /* R252 */
0x1000, /* R253 - DCDC6 Test Controls */
};
#endif
#ifdef CONFIG_MFD_WM8352_CONFIG_MODE_1
#undef WM8350_HAVE_CONFIG_MODE
#define WM8350_HAVE_CONFIG_MODE
const u16 wm8352_mode1_defaults[] = {
0x6143, /* R0 - Reset/ID */
0x0000, /* R1 - ID */
0x0002, /* R2 - Revision */
0x1C02, /* R3 - System Control 1 */
0x0204, /* R4 - System Control 2 */
0x0000, /* R5 - System Hibernate */
0x8A00, /* R6 - Interface Control */
0x0000, /* R7 */
0x8000, /* R8 - Power mgmt (1) */
0x0000, /* R9 - Power mgmt (2) */
0x0000, /* R10 - Power mgmt (3) */
0x2000, /* R11 - Power mgmt (4) */
0x0E00, /* R12 - Power mgmt (5) */
0x0000, /* R13 - Power mgmt (6) */
0x0000, /* R14 - Power mgmt (7) */
0x0000, /* R15 */
0x0000, /* R16 - RTC Seconds/Minutes */
0x0100, /* R17 - RTC Hours/Day */
0x0101, /* R18 - RTC Date/Month */
0x1400, /* R19 - RTC Year */
0x0000, /* R20 - Alarm Seconds/Minutes */
0x0000, /* R21 - Alarm Hours/Day */
0x0000, /* R22 - Alarm Date/Month */
0x0320, /* R23 - RTC Time Control */
0x0000, /* R24 - System Interrupts */
0x0000, /* R25 - Interrupt Status 1 */
0x0000, /* R26 - Interrupt Status 2 */
0x0000, /* R27 */
0x0000, /* R28 - Under Voltage Interrupt status */
0x0000, /* R29 - Over Current Interrupt status */
0x0000, /* R30 - GPIO Interrupt Status */
0x0000, /* R31 - Comparator Interrupt Status */
0x3FFF, /* R32 - System Interrupts Mask */
0x0000, /* R33 - Interrupt Status 1 Mask */
0x0000, /* R34 - Interrupt Status 2 Mask */
0x0000, /* R35 */
0x0000, /* R36 - Under Voltage Interrupt status Mask */
0x0000, /* R37 - Over Current Interrupt status Mask */
0x0000, /* R38 - GPIO Interrupt Status Mask */
0x0000, /* R39 - Comparator Interrupt Status Mask */
0x0040, /* R40 - Clock Control 1 */
0x0000, /* R41 - Clock Control 2 */
0x3A00, /* R42 - FLL Control 1 */
0x7086, /* R43 - FLL Control 2 */
0xC226, /* R44 - FLL Control 3 */
0x0000, /* R45 - FLL Control 4 */
0x0000, /* R46 */
0x0000, /* R47 */
0x0000, /* R48 - DAC Control */
0x0000, /* R49 */
0x00C0, /* R50 - DAC Digital Volume L */
0x00C0, /* R51 - DAC Digital Volume R */
0x0000, /* R52 */
0x0040, /* R53 - DAC LR Rate */
0x0000, /* R54 - DAC Clock Control */
0x0000, /* R55 */
0x0000, /* R56 */
0x0000, /* R57 */
0x4000, /* R58 - DAC Mute */
0x0000, /* R59 - DAC Mute Volume */
0x0000, /* R60 - DAC Side */
0x0000, /* R61 */
0x0000, /* R62 */
0x0000, /* R63 */
0x8000, /* R64 - ADC Control */
0x0000, /* R65 */
0x00C0, /* R66 - ADC Digital Volume L */
0x00C0, /* R67 - ADC Digital Volume R */
0x0000, /* R68 - ADC Divider */
0x0000, /* R69 */
0x0040, /* R70 - ADC LR Rate */
0x0000, /* R71 */
0x0303, /* R72 - Input Control */
0x0000, /* R73 - IN3 Input Control */
0x0000, /* R74 - Mic Bias Control */
0x0000, /* R75 */
0x0000, /* R76 - Output Control */
0x0000, /* R77 - Jack Detect */
0x0000, /* R78 - Anti Pop Control */
0x0000, /* R79 */
0x0040, /* R80 - Left Input Volume */
0x0040, /* R81 - Right Input Volume */
0x0000, /* R82 */
0x0000, /* R83 */
0x0000, /* R84 */
0x0000, /* R85 */
0x0000, /* R86 */
0x0000, /* R87 */
0x0800, /* R88 - Left Mixer Control */
0x1000, /* R89 - Right Mixer Control */
0x0000, /* R90 */
0x0000, /* R91 */
0x0000, /* R92 - OUT3 Mixer Control */
0x0000, /* R93 - OUT4 Mixer Control */
0x0000, /* R94 */
0x0000, /* R95 */
0x0000, /* R96 - Output Left Mixer Volume */
0x0000, /* R97 - Output Right Mixer Volume */
0x0000, /* R98 - Input Mixer Volume L */
0x0000, /* R99 - Input Mixer Volume R */
0x0000, /* R100 - Input Mixer Volume */
0x0000, /* R101 */
0x0000, /* R102 */
0x0000, /* R103 */
0x00E4, /* R104 - OUT1L Volume */
0x00E4, /* R105 - OUT1R Volume */
0x00E4, /* R106 - OUT2L Volume */
0x02E4, /* R107 - OUT2R Volume */
0x0000, /* R108 */
0x0000, /* R109 */
0x0000, /* R110 */
0x0000, /* R111 - BEEP Volume */
0x0A00, /* R112 - AI Formating */
0x0000, /* R113 - ADC DAC COMP */
0x0020, /* R114 - AI ADC Control */
0x0020, /* R115 - AI DAC Control */
0x0000, /* R116 */
0x0000, /* R117 */
0x0000, /* R118 */
0x0000, /* R119 */
0x0000, /* R120 */
0x0000, /* R121 */
0x0000, /* R122 */
0x0000, /* R123 */
0x0000, /* R124 */
0x0000, /* R125 */
0x0000, /* R126 */
0x0000, /* R127 */
0x1FFF, /* R128 - GPIO Debounce */
0x0000, /* R129 - GPIO Pin pull up Control */
0x0000, /* R130 - GPIO Pull down Control */
0x0000, /* R131 - GPIO Interrupt Mode */
0x0000, /* R132 */
0x0000, /* R133 - GPIO Control */
0x0BFB, /* R134 - GPIO Configuration (i/o) */
0x0FFF, /* R135 - GPIO Pin Polarity / Type */
0x0000, /* R136 */
0x0000, /* R137 */
0x0000, /* R138 */
0x0000, /* R139 */
0x0300, /* R140 - GPIO Function Select 1 */
0x0000, /* R141 - GPIO Function Select 2 */
0x2300, /* R142 - GPIO Function Select 3 */
0x0003, /* R143 - GPIO Function Select 4 */
0x0000, /* R144 - Digitiser Control (1) */
0x0002, /* R145 - Digitiser Control (2) */
0x0000, /* R146 */
0x0000, /* R147 */
0x0000, /* R148 */
0x0000, /* R149 */
0x0000, /* R150 */
0x0000, /* R151 */
0x7000, /* R152 - AUX1 Readback */
0x7000, /* R153 - AUX2 Readback */
0x7000, /* R154 - AUX3 Readback */
0x7000, /* R155 - AUX4 Readback */
0x0000, /* R156 - USB Voltage Readback */
0x0000, /* R157 - LINE Voltage Readback */
0x0000, /* R158 - BATT Voltage Readback */
0x0000, /* R159 - Chip Temp Readback */
0x0000, /* R160 */
0x0000, /* R161 */
0x0000, /* R162 */
0x0000, /* R163 - Generic Comparator Control */
0x0000, /* R164 - Generic comparator 1 */
0x0000, /* R165 - Generic comparator 2 */
0x0000, /* R166 - Generic comparator 3 */
0x0000, /* R167 - Generic comparator 4 */
0xA00F, /* R168 - Battery Charger Control 1 */
0x0B06, /* R169 - Battery Charger Control 2 */
0x0000, /* R170 - Battery Charger Control 3 */
0x0000, /* R171 */
0x0000, /* R172 - Current Sink Driver A */
0x0000, /* R173 - CSA Flash control */
0x0000, /* R174 - Current Sink Driver B */
0x0000, /* R175 - CSB Flash control */
0x0000, /* R176 - DCDC/LDO requested */
0x032D, /* R177 - DCDC Active options */
0x0000, /* R178 - DCDC Sleep options */
0x0025, /* R179 - Power-check comparator */
0x0062, /* R180 - DCDC1 Control */
0x0400, /* R181 - DCDC1 Timeouts */
0x1006, /* R182 - DCDC1 Low Power */
0x0018, /* R183 - DCDC2 Control */
0x0000, /* R184 - DCDC2 Timeouts */
0x0000, /* R185 */
0x0006, /* R186 - DCDC3 Control */
0x0800, /* R187 - DCDC3 Timeouts */
0x0006, /* R188 - DCDC3 Low Power */
0x0006, /* R189 - DCDC4 Control */
0x0C00, /* R190 - DCDC4 Timeouts */
0x0006, /* R191 - DCDC4 Low Power */
0x0008, /* R192 - DCDC5 Control */
0x0000, /* R193 - DCDC5 Timeouts */
0x0000, /* R194 */
0x0026, /* R195 - DCDC6 Control */
0x1000, /* R196 - DCDC6 Timeouts */
0x0006, /* R197 - DCDC6 Low Power */
0x0000, /* R198 */
0x0003, /* R199 - Limit Switch Control */
0x0002, /* R200 - LDO1 Control */
0x0000, /* R201 - LDO1 Timeouts */
0x001C, /* R202 - LDO1 Low Power */
0x001A, /* R203 - LDO2 Control */
0x0000, /* R204 - LDO2 Timeouts */
0x001C, /* R205 - LDO2 Low Power */
0x001F, /* R206 - LDO3 Control */
0x0000, /* R207 - LDO3 Timeouts */
0x001C, /* R208 - LDO3 Low Power */
0x001F, /* R209 - LDO4 Control */
0x0000, /* R210 - LDO4 Timeouts */
0x001C, /* R211 - LDO4 Low Power */
0x0000, /* R212 */
0x0000, /* R213 */
0x0000, /* R214 */
0x0000, /* R215 - VCC_FAULT Masks */
0x001F, /* R216 - Main Bandgap Control */
0x0000, /* R217 - OSC Control */
0x9000, /* R218 - RTC Tick Control */
0x0000, /* R219 - Security1 */
0x4000, /* R220 */
0x0000, /* R221 */
0x0000, /* R222 */
0x0000, /* R223 */
0x0000, /* R224 - Signal overrides */
0x0000, /* R225 - DCDC/LDO status */
0x0000, /* R226 - Charger Overides/status */
0x0000, /* R227 - misc overrides */
0x0000, /* R228 - Supply overrides/status 1 */
0x0000, /* R229 - Supply overrides/status 2 */
0xE000, /* R230 - GPIO Pin Status */
0x0000, /* R231 - comparotor overrides */
0x0000, /* R232 */
0x0000, /* R233 - State Machine status */
0x1200, /* R234 */
0x0000, /* R235 */
0x8000, /* R236 */
0x0000, /* R237 */
0x0000, /* R238 */
0x0000, /* R239 */
0x0003, /* R240 */
0x0000, /* R241 */
0x0000, /* R242 */
0x0004, /* R243 */
0x0300, /* R244 */
0x0000, /* R245 */
0x0200, /* R246 */
0x0000, /* R247 */
0x1000, /* R248 - DCDC1 Test Controls */
0x5000, /* R249 */
0x1000, /* R250 - DCDC3 Test Controls */
0x1000, /* R251 - DCDC4 Test Controls */
0x5100, /* R252 */
0x1000, /* R253 - DCDC6 Test Controls */
};
#endif
#ifdef CONFIG_MFD_WM8352_CONFIG_MODE_2
#undef WM8350_HAVE_CONFIG_MODE
#define WM8350_HAVE_CONFIG_MODE
const u16 wm8352_mode2_defaults[] = {
0x6143, /* R0 - Reset/ID */
0x0000, /* R1 - ID */
0x0002, /* R2 - Revision */
0x1C02, /* R3 - System Control 1 */
0x0204, /* R4 - System Control 2 */
0x0000, /* R5 - System Hibernate */
0x8A00, /* R6 - Interface Control */
0x0000, /* R7 */
0x8000, /* R8 - Power mgmt (1) */
0x0000, /* R9 - Power mgmt (2) */
0x0000, /* R10 - Power mgmt (3) */
0x2000, /* R11 - Power mgmt (4) */
0x0E00, /* R12 - Power mgmt (5) */
0x0000, /* R13 - Power mgmt (6) */
0x0000, /* R14 - Power mgmt (7) */
0x0000, /* R15 */
0x0000, /* R16 - RTC Seconds/Minutes */
0x0100, /* R17 - RTC Hours/Day */
0x0101, /* R18 - RTC Date/Month */
0x1400, /* R19 - RTC Year */
0x0000, /* R20 - Alarm Seconds/Minutes */
0x0000, /* R21 - Alarm Hours/Day */
0x0000, /* R22 - Alarm Date/Month */
0x0320, /* R23 - RTC Time Control */
0x0000, /* R24 - System Interrupts */
0x0000, /* R25 - Interrupt Status 1 */
0x0000, /* R26 - Interrupt Status 2 */
0x0000, /* R27 */
0x0000, /* R28 - Under Voltage Interrupt status */
0x0000, /* R29 - Over Current Interrupt status */
0x0000, /* R30 - GPIO Interrupt Status */
0x0000, /* R31 - Comparator Interrupt Status */
0x3FFF, /* R32 - System Interrupts Mask */
0x0000, /* R33 - Interrupt Status 1 Mask */
0x0000, /* R34 - Interrupt Status 2 Mask */
0x0000, /* R35 */
0x0000, /* R36 - Under Voltage Interrupt status Mask */
0x0000, /* R37 - Over Current Interrupt status Mask */
0x0000, /* R38 - GPIO Interrupt Status Mask */
0x0000, /* R39 - Comparator Interrupt Status Mask */
0x0040, /* R40 - Clock Control 1 */
0x0000, /* R41 - Clock Control 2 */
0x3A00, /* R42 - FLL Control 1 */
0x7086, /* R43 - FLL Control 2 */
0xC226, /* R44 - FLL Control 3 */
0x0000, /* R45 - FLL Control 4 */
0x0000, /* R46 */
0x0000, /* R47 */
0x0000, /* R48 - DAC Control */
0x0000, /* R49 */
0x00C0, /* R50 - DAC Digital Volume L */
0x00C0, /* R51 - DAC Digital Volume R */
0x0000, /* R52 */
0x0040, /* R53 - DAC LR Rate */
0x0000, /* R54 - DAC Clock Control */
0x0000, /* R55 */
0x0000, /* R56 */
0x0000, /* R57 */
0x4000, /* R58 - DAC Mute */
0x0000, /* R59 - DAC Mute Volume */
0x0000, /* R60 - DAC Side */
0x0000, /* R61 */
0x0000, /* R62 */
0x0000, /* R63 */
0x8000, /* R64 - ADC Control */
0x0000, /* R65 */
0x00C0, /* R66 - ADC Digital Volume L */
0x00C0, /* R67 - ADC Digital Volume R */
0x0000, /* R68 - ADC Divider */
0x0000, /* R69 */
0x0040, /* R70 - ADC LR Rate */
0x0000, /* R71 */
0x0303, /* R72 - Input Control */
0x0000, /* R73 - IN3 Input Control */
0x0000, /* R74 - Mic Bias Control */
0x0000, /* R75 */
0x0000, /* R76 - Output Control */
0x0000, /* R77 - Jack Detect */
0x0000, /* R78 - Anti Pop Control */
0x0000, /* R79 */
0x0040, /* R80 - Left Input Volume */
0x0040, /* R81 - Right Input Volume */
0x0000, /* R82 */
0x0000, /* R83 */
0x0000, /* R84 */
0x0000, /* R85 */
0x0000, /* R86 */
0x0000, /* R87 */
0x0800, /* R88 - Left Mixer Control */
0x1000, /* R89 - Right Mixer Control */
0x0000, /* R90 */
0x0000, /* R91 */
0x0000, /* R92 - OUT3 Mixer Control */
0x0000, /* R93 - OUT4 Mixer Control */
0x0000, /* R94 */
0x0000, /* R95 */
0x0000, /* R96 - Output Left Mixer Volume */
0x0000, /* R97 - Output Right Mixer Volume */
0x0000, /* R98 - Input Mixer Volume L */
0x0000, /* R99 - Input Mixer Volume R */
0x0000, /* R100 - Input Mixer Volume */
0x0000, /* R101 */
0x0000, /* R102 */
0x0000, /* R103 */
0x00E4, /* R104 - OUT1L Volume */
0x00E4, /* R105 - OUT1R Volume */
0x00E4, /* R106 - OUT2L Volume */
0x02E4, /* R107 - OUT2R Volume */
0x0000, /* R108 */
0x0000, /* R109 */
0x0000, /* R110 */
0x0000, /* R111 - BEEP Volume */
0x0A00, /* R112 - AI Formating */
0x0000, /* R113 - ADC DAC COMP */
0x0020, /* R114 - AI ADC Control */
0x0020, /* R115 - AI DAC Control */
0x0000, /* R116 */
0x0000, /* R117 */
0x0000, /* R118 */
0x0000, /* R119 */
0x0000, /* R120 */
0x0000, /* R121 */
0x0000, /* R122 */
0x0000, /* R123 */
0x0000, /* R124 */
0x0000, /* R125 */
0x0000, /* R126 */
0x0000, /* R127 */
0x1FFF, /* R128 - GPIO Debounce */
0x0000, /* R129 - GPIO Pin pull up Control */
0x0110, /* R130 - GPIO Pull down Control */
0x0000, /* R131 - GPIO Interrupt Mode */
0x0000, /* R132 */
0x0000, /* R133 - GPIO Control */
0x09DA, /* R134 - GPIO Configuration (i/o) */
0x0DD6, /* R135 - GPIO Pin Polarity / Type */
0x0000, /* R136 */
0x0000, /* R137 */
0x0000, /* R138 */
0x0000, /* R139 */
0x1310, /* R140 - GPIO Function Select 1 */
0x0033, /* R141 - GPIO Function Select 2 */
0x2000, /* R142 - GPIO Function Select 3 */
0x0000, /* R143 - GPIO Function Select 4 */
0x0000, /* R144 - Digitiser Control (1) */
0x0002, /* R145 - Digitiser Control (2) */
0x0000, /* R146 */
0x0000, /* R147 */
0x0000, /* R148 */
0x0000, /* R149 */
0x0000, /* R150 */
0x0000, /* R151 */
0x7000, /* R152 - AUX1 Readback */
0x7000, /* R153 - AUX2 Readback */
0x7000, /* R154 - AUX3 Readback */
0x7000, /* R155 - AUX4 Readback */
0x0000, /* R156 - USB Voltage Readback */
0x0000, /* R157 - LINE Voltage Readback */
0x0000, /* R158 - BATT Voltage Readback */
0x0000, /* R159 - Chip Temp Readback */
0x0000, /* R160 */
0x0000, /* R161 */
0x0000, /* R162 */
0x0000, /* R163 - Generic Comparator Control */
0x0000, /* R164 - Generic comparator 1 */
0x0000, /* R165 - Generic comparator 2 */
0x0000, /* R166 - Generic comparator 3 */
0x0000, /* R167 - Generic comparator 4 */
0xA00F, /* R168 - Battery Charger Control 1 */
0x0B06, /* R169 - Battery Charger Control 2 */
0x0000, /* R170 - Battery Charger Control 3 */
0x0000, /* R171 */
0x0000, /* R172 - Current Sink Driver A */
0x0000, /* R173 - CSA Flash control */
0x0000, /* R174 - Current Sink Driver B */
0x0000, /* R175 - CSB Flash control */
0x0000, /* R176 - DCDC/LDO requested */
0x032D, /* R177 - DCDC Active options */
0x0000, /* R178 - DCDC Sleep options */
0x0025, /* R179 - Power-check comparator */
0x000E, /* R180 - DCDC1 Control */
0x0800, /* R181 - DCDC1 Timeouts */
0x1006, /* R182 - DCDC1 Low Power */
0x0018, /* R183 - DCDC2 Control */
0x0000, /* R184 - DCDC2 Timeouts */
0x0000, /* R185 */
0x0056, /* R186 - DCDC3 Control */
0x1800, /* R187 - DCDC3 Timeouts */
0x0006, /* R188 - DCDC3 Low Power */
0x000E, /* R189 - DCDC4 Control */
0x1000, /* R190 - DCDC4 Timeouts */
0x0006, /* R191 - DCDC4 Low Power */
0x0008, /* R192 - DCDC5 Control */
0x0000, /* R193 - DCDC5 Timeouts */
0x0000, /* R194 */
0x0026, /* R195 - DCDC6 Control */
0x0C00, /* R196 - DCDC6 Timeouts */
0x0006, /* R197 - DCDC6 Low Power */
0x0000, /* R198 */
0x0003, /* R199 - Limit Switch Control */
0x001C, /* R200 - LDO1 Control */
0x0000, /* R201 - LDO1 Timeouts */
0x001C, /* R202 - LDO1 Low Power */
0x0006, /* R203 - LDO2 Control */
0x0400, /* R204 - LDO2 Timeouts */
0x001C, /* R205 - LDO2 Low Power */
0x001C, /* R206 - LDO3 Control */
0x1400, /* R207 - LDO3 Timeouts */
0x001C, /* R208 - LDO3 Low Power */
0x001A, /* R209 - LDO4 Control */
0x0000, /* R210 - LDO4 Timeouts */
0x001C, /* R211 - LDO4 Low Power */
0x0000, /* R212 */
0x0000, /* R213 */
0x0000, /* R214 */
0x0000, /* R215 - VCC_FAULT Masks */
0x001F, /* R216 - Main Bandgap Control */
0x0000, /* R217 - OSC Control */
0x9000, /* R218 - RTC Tick Control */
0x0000, /* R219 - Security1 */
0x4000, /* R220 */
0x0000, /* R221 */
0x0000, /* R222 */
0x0000, /* R223 */
0x0000, /* R224 - Signal overrides */
0x0000, /* R225 - DCDC/LDO status */
0x0000, /* R226 - Charger Overides/status */
0x0000, /* R227 - misc overrides */
0x0000, /* R228 - Supply overrides/status 1 */
0x0000, /* R229 - Supply overrides/status 2 */
0xE000, /* R230 - GPIO Pin Status */
0x0000, /* R231 - comparotor overrides */
0x0000, /* R232 */
0x0000, /* R233 - State Machine status */
0x1200, /* R234 */
0x0000, /* R235 */
0x8000, /* R236 */
0x0000, /* R237 */
0x0000, /* R238 */
0x0000, /* R239 */
0x0003, /* R240 */
0x0000, /* R241 */
0x0000, /* R242 */
0x0004, /* R243 */
0x0300, /* R244 */
0x0000, /* R245 */
0x0200, /* R246 */
0x0000, /* R247 */
0x1000, /* R248 - DCDC1 Test Controls */
0x5000, /* R249 */
0x1000, /* R250 - DCDC3 Test Controls */
0x1000, /* R251 - DCDC4 Test Controls */
0x5100, /* R252 */
0x1000, /* R253 - DCDC6 Test Controls */
};
#endif
#ifdef CONFIG_MFD_WM8352_CONFIG_MODE_3
#undef WM8350_HAVE_CONFIG_MODE
#define WM8350_HAVE_CONFIG_MODE
const u16 wm8352_mode3_defaults[] = {
0x6143, /* R0 - Reset/ID */
0x0000, /* R1 - ID */
0x0002, /* R2 - Revision */
0x1C02, /* R3 - System Control 1 */
0x0204, /* R4 - System Control 2 */
0x0000, /* R5 - System Hibernate */
0x8A00, /* R6 - Interface Control */
0x0000, /* R7 */
0x8000, /* R8 - Power mgmt (1) */
0x0000, /* R9 - Power mgmt (2) */
0x0000, /* R10 - Power mgmt (3) */
0x2000, /* R11 - Power mgmt (4) */
0x0E00, /* R12 - Power mgmt (5) */
0x0000, /* R13 - Power mgmt (6) */
0x0000, /* R14 - Power mgmt (7) */
0x0000, /* R15 */
0x0000, /* R16 - RTC Seconds/Minutes */
0x0100, /* R17 - RTC Hours/Day */
0x0101, /* R18 - RTC Date/Month */
0x1400, /* R19 - RTC Year */
0x0000, /* R20 - Alarm Seconds/Minutes */
0x0000, /* R21 - Alarm Hours/Day */
0x0000, /* R22 - Alarm Date/Month */
0x0320, /* R23 - RTC Time Control */
0x0000, /* R24 - System Interrupts */
0x0000, /* R25 - Interrupt Status 1 */
0x0000, /* R26 - Interrupt Status 2 */
0x0000, /* R27 */
0x0000, /* R28 - Under Voltage Interrupt status */
0x0000, /* R29 - Over Current Interrupt status */
0x0000, /* R30 - GPIO Interrupt Status */
0x0000, /* R31 - Comparator Interrupt Status */
0x3FFF, /* R32 - System Interrupts Mask */
0x0000, /* R33 - Interrupt Status 1 Mask */
0x0000, /* R34 - Interrupt Status 2 Mask */
0x0000, /* R35 */
0x0000, /* R36 - Under Voltage Interrupt status Mask */
0x0000, /* R37 - Over Current Interrupt status Mask */
0x0000, /* R38 - GPIO Interrupt Status Mask */
0x0000, /* R39 - Comparator Interrupt Status Mask */
0x0040, /* R40 - Clock Control 1 */
0x0000, /* R41 - Clock Control 2 */
0x3A00, /* R42 - FLL Control 1 */
0x7086, /* R43 - FLL Control 2 */
0xC226, /* R44 - FLL Control 3 */
0x0000, /* R45 - FLL Control 4 */
0x0000, /* R46 */
0x0000, /* R47 */
0x0000, /* R48 - DAC Control */
0x0000, /* R49 */
0x00C0, /* R50 - DAC Digital Volume L */
0x00C0, /* R51 - DAC Digital Volume R */
0x0000, /* R52 */
0x0040, /* R53 - DAC LR Rate */
0x0000, /* R54 - DAC Clock Control */
0x0000, /* R55 */
0x0000, /* R56 */
0x0000, /* R57 */
0x4000, /* R58 - DAC Mute */
0x0000, /* R59 - DAC Mute Volume */
0x0000, /* R60 - DAC Side */
0x0000, /* R61 */
0x0000, /* R62 */
0x0000, /* R63 */
0x8000, /* R64 - ADC Control */
0x0000, /* R65 */
0x00C0, /* R66 - ADC Digital Volume L */
0x00C0, /* R67 - ADC Digital Volume R */
0x0000, /* R68 - ADC Divider */
0x0000, /* R69 */
0x0040, /* R70 - ADC LR Rate */
0x0000, /* R71 */
0x0303, /* R72 - Input Control */
0x0000, /* R73 - IN3 Input Control */
0x0000, /* R74 - Mic Bias Control */
0x0000, /* R75 */
0x0000, /* R76 - Output Control */
0x0000, /* R77 - Jack Detect */
0x0000, /* R78 - Anti Pop Control */
0x0000, /* R79 */
0x0040, /* R80 - Left Input Volume */
0x0040, /* R81 - Right Input Volume */
0x0000, /* R82 */
0x0000, /* R83 */
0x0000, /* R84 */
0x0000, /* R85 */
0x0000, /* R86 */
0x0000, /* R87 */
0x0800, /* R88 - Left Mixer Control */
0x1000, /* R89 - Right Mixer Control */
0x0000, /* R90 */
0x0000, /* R91 */
0x0000, /* R92 - OUT3 Mixer Control */
0x0000, /* R93 - OUT4 Mixer Control */
0x0000, /* R94 */
0x0000, /* R95 */
0x0000, /* R96 - Output Left Mixer Volume */
0x0000, /* R97 - Output Right Mixer Volume */
0x0000, /* R98 - Input Mixer Volume L */
0x0000, /* R99 - Input Mixer Volume R */
0x0000, /* R100 - Input Mixer Volume */
0x0000, /* R101 */
0x0000, /* R102 */
0x0000, /* R103 */
0x00E4, /* R104 - OUT1L Volume */
0x00E4, /* R105 - OUT1R Volume */
0x00E4, /* R106 - OUT2L Volume */
0x02E4, /* R107 - OUT2R Volume */
0x0000, /* R108 */
0x0000, /* R109 */
0x0000, /* R110 */
0x0000, /* R111 - BEEP Volume */
0x0A00, /* R112 - AI Formating */
0x0000, /* R113 - ADC DAC COMP */
0x0020, /* R114 - AI ADC Control */
0x0020, /* R115 - AI DAC Control */
0x0000, /* R116 */
0x0000, /* R117 */
0x0000, /* R118 */
0x0000, /* R119 */
0x0000, /* R120 */
0x0000, /* R121 */
0x0000, /* R122 */
0x0000, /* R123 */
0x0000, /* R124 */
0x0000, /* R125 */
0x0000, /* R126 */
0x0000, /* R127 */
0x1FFF, /* R128 - GPIO Debounce */
0x0010, /* R129 - GPIO Pin pull up Control */
0x0000, /* R130 - GPIO Pull down Control */
0x0000, /* R131 - GPIO Interrupt Mode */
0x0000, /* R132 */
0x0000, /* R133 - GPIO Control */
0x0BFB, /* R134 - GPIO Configuration (i/o) */
0x0FFD, /* R135 - GPIO Pin Polarity / Type */
0x0000, /* R136 */
0x0000, /* R137 */
0x0000, /* R138 */
0x0000, /* R139 */
0x0310, /* R140 - GPIO Function Select 1 */
0x0001, /* R141 - GPIO Function Select 2 */
0x2300, /* R142 - GPIO Function Select 3 */
0x0003, /* R143 - GPIO Function Select 4 */
0x0000, /* R144 - Digitiser Control (1) */
0x0002, /* R145 - Digitiser Control (2) */
0x0000, /* R146 */
0x0000, /* R147 */
0x0000, /* R148 */
0x0000, /* R149 */
0x0000, /* R150 */
0x0000, /* R151 */
0x7000, /* R152 - AUX1 Readback */
0x7000, /* R153 - AUX2 Readback */
0x7000, /* R154 - AUX3 Readback */
0x7000, /* R155 - AUX4 Readback */
0x0000, /* R156 - USB Voltage Readback */
0x0000, /* R157 - LINE Voltage Readback */
0x0000, /* R158 - BATT Voltage Readback */
0x0000, /* R159 - Chip Temp Readback */
0x0000, /* R160 */
0x0000, /* R161 */
0x0000, /* R162 */
0x0000, /* R163 - Generic Comparator Control */
0x0000, /* R164 - Generic comparator 1 */
0x0000, /* R165 - Generic comparator 2 */
0x0000, /* R166 - Generic comparator 3 */
0x0000, /* R167 - Generic comparator 4 */
0xA00F, /* R168 - Battery Charger Control 1 */
0x0B06, /* R169 - Battery Charger Control 2 */
0x0000, /* R170 - Battery Charger Control 3 */
0x0000, /* R171 */
0x0000, /* R172 - Current Sink Driver A */
0x0000, /* R173 - CSA Flash control */
0x0000, /* R174 - Current Sink Driver B */
0x0000, /* R175 - CSB Flash control */
0x0000, /* R176 - DCDC/LDO requested */
0x032D, /* R177 - DCDC Active options */
0x0000, /* R178 - DCDC Sleep options */
0x0025, /* R179 - Power-check comparator */
0x0006, /* R180 - DCDC1 Control */
0x0400, /* R181 - DCDC1 Timeouts */
0x1006, /* R182 - DCDC1 Low Power */
0x0018, /* R183 - DCDC2 Control */
0x0000, /* R184 - DCDC2 Timeouts */
0x0000, /* R185 */
0x0050, /* R186 - DCDC3 Control */
0x0C00, /* R187 - DCDC3 Timeouts */
0x0006, /* R188 - DCDC3 Low Power */
0x000E, /* R189 - DCDC4 Control */
0x0400, /* R190 - DCDC4 Timeouts */
0x0006, /* R191 - DCDC4 Low Power */
0x0008, /* R192 - DCDC5 Control */
0x0000, /* R193 - DCDC5 Timeouts */
0x0000, /* R194 */
0x0029, /* R195 - DCDC6 Control */
0x0800, /* R196 - DCDC6 Timeouts */
0x0006, /* R197 - DCDC6 Low Power */
0x0000, /* R198 */
0x0003, /* R199 - Limit Switch Control */
0x001D, /* R200 - LDO1 Control */
0x1000, /* R201 - LDO1 Timeouts */
0x001C, /* R202 - LDO1 Low Power */
0x0017, /* R203 - LDO2 Control */
0x1000, /* R204 - LDO2 Timeouts */
0x001C, /* R205 - LDO2 Low Power */
0x0006, /* R206 - LDO3 Control */
0x1000, /* R207 - LDO3 Timeouts */
0x001C, /* R208 - LDO3 Low Power */
0x0010, /* R209 - LDO4 Control */
0x1000, /* R210 - LDO4 Timeouts */
0x001C, /* R211 - LDO4 Low Power */
0x0000, /* R212 */
0x0000, /* R213 */
0x0000, /* R214 */
0x0000, /* R215 - VCC_FAULT Masks */
0x001F, /* R216 - Main Bandgap Control */
0x0000, /* R217 - OSC Control */
0x9000, /* R218 - RTC Tick Control */
0x0000, /* R219 - Security1 */
0x4000, /* R220 */
0x0000, /* R221 */
0x0000, /* R222 */
0x0000, /* R223 */
0x0000, /* R224 - Signal overrides */
0x0000, /* R225 - DCDC/LDO status */
0x0000, /* R226 - Charger Overides/status */
0x0000, /* R227 - misc overrides */
0x0000, /* R228 - Supply overrides/status 1 */
0x0000, /* R229 - Supply overrides/status 2 */
0xE000, /* R230 - GPIO Pin Status */
0x0000, /* R231 - comparotor overrides */
0x0000, /* R232 */
0x0000, /* R233 - State Machine status */
0x1200, /* R234 */
0x0000, /* R235 */
0x8000, /* R236 */
0x0000, /* R237 */
0x0000, /* R238 */
0x0000, /* R239 */
0x0003, /* R240 */
0x0000, /* R241 */
0x0000, /* R242 */
0x0004, /* R243 */
0x0300, /* R244 */
0x0000, /* R245 */
0x0200, /* R246 */
0x0000, /* R247 */
0x1000, /* R248 - DCDC1 Test Controls */
0x5000, /* R249 */
0x1000, /* R250 - DCDC3 Test Controls */
0x1000, /* R251 - DCDC4 Test Controls */
0x5100, /* R252 */
0x1000, /* R253 - DCDC6 Test Controls */
};
#endif
/*
* Access masks.
*/
const struct wm8350_reg_access wm8350_reg_io_map[] = {
/* read write volatile */
{ 0xFFFF, 0xFFFF, 0xFFFF }, /* R0 - Reset/ID */
{ 0x7CFF, 0x0C00, 0x7FFF }, /* R1 - ID */
{ 0x007F, 0x0000, 0x0000 }, /* R2 - ROM Mask ID */
{ 0xBE3B, 0xBE3B, 0x8000 }, /* R3 - System Control 1 */
{ 0xFEF7, 0xFEF7, 0xF800 }, /* R4 - System Control 2 */
{ 0x80FF, 0x80FF, 0x8000 }, /* R5 - System Hibernate */
{ 0xFB0E, 0xFB0E, 0x0000 }, /* R6 - Interface Control */
{ 0x0000, 0x0000, 0x0000 }, /* R7 */
{ 0xE537, 0xE537, 0xFFFF }, /* R8 - Power mgmt (1) */
{ 0x0FF3, 0x0FF3, 0xFFFF }, /* R9 - Power mgmt (2) */
{ 0x008F, 0x008F, 0xFFFF }, /* R10 - Power mgmt (3) */
{ 0x6D3C, 0x6D3C, 0xFFFF }, /* R11 - Power mgmt (4) */
{ 0x1F8F, 0x1F8F, 0xFFFF }, /* R12 - Power mgmt (5) */
{ 0x8F3F, 0x8F3F, 0xFFFF }, /* R13 - Power mgmt (6) */
{ 0x0003, 0x0003, 0xFFFF }, /* R14 - Power mgmt (7) */
{ 0x0000, 0x0000, 0x0000 }, /* R15 */
{ 0x7F7F, 0x7F7F, 0xFFFF }, /* R16 - RTC Seconds/Minutes */
{ 0x073F, 0x073F, 0xFFFF }, /* R17 - RTC Hours/Day */
{ 0x1F3F, 0x1F3F, 0xFFFF }, /* R18 - RTC Date/Month */
{ 0x3FFF, 0x00FF, 0xFFFF }, /* R19 - RTC Year */
{ 0x7F7F, 0x7F7F, 0x0000 }, /* R20 - Alarm Seconds/Minutes */
{ 0x0F3F, 0x0F3F, 0x0000 }, /* R21 - Alarm Hours/Day */
{ 0x1F3F, 0x1F3F, 0x0000 }, /* R22 - Alarm Date/Month */
{ 0xEF7F, 0xEA7F, 0xFFFF }, /* R23 - RTC Time Control */
{ 0x3BFF, 0x0000, 0xFFFF }, /* R24 - System Interrupts */
{ 0xFEE7, 0x0000, 0xFFFF }, /* R25 - Interrupt Status 1 */
{ 0x35FF, 0x0000, 0xFFFF }, /* R26 - Interrupt Status 2 */
{ 0x0F3F, 0x0000, 0xFFFF }, /* R27 - Power Up Interrupt Status */
{ 0x0F3F, 0x0000, 0xFFFF }, /* R28 - Under Voltage Interrupt status */
{ 0x8000, 0x0000, 0xFFFF }, /* R29 - Over Current Interrupt status */
{ 0x1FFF, 0x0000, 0xFFFF }, /* R30 - GPIO Interrupt Status */
{ 0xEF7F, 0x0000, 0xFFFF }, /* R31 - Comparator Interrupt Status */
{ 0x3FFF, 0x3FFF, 0x0000 }, /* R32 - System Interrupts Mask */
{ 0xFEE7, 0xFEE7, 0x0000 }, /* R33 - Interrupt Status 1 Mask */
{ 0xF5FF, 0xF5FF, 0x0000 }, /* R34 - Interrupt Status 2 Mask */
{ 0x0F3F, 0x0F3F, 0x0000 }, /* R35 - Power Up Interrupt Status Mask */
{ 0x0F3F, 0x0F3F, 0x0000 }, /* R36 - Under Voltage Int status Mask */
{ 0x8000, 0x8000, 0x0000 }, /* R37 - Over Current Int status Mask */
{ 0x1FFF, 0x1FFF, 0x0000 }, /* R38 - GPIO Interrupt Status Mask */
{ 0xEF7F, 0xEF7F, 0x0000 }, /* R39 - Comparator IntStatus Mask */
{ 0xC9F7, 0xC9F7, 0xFFFF }, /* R40 - Clock Control 1 */
{ 0x8001, 0x8001, 0x0000 }, /* R41 - Clock Control 2 */
{ 0xFFF7, 0xFFF7, 0xFFFF }, /* R42 - FLL Control 1 */
{ 0xFBFF, 0xFBFF, 0x0000 }, /* R43 - FLL Control 2 */
{ 0xFFFF, 0xFFFF, 0x0000 }, /* R44 - FLL Control 3 */
{ 0x0033, 0x0033, 0x0000 }, /* R45 - FLL Control 4 */
{ 0x0000, 0x0000, 0x0000 }, /* R46 */
{ 0x0000, 0x0000, 0x0000 }, /* R47 */
{ 0x3033, 0x3033, 0x0000 }, /* R48 - DAC Control */
{ 0x0000, 0x0000, 0x0000 }, /* R49 */
{ 0x81FF, 0x81FF, 0xFFFF }, /* R50 - DAC Digital Volume L */
{ 0x81FF, 0x81FF, 0xFFFF }, /* R51 - DAC Digital Volume R */
{ 0x0000, 0x0000, 0x0000 }, /* R52 */
{ 0x0FFF, 0x0FFF, 0xFFFF }, /* R53 - DAC LR Rate */
{ 0x0017, 0x0017, 0x0000 }, /* R54 - DAC Clock Control */
{ 0x0000, 0x0000, 0x0000 }, /* R55 */
{ 0x0000, 0x0000, 0x0000 }, /* R56 */
{ 0x0000, 0x0000, 0x0000 }, /* R57 */
{ 0x4000, 0x4000, 0x0000 }, /* R58 - DAC Mute */
{ 0x7000, 0x7000, 0x0000 }, /* R59 - DAC Mute Volume */
{ 0x3C00, 0x3C00, 0x0000 }, /* R60 - DAC Side */
{ 0x0000, 0x0000, 0x0000 }, /* R61 */
{ 0x0000, 0x0000, 0x0000 }, /* R62 */
{ 0x0000, 0x0000, 0x0000 }, /* R63 */
{ 0x8303, 0x8303, 0xFFFF }, /* R64 - ADC Control */
{ 0x0000, 0x0000, 0x0000 }, /* R65 */
{ 0x81FF, 0x81FF, 0xFFFF }, /* R66 - ADC Digital Volume L */
{ 0x81FF, 0x81FF, 0xFFFF }, /* R67 - ADC Digital Volume R */
{ 0x0FFF, 0x0FFF, 0x0000 }, /* R68 - ADC Divider */
{ 0x0000, 0x0000, 0x0000 }, /* R69 */
{ 0x0FFF, 0x0FFF, 0xFFFF }, /* R70 - ADC LR Rate */
{ 0x0000, 0x0000, 0x0000 }, /* R71 */
{ 0x0707, 0x0707, 0xFFFF }, /* R72 - Input Control */
{ 0xC0C0, 0xC0C0, 0xFFFF }, /* R73 - IN3 Input Control */
{ 0xC09F, 0xC09F, 0xFFFF }, /* R74 - Mic Bias Control */
{ 0x0000, 0x0000, 0x0000 }, /* R75 */
{ 0x0F15, 0x0F15, 0xFFFF }, /* R76 - Output Control */
{ 0xC000, 0xC000, 0xFFFF }, /* R77 - Jack Detect */
{ 0x03FF, 0x03FF, 0x0000 }, /* R78 - Anti Pop Control */
{ 0x0000, 0x0000, 0x0000 }, /* R79 */
{ 0xE1FC, 0xE1FC, 0x8000 }, /* R80 - Left Input Volume */
{ 0xE1FC, 0xE1FC, 0x8000 }, /* R81 - Right Input Volume */
{ 0x0000, 0x0000, 0x0000 }, /* R82 */
{ 0x0000, 0x0000, 0x0000 }, /* R83 */
{ 0x0000, 0x0000, 0x0000 }, /* R84 */
{ 0x0000, 0x0000, 0x0000 }, /* R85 */
{ 0x0000, 0x0000, 0x0000 }, /* R86 */
{ 0x0000, 0x0000, 0x0000 }, /* R87 */
{ 0x9807, 0x9807, 0xFFFF }, /* R88 - Left Mixer Control */
{ 0x980B, 0x980B, 0xFFFF }, /* R89 - Right Mixer Control */
{ 0x0000, 0x0000, 0x0000 }, /* R90 */
{ 0x0000, 0x0000, 0x0000 }, /* R91 */
{ 0x8909, 0x8909, 0xFFFF }, /* R92 - OUT3 Mixer Control */
{ 0x9E07, 0x9E07, 0xFFFF }, /* R93 - OUT4 Mixer Control */
{ 0x0000, 0x0000, 0x0000 }, /* R94 */
{ 0x0000, 0x0000, 0x0000 }, /* R95 */
{ 0x0EEE, 0x0EEE, 0x0000 }, /* R96 - Output Left Mixer Volume */
{ 0xE0EE, 0xE0EE, 0x0000 }, /* R97 - Output Right Mixer Volume */
{ 0x0E0F, 0x0E0F, 0x0000 }, /* R98 - Input Mixer Volume L */
{ 0xE0E1, 0xE0E1, 0x0000 }, /* R99 - Input Mixer Volume R */
{ 0x800E, 0x800E, 0x0000 }, /* R100 - Input Mixer Volume */
{ 0x0000, 0x0000, 0x0000 }, /* R101 */
{ 0x0000, 0x0000, 0x0000 }, /* R102 */
{ 0x0000, 0x0000, 0x0000 }, /* R103 */
{ 0xE1FC, 0xE1FC, 0xFFFF }, /* R104 - LOUT1 Volume */
{ 0xE1FC, 0xE1FC, 0xFFFF }, /* R105 - ROUT1 Volume */
{ 0xE1FC, 0xE1FC, 0xFFFF }, /* R106 - LOUT2 Volume */
{ 0xE7FC, 0xE7FC, 0xFFFF }, /* R107 - ROUT2 Volume */
{ 0x0000, 0x0000, 0x0000 }, /* R108 */
{ 0x0000, 0x0000, 0x0000 }, /* R109 */
{ 0x0000, 0x0000, 0x0000 }, /* R110 */
{ 0x80E0, 0x80E0, 0xFFFF }, /* R111 - BEEP Volume */
{ 0xBF00, 0xBF00, 0x0000 }, /* R112 - AI Formating */
{ 0x00F1, 0x00F1, 0x0000 }, /* R113 - ADC DAC COMP */
{ 0x00F8, 0x00F8, 0x0000 }, /* R114 - AI ADC Control */
{ 0x40FB, 0x40FB, 0x0000 }, /* R115 - AI DAC Control */
{ 0x7C30, 0x7C30, 0x0000 }, /* R116 - AIF Test */
{ 0x0000, 0x0000, 0x0000 }, /* R117 */
{ 0x0000, 0x0000, 0x0000 }, /* R118 */
{ 0x0000, 0x0000, 0x0000 }, /* R119 */
{ 0x0000, 0x0000, 0x0000 }, /* R120 */
{ 0x0000, 0x0000, 0x0000 }, /* R121 */
{ 0x0000, 0x0000, 0x0000 }, /* R122 */
{ 0x0000, 0x0000, 0x0000 }, /* R123 */
{ 0x0000, 0x0000, 0x0000 }, /* R124 */
{ 0x0000, 0x0000, 0x0000 }, /* R125 */
{ 0x0000, 0x0000, 0x0000 }, /* R126 */
{ 0x0000, 0x0000, 0x0000 }, /* R127 */
{ 0x1FFF, 0x1FFF, 0x0000 }, /* R128 - GPIO Debounce */
{ 0x1FFF, 0x1FFF, 0x0000 }, /* R129 - GPIO Pin pull up Control */
{ 0x1FFF, 0x1FFF, 0x0000 }, /* R130 - GPIO Pull down Control */
{ 0x1FFF, 0x1FFF, 0x0000 }, /* R131 - GPIO Interrupt Mode */
{ 0x0000, 0x0000, 0x0000 }, /* R132 */
{ 0x00C0, 0x00C0, 0x0000 }, /* R133 - GPIO Control */
{ 0x1FFF, 0x1FFF, 0x0000 }, /* R134 - GPIO Configuration (i/o) */
{ 0x1FFF, 0x1FFF, 0x0000 }, /* R135 - GPIO Pin Polarity / Type */
{ 0x0000, 0x0000, 0x0000 }, /* R136 */
{ 0x0000, 0x0000, 0x0000 }, /* R137 */
{ 0x0000, 0x0000, 0x0000 }, /* R138 */
{ 0x0000, 0x0000, 0x0000 }, /* R139 */
{ 0xFFFF, 0xFFFF, 0x0000 }, /* R140 - GPIO Function Select 1 */
{ 0xFFFF, 0xFFFF, 0x0000 }, /* R141 - GPIO Function Select 2 */
{ 0xFFFF, 0xFFFF, 0x0000 }, /* R142 - GPIO Function Select 3 */
{ 0x000F, 0x000F, 0x0000 }, /* R143 - GPIO Function Select 4 */
{ 0xF0FF, 0xF0FF, 0xA000 }, /* R144 - Digitiser Control (1) */
{ 0x3707, 0x3707, 0x0000 }, /* R145 - Digitiser Control (2) */
{ 0x0000, 0x0000, 0x0000 }, /* R146 */
{ 0x0000, 0x0000, 0x0000 }, /* R147 */
{ 0x0000, 0x0000, 0x0000 }, /* R148 */
{ 0x0000, 0x0000, 0x0000 }, /* R149 */
{ 0x0000, 0x0000, 0x0000 }, /* R150 */
{ 0x0000, 0x0000, 0x0000 }, /* R151 */
{ 0x7FFF, 0x7000, 0xFFFF }, /* R152 - AUX1 Readback */
{ 0x7FFF, 0x7000, 0xFFFF }, /* R153 - AUX2 Readback */
{ 0x7FFF, 0x7000, 0xFFFF }, /* R154 - AUX3 Readback */
{ 0x7FFF, 0x7000, 0xFFFF }, /* R155 - AUX4 Readback */
{ 0x0FFF, 0x0000, 0xFFFF }, /* R156 - USB Voltage Readback */
{ 0x0FFF, 0x0000, 0xFFFF }, /* R157 - LINE Voltage Readback */
{ 0x0FFF, 0x0000, 0xFFFF }, /* R158 - BATT Voltage Readback */
{ 0x0FFF, 0x0000, 0xFFFF }, /* R159 - Chip Temp Readback */
{ 0x0000, 0x0000, 0x0000 }, /* R160 */
{ 0x0000, 0x0000, 0x0000 }, /* R161 */
{ 0x0000, 0x0000, 0x0000 }, /* R162 */
{ 0x000F, 0x000F, 0x0000 }, /* R163 - Generic Comparator Control */
{ 0xFFFF, 0xFFFF, 0x0000 }, /* R164 - Generic comparator 1 */
{ 0xFFFF, 0xFFFF, 0x0000 }, /* R165 - Generic comparator 2 */
{ 0xFFFF, 0xFFFF, 0x0000 }, /* R166 - Generic comparator 3 */
{ 0xFFFF, 0xFFFF, 0x0000 }, /* R167 - Generic comparator 4 */
{ 0xBFFF, 0xBFFF, 0x8000 }, /* R168 - Battery Charger Control 1 */
{ 0xFFFF, 0x4FFF, 0xB000 }, /* R169 - Battery Charger Control 2 */
{ 0x007F, 0x007F, 0x0000 }, /* R170 - Battery Charger Control 3 */
{ 0x0000, 0x0000, 0x0000 }, /* R171 */
{ 0x903F, 0x903F, 0xFFFF }, /* R172 - Current Sink Driver A */
{ 0xE333, 0xE333, 0xFFFF }, /* R173 - CSA Flash control */
{ 0x903F, 0x903F, 0xFFFF }, /* R174 - Current Sink Driver B */
{ 0xE333, 0xE333, 0xFFFF }, /* R175 - CSB Flash control */
{ 0x8F3F, 0x8F3F, 0xFFFF }, /* R176 - DCDC/LDO requested */
{ 0x332D, 0x332D, 0x0000 }, /* R177 - DCDC Active options */
{ 0x002D, 0x002D, 0x0000 }, /* R178 - DCDC Sleep options */
{ 0x5177, 0x5177, 0x8000 }, /* R179 - Power-check comparator */
{ 0x047F, 0x047F, 0x0000 }, /* R180 - DCDC1 Control */
{ 0xFFC0, 0xFFC0, 0x0000 }, /* R181 - DCDC1 Timeouts */
{ 0x737F, 0x737F, 0x0000 }, /* R182 - DCDC1 Low Power */
{ 0x535B, 0x535B, 0x0000 }, /* R183 - DCDC2 Control */
{ 0xFFC0, 0xFFC0, 0x0000 }, /* R184 - DCDC2 Timeouts */
{ 0x0000, 0x0000, 0x0000 }, /* R185 */
{ 0x047F, 0x047F, 0x0000 }, /* R186 - DCDC3 Control */
{ 0xFFC0, 0xFFC0, 0x0000 }, /* R187 - DCDC3 Timeouts */
{ 0x737F, 0x737F, 0x0000 }, /* R188 - DCDC3 Low Power */
{ 0x047F, 0x047F, 0x0000 }, /* R189 - DCDC4 Control */
{ 0xFFC0, 0xFFC0, 0x0000 }, /* R190 - DCDC4 Timeouts */
{ 0x737F, 0x737F, 0x0000 }, /* R191 - DCDC4 Low Power */
{ 0x535B, 0x535B, 0x0000 }, /* R192 - DCDC5 Control */
{ 0xFFC0, 0xFFC0, 0x0000 }, /* R193 - DCDC5 Timeouts */
{ 0x0000, 0x0000, 0x0000 }, /* R194 */
{ 0x047F, 0x047F, 0x0000 }, /* R195 - DCDC6 Control */
{ 0xFFC0, 0xFFC0, 0x0000 }, /* R196 - DCDC6 Timeouts */
{ 0x737F, 0x737F, 0x0000 }, /* R197 - DCDC6 Low Power */
{ 0x0000, 0x0000, 0x0000 }, /* R198 */
{ 0xFFD3, 0xFFD3, 0x0000 }, /* R199 - Limit Switch Control */
{ 0x441F, 0x441F, 0x0000 }, /* R200 - LDO1 Control */
{ 0xFFC0, 0xFFC0, 0x0000 }, /* R201 - LDO1 Timeouts */
{ 0x331F, 0x331F, 0x0000 }, /* R202 - LDO1 Low Power */
{ 0x441F, 0x441F, 0x0000 }, /* R203 - LDO2 Control */
{ 0xFFC0, 0xFFC0, 0x0000 }, /* R204 - LDO2 Timeouts */
{ 0x331F, 0x331F, 0x0000 }, /* R205 - LDO2 Low Power */
{ 0x441F, 0x441F, 0x0000 }, /* R206 - LDO3 Control */
{ 0xFFC0, 0xFFC0, 0x0000 }, /* R207 - LDO3 Timeouts */
{ 0x331F, 0x331F, 0x0000 }, /* R208 - LDO3 Low Power */
{ 0x441F, 0x441F, 0x0000 }, /* R209 - LDO4 Control */
{ 0xFFC0, 0xFFC0, 0x0000 }, /* R210 - LDO4 Timeouts */
{ 0x331F, 0x331F, 0x0000 }, /* R211 - LDO4 Low Power */
{ 0x0000, 0x0000, 0x0000 }, /* R212 */
{ 0x0000, 0x0000, 0x0000 }, /* R213 */
{ 0x0000, 0x0000, 0x0000 }, /* R214 */
{ 0x8F3F, 0x8F3F, 0x0000 }, /* R215 - VCC_FAULT Masks */
{ 0xFF3F, 0xE03F, 0x0000 }, /* R216 - Main Bandgap Control */
{ 0xEF2F, 0xE02F, 0x0000 }, /* R217 - OSC Control */
{ 0xF3FF, 0xB3FF, 0xc000 }, /* R218 - RTC Tick Control */
{ 0xFFFF, 0xFFFF, 0x0000 }, /* R219 - Security */
{ 0x09FF, 0x01FF, 0x0000 }, /* R220 - RAM BIST 1 */
{ 0x0000, 0x0000, 0x0000 }, /* R221 */
{ 0xFFFF, 0xFFFF, 0xFFFF }, /* R222 */
{ 0xFFFF, 0xFFFF, 0xFFFF }, /* R223 */
{ 0x0000, 0x0000, 0x0000 }, /* R224 */
{ 0x8F3F, 0x0000, 0xFFFF }, /* R225 - DCDC/LDO status */
{ 0x0000, 0x0000, 0xFFFF }, /* R226 - Charger status */
{ 0x34FE, 0x0000, 0xFFFF }, /* R227 */
{ 0x0000, 0x0000, 0x0000 }, /* R228 */
{ 0x0000, 0x0000, 0x0000 }, /* R229 */
{ 0xFFFF, 0x1FFF, 0xFFFF }, /* R230 - GPIO Pin Status */
{ 0xFFFF, 0x1FFF, 0xFFFF }, /* R231 */
{ 0xFFFF, 0x1FFF, 0xFFFF }, /* R232 */
{ 0xFFFF, 0x1FFF, 0xFFFF }, /* R233 */
{ 0x0000, 0x0000, 0x0000 }, /* R234 */
{ 0x0000, 0x0000, 0x0000 }, /* R235 */
{ 0x0000, 0x0000, 0x0000 }, /* R236 */
{ 0x0000, 0x0000, 0x0000 }, /* R237 */
{ 0x0000, 0x0000, 0x0000 }, /* R238 */
{ 0x0000, 0x0000, 0x0000 }, /* R239 */
{ 0x0000, 0x0000, 0x0000 }, /* R240 */
{ 0x0000, 0x0000, 0x0000 }, /* R241 */
{ 0x0000, 0x0000, 0x0000 }, /* R242 */
{ 0x0000, 0x0000, 0x0000 }, /* R243 */
{ 0x0000, 0x0000, 0x0000 }, /* R244 */
{ 0x0000, 0x0000, 0x0000 }, /* R245 */
{ 0x0000, 0x0000, 0x0000 }, /* R246 */
{ 0x0000, 0x0000, 0x0000 }, /* R247 */
{ 0xFFFF, 0x0010, 0xFFFF }, /* R248 */
{ 0x0000, 0x0000, 0x0000 }, /* R249 */
{ 0xFFFF, 0x0010, 0xFFFF }, /* R250 */
{ 0xFFFF, 0x0010, 0xFFFF }, /* R251 */
{ 0x0000, 0x0000, 0x0000 }, /* R252 */
{ 0xFFFF, 0x0010, 0xFFFF }, /* R253 */
{ 0x0000, 0x0000, 0x0000 }, /* R254 */
{ 0x0000, 0x0000, 0x0000 }, /* R255 */
};
| gpl-2.0 |
jiangdapeng/btrfs-next | sound/pci/echoaudio/darla20_dsp.c | 12526 | 3506 | /***************************************************************************
Copyright Echo Digital Audio Corporation (c) 1998 - 2004
All rights reserved
www.echoaudio.com
This file is part of Echo Digital Audio's generic driver library.
Echo Digital Audio's generic driver library is free software;
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 will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU 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.
*************************************************************************
Translation from C++ and adaptation for use in ALSA-Driver
were made by Giuliano Pochini <pochini@shiny.it>
****************************************************************************/
static int init_hw(struct echoaudio *chip, u16 device_id, u16 subdevice_id)
{
int err;
DE_INIT(("init_hw() - Darla20\n"));
if (snd_BUG_ON((subdevice_id & 0xfff0) != DARLA20))
return -ENODEV;
if ((err = init_dsp_comm_page(chip))) {
DE_INIT(("init_hw - could not initialize DSP comm page\n"));
return err;
}
chip->device_id = device_id;
chip->subdevice_id = subdevice_id;
chip->bad_board = TRUE;
chip->dsp_code_to_load = FW_DARLA20_DSP;
chip->spdif_status = GD_SPDIF_STATUS_UNDEF;
chip->clock_state = GD_CLOCK_UNDEF;
/* Since this card has no ASIC, mark it as loaded so everything
works OK */
chip->asic_loaded = TRUE;
chip->input_clock_types = ECHO_CLOCK_BIT_INTERNAL;
if ((err = load_firmware(chip)) < 0)
return err;
chip->bad_board = FALSE;
DE_INIT(("init_hw done\n"));
return err;
}
static int set_mixer_defaults(struct echoaudio *chip)
{
return init_line_levels(chip);
}
/* The Darla20 has no external clock sources */
static u32 detect_input_clocks(const struct echoaudio *chip)
{
return ECHO_CLOCK_BIT_INTERNAL;
}
/* The Darla20 has no ASIC. Just do nothing */
static int load_asic(struct echoaudio *chip)
{
return 0;
}
static int set_sample_rate(struct echoaudio *chip, u32 rate)
{
u8 clock_state, spdif_status;
if (wait_handshake(chip))
return -EIO;
switch (rate) {
case 44100:
clock_state = GD_CLOCK_44;
spdif_status = GD_SPDIF_STATUS_44;
break;
case 48000:
clock_state = GD_CLOCK_48;
spdif_status = GD_SPDIF_STATUS_48;
break;
default:
clock_state = GD_CLOCK_NOCHANGE;
spdif_status = GD_SPDIF_STATUS_NOCHANGE;
break;
}
if (chip->clock_state == clock_state)
clock_state = GD_CLOCK_NOCHANGE;
if (spdif_status == chip->spdif_status)
spdif_status = GD_SPDIF_STATUS_NOCHANGE;
chip->comm_page->sample_rate = cpu_to_le32(rate);
chip->comm_page->gd_clock_state = clock_state;
chip->comm_page->gd_spdif_status = spdif_status;
chip->comm_page->gd_resampler_state = 3; /* magic number - should always be 3 */
/* Save the new audio state if it changed */
if (clock_state != GD_CLOCK_NOCHANGE)
chip->clock_state = clock_state;
if (spdif_status != GD_SPDIF_STATUS_NOCHANGE)
chip->spdif_status = spdif_status;
chip->sample_rate = rate;
clear_handshake(chip);
return send_vector(chip, DSP_VC_SET_GD_AUDIO_STATE);
}
| gpl-2.0 |
kurisuxx/android_kernel_samsung_klimtlte | sound/pci/echoaudio/gina24_dsp.c | 12526 | 9339 | /****************************************************************************
Copyright Echo Digital Audio Corporation (c) 1998 - 2004
All rights reserved
www.echoaudio.com
This file is part of Echo Digital Audio's generic driver library.
Echo Digital Audio's generic driver library is free software;
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 will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU 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.
*************************************************************************
Translation from C++ and adaptation for use in ALSA-Driver
were made by Giuliano Pochini <pochini@shiny.it>
****************************************************************************/
static int write_control_reg(struct echoaudio *chip, u32 value, char force);
static int set_input_clock(struct echoaudio *chip, u16 clock);
static int set_professional_spdif(struct echoaudio *chip, char prof);
static int set_digital_mode(struct echoaudio *chip, u8 mode);
static int load_asic_generic(struct echoaudio *chip, u32 cmd, short asic);
static int check_asic_status(struct echoaudio *chip);
static int init_hw(struct echoaudio *chip, u16 device_id, u16 subdevice_id)
{
int err;
DE_INIT(("init_hw() - Gina24\n"));
if (snd_BUG_ON((subdevice_id & 0xfff0) != GINA24))
return -ENODEV;
if ((err = init_dsp_comm_page(chip))) {
DE_INIT(("init_hw - could not initialize DSP comm page\n"));
return err;
}
chip->device_id = device_id;
chip->subdevice_id = subdevice_id;
chip->bad_board = TRUE;
chip->input_clock_types =
ECHO_CLOCK_BIT_INTERNAL | ECHO_CLOCK_BIT_SPDIF |
ECHO_CLOCK_BIT_ESYNC | ECHO_CLOCK_BIT_ESYNC96 |
ECHO_CLOCK_BIT_ADAT;
/* Gina24 comes in both '301 and '361 flavors */
if (chip->device_id == DEVICE_ID_56361) {
chip->dsp_code_to_load = FW_GINA24_361_DSP;
chip->digital_modes =
ECHOCAPS_HAS_DIGITAL_MODE_SPDIF_RCA |
ECHOCAPS_HAS_DIGITAL_MODE_SPDIF_OPTICAL |
ECHOCAPS_HAS_DIGITAL_MODE_ADAT;
} else {
chip->dsp_code_to_load = FW_GINA24_301_DSP;
chip->digital_modes =
ECHOCAPS_HAS_DIGITAL_MODE_SPDIF_RCA |
ECHOCAPS_HAS_DIGITAL_MODE_SPDIF_OPTICAL |
ECHOCAPS_HAS_DIGITAL_MODE_ADAT |
ECHOCAPS_HAS_DIGITAL_MODE_SPDIF_CDROM;
}
if ((err = load_firmware(chip)) < 0)
return err;
chip->bad_board = FALSE;
DE_INIT(("init_hw done\n"));
return err;
}
static int set_mixer_defaults(struct echoaudio *chip)
{
chip->digital_mode = DIGITAL_MODE_SPDIF_RCA;
chip->professional_spdif = FALSE;
chip->digital_in_automute = TRUE;
return init_line_levels(chip);
}
static u32 detect_input_clocks(const struct echoaudio *chip)
{
u32 clocks_from_dsp, clock_bits;
/* Map the DSP clock detect bits to the generic driver clock
detect bits */
clocks_from_dsp = le32_to_cpu(chip->comm_page->status_clocks);
clock_bits = ECHO_CLOCK_BIT_INTERNAL;
if (clocks_from_dsp & GML_CLOCK_DETECT_BIT_SPDIF)
clock_bits |= ECHO_CLOCK_BIT_SPDIF;
if (clocks_from_dsp & GML_CLOCK_DETECT_BIT_ADAT)
clock_bits |= ECHO_CLOCK_BIT_ADAT;
if (clocks_from_dsp & GML_CLOCK_DETECT_BIT_ESYNC)
clock_bits |= ECHO_CLOCK_BIT_ESYNC | ECHO_CLOCK_BIT_ESYNC96;
return clock_bits;
}
/* Gina24 has an ASIC on the PCI card which must be loaded for anything
interesting to happen. */
static int load_asic(struct echoaudio *chip)
{
u32 control_reg;
int err;
short asic;
if (chip->asic_loaded)
return 1;
/* Give the DSP a few milliseconds to settle down */
mdelay(10);
/* Pick the correct ASIC for '301 or '361 Gina24 */
if (chip->device_id == DEVICE_ID_56361)
asic = FW_GINA24_361_ASIC;
else
asic = FW_GINA24_301_ASIC;
err = load_asic_generic(chip, DSP_FNC_LOAD_GINA24_ASIC, asic);
if (err < 0)
return err;
chip->asic_code = asic;
/* Now give the new ASIC a little time to set up */
mdelay(10);
/* See if it worked */
err = check_asic_status(chip);
/* Set up the control register if the load succeeded -
48 kHz, internal clock, S/PDIF RCA mode */
if (!err) {
control_reg = GML_CONVERTER_ENABLE | GML_48KHZ;
err = write_control_reg(chip, control_reg, TRUE);
}
DE_INIT(("load_asic() done\n"));
return err;
}
static int set_sample_rate(struct echoaudio *chip, u32 rate)
{
u32 control_reg, clock;
if (snd_BUG_ON(rate >= 50000 &&
chip->digital_mode == DIGITAL_MODE_ADAT))
return -EINVAL;
/* Only set the clock for internal mode. */
if (chip->input_clock != ECHO_CLOCK_INTERNAL) {
DE_ACT(("set_sample_rate: Cannot set sample rate - "
"clock not set to CLK_CLOCKININTERNAL\n"));
/* Save the rate anyhow */
chip->comm_page->sample_rate = cpu_to_le32(rate);
chip->sample_rate = rate;
return 0;
}
clock = 0;
control_reg = le32_to_cpu(chip->comm_page->control_register);
control_reg &= GML_CLOCK_CLEAR_MASK & GML_SPDIF_RATE_CLEAR_MASK;
switch (rate) {
case 96000:
clock = GML_96KHZ;
break;
case 88200:
clock = GML_88KHZ;
break;
case 48000:
clock = GML_48KHZ | GML_SPDIF_SAMPLE_RATE1;
break;
case 44100:
clock = GML_44KHZ;
/* Professional mode ? */
if (control_reg & GML_SPDIF_PRO_MODE)
clock |= GML_SPDIF_SAMPLE_RATE0;
break;
case 32000:
clock = GML_32KHZ | GML_SPDIF_SAMPLE_RATE0 |
GML_SPDIF_SAMPLE_RATE1;
break;
case 22050:
clock = GML_22KHZ;
break;
case 16000:
clock = GML_16KHZ;
break;
case 11025:
clock = GML_11KHZ;
break;
case 8000:
clock = GML_8KHZ;
break;
default:
DE_ACT(("set_sample_rate: %d invalid!\n", rate));
return -EINVAL;
}
control_reg |= clock;
chip->comm_page->sample_rate = cpu_to_le32(rate); /* ignored by the DSP */
chip->sample_rate = rate;
DE_ACT(("set_sample_rate: %d clock %d\n", rate, clock));
return write_control_reg(chip, control_reg, FALSE);
}
static int set_input_clock(struct echoaudio *chip, u16 clock)
{
u32 control_reg, clocks_from_dsp;
DE_ACT(("set_input_clock:\n"));
/* Mask off the clock select bits */
control_reg = le32_to_cpu(chip->comm_page->control_register) &
GML_CLOCK_CLEAR_MASK;
clocks_from_dsp = le32_to_cpu(chip->comm_page->status_clocks);
switch (clock) {
case ECHO_CLOCK_INTERNAL:
DE_ACT(("Set Gina24 clock to INTERNAL\n"));
chip->input_clock = ECHO_CLOCK_INTERNAL;
return set_sample_rate(chip, chip->sample_rate);
case ECHO_CLOCK_SPDIF:
if (chip->digital_mode == DIGITAL_MODE_ADAT)
return -EAGAIN;
DE_ACT(("Set Gina24 clock to SPDIF\n"));
control_reg |= GML_SPDIF_CLOCK;
if (clocks_from_dsp & GML_CLOCK_DETECT_BIT_SPDIF96)
control_reg |= GML_DOUBLE_SPEED_MODE;
else
control_reg &= ~GML_DOUBLE_SPEED_MODE;
break;
case ECHO_CLOCK_ADAT:
if (chip->digital_mode != DIGITAL_MODE_ADAT)
return -EAGAIN;
DE_ACT(("Set Gina24 clock to ADAT\n"));
control_reg |= GML_ADAT_CLOCK;
control_reg &= ~GML_DOUBLE_SPEED_MODE;
break;
case ECHO_CLOCK_ESYNC:
DE_ACT(("Set Gina24 clock to ESYNC\n"));
control_reg |= GML_ESYNC_CLOCK;
control_reg &= ~GML_DOUBLE_SPEED_MODE;
break;
case ECHO_CLOCK_ESYNC96:
DE_ACT(("Set Gina24 clock to ESYNC96\n"));
control_reg |= GML_ESYNC_CLOCK | GML_DOUBLE_SPEED_MODE;
break;
default:
DE_ACT(("Input clock 0x%x not supported for Gina24\n", clock));
return -EINVAL;
}
chip->input_clock = clock;
return write_control_reg(chip, control_reg, TRUE);
}
static int dsp_set_digital_mode(struct echoaudio *chip, u8 mode)
{
u32 control_reg;
int err, incompatible_clock;
/* Set clock to "internal" if it's not compatible with the new mode */
incompatible_clock = FALSE;
switch (mode) {
case DIGITAL_MODE_SPDIF_OPTICAL:
case DIGITAL_MODE_SPDIF_CDROM:
case DIGITAL_MODE_SPDIF_RCA:
if (chip->input_clock == ECHO_CLOCK_ADAT)
incompatible_clock = TRUE;
break;
case DIGITAL_MODE_ADAT:
if (chip->input_clock == ECHO_CLOCK_SPDIF)
incompatible_clock = TRUE;
break;
default:
DE_ACT(("Digital mode not supported: %d\n", mode));
return -EINVAL;
}
spin_lock_irq(&chip->lock);
if (incompatible_clock) { /* Switch to 48KHz, internal */
chip->sample_rate = 48000;
set_input_clock(chip, ECHO_CLOCK_INTERNAL);
}
/* Clear the current digital mode */
control_reg = le32_to_cpu(chip->comm_page->control_register);
control_reg &= GML_DIGITAL_MODE_CLEAR_MASK;
/* Tweak the control reg */
switch (mode) {
case DIGITAL_MODE_SPDIF_OPTICAL:
control_reg |= GML_SPDIF_OPTICAL_MODE;
break;
case DIGITAL_MODE_SPDIF_CDROM:
/* '361 Gina24 cards do not have the S/PDIF CD-ROM mode */
if (chip->device_id == DEVICE_ID_56301)
control_reg |= GML_SPDIF_CDROM_MODE;
break;
case DIGITAL_MODE_SPDIF_RCA:
/* GML_SPDIF_OPTICAL_MODE bit cleared */
break;
case DIGITAL_MODE_ADAT:
control_reg |= GML_ADAT_MODE;
control_reg &= ~GML_DOUBLE_SPEED_MODE;
break;
}
err = write_control_reg(chip, control_reg, TRUE);
spin_unlock_irq(&chip->lock);
if (err < 0)
return err;
chip->digital_mode = mode;
DE_ACT(("set_digital_mode to %d\n", chip->digital_mode));
return incompatible_clock;
}
| gpl-2.0 |
rdeva31/kernel-msm-3.10 | sound/pci/echoaudio/gina24_dsp.c | 12526 | 9339 | /****************************************************************************
Copyright Echo Digital Audio Corporation (c) 1998 - 2004
All rights reserved
www.echoaudio.com
This file is part of Echo Digital Audio's generic driver library.
Echo Digital Audio's generic driver library is free software;
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 will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU 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.
*************************************************************************
Translation from C++ and adaptation for use in ALSA-Driver
were made by Giuliano Pochini <pochini@shiny.it>
****************************************************************************/
static int write_control_reg(struct echoaudio *chip, u32 value, char force);
static int set_input_clock(struct echoaudio *chip, u16 clock);
static int set_professional_spdif(struct echoaudio *chip, char prof);
static int set_digital_mode(struct echoaudio *chip, u8 mode);
static int load_asic_generic(struct echoaudio *chip, u32 cmd, short asic);
static int check_asic_status(struct echoaudio *chip);
static int init_hw(struct echoaudio *chip, u16 device_id, u16 subdevice_id)
{
int err;
DE_INIT(("init_hw() - Gina24\n"));
if (snd_BUG_ON((subdevice_id & 0xfff0) != GINA24))
return -ENODEV;
if ((err = init_dsp_comm_page(chip))) {
DE_INIT(("init_hw - could not initialize DSP comm page\n"));
return err;
}
chip->device_id = device_id;
chip->subdevice_id = subdevice_id;
chip->bad_board = TRUE;
chip->input_clock_types =
ECHO_CLOCK_BIT_INTERNAL | ECHO_CLOCK_BIT_SPDIF |
ECHO_CLOCK_BIT_ESYNC | ECHO_CLOCK_BIT_ESYNC96 |
ECHO_CLOCK_BIT_ADAT;
/* Gina24 comes in both '301 and '361 flavors */
if (chip->device_id == DEVICE_ID_56361) {
chip->dsp_code_to_load = FW_GINA24_361_DSP;
chip->digital_modes =
ECHOCAPS_HAS_DIGITAL_MODE_SPDIF_RCA |
ECHOCAPS_HAS_DIGITAL_MODE_SPDIF_OPTICAL |
ECHOCAPS_HAS_DIGITAL_MODE_ADAT;
} else {
chip->dsp_code_to_load = FW_GINA24_301_DSP;
chip->digital_modes =
ECHOCAPS_HAS_DIGITAL_MODE_SPDIF_RCA |
ECHOCAPS_HAS_DIGITAL_MODE_SPDIF_OPTICAL |
ECHOCAPS_HAS_DIGITAL_MODE_ADAT |
ECHOCAPS_HAS_DIGITAL_MODE_SPDIF_CDROM;
}
if ((err = load_firmware(chip)) < 0)
return err;
chip->bad_board = FALSE;
DE_INIT(("init_hw done\n"));
return err;
}
static int set_mixer_defaults(struct echoaudio *chip)
{
chip->digital_mode = DIGITAL_MODE_SPDIF_RCA;
chip->professional_spdif = FALSE;
chip->digital_in_automute = TRUE;
return init_line_levels(chip);
}
static u32 detect_input_clocks(const struct echoaudio *chip)
{
u32 clocks_from_dsp, clock_bits;
/* Map the DSP clock detect bits to the generic driver clock
detect bits */
clocks_from_dsp = le32_to_cpu(chip->comm_page->status_clocks);
clock_bits = ECHO_CLOCK_BIT_INTERNAL;
if (clocks_from_dsp & GML_CLOCK_DETECT_BIT_SPDIF)
clock_bits |= ECHO_CLOCK_BIT_SPDIF;
if (clocks_from_dsp & GML_CLOCK_DETECT_BIT_ADAT)
clock_bits |= ECHO_CLOCK_BIT_ADAT;
if (clocks_from_dsp & GML_CLOCK_DETECT_BIT_ESYNC)
clock_bits |= ECHO_CLOCK_BIT_ESYNC | ECHO_CLOCK_BIT_ESYNC96;
return clock_bits;
}
/* Gina24 has an ASIC on the PCI card which must be loaded for anything
interesting to happen. */
static int load_asic(struct echoaudio *chip)
{
u32 control_reg;
int err;
short asic;
if (chip->asic_loaded)
return 1;
/* Give the DSP a few milliseconds to settle down */
mdelay(10);
/* Pick the correct ASIC for '301 or '361 Gina24 */
if (chip->device_id == DEVICE_ID_56361)
asic = FW_GINA24_361_ASIC;
else
asic = FW_GINA24_301_ASIC;
err = load_asic_generic(chip, DSP_FNC_LOAD_GINA24_ASIC, asic);
if (err < 0)
return err;
chip->asic_code = asic;
/* Now give the new ASIC a little time to set up */
mdelay(10);
/* See if it worked */
err = check_asic_status(chip);
/* Set up the control register if the load succeeded -
48 kHz, internal clock, S/PDIF RCA mode */
if (!err) {
control_reg = GML_CONVERTER_ENABLE | GML_48KHZ;
err = write_control_reg(chip, control_reg, TRUE);
}
DE_INIT(("load_asic() done\n"));
return err;
}
static int set_sample_rate(struct echoaudio *chip, u32 rate)
{
u32 control_reg, clock;
if (snd_BUG_ON(rate >= 50000 &&
chip->digital_mode == DIGITAL_MODE_ADAT))
return -EINVAL;
/* Only set the clock for internal mode. */
if (chip->input_clock != ECHO_CLOCK_INTERNAL) {
DE_ACT(("set_sample_rate: Cannot set sample rate - "
"clock not set to CLK_CLOCKININTERNAL\n"));
/* Save the rate anyhow */
chip->comm_page->sample_rate = cpu_to_le32(rate);
chip->sample_rate = rate;
return 0;
}
clock = 0;
control_reg = le32_to_cpu(chip->comm_page->control_register);
control_reg &= GML_CLOCK_CLEAR_MASK & GML_SPDIF_RATE_CLEAR_MASK;
switch (rate) {
case 96000:
clock = GML_96KHZ;
break;
case 88200:
clock = GML_88KHZ;
break;
case 48000:
clock = GML_48KHZ | GML_SPDIF_SAMPLE_RATE1;
break;
case 44100:
clock = GML_44KHZ;
/* Professional mode ? */
if (control_reg & GML_SPDIF_PRO_MODE)
clock |= GML_SPDIF_SAMPLE_RATE0;
break;
case 32000:
clock = GML_32KHZ | GML_SPDIF_SAMPLE_RATE0 |
GML_SPDIF_SAMPLE_RATE1;
break;
case 22050:
clock = GML_22KHZ;
break;
case 16000:
clock = GML_16KHZ;
break;
case 11025:
clock = GML_11KHZ;
break;
case 8000:
clock = GML_8KHZ;
break;
default:
DE_ACT(("set_sample_rate: %d invalid!\n", rate));
return -EINVAL;
}
control_reg |= clock;
chip->comm_page->sample_rate = cpu_to_le32(rate); /* ignored by the DSP */
chip->sample_rate = rate;
DE_ACT(("set_sample_rate: %d clock %d\n", rate, clock));
return write_control_reg(chip, control_reg, FALSE);
}
static int set_input_clock(struct echoaudio *chip, u16 clock)
{
u32 control_reg, clocks_from_dsp;
DE_ACT(("set_input_clock:\n"));
/* Mask off the clock select bits */
control_reg = le32_to_cpu(chip->comm_page->control_register) &
GML_CLOCK_CLEAR_MASK;
clocks_from_dsp = le32_to_cpu(chip->comm_page->status_clocks);
switch (clock) {
case ECHO_CLOCK_INTERNAL:
DE_ACT(("Set Gina24 clock to INTERNAL\n"));
chip->input_clock = ECHO_CLOCK_INTERNAL;
return set_sample_rate(chip, chip->sample_rate);
case ECHO_CLOCK_SPDIF:
if (chip->digital_mode == DIGITAL_MODE_ADAT)
return -EAGAIN;
DE_ACT(("Set Gina24 clock to SPDIF\n"));
control_reg |= GML_SPDIF_CLOCK;
if (clocks_from_dsp & GML_CLOCK_DETECT_BIT_SPDIF96)
control_reg |= GML_DOUBLE_SPEED_MODE;
else
control_reg &= ~GML_DOUBLE_SPEED_MODE;
break;
case ECHO_CLOCK_ADAT:
if (chip->digital_mode != DIGITAL_MODE_ADAT)
return -EAGAIN;
DE_ACT(("Set Gina24 clock to ADAT\n"));
control_reg |= GML_ADAT_CLOCK;
control_reg &= ~GML_DOUBLE_SPEED_MODE;
break;
case ECHO_CLOCK_ESYNC:
DE_ACT(("Set Gina24 clock to ESYNC\n"));
control_reg |= GML_ESYNC_CLOCK;
control_reg &= ~GML_DOUBLE_SPEED_MODE;
break;
case ECHO_CLOCK_ESYNC96:
DE_ACT(("Set Gina24 clock to ESYNC96\n"));
control_reg |= GML_ESYNC_CLOCK | GML_DOUBLE_SPEED_MODE;
break;
default:
DE_ACT(("Input clock 0x%x not supported for Gina24\n", clock));
return -EINVAL;
}
chip->input_clock = clock;
return write_control_reg(chip, control_reg, TRUE);
}
static int dsp_set_digital_mode(struct echoaudio *chip, u8 mode)
{
u32 control_reg;
int err, incompatible_clock;
/* Set clock to "internal" if it's not compatible with the new mode */
incompatible_clock = FALSE;
switch (mode) {
case DIGITAL_MODE_SPDIF_OPTICAL:
case DIGITAL_MODE_SPDIF_CDROM:
case DIGITAL_MODE_SPDIF_RCA:
if (chip->input_clock == ECHO_CLOCK_ADAT)
incompatible_clock = TRUE;
break;
case DIGITAL_MODE_ADAT:
if (chip->input_clock == ECHO_CLOCK_SPDIF)
incompatible_clock = TRUE;
break;
default:
DE_ACT(("Digital mode not supported: %d\n", mode));
return -EINVAL;
}
spin_lock_irq(&chip->lock);
if (incompatible_clock) { /* Switch to 48KHz, internal */
chip->sample_rate = 48000;
set_input_clock(chip, ECHO_CLOCK_INTERNAL);
}
/* Clear the current digital mode */
control_reg = le32_to_cpu(chip->comm_page->control_register);
control_reg &= GML_DIGITAL_MODE_CLEAR_MASK;
/* Tweak the control reg */
switch (mode) {
case DIGITAL_MODE_SPDIF_OPTICAL:
control_reg |= GML_SPDIF_OPTICAL_MODE;
break;
case DIGITAL_MODE_SPDIF_CDROM:
/* '361 Gina24 cards do not have the S/PDIF CD-ROM mode */
if (chip->device_id == DEVICE_ID_56301)
control_reg |= GML_SPDIF_CDROM_MODE;
break;
case DIGITAL_MODE_SPDIF_RCA:
/* GML_SPDIF_OPTICAL_MODE bit cleared */
break;
case DIGITAL_MODE_ADAT:
control_reg |= GML_ADAT_MODE;
control_reg &= ~GML_DOUBLE_SPEED_MODE;
break;
}
err = write_control_reg(chip, control_reg, TRUE);
spin_unlock_irq(&chip->lock);
if (err < 0)
return err;
chip->digital_mode = mode;
DE_ACT(("set_digital_mode to %d\n", chip->digital_mode));
return incompatible_clock;
}
| gpl-2.0 |
bmourit/owl2x-linux__old__ | arch/powerpc/boot/cuboot-85xx-cpm2.c | 14062 | 1764 | /*
* Old U-boot compatibility for 85xx
*
* Author: Scott Wood <scottwood@freescale.com>
*
* Copyright (c) 2007 Freescale Semiconductor, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include "ops.h"
#include "stdio.h"
#include "cuboot.h"
#define TARGET_85xx
#define TARGET_CPM2
#include "ppcboot.h"
static bd_t bd;
static void platform_fixups(void)
{
void *devp;
dt_fixup_memory(bd.bi_memstart, bd.bi_memsize);
dt_fixup_mac_address_by_alias("ethernet0", bd.bi_enetaddr);
dt_fixup_mac_address_by_alias("ethernet1", bd.bi_enet1addr);
dt_fixup_mac_address_by_alias("ethernet2", bd.bi_enet2addr);
dt_fixup_cpu_clocks(bd.bi_intfreq, bd.bi_busfreq / 8, bd.bi_busfreq);
/* Unfortunately, the specific model number is encoded in the
* soc node name in existing dts files -- once that is fixed,
* this can do a simple path lookup.
*/
devp = find_node_by_devtype(NULL, "soc");
if (devp) {
void *serial = NULL;
setprop(devp, "bus-frequency", &bd.bi_busfreq,
sizeof(bd.bi_busfreq));
while ((serial = find_node_by_devtype(serial, "serial"))) {
if (get_parent(serial) != devp)
continue;
setprop(serial, "clock-frequency", &bd.bi_busfreq,
sizeof(bd.bi_busfreq));
}
}
devp = find_node_by_compatible(NULL, "fsl,cpm2-brg");
if (devp)
setprop(devp, "clock-frequency", &bd.bi_brgfreq,
sizeof(bd.bi_brgfreq));
}
void platform_init(unsigned long r3, unsigned long r4, unsigned long r5,
unsigned long r6, unsigned long r7)
{
CUBOOT_INIT();
fdt_init(_dtb_start);
serial_console_init();
platform_ops.fixups = platform_fixups;
}
| gpl-2.0 |
yellowback/ubuntu-precise-armadaxp | drivers/media/video/s5k6aa.c | 239 | 44842 | /*
* Driver for Samsung S5K6AAFX SXGA 1/6" 1.3M CMOS Image Sensor
* with embedded SoC ISP.
*
* Copyright (C) 2011, Samsung Electronics Co., Ltd.
* Sylwester Nawrocki <s.nawrocki@samsung.com>
*
* Based on a driver authored by Dongsoo Nathaniel Kim.
* Copyright (C) 2009, Dongsoo Nathaniel Kim <dongsoo45.kim@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <linux/media.h>
#include <linux/module.h>
#include <linux/regulator/consumer.h>
#include <linux/slab.h>
#include <media/media-entity.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-device.h>
#include <media/v4l2-subdev.h>
#include <media/v4l2-mediabus.h>
#include <media/s5k6aa.h>
static int debug;
module_param(debug, int, 0644);
#define DRIVER_NAME "S5K6AA"
/* The token to indicate array termination */
#define S5K6AA_TERM 0xffff
#define S5K6AA_OUT_WIDTH_DEF 640
#define S5K6AA_OUT_HEIGHT_DEF 480
#define S5K6AA_WIN_WIDTH_MAX 1280
#define S5K6AA_WIN_HEIGHT_MAX 1024
#define S5K6AA_WIN_WIDTH_MIN 8
#define S5K6AA_WIN_HEIGHT_MIN 8
/*
* H/W register Interface (0xD0000000 - 0xD0000FFF)
*/
#define AHB_MSB_ADDR_PTR 0xfcfc
#define GEN_REG_OFFSH 0xd000
#define REG_CMDWR_ADDRH 0x0028
#define REG_CMDWR_ADDRL 0x002a
#define REG_CMDRD_ADDRH 0x002c
#define REG_CMDRD_ADDRL 0x002e
#define REG_CMDBUF0_ADDR 0x0f12
#define REG_CMDBUF1_ADDR 0x0f10
/*
* Host S/W Register interface (0x70000000 - 0x70002000)
* The value of the two most significant address bytes is 0x7000,
* (HOST_SWIF_OFFS_H). The register addresses below specify 2 LSBs.
*/
#define HOST_SWIF_OFFSH 0x7000
/* Initialization parameters */
/* Master clock frequency in KHz */
#define REG_I_INCLK_FREQ_L 0x01b8
#define REG_I_INCLK_FREQ_H 0x01ba
#define MIN_MCLK_FREQ_KHZ 6000U
#define MAX_MCLK_FREQ_KHZ 27000U
#define REG_I_USE_NPVI_CLOCKS 0x01c6
#define REG_I_USE_NMIPI_CLOCKS 0x01c8
/* Clock configurations, n = 0..2. REG_I_* frequency unit is 4 kHz. */
#define REG_I_OPCLK_4KHZ(n) ((n) * 6 + 0x01cc)
#define REG_I_MIN_OUTRATE_4KHZ(n) ((n) * 6 + 0x01ce)
#define REG_I_MAX_OUTRATE_4KHZ(n) ((n) * 6 + 0x01d0)
#define SYS_PLL_OUT_FREQ (48000000 / 4000)
#define PCLK_FREQ_MIN (24000000 / 4000)
#define PCLK_FREQ_MAX (48000000 / 4000)
#define REG_I_INIT_PARAMS_UPDATED 0x01e0
#define REG_I_ERROR_INFO 0x01e2
/* General purpose parameters */
#define REG_USER_BRIGHTNESS 0x01e4
#define REG_USER_CONTRAST 0x01e6
#define REG_USER_SATURATION 0x01e8
#define REG_USER_SHARPBLUR 0x01ea
#define REG_G_SPEC_EFFECTS 0x01ee
#define REG_G_ENABLE_PREV 0x01f0
#define REG_G_ENABLE_PREV_CHG 0x01f2
#define REG_G_NEW_CFG_SYNC 0x01f8
#define REG_G_PREVZOOM_IN_WIDTH 0x020a
#define REG_G_PREVZOOM_IN_HEIGHT 0x020c
#define REG_G_PREVZOOM_IN_XOFFS 0x020e
#define REG_G_PREVZOOM_IN_YOFFS 0x0210
#define REG_G_INPUTS_CHANGE_REQ 0x021a
#define REG_G_ACTIVE_PREV_CFG 0x021c
#define REG_G_PREV_CFG_CHG 0x021e
#define REG_G_PREV_OPEN_AFTER_CH 0x0220
#define REG_G_PREV_CFG_ERROR 0x0222
/* Preview control section. n = 0...4. */
#define PREG(n, x) ((n) * 0x26 + x)
#define REG_P_OUT_WIDTH(n) PREG(n, 0x0242)
#define REG_P_OUT_HEIGHT(n) PREG(n, 0x0244)
#define REG_P_FMT(n) PREG(n, 0x0246)
#define REG_P_MAX_OUT_RATE(n) PREG(n, 0x0248)
#define REG_P_MIN_OUT_RATE(n) PREG(n, 0x024a)
#define REG_P_PVI_MASK(n) PREG(n, 0x024c)
#define REG_P_CLK_INDEX(n) PREG(n, 0x024e)
#define REG_P_FR_RATE_TYPE(n) PREG(n, 0x0250)
#define FR_RATE_DYNAMIC 0
#define FR_RATE_FIXED 1
#define FR_RATE_FIXED_ACCURATE 2
#define REG_P_FR_RATE_Q_TYPE(n) PREG(n, 0x0252)
#define FR_RATE_Q_BEST_FRRATE 1 /* Binning enabled */
#define FR_RATE_Q_BEST_QUALITY 2 /* Binning disabled */
/* Frame period in 0.1 ms units */
#define REG_P_MAX_FR_TIME(n) PREG(n, 0x0254)
#define REG_P_MIN_FR_TIME(n) PREG(n, 0x0256)
/* Conversion to REG_P_[MAX/MIN]_FR_TIME value; __t: time in us */
#define US_TO_FR_TIME(__t) ((__t) / 100)
#define S5K6AA_MIN_FR_TIME 33300 /* us */
#define S5K6AA_MAX_FR_TIME 650000 /* us */
#define S5K6AA_MAX_HIGHRES_FR_TIME 666 /* x100 us */
/* The below 5 registers are for "device correction" values */
#define REG_P_COLORTEMP(n) PREG(n, 0x025e)
#define REG_P_PREV_MIRROR(n) PREG(n, 0x0262)
/* Extended image property controls */
/* Exposure time in 10 us units */
#define REG_SF_USR_EXPOSURE_L 0x03c6
#define REG_SF_USR_EXPOSURE_H 0x03c8
#define REG_SF_USR_EXPOSURE_CHG 0x03ca
#define REG_SF_USR_TOT_GAIN 0x03cc
#define REG_SF_USR_TOT_GAIN_CHG 0x03ce
#define REG_SF_RGAIN 0x03d0
#define REG_SF_RGAIN_CHG 0x03d2
#define REG_SF_GGAIN 0x03d4
#define REG_SF_GGAIN_CHG 0x03d6
#define REG_SF_BGAIN 0x03d8
#define REG_SF_BGAIN_CHG 0x03da
#define REG_SF_FLICKER_QUANT 0x03dc
#define REG_SF_FLICKER_QUANT_CHG 0x03de
/* Output interface (parallel/MIPI) setup */
#define REG_OIF_EN_MIPI_LANES 0x03fa
#define REG_OIF_EN_PACKETS 0x03fc
#define REG_OIF_CFG_CHG 0x03fe
/* Auto-algorithms enable mask */
#define REG_DBG_AUTOALG_EN 0x0400
#define AALG_ALL_EN_MASK (1 << 0)
#define AALG_AE_EN_MASK (1 << 1)
#define AALG_DIVLEI_EN_MASK (1 << 2)
#define AALG_WB_EN_MASK (1 << 3)
#define AALG_FLICKER_EN_MASK (1 << 5)
#define AALG_FIT_EN_MASK (1 << 6)
#define AALG_WRHW_EN_MASK (1 << 7)
/* Firmware revision information */
#define REG_FW_APIVER 0x012e
#define S5K6AAFX_FW_APIVER 0x0001
#define REG_FW_REVISION 0x0130
/* For now we use only one user configuration register set */
#define S5K6AA_MAX_PRESETS 1
static const char * const s5k6aa_supply_names[] = {
"vdd_core", /* Digital core supply 1.5V (1.4V to 1.6V) */
"vdda", /* Analog power supply 2.8V (2.6V to 3.0V) */
"vdd_reg", /* Regulator input power 1.8V (1.7V to 1.9V)
or 2.8V (2.6V to 3.0) */
"vddio", /* I/O supply 1.8V (1.65V to 1.95V)
or 2.8V (2.5V to 3.1V) */
};
#define S5K6AA_NUM_SUPPLIES ARRAY_SIZE(s5k6aa_supply_names)
enum s5k6aa_gpio_id {
STBY,
RST,
GPIO_NUM,
};
struct s5k6aa_regval {
u16 addr;
u16 val;
};
struct s5k6aa_pixfmt {
enum v4l2_mbus_pixelcode code;
u32 colorspace;
/* REG_P_FMT(x) register value */
u16 reg_p_fmt;
};
struct s5k6aa_preset {
/* output pixel format and resolution */
struct v4l2_mbus_framefmt mbus_fmt;
u8 clk_id;
u8 index;
};
struct s5k6aa_ctrls {
struct v4l2_ctrl_handler handler;
/* Auto / manual white balance cluster */
struct v4l2_ctrl *awb;
struct v4l2_ctrl *gain_red;
struct v4l2_ctrl *gain_blue;
struct v4l2_ctrl *gain_green;
/* Mirror cluster */
struct v4l2_ctrl *hflip;
struct v4l2_ctrl *vflip;
/* Auto exposure / manual exposure and gain cluster */
struct v4l2_ctrl *auto_exp;
struct v4l2_ctrl *exposure;
struct v4l2_ctrl *gain;
};
struct s5k6aa_interval {
u16 reg_fr_time;
struct v4l2_fract interval;
/* Maximum rectangle for the interval */
struct v4l2_frmsize_discrete size;
};
struct s5k6aa {
struct v4l2_subdev sd;
struct media_pad pad;
enum v4l2_mbus_type bus_type;
u8 mipi_lanes;
int (*s_power)(int enable);
struct regulator_bulk_data supplies[S5K6AA_NUM_SUPPLIES];
struct s5k6aa_gpio gpio[GPIO_NUM];
/* external master clock frequency */
unsigned long mclk_frequency;
/* ISP internal master clock frequency */
u16 clk_fop;
/* output pixel clock frequency range */
u16 pclk_fmin;
u16 pclk_fmax;
unsigned int inv_hflip:1;
unsigned int inv_vflip:1;
/* protects the struct members below */
struct mutex lock;
/* sensor matrix scan window */
struct v4l2_rect ccd_rect;
struct s5k6aa_ctrls ctrls;
struct s5k6aa_preset presets[S5K6AA_MAX_PRESETS];
struct s5k6aa_preset *preset;
const struct s5k6aa_interval *fiv;
unsigned int streaming:1;
unsigned int apply_cfg:1;
unsigned int apply_crop:1;
unsigned int power;
};
static struct s5k6aa_regval s5k6aa_analog_config[] = {
/* Analog settings */
{ 0x112a, 0x0000 }, { 0x1132, 0x0000 },
{ 0x113e, 0x0000 }, { 0x115c, 0x0000 },
{ 0x1164, 0x0000 }, { 0x1174, 0x0000 },
{ 0x1178, 0x0000 }, { 0x077a, 0x0000 },
{ 0x077c, 0x0000 }, { 0x077e, 0x0000 },
{ 0x0780, 0x0000 }, { 0x0782, 0x0000 },
{ 0x0784, 0x0000 }, { 0x0786, 0x0000 },
{ 0x0788, 0x0000 }, { 0x07a2, 0x0000 },
{ 0x07a4, 0x0000 }, { 0x07a6, 0x0000 },
{ 0x07a8, 0x0000 }, { 0x07b6, 0x0000 },
{ 0x07b8, 0x0002 }, { 0x07ba, 0x0004 },
{ 0x07bc, 0x0004 }, { 0x07be, 0x0005 },
{ 0x07c0, 0x0005 }, { S5K6AA_TERM, 0 },
};
/* TODO: Add RGB888 and Bayer format */
static const struct s5k6aa_pixfmt s5k6aa_formats[] = {
{ V4L2_MBUS_FMT_YUYV8_2X8, V4L2_COLORSPACE_JPEG, 5 },
/* range 16-240 */
{ V4L2_MBUS_FMT_YUYV8_2X8, V4L2_COLORSPACE_REC709, 6 },
{ V4L2_MBUS_FMT_RGB565_2X8_BE, V4L2_COLORSPACE_JPEG, 0 },
};
static const struct s5k6aa_interval s5k6aa_intervals[] = {
{ 1000, {10000, 1000000}, {1280, 1024} }, /* 10 fps */
{ 666, {15000, 1000000}, {1280, 1024} }, /* 15 fps */
{ 500, {20000, 1000000}, {1280, 720} }, /* 20 fps */
{ 400, {25000, 1000000}, {640, 480} }, /* 25 fps */
{ 333, {33300, 1000000}, {640, 480} }, /* 30 fps */
};
#define S5K6AA_INTERVAL_DEF_INDEX 1 /* 15 fps */
static inline struct v4l2_subdev *ctrl_to_sd(struct v4l2_ctrl *ctrl)
{
return &container_of(ctrl->handler, struct s5k6aa, ctrls.handler)->sd;
}
static inline struct s5k6aa *to_s5k6aa(struct v4l2_subdev *sd)
{
return container_of(sd, struct s5k6aa, sd);
}
/* Set initial values for all preview presets */
static void s5k6aa_presets_data_init(struct s5k6aa *s5k6aa)
{
struct s5k6aa_preset *preset = &s5k6aa->presets[0];
int i;
for (i = 0; i < S5K6AA_MAX_PRESETS; i++) {
preset->mbus_fmt.width = S5K6AA_OUT_WIDTH_DEF;
preset->mbus_fmt.height = S5K6AA_OUT_HEIGHT_DEF;
preset->mbus_fmt.code = s5k6aa_formats[0].code;
preset->index = i;
preset->clk_id = 0;
preset++;
}
s5k6aa->fiv = &s5k6aa_intervals[S5K6AA_INTERVAL_DEF_INDEX];
s5k6aa->preset = &s5k6aa->presets[0];
}
static int s5k6aa_i2c_read(struct i2c_client *client, u16 addr, u16 *val)
{
u8 wbuf[2] = {addr >> 8, addr & 0xFF};
struct i2c_msg msg[2];
u8 rbuf[2];
int ret;
msg[0].addr = client->addr;
msg[0].flags = 0;
msg[0].len = 2;
msg[0].buf = wbuf;
msg[1].addr = client->addr;
msg[1].flags = I2C_M_RD;
msg[1].len = 2;
msg[1].buf = rbuf;
ret = i2c_transfer(client->adapter, msg, 2);
*val = be16_to_cpu(*((u16 *)rbuf));
v4l2_dbg(3, debug, client, "i2c_read: 0x%04X : 0x%04x\n", addr, *val);
return ret == 2 ? 0 : ret;
}
static int s5k6aa_i2c_write(struct i2c_client *client, u16 addr, u16 val)
{
u8 buf[4] = {addr >> 8, addr & 0xFF, val >> 8, val & 0xFF};
int ret = i2c_master_send(client, buf, 4);
v4l2_dbg(3, debug, client, "i2c_write: 0x%04X : 0x%04x\n", addr, val);
return ret == 4 ? 0 : ret;
}
/* The command register write, assumes Command_Wr_addH = 0x7000. */
static int s5k6aa_write(struct i2c_client *c, u16 addr, u16 val)
{
int ret = s5k6aa_i2c_write(c, REG_CMDWR_ADDRL, addr);
if (ret)
return ret;
return s5k6aa_i2c_write(c, REG_CMDBUF0_ADDR, val);
}
/* The command register read, assumes Command_Rd_addH = 0x7000. */
static int s5k6aa_read(struct i2c_client *client, u16 addr, u16 *val)
{
int ret = s5k6aa_i2c_write(client, REG_CMDRD_ADDRL, addr);
if (ret)
return ret;
return s5k6aa_i2c_read(client, REG_CMDBUF0_ADDR, val);
}
static int s5k6aa_write_array(struct v4l2_subdev *sd,
const struct s5k6aa_regval *msg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
u16 addr_incr = 0;
int ret = 0;
while (msg->addr != S5K6AA_TERM) {
if (addr_incr != 2)
ret = s5k6aa_i2c_write(client, REG_CMDWR_ADDRL,
msg->addr);
if (ret)
break;
ret = s5k6aa_i2c_write(client, REG_CMDBUF0_ADDR, msg->val);
if (ret)
break;
/* Assume that msg->addr is always less than 0xfffc */
addr_incr = (msg + 1)->addr - msg->addr;
msg++;
}
return ret;
}
/* Configure the AHB high address bytes for GTG registers access */
static int s5k6aa_set_ahb_address(struct i2c_client *client)
{
int ret = s5k6aa_i2c_write(client, AHB_MSB_ADDR_PTR, GEN_REG_OFFSH);
if (ret)
return ret;
ret = s5k6aa_i2c_write(client, REG_CMDRD_ADDRH, HOST_SWIF_OFFSH);
if (ret)
return ret;
return s5k6aa_i2c_write(client, REG_CMDWR_ADDRH, HOST_SWIF_OFFSH);
}
/**
* s5k6aa_configure_pixel_clock - apply ISP main clock/PLL configuration
*
* Configure the internal ISP PLL for the required output frequency.
* Locking: called with s5k6aa.lock mutex held.
*/
static int s5k6aa_configure_pixel_clocks(struct s5k6aa *s5k6aa)
{
struct i2c_client *c = v4l2_get_subdevdata(&s5k6aa->sd);
unsigned long fmclk = s5k6aa->mclk_frequency / 1000;
u16 status;
int ret;
if (WARN(fmclk < MIN_MCLK_FREQ_KHZ || fmclk > MAX_MCLK_FREQ_KHZ,
"Invalid clock frequency: %ld\n", fmclk))
return -EINVAL;
s5k6aa->pclk_fmin = PCLK_FREQ_MIN;
s5k6aa->pclk_fmax = PCLK_FREQ_MAX;
s5k6aa->clk_fop = SYS_PLL_OUT_FREQ;
/* External input clock frequency in kHz */
ret = s5k6aa_write(c, REG_I_INCLK_FREQ_H, fmclk >> 16);
if (!ret)
ret = s5k6aa_write(c, REG_I_INCLK_FREQ_L, fmclk & 0xFFFF);
if (!ret)
ret = s5k6aa_write(c, REG_I_USE_NPVI_CLOCKS, 1);
/* Internal PLL frequency */
if (!ret)
ret = s5k6aa_write(c, REG_I_OPCLK_4KHZ(0), s5k6aa->clk_fop);
if (!ret)
ret = s5k6aa_write(c, REG_I_MIN_OUTRATE_4KHZ(0),
s5k6aa->pclk_fmin);
if (!ret)
ret = s5k6aa_write(c, REG_I_MAX_OUTRATE_4KHZ(0),
s5k6aa->pclk_fmax);
if (!ret)
ret = s5k6aa_write(c, REG_I_INIT_PARAMS_UPDATED, 1);
if (!ret)
ret = s5k6aa_read(c, REG_I_ERROR_INFO, &status);
return ret ? ret : (status ? -EINVAL : 0);
}
/* Set horizontal and vertical image flipping */
static int s5k6aa_set_mirror(struct s5k6aa *s5k6aa, int horiz_flip)
{
struct i2c_client *client = v4l2_get_subdevdata(&s5k6aa->sd);
int index = s5k6aa->preset->index;
unsigned int vflip = s5k6aa->ctrls.vflip->val ^ s5k6aa->inv_vflip;
unsigned int flip = (horiz_flip ^ s5k6aa->inv_hflip) | (vflip << 1);
return s5k6aa_write(client, REG_P_PREV_MIRROR(index), flip);
}
/* Configure auto/manual white balance and R/G/B gains */
static int s5k6aa_set_awb(struct s5k6aa *s5k6aa, int awb)
{
struct i2c_client *c = v4l2_get_subdevdata(&s5k6aa->sd);
struct s5k6aa_ctrls *ctrls = &s5k6aa->ctrls;
u16 reg;
int ret = s5k6aa_read(c, REG_DBG_AUTOALG_EN, ®);
if (!ret && !awb) {
ret = s5k6aa_write(c, REG_SF_RGAIN, ctrls->gain_red->val);
if (!ret)
ret = s5k6aa_write(c, REG_SF_RGAIN_CHG, 1);
if (ret)
return ret;
ret = s5k6aa_write(c, REG_SF_GGAIN, ctrls->gain_green->val);
if (!ret)
ret = s5k6aa_write(c, REG_SF_GGAIN_CHG, 1);
if (ret)
return ret;
ret = s5k6aa_write(c, REG_SF_BGAIN, ctrls->gain_blue->val);
if (!ret)
ret = s5k6aa_write(c, REG_SF_BGAIN_CHG, 1);
}
if (!ret) {
reg = awb ? reg | AALG_WB_EN_MASK : reg & ~AALG_WB_EN_MASK;
ret = s5k6aa_write(c, REG_DBG_AUTOALG_EN, reg);
}
return ret;
}
/* Program FW with exposure time, 'exposure' in us units */
static int s5k6aa_set_user_exposure(struct i2c_client *client, int exposure)
{
unsigned int time = exposure / 10;
int ret = s5k6aa_write(client, REG_SF_USR_EXPOSURE_L, time & 0xffff);
if (!ret)
ret = s5k6aa_write(client, REG_SF_USR_EXPOSURE_H, time >> 16);
if (ret)
return ret;
return s5k6aa_write(client, REG_SF_USR_EXPOSURE_CHG, 1);
}
static int s5k6aa_set_user_gain(struct i2c_client *client, int gain)
{
int ret = s5k6aa_write(client, REG_SF_USR_TOT_GAIN, gain);
if (ret)
return ret;
return s5k6aa_write(client, REG_SF_USR_TOT_GAIN_CHG, 1);
}
/* Set auto/manual exposure and total gain */
static int s5k6aa_set_auto_exposure(struct s5k6aa *s5k6aa, int value)
{
struct i2c_client *c = v4l2_get_subdevdata(&s5k6aa->sd);
unsigned int exp_time = s5k6aa->ctrls.exposure->val;
u16 auto_alg;
int ret = s5k6aa_read(c, REG_DBG_AUTOALG_EN, &auto_alg);
if (ret)
return ret;
v4l2_dbg(1, debug, c, "man_exp: %d, auto_exp: %d, a_alg: 0x%x\n",
exp_time, value, auto_alg);
if (value == V4L2_EXPOSURE_AUTO) {
auto_alg |= AALG_AE_EN_MASK | AALG_DIVLEI_EN_MASK;
} else {
ret = s5k6aa_set_user_exposure(c, exp_time);
if (ret)
return ret;
ret = s5k6aa_set_user_gain(c, s5k6aa->ctrls.gain->val);
if (ret)
return ret;
auto_alg &= ~(AALG_AE_EN_MASK | AALG_DIVLEI_EN_MASK);
}
return s5k6aa_write(c, REG_DBG_AUTOALG_EN, auto_alg);
}
static int s5k6aa_set_anti_flicker(struct s5k6aa *s5k6aa, int value)
{
struct i2c_client *client = v4l2_get_subdevdata(&s5k6aa->sd);
u16 auto_alg;
int ret;
ret = s5k6aa_read(client, REG_DBG_AUTOALG_EN, &auto_alg);
if (ret)
return ret;
if (value == V4L2_CID_POWER_LINE_FREQUENCY_AUTO) {
auto_alg |= AALG_FLICKER_EN_MASK;
} else {
auto_alg &= ~AALG_FLICKER_EN_MASK;
/* The V4L2_CID_LINE_FREQUENCY control values match
* the register values */
ret = s5k6aa_write(client, REG_SF_FLICKER_QUANT, value);
if (ret)
return ret;
ret = s5k6aa_write(client, REG_SF_FLICKER_QUANT_CHG, 1);
if (ret)
return ret;
}
return s5k6aa_write(client, REG_DBG_AUTOALG_EN, auto_alg);
}
static int s5k6aa_set_colorfx(struct s5k6aa *s5k6aa, int val)
{
struct i2c_client *client = v4l2_get_subdevdata(&s5k6aa->sd);
static const struct v4l2_control colorfx[] = {
{ V4L2_COLORFX_NONE, 0 },
{ V4L2_COLORFX_BW, 1 },
{ V4L2_COLORFX_NEGATIVE, 2 },
{ V4L2_COLORFX_SEPIA, 3 },
{ V4L2_COLORFX_SKY_BLUE, 4 },
{ V4L2_COLORFX_SKETCH, 5 },
};
int i;
for (i = 0; i < ARRAY_SIZE(colorfx); i++) {
if (colorfx[i].id == val)
return s5k6aa_write(client, REG_G_SPEC_EFFECTS,
colorfx[i].value);
}
return -EINVAL;
}
static int s5k6aa_preview_config_status(struct i2c_client *client)
{
u16 error = 0;
int ret = s5k6aa_read(client, REG_G_PREV_CFG_ERROR, &error);
v4l2_dbg(1, debug, client, "error: 0x%x (%d)\n", error, ret);
return ret ? ret : (error ? -EINVAL : 0);
}
static int s5k6aa_get_pixfmt_index(struct s5k6aa *s5k6aa,
struct v4l2_mbus_framefmt *mf)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(s5k6aa_formats); i++)
if (mf->colorspace == s5k6aa_formats[i].colorspace &&
mf->code == s5k6aa_formats[i].code)
return i;
return 0;
}
static int s5k6aa_set_output_framefmt(struct s5k6aa *s5k6aa,
struct s5k6aa_preset *preset)
{
struct i2c_client *client = v4l2_get_subdevdata(&s5k6aa->sd);
int fmt_index = s5k6aa_get_pixfmt_index(s5k6aa, &preset->mbus_fmt);
int ret;
ret = s5k6aa_write(client, REG_P_OUT_WIDTH(preset->index),
preset->mbus_fmt.width);
if (!ret)
ret = s5k6aa_write(client, REG_P_OUT_HEIGHT(preset->index),
preset->mbus_fmt.height);
if (!ret)
ret = s5k6aa_write(client, REG_P_FMT(preset->index),
s5k6aa_formats[fmt_index].reg_p_fmt);
return ret;
}
static int s5k6aa_set_input_params(struct s5k6aa *s5k6aa)
{
struct i2c_client *c = v4l2_get_subdevdata(&s5k6aa->sd);
struct v4l2_rect *r = &s5k6aa->ccd_rect;
int ret;
ret = s5k6aa_write(c, REG_G_PREVZOOM_IN_WIDTH, r->width);
if (!ret)
ret = s5k6aa_write(c, REG_G_PREVZOOM_IN_HEIGHT, r->height);
if (!ret)
ret = s5k6aa_write(c, REG_G_PREVZOOM_IN_XOFFS, r->left);
if (!ret)
ret = s5k6aa_write(c, REG_G_PREVZOOM_IN_YOFFS, r->top);
if (!ret)
ret = s5k6aa_write(c, REG_G_INPUTS_CHANGE_REQ, 1);
if (!ret)
s5k6aa->apply_crop = 0;
return ret;
}
/**
* s5k6aa_configure_video_bus - configure the video output interface
* @bus_type: video bus type: parallel or MIPI-CSI
* @nlanes: number of MIPI lanes to be used (MIPI-CSI only)
*
* Note: Only parallel bus operation has been tested.
*/
static int s5k6aa_configure_video_bus(struct s5k6aa *s5k6aa,
enum v4l2_mbus_type bus_type, int nlanes)
{
struct i2c_client *client = v4l2_get_subdevdata(&s5k6aa->sd);
u16 cfg = 0;
int ret;
/*
* TODO: The sensor is supposed to support BT.601 and BT.656
* but there is nothing indicating how to switch between both
* in the datasheet. For now default BT.601 interface is assumed.
*/
if (bus_type == V4L2_MBUS_CSI2)
cfg = nlanes;
else if (bus_type != V4L2_MBUS_PARALLEL)
return -EINVAL;
ret = s5k6aa_write(client, REG_OIF_EN_MIPI_LANES, cfg);
if (ret)
return ret;
return s5k6aa_write(client, REG_OIF_CFG_CHG, 1);
}
/* This function should be called when switching to new user configuration set*/
static int s5k6aa_new_config_sync(struct i2c_client *client, int timeout,
int cid)
{
unsigned long end = jiffies + msecs_to_jiffies(timeout);
u16 reg = 1;
int ret;
ret = s5k6aa_write(client, REG_G_ACTIVE_PREV_CFG, cid);
if (!ret)
ret = s5k6aa_write(client, REG_G_PREV_CFG_CHG, 1);
if (!ret)
ret = s5k6aa_write(client, REG_G_NEW_CFG_SYNC, 1);
if (timeout == 0)
return ret;
while (ret >= 0 && time_is_after_jiffies(end)) {
ret = s5k6aa_read(client, REG_G_NEW_CFG_SYNC, ®);
if (!reg)
return 0;
usleep_range(1000, 5000);
}
return ret ? ret : -ETIMEDOUT;
}
/**
* s5k6aa_set_prev_config - write user preview register set
*
* Configure output resolution and color fromat, pixel clock
* frequency range, device frame rate type and frame period range.
*/
static int s5k6aa_set_prev_config(struct s5k6aa *s5k6aa,
struct s5k6aa_preset *preset)
{
struct i2c_client *client = v4l2_get_subdevdata(&s5k6aa->sd);
int idx = preset->index;
u16 frame_rate_q;
int ret;
if (s5k6aa->fiv->reg_fr_time >= S5K6AA_MAX_HIGHRES_FR_TIME)
frame_rate_q = FR_RATE_Q_BEST_FRRATE;
else
frame_rate_q = FR_RATE_Q_BEST_QUALITY;
ret = s5k6aa_set_output_framefmt(s5k6aa, preset);
if (!ret)
ret = s5k6aa_write(client, REG_P_MAX_OUT_RATE(idx),
s5k6aa->pclk_fmax);
if (!ret)
ret = s5k6aa_write(client, REG_P_MIN_OUT_RATE(idx),
s5k6aa->pclk_fmin);
if (!ret)
ret = s5k6aa_write(client, REG_P_CLK_INDEX(idx),
preset->clk_id);
if (!ret)
ret = s5k6aa_write(client, REG_P_FR_RATE_TYPE(idx),
FR_RATE_DYNAMIC);
if (!ret)
ret = s5k6aa_write(client, REG_P_FR_RATE_Q_TYPE(idx),
frame_rate_q);
if (!ret)
ret = s5k6aa_write(client, REG_P_MAX_FR_TIME(idx),
s5k6aa->fiv->reg_fr_time + 33);
if (!ret)
ret = s5k6aa_write(client, REG_P_MIN_FR_TIME(idx),
s5k6aa->fiv->reg_fr_time - 33);
if (!ret)
ret = s5k6aa_new_config_sync(client, 250, idx);
if (!ret)
ret = s5k6aa_preview_config_status(client);
if (!ret)
s5k6aa->apply_cfg = 0;
v4l2_dbg(1, debug, client, "Frame interval: %d +/- 3.3ms. (%d)\n",
s5k6aa->fiv->reg_fr_time, ret);
return ret;
}
/**
* s5k6aa_initialize_isp - basic ISP MCU initialization
*
* Configure AHB addresses for registers read/write; configure PLLs for
* required output pixel clock. The ISP power supply needs to be already
* enabled, with an optional H/W reset.
* Locking: called with s5k6aa.lock mutex held.
*/
static int s5k6aa_initialize_isp(struct v4l2_subdev *sd)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct s5k6aa *s5k6aa = to_s5k6aa(sd);
int ret;
s5k6aa->apply_crop = 1;
s5k6aa->apply_cfg = 1;
msleep(100);
ret = s5k6aa_set_ahb_address(client);
if (ret)
return ret;
ret = s5k6aa_configure_video_bus(s5k6aa, s5k6aa->bus_type,
s5k6aa->mipi_lanes);
if (ret)
return ret;
ret = s5k6aa_write_array(sd, s5k6aa_analog_config);
if (ret)
return ret;
msleep(20);
return s5k6aa_configure_pixel_clocks(s5k6aa);
}
static int s5k6aa_gpio_set_value(struct s5k6aa *priv, int id, u32 val)
{
if (!gpio_is_valid(priv->gpio[id].gpio))
return 0;
gpio_set_value(priv->gpio[id].gpio, !!val);
return 1;
}
static int s5k6aa_gpio_assert(struct s5k6aa *priv, int id)
{
return s5k6aa_gpio_set_value(priv, id, priv->gpio[id].level);
}
static int s5k6aa_gpio_deassert(struct s5k6aa *priv, int id)
{
return s5k6aa_gpio_set_value(priv, id, !priv->gpio[id].level);
}
static int __s5k6aa_power_on(struct s5k6aa *s5k6aa)
{
int ret;
ret = regulator_bulk_enable(S5K6AA_NUM_SUPPLIES, s5k6aa->supplies);
if (ret)
return ret;
if (s5k6aa_gpio_deassert(s5k6aa, STBY))
usleep_range(150, 200);
if (s5k6aa->s_power)
ret = s5k6aa->s_power(1);
usleep_range(4000, 4000);
if (s5k6aa_gpio_deassert(s5k6aa, RST))
msleep(20);
return ret;
}
static int __s5k6aa_power_off(struct s5k6aa *s5k6aa)
{
int ret;
if (s5k6aa_gpio_assert(s5k6aa, RST))
usleep_range(100, 150);
if (s5k6aa->s_power) {
ret = s5k6aa->s_power(0);
if (ret)
return ret;
}
if (s5k6aa_gpio_assert(s5k6aa, STBY))
usleep_range(50, 100);
s5k6aa->streaming = 0;
return regulator_bulk_disable(S5K6AA_NUM_SUPPLIES, s5k6aa->supplies);
}
/*
* V4L2 subdev core and video operations
*/
static int s5k6aa_set_power(struct v4l2_subdev *sd, int on)
{
struct s5k6aa *s5k6aa = to_s5k6aa(sd);
int ret = 0;
mutex_lock(&s5k6aa->lock);
if (!on == s5k6aa->power) {
if (on) {
ret = __s5k6aa_power_on(s5k6aa);
if (!ret)
ret = s5k6aa_initialize_isp(sd);
} else {
ret = __s5k6aa_power_off(s5k6aa);
}
if (!ret)
s5k6aa->power += on ? 1 : -1;
}
mutex_unlock(&s5k6aa->lock);
if (!on || ret || s5k6aa->power != 1)
return ret;
return v4l2_ctrl_handler_setup(sd->ctrl_handler);
}
static int __s5k6aa_stream(struct s5k6aa *s5k6aa, int enable)
{
struct i2c_client *client = v4l2_get_subdevdata(&s5k6aa->sd);
int ret = 0;
ret = s5k6aa_write(client, REG_G_ENABLE_PREV, enable);
if (!ret)
ret = s5k6aa_write(client, REG_G_ENABLE_PREV_CHG, 1);
if (!ret)
s5k6aa->streaming = enable;
return ret;
}
static int s5k6aa_s_stream(struct v4l2_subdev *sd, int on)
{
struct s5k6aa *s5k6aa = to_s5k6aa(sd);
int ret = 0;
mutex_lock(&s5k6aa->lock);
if (s5k6aa->streaming == !on) {
if (!ret && s5k6aa->apply_cfg)
ret = s5k6aa_set_prev_config(s5k6aa, s5k6aa->preset);
if (s5k6aa->apply_crop)
ret = s5k6aa_set_input_params(s5k6aa);
if (!ret)
ret = __s5k6aa_stream(s5k6aa, !!on);
}
mutex_unlock(&s5k6aa->lock);
return ret;
}
static int s5k6aa_g_frame_interval(struct v4l2_subdev *sd,
struct v4l2_subdev_frame_interval *fi)
{
struct s5k6aa *s5k6aa = to_s5k6aa(sd);
mutex_lock(&s5k6aa->lock);
fi->interval = s5k6aa->fiv->interval;
mutex_unlock(&s5k6aa->lock);
return 0;
}
static int __s5k6aa_set_frame_interval(struct s5k6aa *s5k6aa,
struct v4l2_subdev_frame_interval *fi)
{
struct v4l2_mbus_framefmt *mbus_fmt = &s5k6aa->preset->mbus_fmt;
const struct s5k6aa_interval *fiv = &s5k6aa_intervals[0];
unsigned int err, min_err = UINT_MAX;
unsigned int i, fr_time;
if (fi->interval.denominator == 0)
return -EINVAL;
fr_time = fi->interval.numerator * 10000 / fi->interval.denominator;
for (i = 0; i < ARRAY_SIZE(s5k6aa_intervals); i++) {
const struct s5k6aa_interval *iv = &s5k6aa_intervals[i];
if (mbus_fmt->width > iv->size.width ||
mbus_fmt->height > iv->size.height)
continue;
err = abs(iv->reg_fr_time - fr_time);
if (err < min_err) {
fiv = iv;
min_err = err;
}
}
s5k6aa->fiv = fiv;
v4l2_dbg(1, debug, &s5k6aa->sd, "Changed frame interval to %d us\n",
fiv->reg_fr_time * 100);
return 0;
}
static int s5k6aa_s_frame_interval(struct v4l2_subdev *sd,
struct v4l2_subdev_frame_interval *fi)
{
struct s5k6aa *s5k6aa = to_s5k6aa(sd);
int ret;
v4l2_dbg(1, debug, sd, "Setting %d/%d frame interval\n",
fi->interval.numerator, fi->interval.denominator);
mutex_lock(&s5k6aa->lock);
ret = __s5k6aa_set_frame_interval(s5k6aa, fi);
s5k6aa->apply_cfg = 1;
mutex_unlock(&s5k6aa->lock);
return ret;
}
/*
* V4L2 subdev pad level and video operations
*/
static int s5k6aa_enum_frame_interval(struct v4l2_subdev *sd,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_frame_interval_enum *fie)
{
struct s5k6aa *s5k6aa = to_s5k6aa(sd);
const struct s5k6aa_interval *fi;
int ret = 0;
if (fie->index > ARRAY_SIZE(s5k6aa_intervals))
return -EINVAL;
v4l_bound_align_image(&fie->width, S5K6AA_WIN_WIDTH_MIN,
S5K6AA_WIN_WIDTH_MAX, 1,
&fie->height, S5K6AA_WIN_HEIGHT_MIN,
S5K6AA_WIN_HEIGHT_MAX, 1, 0);
mutex_lock(&s5k6aa->lock);
fi = &s5k6aa_intervals[fie->index];
if (fie->width > fi->size.width || fie->height > fi->size.height)
ret = -EINVAL;
else
fie->interval = fi->interval;
mutex_unlock(&s5k6aa->lock);
return ret;
}
static int s5k6aa_enum_mbus_code(struct v4l2_subdev *sd,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_mbus_code_enum *code)
{
if (code->index >= ARRAY_SIZE(s5k6aa_formats))
return -EINVAL;
code->code = s5k6aa_formats[code->index].code;
return 0;
}
static int s5k6aa_enum_frame_size(struct v4l2_subdev *sd,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_frame_size_enum *fse)
{
int i = ARRAY_SIZE(s5k6aa_formats);
if (fse->index > 0)
return -EINVAL;
while (--i)
if (fse->code == s5k6aa_formats[i].code)
break;
fse->code = s5k6aa_formats[i].code;
fse->min_width = S5K6AA_WIN_WIDTH_MIN;
fse->max_width = S5K6AA_WIN_WIDTH_MAX;
fse->max_height = S5K6AA_WIN_HEIGHT_MIN;
fse->min_height = S5K6AA_WIN_HEIGHT_MAX;
return 0;
}
static struct v4l2_rect *
__s5k6aa_get_crop_rect(struct s5k6aa *s5k6aa, struct v4l2_subdev_fh *fh,
enum v4l2_subdev_format_whence which)
{
if (which == V4L2_SUBDEV_FORMAT_ACTIVE)
return &s5k6aa->ccd_rect;
if (which == V4L2_SUBDEV_FORMAT_TRY)
return v4l2_subdev_get_try_crop(fh, 0);
return NULL;
}
static void s5k6aa_try_format(struct s5k6aa *s5k6aa,
struct v4l2_mbus_framefmt *mf)
{
unsigned int index;
v4l_bound_align_image(&mf->width, S5K6AA_WIN_WIDTH_MIN,
S5K6AA_WIN_WIDTH_MAX, 1,
&mf->height, S5K6AA_WIN_HEIGHT_MIN,
S5K6AA_WIN_HEIGHT_MAX, 1, 0);
if (mf->colorspace != V4L2_COLORSPACE_JPEG &&
mf->colorspace != V4L2_COLORSPACE_REC709)
mf->colorspace = V4L2_COLORSPACE_JPEG;
index = s5k6aa_get_pixfmt_index(s5k6aa, mf);
mf->colorspace = s5k6aa_formats[index].colorspace;
mf->code = s5k6aa_formats[index].code;
mf->field = V4L2_FIELD_NONE;
}
static int s5k6aa_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh,
struct v4l2_subdev_format *fmt)
{
struct s5k6aa *s5k6aa = to_s5k6aa(sd);
struct v4l2_mbus_framefmt *mf;
memset(fmt->reserved, 0, sizeof(fmt->reserved));
if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
mf = v4l2_subdev_get_try_format(fh, 0);
fmt->format = *mf;
return 0;
}
mutex_lock(&s5k6aa->lock);
fmt->format = s5k6aa->preset->mbus_fmt;
mutex_unlock(&s5k6aa->lock);
return 0;
}
static int s5k6aa_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh,
struct v4l2_subdev_format *fmt)
{
struct s5k6aa *s5k6aa = to_s5k6aa(sd);
struct s5k6aa_preset *preset = s5k6aa->preset;
struct v4l2_mbus_framefmt *mf;
struct v4l2_rect *crop;
int ret = 0;
mutex_lock(&s5k6aa->lock);
s5k6aa_try_format(s5k6aa, &fmt->format);
if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
mf = v4l2_subdev_get_try_format(fh, fmt->pad);
crop = v4l2_subdev_get_try_crop(fh, 0);
} else {
if (s5k6aa->streaming) {
ret = -EBUSY;
} else {
mf = &preset->mbus_fmt;
crop = &s5k6aa->ccd_rect;
s5k6aa->apply_cfg = 1;
}
}
if (ret == 0) {
struct v4l2_subdev_frame_interval fiv = {
.interval = {0, 1}
};
*mf = fmt->format;
/*
* Make sure the crop window is valid, i.e. its size is
* greater than the output window, as the ISP supports
* only down-scaling.
*/
crop->width = clamp_t(unsigned int, crop->width, mf->width,
S5K6AA_WIN_WIDTH_MAX);
crop->height = clamp_t(unsigned int, crop->height, mf->height,
S5K6AA_WIN_HEIGHT_MAX);
crop->left = clamp_t(unsigned int, crop->left, 0,
S5K6AA_WIN_WIDTH_MAX - crop->width);
crop->top = clamp_t(unsigned int, crop->top, 0,
S5K6AA_WIN_HEIGHT_MAX - crop->height);
/* Reset to minimum possible frame interval */
ret = __s5k6aa_set_frame_interval(s5k6aa, &fiv);
}
mutex_unlock(&s5k6aa->lock);
return ret;
}
static int s5k6aa_get_crop(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh,
struct v4l2_subdev_crop *crop)
{
struct s5k6aa *s5k6aa = to_s5k6aa(sd);
struct v4l2_rect *rect;
memset(crop->reserved, 0, sizeof(crop->reserved));
mutex_lock(&s5k6aa->lock);
rect = __s5k6aa_get_crop_rect(s5k6aa, fh, crop->which);
if (rect)
crop->rect = *rect;
mutex_unlock(&s5k6aa->lock);
v4l2_dbg(1, debug, sd, "Current crop rectangle: (%d,%d)/%dx%d\n",
rect->left, rect->top, rect->width, rect->height);
return 0;
}
static int s5k6aa_set_crop(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh,
struct v4l2_subdev_crop *crop)
{
struct s5k6aa *s5k6aa = to_s5k6aa(sd);
struct v4l2_mbus_framefmt *mf;
unsigned int max_x, max_y;
struct v4l2_rect *crop_r;
mutex_lock(&s5k6aa->lock);
crop_r = __s5k6aa_get_crop_rect(s5k6aa, fh, crop->which);
if (crop->which == V4L2_SUBDEV_FORMAT_ACTIVE) {
mf = &s5k6aa->preset->mbus_fmt;
s5k6aa->apply_crop = 1;
} else {
mf = v4l2_subdev_get_try_format(fh, 0);
}
v4l_bound_align_image(&crop->rect.width, mf->width,
S5K6AA_WIN_WIDTH_MAX, 1,
&crop->rect.height, mf->height,
S5K6AA_WIN_HEIGHT_MAX, 1, 0);
max_x = (S5K6AA_WIN_WIDTH_MAX - crop->rect.width) & ~1;
max_y = (S5K6AA_WIN_HEIGHT_MAX - crop->rect.height) & ~1;
crop->rect.left = clamp_t(unsigned int, crop->rect.left, 0, max_x);
crop->rect.top = clamp_t(unsigned int, crop->rect.top, 0, max_y);
*crop_r = crop->rect;
mutex_unlock(&s5k6aa->lock);
v4l2_dbg(1, debug, sd, "Set crop rectangle: (%d,%d)/%dx%d\n",
crop_r->left, crop_r->top, crop_r->width, crop_r->height);
return 0;
}
static const struct v4l2_subdev_pad_ops s5k6aa_pad_ops = {
.enum_mbus_code = s5k6aa_enum_mbus_code,
.enum_frame_size = s5k6aa_enum_frame_size,
.enum_frame_interval = s5k6aa_enum_frame_interval,
.get_fmt = s5k6aa_get_fmt,
.set_fmt = s5k6aa_set_fmt,
.get_crop = s5k6aa_get_crop,
.set_crop = s5k6aa_set_crop,
};
static const struct v4l2_subdev_video_ops s5k6aa_video_ops = {
.g_frame_interval = s5k6aa_g_frame_interval,
.s_frame_interval = s5k6aa_s_frame_interval,
.s_stream = s5k6aa_s_stream,
};
/*
* V4L2 subdev controls
*/
static int s5k6aa_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct v4l2_subdev *sd = ctrl_to_sd(ctrl);
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct s5k6aa *s5k6aa = to_s5k6aa(sd);
int idx, err = 0;
v4l2_dbg(1, debug, sd, "ctrl: 0x%x, value: %d\n", ctrl->id, ctrl->val);
mutex_lock(&s5k6aa->lock);
/*
* If the device is not powered up by the host driver do
* not apply any controls to H/W at this time. Instead
* the controls will be restored right after power-up.
*/
if (s5k6aa->power == 0)
goto unlock;
idx = s5k6aa->preset->index;
switch (ctrl->id) {
case V4L2_CID_AUTO_WHITE_BALANCE:
err = s5k6aa_set_awb(s5k6aa, ctrl->val);
break;
case V4L2_CID_BRIGHTNESS:
err = s5k6aa_write(client, REG_USER_BRIGHTNESS, ctrl->val);
break;
case V4L2_CID_COLORFX:
err = s5k6aa_set_colorfx(s5k6aa, ctrl->val);
break;
case V4L2_CID_CONTRAST:
err = s5k6aa_write(client, REG_USER_CONTRAST, ctrl->val);
break;
case V4L2_CID_EXPOSURE_AUTO:
err = s5k6aa_set_auto_exposure(s5k6aa, ctrl->val);
break;
case V4L2_CID_HFLIP:
err = s5k6aa_set_mirror(s5k6aa, ctrl->val);
if (err)
break;
err = s5k6aa_write(client, REG_G_PREV_CFG_CHG, 1);
break;
case V4L2_CID_POWER_LINE_FREQUENCY:
err = s5k6aa_set_anti_flicker(s5k6aa, ctrl->val);
break;
case V4L2_CID_SATURATION:
err = s5k6aa_write(client, REG_USER_SATURATION, ctrl->val);
break;
case V4L2_CID_SHARPNESS:
err = s5k6aa_write(client, REG_USER_SHARPBLUR, ctrl->val);
break;
case V4L2_CID_WHITE_BALANCE_TEMPERATURE:
err = s5k6aa_write(client, REG_P_COLORTEMP(idx), ctrl->val);
if (err)
break;
err = s5k6aa_write(client, REG_G_PREV_CFG_CHG, 1);
break;
}
unlock:
mutex_unlock(&s5k6aa->lock);
return err;
}
static const struct v4l2_ctrl_ops s5k6aa_ctrl_ops = {
.s_ctrl = s5k6aa_s_ctrl,
};
static int s5k6aa_log_status(struct v4l2_subdev *sd)
{
v4l2_ctrl_handler_log_status(sd->ctrl_handler, sd->name);
return 0;
}
#define V4L2_CID_RED_GAIN (V4L2_CTRL_CLASS_CAMERA | 0x1001)
#define V4L2_CID_GREEN_GAIN (V4L2_CTRL_CLASS_CAMERA | 0x1002)
#define V4L2_CID_BLUE_GAIN (V4L2_CTRL_CLASS_CAMERA | 0x1003)
static const struct v4l2_ctrl_config s5k6aa_ctrls[] = {
{
.ops = &s5k6aa_ctrl_ops,
.id = V4L2_CID_RED_GAIN,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Gain, Red",
.min = 0,
.max = 256,
.def = 127,
.step = 1,
}, {
.ops = &s5k6aa_ctrl_ops,
.id = V4L2_CID_GREEN_GAIN,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Gain, Green",
.min = 0,
.max = 256,
.def = 127,
.step = 1,
}, {
.ops = &s5k6aa_ctrl_ops,
.id = V4L2_CID_BLUE_GAIN,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Gain, Blue",
.min = 0,
.max = 256,
.def = 127,
.step = 1,
},
};
static int s5k6aa_initialize_ctrls(struct s5k6aa *s5k6aa)
{
const struct v4l2_ctrl_ops *ops = &s5k6aa_ctrl_ops;
struct s5k6aa_ctrls *ctrls = &s5k6aa->ctrls;
struct v4l2_ctrl_handler *hdl = &ctrls->handler;
int ret = v4l2_ctrl_handler_init(hdl, 16);
if (ret)
return ret;
/* Auto white balance cluster */
ctrls->awb = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_AUTO_WHITE_BALANCE,
0, 1, 1, 1);
ctrls->gain_red = v4l2_ctrl_new_custom(hdl, &s5k6aa_ctrls[0], NULL);
ctrls->gain_green = v4l2_ctrl_new_custom(hdl, &s5k6aa_ctrls[1], NULL);
ctrls->gain_blue = v4l2_ctrl_new_custom(hdl, &s5k6aa_ctrls[2], NULL);
v4l2_ctrl_auto_cluster(4, &ctrls->awb, 0, false);
ctrls->hflip = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_HFLIP, 0, 1, 1, 0);
ctrls->vflip = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_VFLIP, 0, 1, 1, 0);
v4l2_ctrl_cluster(2, &ctrls->hflip);
ctrls->auto_exp = v4l2_ctrl_new_std_menu(hdl, ops,
V4L2_CID_EXPOSURE_AUTO,
V4L2_EXPOSURE_MANUAL, 0, V4L2_EXPOSURE_AUTO);
/* Exposure time: x 1 us */
ctrls->exposure = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_EXPOSURE,
0, 6000000U, 1, 100000U);
/* Total gain: 256 <=> 1x */
ctrls->gain = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_GAIN,
0, 256, 1, 256);
v4l2_ctrl_auto_cluster(3, &ctrls->auto_exp, 0, false);
v4l2_ctrl_new_std_menu(hdl, ops, V4L2_CID_POWER_LINE_FREQUENCY,
V4L2_CID_POWER_LINE_FREQUENCY_AUTO, 0,
V4L2_CID_POWER_LINE_FREQUENCY_AUTO);
v4l2_ctrl_new_std_menu(hdl, ops, V4L2_CID_COLORFX,
V4L2_COLORFX_SKY_BLUE, ~0x6f, V4L2_COLORFX_NONE);
v4l2_ctrl_new_std(hdl, ops, V4L2_CID_WHITE_BALANCE_TEMPERATURE,
0, 256, 1, 0);
v4l2_ctrl_new_std(hdl, ops, V4L2_CID_SATURATION, -127, 127, 1, 0);
v4l2_ctrl_new_std(hdl, ops, V4L2_CID_BRIGHTNESS, -127, 127, 1, 0);
v4l2_ctrl_new_std(hdl, ops, V4L2_CID_CONTRAST, -127, 127, 1, 0);
v4l2_ctrl_new_std(hdl, ops, V4L2_CID_SHARPNESS, -127, 127, 1, 0);
if (hdl->error) {
ret = hdl->error;
v4l2_ctrl_handler_free(hdl);
return ret;
}
s5k6aa->sd.ctrl_handler = hdl;
return 0;
}
/*
* V4L2 subdev internal operations
*/
static int s5k6aa_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh)
{
struct v4l2_mbus_framefmt *format = v4l2_subdev_get_try_format(fh, 0);
struct v4l2_rect *crop = v4l2_subdev_get_try_crop(fh, 0);
format->colorspace = s5k6aa_formats[0].colorspace;
format->code = s5k6aa_formats[0].code;
format->width = S5K6AA_OUT_WIDTH_DEF;
format->height = S5K6AA_OUT_HEIGHT_DEF;
format->field = V4L2_FIELD_NONE;
crop->width = S5K6AA_WIN_WIDTH_MAX;
crop->height = S5K6AA_WIN_HEIGHT_MAX;
crop->left = 0;
crop->top = 0;
return 0;
}
int s5k6aa_check_fw_revision(struct s5k6aa *s5k6aa)
{
struct i2c_client *client = v4l2_get_subdevdata(&s5k6aa->sd);
u16 api_ver = 0, fw_rev = 0;
int ret = s5k6aa_set_ahb_address(client);
if (!ret)
ret = s5k6aa_read(client, REG_FW_APIVER, &api_ver);
if (!ret)
ret = s5k6aa_read(client, REG_FW_REVISION, &fw_rev);
if (ret) {
v4l2_err(&s5k6aa->sd, "FW revision check failed!\n");
return ret;
}
v4l2_info(&s5k6aa->sd, "FW API ver.: 0x%X, FW rev.: 0x%X\n",
api_ver, fw_rev);
return api_ver == S5K6AAFX_FW_APIVER ? 0 : -ENODEV;
}
static int s5k6aa_registered(struct v4l2_subdev *sd)
{
struct s5k6aa *s5k6aa = to_s5k6aa(sd);
int ret;
mutex_lock(&s5k6aa->lock);
ret = __s5k6aa_power_on(s5k6aa);
if (!ret) {
msleep(100);
ret = s5k6aa_check_fw_revision(s5k6aa);
__s5k6aa_power_off(s5k6aa);
}
mutex_unlock(&s5k6aa->lock);
return ret;
}
static const struct v4l2_subdev_internal_ops s5k6aa_subdev_internal_ops = {
.registered = s5k6aa_registered,
.open = s5k6aa_open,
};
static const struct v4l2_subdev_core_ops s5k6aa_core_ops = {
.s_power = s5k6aa_set_power,
.log_status = s5k6aa_log_status,
};
static const struct v4l2_subdev_ops s5k6aa_subdev_ops = {
.core = &s5k6aa_core_ops,
.pad = &s5k6aa_pad_ops,
.video = &s5k6aa_video_ops,
};
/*
* GPIO setup
*/
static int s5k6aa_configure_gpio(int nr, int val, const char *name)
{
unsigned long flags = val ? GPIOF_OUT_INIT_HIGH : GPIOF_OUT_INIT_LOW;
int ret;
if (!gpio_is_valid(nr))
return 0;
ret = gpio_request_one(nr, flags, name);
if (!ret)
gpio_export(nr, 0);
return ret;
}
static void s5k6aa_free_gpios(struct s5k6aa *s5k6aa)
{
int i;
for (i = 0; i < ARRAY_SIZE(s5k6aa->gpio); i++) {
if (!gpio_is_valid(s5k6aa->gpio[i].gpio))
continue;
gpio_free(s5k6aa->gpio[i].gpio);
s5k6aa->gpio[i].gpio = -EINVAL;
}
}
static int s5k6aa_configure_gpios(struct s5k6aa *s5k6aa,
const struct s5k6aa_platform_data *pdata)
{
const struct s5k6aa_gpio *gpio = &pdata->gpio_stby;
int ret;
s5k6aa->gpio[STBY].gpio = -EINVAL;
s5k6aa->gpio[RST].gpio = -EINVAL;
ret = s5k6aa_configure_gpio(gpio->gpio, gpio->level, "S5K6AA_STBY");
if (ret) {
s5k6aa_free_gpios(s5k6aa);
return ret;
}
s5k6aa->gpio[STBY] = *gpio;
if (gpio_is_valid(gpio->gpio))
gpio_set_value(gpio->gpio, 0);
gpio = &pdata->gpio_reset;
ret = s5k6aa_configure_gpio(gpio->gpio, gpio->level, "S5K6AA_RST");
if (ret) {
s5k6aa_free_gpios(s5k6aa);
return ret;
}
s5k6aa->gpio[RST] = *gpio;
if (gpio_is_valid(gpio->gpio))
gpio_set_value(gpio->gpio, 0);
return 0;
}
static int s5k6aa_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
const struct s5k6aa_platform_data *pdata = client->dev.platform_data;
struct v4l2_subdev *sd;
struct s5k6aa *s5k6aa;
int i, ret;
if (pdata == NULL) {
dev_err(&client->dev, "Platform data not specified\n");
return -EINVAL;
}
if (pdata->mclk_frequency == 0) {
dev_err(&client->dev, "MCLK frequency not specified\n");
return -EINVAL;
}
s5k6aa = kzalloc(sizeof(*s5k6aa), GFP_KERNEL);
if (!s5k6aa)
return -ENOMEM;
mutex_init(&s5k6aa->lock);
s5k6aa->mclk_frequency = pdata->mclk_frequency;
s5k6aa->bus_type = pdata->bus_type;
s5k6aa->mipi_lanes = pdata->nlanes;
s5k6aa->s_power = pdata->set_power;
s5k6aa->inv_hflip = pdata->horiz_flip;
s5k6aa->inv_vflip = pdata->vert_flip;
sd = &s5k6aa->sd;
strlcpy(sd->name, DRIVER_NAME, sizeof(sd->name));
v4l2_i2c_subdev_init(sd, client, &s5k6aa_subdev_ops);
sd->internal_ops = &s5k6aa_subdev_internal_ops;
sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
s5k6aa->pad.flags = MEDIA_PAD_FL_SOURCE;
sd->entity.type = MEDIA_ENT_T_V4L2_SUBDEV_SENSOR;
ret = media_entity_init(&sd->entity, 1, &s5k6aa->pad, 0);
if (ret)
goto out_err1;
ret = s5k6aa_configure_gpios(s5k6aa, pdata);
if (ret)
goto out_err2;
for (i = 0; i < S5K6AA_NUM_SUPPLIES; i++)
s5k6aa->supplies[i].supply = s5k6aa_supply_names[i];
ret = regulator_bulk_get(&client->dev, S5K6AA_NUM_SUPPLIES,
s5k6aa->supplies);
if (ret) {
dev_err(&client->dev, "Failed to get regulators\n");
goto out_err3;
}
ret = s5k6aa_initialize_ctrls(s5k6aa);
if (ret)
goto out_err4;
s5k6aa_presets_data_init(s5k6aa);
s5k6aa->ccd_rect.width = S5K6AA_WIN_WIDTH_MAX;
s5k6aa->ccd_rect.height = S5K6AA_WIN_HEIGHT_MAX;
s5k6aa->ccd_rect.left = 0;
s5k6aa->ccd_rect.top = 0;
return 0;
out_err4:
regulator_bulk_free(S5K6AA_NUM_SUPPLIES, s5k6aa->supplies);
out_err3:
s5k6aa_free_gpios(s5k6aa);
out_err2:
media_entity_cleanup(&s5k6aa->sd.entity);
out_err1:
kfree(s5k6aa);
return ret;
}
static int s5k6aa_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
struct s5k6aa *s5k6aa = to_s5k6aa(sd);
v4l2_device_unregister_subdev(sd);
v4l2_ctrl_handler_free(sd->ctrl_handler);
media_entity_cleanup(&sd->entity);
regulator_bulk_free(S5K6AA_NUM_SUPPLIES, s5k6aa->supplies);
s5k6aa_free_gpios(s5k6aa);
kfree(s5k6aa);
return 0;
}
static const struct i2c_device_id s5k6aa_id[] = {
{ DRIVER_NAME, 0 },
{ },
};
MODULE_DEVICE_TABLE(i2c, s5k6aa_id);
static struct i2c_driver s5k6aa_i2c_driver = {
.driver = {
.name = DRIVER_NAME
},
.probe = s5k6aa_probe,
.remove = s5k6aa_remove,
.id_table = s5k6aa_id,
};
static int __init s5k6aa_init(void)
{
return i2c_add_driver(&s5k6aa_i2c_driver);
}
static void __exit s5k6aa_exit(void)
{
i2c_del_driver(&s5k6aa_i2c_driver);
}
module_init(s5k6aa_init);
module_exit(s5k6aa_exit);
MODULE_DESCRIPTION("Samsung S5K6AA(FX) SXGA camera driver");
MODULE_AUTHOR("Sylwester Nawrocki <s.nawrocki@samsung.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
nsat/zynq-linux | net/sctp/auth.c | 239 | 24243 | /* SCTP kernel implementation
* (C) Copyright 2007 Hewlett-Packard Development Company, L.P.
*
* This file is part of the SCTP kernel implementation
*
* This SCTP implementation is free software;
* you can redistribute 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 SCTP implementation is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied
* ************************
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU CC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <linux-sctp@vger.kernel.org>
*
* Written or modified by:
* Vlad Yasevich <vladislav.yasevich@hp.com>
*/
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/crypto.h>
#include <linux/scatterlist.h>
#include <net/sctp/sctp.h>
#include <net/sctp/auth.h>
static struct sctp_hmac sctp_hmac_list[SCTP_AUTH_NUM_HMACS] = {
{
/* id 0 is reserved. as all 0 */
.hmac_id = SCTP_AUTH_HMAC_ID_RESERVED_0,
},
{
.hmac_id = SCTP_AUTH_HMAC_ID_SHA1,
.hmac_name = "hmac(sha1)",
.hmac_len = SCTP_SHA1_SIG_SIZE,
},
{
/* id 2 is reserved as well */
.hmac_id = SCTP_AUTH_HMAC_ID_RESERVED_2,
},
#if defined (CONFIG_CRYPTO_SHA256) || defined (CONFIG_CRYPTO_SHA256_MODULE)
{
.hmac_id = SCTP_AUTH_HMAC_ID_SHA256,
.hmac_name = "hmac(sha256)",
.hmac_len = SCTP_SHA256_SIG_SIZE,
}
#endif
};
void sctp_auth_key_put(struct sctp_auth_bytes *key)
{
if (!key)
return;
if (atomic_dec_and_test(&key->refcnt)) {
kzfree(key);
SCTP_DBG_OBJCNT_DEC(keys);
}
}
/* Create a new key structure of a given length */
static struct sctp_auth_bytes *sctp_auth_create_key(__u32 key_len, gfp_t gfp)
{
struct sctp_auth_bytes *key;
/* Verify that we are not going to overflow INT_MAX */
if (key_len > (INT_MAX - sizeof(struct sctp_auth_bytes)))
return NULL;
/* Allocate the shared key */
key = kmalloc(sizeof(struct sctp_auth_bytes) + key_len, gfp);
if (!key)
return NULL;
key->len = key_len;
atomic_set(&key->refcnt, 1);
SCTP_DBG_OBJCNT_INC(keys);
return key;
}
/* Create a new shared key container with a give key id */
struct sctp_shared_key *sctp_auth_shkey_create(__u16 key_id, gfp_t gfp)
{
struct sctp_shared_key *new;
/* Allocate the shared key container */
new = kzalloc(sizeof(struct sctp_shared_key), gfp);
if (!new)
return NULL;
INIT_LIST_HEAD(&new->key_list);
new->key_id = key_id;
return new;
}
/* Free the shared key structure */
static void sctp_auth_shkey_free(struct sctp_shared_key *sh_key)
{
BUG_ON(!list_empty(&sh_key->key_list));
sctp_auth_key_put(sh_key->key);
sh_key->key = NULL;
kfree(sh_key);
}
/* Destroy the entire key list. This is done during the
* associon and endpoint free process.
*/
void sctp_auth_destroy_keys(struct list_head *keys)
{
struct sctp_shared_key *ep_key;
struct sctp_shared_key *tmp;
if (list_empty(keys))
return;
key_for_each_safe(ep_key, tmp, keys) {
list_del_init(&ep_key->key_list);
sctp_auth_shkey_free(ep_key);
}
}
/* Compare two byte vectors as numbers. Return values
* are:
* 0 - vectors are equal
* < 0 - vector 1 is smaller than vector2
* > 0 - vector 1 is greater than vector2
*
* Algorithm is:
* This is performed by selecting the numerically smaller key vector...
* If the key vectors are equal as numbers but differ in length ...
* the shorter vector is considered smaller
*
* Examples (with small values):
* 000123456789 > 123456789 (first number is longer)
* 000123456789 < 234567891 (second number is larger numerically)
* 123456789 > 2345678 (first number is both larger & longer)
*/
static int sctp_auth_compare_vectors(struct sctp_auth_bytes *vector1,
struct sctp_auth_bytes *vector2)
{
int diff;
int i;
const __u8 *longer;
diff = vector1->len - vector2->len;
if (diff) {
longer = (diff > 0) ? vector1->data : vector2->data;
/* Check to see if the longer number is
* lead-zero padded. If it is not, it
* is automatically larger numerically.
*/
for (i = 0; i < abs(diff); i++) {
if (longer[i] != 0)
return diff;
}
}
/* lengths are the same, compare numbers */
return memcmp(vector1->data, vector2->data, vector1->len);
}
/*
* Create a key vector as described in SCTP-AUTH, Section 6.1
* The RANDOM parameter, the CHUNKS parameter and the HMAC-ALGO
* parameter sent by each endpoint are concatenated as byte vectors.
* These parameters include the parameter type, parameter length, and
* the parameter value, but padding is omitted; all padding MUST be
* removed from this concatenation before proceeding with further
* computation of keys. Parameters which were not sent are simply
* omitted from the concatenation process. The resulting two vectors
* are called the two key vectors.
*/
static struct sctp_auth_bytes *sctp_auth_make_key_vector(
sctp_random_param_t *random,
sctp_chunks_param_t *chunks,
sctp_hmac_algo_param_t *hmacs,
gfp_t gfp)
{
struct sctp_auth_bytes *new;
__u32 len;
__u32 offset = 0;
__u16 random_len, hmacs_len, chunks_len = 0;
random_len = ntohs(random->param_hdr.length);
hmacs_len = ntohs(hmacs->param_hdr.length);
if (chunks)
chunks_len = ntohs(chunks->param_hdr.length);
len = random_len + hmacs_len + chunks_len;
new = sctp_auth_create_key(len, gfp);
if (!new)
return NULL;
memcpy(new->data, random, random_len);
offset += random_len;
if (chunks) {
memcpy(new->data + offset, chunks, chunks_len);
offset += chunks_len;
}
memcpy(new->data + offset, hmacs, hmacs_len);
return new;
}
/* Make a key vector based on our local parameters */
static struct sctp_auth_bytes *sctp_auth_make_local_vector(
const struct sctp_association *asoc,
gfp_t gfp)
{
return sctp_auth_make_key_vector(
(sctp_random_param_t *)asoc->c.auth_random,
(sctp_chunks_param_t *)asoc->c.auth_chunks,
(sctp_hmac_algo_param_t *)asoc->c.auth_hmacs,
gfp);
}
/* Make a key vector based on peer's parameters */
static struct sctp_auth_bytes *sctp_auth_make_peer_vector(
const struct sctp_association *asoc,
gfp_t gfp)
{
return sctp_auth_make_key_vector(asoc->peer.peer_random,
asoc->peer.peer_chunks,
asoc->peer.peer_hmacs,
gfp);
}
/* Set the value of the association shared key base on the parameters
* given. The algorithm is:
* From the endpoint pair shared keys and the key vectors the
* association shared keys are computed. This is performed by selecting
* the numerically smaller key vector and concatenating it to the
* endpoint pair shared key, and then concatenating the numerically
* larger key vector to that. The result of the concatenation is the
* association shared key.
*/
static struct sctp_auth_bytes *sctp_auth_asoc_set_secret(
struct sctp_shared_key *ep_key,
struct sctp_auth_bytes *first_vector,
struct sctp_auth_bytes *last_vector,
gfp_t gfp)
{
struct sctp_auth_bytes *secret;
__u32 offset = 0;
__u32 auth_len;
auth_len = first_vector->len + last_vector->len;
if (ep_key->key)
auth_len += ep_key->key->len;
secret = sctp_auth_create_key(auth_len, gfp);
if (!secret)
return NULL;
if (ep_key->key) {
memcpy(secret->data, ep_key->key->data, ep_key->key->len);
offset += ep_key->key->len;
}
memcpy(secret->data + offset, first_vector->data, first_vector->len);
offset += first_vector->len;
memcpy(secret->data + offset, last_vector->data, last_vector->len);
return secret;
}
/* Create an association shared key. Follow the algorithm
* described in SCTP-AUTH, Section 6.1
*/
static struct sctp_auth_bytes *sctp_auth_asoc_create_secret(
const struct sctp_association *asoc,
struct sctp_shared_key *ep_key,
gfp_t gfp)
{
struct sctp_auth_bytes *local_key_vector;
struct sctp_auth_bytes *peer_key_vector;
struct sctp_auth_bytes *first_vector,
*last_vector;
struct sctp_auth_bytes *secret = NULL;
int cmp;
/* Now we need to build the key vectors
* SCTP-AUTH , Section 6.1
* The RANDOM parameter, the CHUNKS parameter and the HMAC-ALGO
* parameter sent by each endpoint are concatenated as byte vectors.
* These parameters include the parameter type, parameter length, and
* the parameter value, but padding is omitted; all padding MUST be
* removed from this concatenation before proceeding with further
* computation of keys. Parameters which were not sent are simply
* omitted from the concatenation process. The resulting two vectors
* are called the two key vectors.
*/
local_key_vector = sctp_auth_make_local_vector(asoc, gfp);
peer_key_vector = sctp_auth_make_peer_vector(asoc, gfp);
if (!peer_key_vector || !local_key_vector)
goto out;
/* Figure out the order in which the key_vectors will be
* added to the endpoint shared key.
* SCTP-AUTH, Section 6.1:
* This is performed by selecting the numerically smaller key
* vector and concatenating it to the endpoint pair shared
* key, and then concatenating the numerically larger key
* vector to that. If the key vectors are equal as numbers
* but differ in length, then the concatenation order is the
* endpoint shared key, followed by the shorter key vector,
* followed by the longer key vector. Otherwise, the key
* vectors are identical, and may be concatenated to the
* endpoint pair key in any order.
*/
cmp = sctp_auth_compare_vectors(local_key_vector,
peer_key_vector);
if (cmp < 0) {
first_vector = local_key_vector;
last_vector = peer_key_vector;
} else {
first_vector = peer_key_vector;
last_vector = local_key_vector;
}
secret = sctp_auth_asoc_set_secret(ep_key, first_vector, last_vector,
gfp);
out:
sctp_auth_key_put(local_key_vector);
sctp_auth_key_put(peer_key_vector);
return secret;
}
/*
* Populate the association overlay list with the list
* from the endpoint.
*/
int sctp_auth_asoc_copy_shkeys(const struct sctp_endpoint *ep,
struct sctp_association *asoc,
gfp_t gfp)
{
struct sctp_shared_key *sh_key;
struct sctp_shared_key *new;
BUG_ON(!list_empty(&asoc->endpoint_shared_keys));
key_for_each(sh_key, &ep->endpoint_shared_keys) {
new = sctp_auth_shkey_create(sh_key->key_id, gfp);
if (!new)
goto nomem;
new->key = sh_key->key;
sctp_auth_key_hold(new->key);
list_add(&new->key_list, &asoc->endpoint_shared_keys);
}
return 0;
nomem:
sctp_auth_destroy_keys(&asoc->endpoint_shared_keys);
return -ENOMEM;
}
/* Public interface to creat the association shared key.
* See code above for the algorithm.
*/
int sctp_auth_asoc_init_active_key(struct sctp_association *asoc, gfp_t gfp)
{
struct sctp_auth_bytes *secret;
struct sctp_shared_key *ep_key;
/* If we don't support AUTH, or peer is not capable
* we don't need to do anything.
*/
if (!asoc->ep->auth_enable || !asoc->peer.auth_capable)
return 0;
/* If the key_id is non-zero and we couldn't find an
* endpoint pair shared key, we can't compute the
* secret.
* For key_id 0, endpoint pair shared key is a NULL key.
*/
ep_key = sctp_auth_get_shkey(asoc, asoc->active_key_id);
BUG_ON(!ep_key);
secret = sctp_auth_asoc_create_secret(asoc, ep_key, gfp);
if (!secret)
return -ENOMEM;
sctp_auth_key_put(asoc->asoc_shared_key);
asoc->asoc_shared_key = secret;
return 0;
}
/* Find the endpoint pair shared key based on the key_id */
struct sctp_shared_key *sctp_auth_get_shkey(
const struct sctp_association *asoc,
__u16 key_id)
{
struct sctp_shared_key *key;
/* First search associations set of endpoint pair shared keys */
key_for_each(key, &asoc->endpoint_shared_keys) {
if (key->key_id == key_id)
return key;
}
return NULL;
}
/*
* Initialize all the possible digest transforms that we can use. Right now
* now, the supported digests are SHA1 and SHA256. We do this here once
* because of the restrictiong that transforms may only be allocated in
* user context. This forces us to pre-allocated all possible transforms
* at the endpoint init time.
*/
int sctp_auth_init_hmacs(struct sctp_endpoint *ep, gfp_t gfp)
{
struct crypto_hash *tfm = NULL;
__u16 id;
/* If AUTH extension is disabled, we are done */
if (!ep->auth_enable) {
ep->auth_hmacs = NULL;
return 0;
}
/* If the transforms are already allocated, we are done */
if (ep->auth_hmacs)
return 0;
/* Allocated the array of pointers to transorms */
ep->auth_hmacs = kzalloc(
sizeof(struct crypto_hash *) * SCTP_AUTH_NUM_HMACS,
gfp);
if (!ep->auth_hmacs)
return -ENOMEM;
for (id = 0; id < SCTP_AUTH_NUM_HMACS; id++) {
/* See is we support the id. Supported IDs have name and
* length fields set, so that we can allocated and use
* them. We can safely just check for name, for without the
* name, we can't allocate the TFM.
*/
if (!sctp_hmac_list[id].hmac_name)
continue;
/* If this TFM has been allocated, we are all set */
if (ep->auth_hmacs[id])
continue;
/* Allocate the ID */
tfm = crypto_alloc_hash(sctp_hmac_list[id].hmac_name, 0,
CRYPTO_ALG_ASYNC);
if (IS_ERR(tfm))
goto out_err;
ep->auth_hmacs[id] = tfm;
}
return 0;
out_err:
/* Clean up any successful allocations */
sctp_auth_destroy_hmacs(ep->auth_hmacs);
return -ENOMEM;
}
/* Destroy the hmac tfm array */
void sctp_auth_destroy_hmacs(struct crypto_hash *auth_hmacs[])
{
int i;
if (!auth_hmacs)
return;
for (i = 0; i < SCTP_AUTH_NUM_HMACS; i++) {
if (auth_hmacs[i])
crypto_free_hash(auth_hmacs[i]);
}
kfree(auth_hmacs);
}
struct sctp_hmac *sctp_auth_get_hmac(__u16 hmac_id)
{
return &sctp_hmac_list[hmac_id];
}
/* Get an hmac description information that we can use to build
* the AUTH chunk
*/
struct sctp_hmac *sctp_auth_asoc_get_hmac(const struct sctp_association *asoc)
{
struct sctp_hmac_algo_param *hmacs;
__u16 n_elt;
__u16 id = 0;
int i;
/* If we have a default entry, use it */
if (asoc->default_hmac_id)
return &sctp_hmac_list[asoc->default_hmac_id];
/* Since we do not have a default entry, find the first entry
* we support and return that. Do not cache that id.
*/
hmacs = asoc->peer.peer_hmacs;
if (!hmacs)
return NULL;
n_elt = (ntohs(hmacs->param_hdr.length) - sizeof(sctp_paramhdr_t)) >> 1;
for (i = 0; i < n_elt; i++) {
id = ntohs(hmacs->hmac_ids[i]);
/* Check the id is in the supported range. And
* see if we support the id. Supported IDs have name and
* length fields set, so that we can allocate and use
* them. We can safely just check for name, for without the
* name, we can't allocate the TFM.
*/
if (id > SCTP_AUTH_HMAC_ID_MAX ||
!sctp_hmac_list[id].hmac_name) {
id = 0;
continue;
}
break;
}
if (id == 0)
return NULL;
return &sctp_hmac_list[id];
}
static int __sctp_auth_find_hmacid(__be16 *hmacs, int n_elts, __be16 hmac_id)
{
int found = 0;
int i;
for (i = 0; i < n_elts; i++) {
if (hmac_id == hmacs[i]) {
found = 1;
break;
}
}
return found;
}
/* See if the HMAC_ID is one that we claim as supported */
int sctp_auth_asoc_verify_hmac_id(const struct sctp_association *asoc,
__be16 hmac_id)
{
struct sctp_hmac_algo_param *hmacs;
__u16 n_elt;
if (!asoc)
return 0;
hmacs = (struct sctp_hmac_algo_param *)asoc->c.auth_hmacs;
n_elt = (ntohs(hmacs->param_hdr.length) - sizeof(sctp_paramhdr_t)) >> 1;
return __sctp_auth_find_hmacid(hmacs->hmac_ids, n_elt, hmac_id);
}
/* Cache the default HMAC id. This to follow this text from SCTP-AUTH:
* Section 6.1:
* The receiver of a HMAC-ALGO parameter SHOULD use the first listed
* algorithm it supports.
*/
void sctp_auth_asoc_set_default_hmac(struct sctp_association *asoc,
struct sctp_hmac_algo_param *hmacs)
{
struct sctp_endpoint *ep;
__u16 id;
int i;
int n_params;
/* if the default id is already set, use it */
if (asoc->default_hmac_id)
return;
n_params = (ntohs(hmacs->param_hdr.length)
- sizeof(sctp_paramhdr_t)) >> 1;
ep = asoc->ep;
for (i = 0; i < n_params; i++) {
id = ntohs(hmacs->hmac_ids[i]);
/* Check the id is in the supported range */
if (id > SCTP_AUTH_HMAC_ID_MAX)
continue;
/* If this TFM has been allocated, use this id */
if (ep->auth_hmacs[id]) {
asoc->default_hmac_id = id;
break;
}
}
}
/* Check to see if the given chunk is supposed to be authenticated */
static int __sctp_auth_cid(sctp_cid_t chunk, struct sctp_chunks_param *param)
{
unsigned short len;
int found = 0;
int i;
if (!param || param->param_hdr.length == 0)
return 0;
len = ntohs(param->param_hdr.length) - sizeof(sctp_paramhdr_t);
/* SCTP-AUTH, Section 3.2
* The chunk types for INIT, INIT-ACK, SHUTDOWN-COMPLETE and AUTH
* chunks MUST NOT be listed in the CHUNKS parameter. However, if
* a CHUNKS parameter is received then the types for INIT, INIT-ACK,
* SHUTDOWN-COMPLETE and AUTH chunks MUST be ignored.
*/
for (i = 0; !found && i < len; i++) {
switch (param->chunks[i]) {
case SCTP_CID_INIT:
case SCTP_CID_INIT_ACK:
case SCTP_CID_SHUTDOWN_COMPLETE:
case SCTP_CID_AUTH:
break;
default:
if (param->chunks[i] == chunk)
found = 1;
break;
}
}
return found;
}
/* Check if peer requested that this chunk is authenticated */
int sctp_auth_send_cid(sctp_cid_t chunk, const struct sctp_association *asoc)
{
if (!asoc)
return 0;
if (!asoc->ep->auth_enable || !asoc->peer.auth_capable)
return 0;
return __sctp_auth_cid(chunk, asoc->peer.peer_chunks);
}
/* Check if we requested that peer authenticate this chunk. */
int sctp_auth_recv_cid(sctp_cid_t chunk, const struct sctp_association *asoc)
{
if (!asoc)
return 0;
if (!asoc->ep->auth_enable)
return 0;
return __sctp_auth_cid(chunk,
(struct sctp_chunks_param *)asoc->c.auth_chunks);
}
/* SCTP-AUTH: Section 6.2:
* The sender MUST calculate the MAC as described in RFC2104 [2] using
* the hash function H as described by the MAC Identifier and the shared
* association key K based on the endpoint pair shared key described by
* the shared key identifier. The 'data' used for the computation of
* the AUTH-chunk is given by the AUTH chunk with its HMAC field set to
* zero (as shown in Figure 6) followed by all chunks that are placed
* after the AUTH chunk in the SCTP packet.
*/
void sctp_auth_calculate_hmac(const struct sctp_association *asoc,
struct sk_buff *skb,
struct sctp_auth_chunk *auth,
gfp_t gfp)
{
struct scatterlist sg;
struct hash_desc desc;
struct sctp_auth_bytes *asoc_key;
__u16 key_id, hmac_id;
__u8 *digest;
unsigned char *end;
int free_key = 0;
/* Extract the info we need:
* - hmac id
* - key id
*/
key_id = ntohs(auth->auth_hdr.shkey_id);
hmac_id = ntohs(auth->auth_hdr.hmac_id);
if (key_id == asoc->active_key_id)
asoc_key = asoc->asoc_shared_key;
else {
struct sctp_shared_key *ep_key;
ep_key = sctp_auth_get_shkey(asoc, key_id);
if (!ep_key)
return;
asoc_key = sctp_auth_asoc_create_secret(asoc, ep_key, gfp);
if (!asoc_key)
return;
free_key = 1;
}
/* set up scatter list */
end = skb_tail_pointer(skb);
sg_init_one(&sg, auth, end - (unsigned char *)auth);
desc.tfm = asoc->ep->auth_hmacs[hmac_id];
desc.flags = 0;
digest = auth->auth_hdr.hmac;
if (crypto_hash_setkey(desc.tfm, &asoc_key->data[0], asoc_key->len))
goto free;
crypto_hash_digest(&desc, &sg, sg.length, digest);
free:
if (free_key)
sctp_auth_key_put(asoc_key);
}
/* API Helpers */
/* Add a chunk to the endpoint authenticated chunk list */
int sctp_auth_ep_add_chunkid(struct sctp_endpoint *ep, __u8 chunk_id)
{
struct sctp_chunks_param *p = ep->auth_chunk_list;
__u16 nchunks;
__u16 param_len;
/* If this chunk is already specified, we are done */
if (__sctp_auth_cid(chunk_id, p))
return 0;
/* Check if we can add this chunk to the array */
param_len = ntohs(p->param_hdr.length);
nchunks = param_len - sizeof(sctp_paramhdr_t);
if (nchunks == SCTP_NUM_CHUNK_TYPES)
return -EINVAL;
p->chunks[nchunks] = chunk_id;
p->param_hdr.length = htons(param_len + 1);
return 0;
}
/* Add hmac identifires to the endpoint list of supported hmac ids */
int sctp_auth_ep_set_hmacs(struct sctp_endpoint *ep,
struct sctp_hmacalgo *hmacs)
{
int has_sha1 = 0;
__u16 id;
int i;
/* Scan the list looking for unsupported id. Also make sure that
* SHA1 is specified.
*/
for (i = 0; i < hmacs->shmac_num_idents; i++) {
id = hmacs->shmac_idents[i];
if (id > SCTP_AUTH_HMAC_ID_MAX)
return -EOPNOTSUPP;
if (SCTP_AUTH_HMAC_ID_SHA1 == id)
has_sha1 = 1;
if (!sctp_hmac_list[id].hmac_name)
return -EOPNOTSUPP;
}
if (!has_sha1)
return -EINVAL;
memcpy(ep->auth_hmacs_list->hmac_ids, &hmacs->shmac_idents[0],
hmacs->shmac_num_idents * sizeof(__u16));
ep->auth_hmacs_list->param_hdr.length = htons(sizeof(sctp_paramhdr_t) +
hmacs->shmac_num_idents * sizeof(__u16));
return 0;
}
/* Set a new shared key on either endpoint or association. If the
* the key with a same ID already exists, replace the key (remove the
* old key and add a new one).
*/
int sctp_auth_set_key(struct sctp_endpoint *ep,
struct sctp_association *asoc,
struct sctp_authkey *auth_key)
{
struct sctp_shared_key *cur_key = NULL;
struct sctp_auth_bytes *key;
struct list_head *sh_keys;
int replace = 0;
/* Try to find the given key id to see if
* we are doing a replace, or adding a new key
*/
if (asoc)
sh_keys = &asoc->endpoint_shared_keys;
else
sh_keys = &ep->endpoint_shared_keys;
key_for_each(cur_key, sh_keys) {
if (cur_key->key_id == auth_key->sca_keynumber) {
replace = 1;
break;
}
}
/* If we are not replacing a key id, we need to allocate
* a shared key.
*/
if (!replace) {
cur_key = sctp_auth_shkey_create(auth_key->sca_keynumber,
GFP_KERNEL);
if (!cur_key)
return -ENOMEM;
}
/* Create a new key data based on the info passed in */
key = sctp_auth_create_key(auth_key->sca_keylength, GFP_KERNEL);
if (!key)
goto nomem;
memcpy(key->data, &auth_key->sca_key[0], auth_key->sca_keylength);
/* If we are replacing, remove the old keys data from the
* key id. If we are adding new key id, add it to the
* list.
*/
if (replace)
sctp_auth_key_put(cur_key->key);
else
list_add(&cur_key->key_list, sh_keys);
cur_key->key = key;
sctp_auth_key_hold(key);
return 0;
nomem:
if (!replace)
sctp_auth_shkey_free(cur_key);
return -ENOMEM;
}
int sctp_auth_set_active_key(struct sctp_endpoint *ep,
struct sctp_association *asoc,
__u16 key_id)
{
struct sctp_shared_key *key;
struct list_head *sh_keys;
int found = 0;
/* The key identifier MUST correst to an existing key */
if (asoc)
sh_keys = &asoc->endpoint_shared_keys;
else
sh_keys = &ep->endpoint_shared_keys;
key_for_each(key, sh_keys) {
if (key->key_id == key_id) {
found = 1;
break;
}
}
if (!found)
return -EINVAL;
if (asoc) {
asoc->active_key_id = key_id;
sctp_auth_asoc_init_active_key(asoc, GFP_KERNEL);
} else
ep->active_key_id = key_id;
return 0;
}
int sctp_auth_del_key_id(struct sctp_endpoint *ep,
struct sctp_association *asoc,
__u16 key_id)
{
struct sctp_shared_key *key;
struct list_head *sh_keys;
int found = 0;
/* The key identifier MUST NOT be the current active key
* The key identifier MUST correst to an existing key
*/
if (asoc) {
if (asoc->active_key_id == key_id)
return -EINVAL;
sh_keys = &asoc->endpoint_shared_keys;
} else {
if (ep->active_key_id == key_id)
return -EINVAL;
sh_keys = &ep->endpoint_shared_keys;
}
key_for_each(key, sh_keys) {
if (key->key_id == key_id) {
found = 1;
break;
}
}
if (!found)
return -EINVAL;
/* Delete the shared key */
list_del_init(&key->key_list);
sctp_auth_shkey_free(key);
return 0;
}
| gpl-2.0 |
snak3ater/android_kernel_lge_mako | arch/arm/mach-msm/lge/mako/board-mako-gpu.c | 239 | 6593 | /* Copyright (c) 2012, The Linux Foundation. All rights reserved.
* Copyright (c) 2012, LGE 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 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/init.h>
#include <linux/platform_device.h>
#include <mach/kgsl.h>
#include <mach/msm_bus_board.h>
#include <mach/board.h>
#include <mach/msm_dcvs.h>
#include <mach/socinfo.h>
#include "devices.h"
#include "board-mako.h"
#ifdef CONFIG_MSM_DCVS
static struct msm_dcvs_freq_entry grp3d_freq[] = {
{0, 900, 0, 0, 0},
{0, 950, 0, 0, 0},
{0, 950, 0, 0, 0},
{0, 1200, 1, 100, 100},
};
static struct msm_dcvs_core_info grp3d_core_info = {
.freq_tbl = &grp3d_freq[0],
.num_cores = 1,
.sensors = (int[]){0},
.thermal_poll_ms = 60000,
.core_param = {
.core_type = MSM_DCVS_CORE_TYPE_GPU,
},
.algo_param = {
.disable_pc_threshold = 0,
.em_win_size_min_us = 100000,
.em_win_size_max_us = 300000,
.em_max_util_pct = 97,
.group_id = 0,
.max_freq_chg_time_us = 100000,
.slack_mode_dynamic = 0,
.slack_time_min_us = 39000,
.slack_time_max_us = 39000,
.ss_win_size_min_us = 1000000,
.ss_win_size_max_us = 1000000,
.ss_util_pct = 95,
.ss_no_corr_below_freq = 0,
},
.energy_coeffs = {
.leakage_coeff_a = -17720,
.leakage_coeff_b = 37,
.leakage_coeff_c = 3329,
.leakage_coeff_d = -277,
.active_coeff_a = 2492,
.active_coeff_b = 0,
.active_coeff_c = 0
},
.power_param = {
.current_temp = 25,
.num_freq = ARRAY_SIZE(grp3d_freq),
}
};
#endif /* CONFIG_MSM_DCVS */
#ifdef CONFIG_MSM_BUS_SCALING
static struct msm_bus_vectors grp3d_init_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_3D,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
{
.src = MSM_BUS_MASTER_GRAPHICS_3D_PORT1,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
};
static struct msm_bus_vectors grp3d_low_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_3D,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(1000),
},
{
.src = MSM_BUS_MASTER_GRAPHICS_3D_PORT1,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(1000),
},
};
static struct msm_bus_vectors grp3d_nominal_low_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_3D,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(2000),
},
{
.src = MSM_BUS_MASTER_GRAPHICS_3D_PORT1,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(2000),
},
};
static struct msm_bus_vectors grp3d_nominal_high_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_3D,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(2656),
},
{
.src = MSM_BUS_MASTER_GRAPHICS_3D_PORT1,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(2656),
},
};
static struct msm_bus_vectors grp3d_max_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_3D,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(4264),
},
{
.src = MSM_BUS_MASTER_GRAPHICS_3D_PORT1,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(4264),
},
};
static struct msm_bus_paths grp3d_bus_scale_usecases[] = {
{
ARRAY_SIZE(grp3d_init_vectors),
grp3d_init_vectors,
},
{
ARRAY_SIZE(grp3d_low_vectors),
grp3d_low_vectors,
},
{
ARRAY_SIZE(grp3d_nominal_low_vectors),
grp3d_nominal_low_vectors,
},
{
ARRAY_SIZE(grp3d_nominal_high_vectors),
grp3d_nominal_high_vectors,
},
{
ARRAY_SIZE(grp3d_max_vectors),
grp3d_max_vectors,
},
};
static struct msm_bus_scale_pdata grp3d_bus_scale_pdata = {
grp3d_bus_scale_usecases,
ARRAY_SIZE(grp3d_bus_scale_usecases),
.name = "grp3d",
};
#endif
static struct resource kgsl_3d0_resources[] = {
{
.name = KGSL_3D0_REG_MEMORY,
.start = 0x04300000, /* GFX3D address */
.end = 0x0430ffff,
.flags = IORESOURCE_MEM,
},
{
.name = KGSL_3D0_SHADER_MEMORY,
.start = 0x04310000,
.end = 0x0431ffff,
.flags = IORESOURCE_MEM,
},
{
.name = KGSL_3D0_IRQ,
.start = GFX3D_IRQ,
.end = GFX3D_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static const struct kgsl_iommu_ctx kgsl_3d0_iommu0_ctxs[] = {
{ "gfx3d_user", 0 },
{ "gfx3d_priv", 1 },
};
static const struct kgsl_iommu_ctx kgsl_3d0_iommu1_ctxs[] = {
{ "gfx3d1_user", 0 },
{ "gfx3d1_priv", 1 },
};
static struct kgsl_device_iommu_data kgsl_3d0_iommu_data[] = {
{
.iommu_ctxs = kgsl_3d0_iommu0_ctxs,
.iommu_ctx_count = ARRAY_SIZE(kgsl_3d0_iommu0_ctxs),
.physstart = 0x07C00000,
.physend = 0x07C00000 + SZ_1M - 1,
},
{
.iommu_ctxs = kgsl_3d0_iommu1_ctxs,
.iommu_ctx_count = ARRAY_SIZE(kgsl_3d0_iommu1_ctxs),
.physstart = 0x07D00000,
.physend = 0x07D00000 + SZ_1M - 1,
},
};
static struct kgsl_device_platform_data kgsl_3d0_pdata = {
.pwrlevel = {
{
.gpu_freq = 400000000,
.bus_freq = 4,
.io_fraction = 0,
},
{
.gpu_freq = 320000000,
.bus_freq = 3,
.io_fraction = 33,
},
{
.gpu_freq = 200000000,
.bus_freq = 2,
.io_fraction = 100,
},
{
.gpu_freq = 128000000,
.bus_freq = 1,
.io_fraction = 100,
},
{
.gpu_freq = 27000000,
.bus_freq = 0,
},
},
.init_level = 1,
.num_levels = 5,
.set_grp_async = NULL,
.idle_timeout = HZ/10,
.strtstp_sleepwake = true,
.clk_map = KGSL_CLK_CORE | KGSL_CLK_IFACE | KGSL_CLK_MEM_IFACE,
#ifdef CONFIG_MSM_BUS_SCALING
.bus_scale_table = &grp3d_bus_scale_pdata,
#endif
.iommu_data = kgsl_3d0_iommu_data,
.iommu_count = ARRAY_SIZE(kgsl_3d0_iommu_data),
#ifdef CONFIG_MSM_DCVS
.core_info = &grp3d_core_info,
#endif
};
struct platform_device device_kgsl_3d0 = {
.name = "kgsl-3d0",
.id = 0,
.num_resources = ARRAY_SIZE(kgsl_3d0_resources),
.resource = kgsl_3d0_resources,
.dev = {
.platform_data = &kgsl_3d0_pdata,
},
};
void __init apq8064_init_gpu(void)
{
unsigned int version = socinfo_get_version();
if (cpu_is_apq8064ab())
kgsl_3d0_pdata.pwrlevel[0].gpu_freq = 450000000;
if (SOCINFO_VERSION_MAJOR(version) == 2) {
kgsl_3d0_pdata.chipid = ADRENO_CHIPID(3, 2, 0, 2);
} else {
if ((SOCINFO_VERSION_MAJOR(version) == 1) &&
(SOCINFO_VERSION_MINOR(version) == 1))
kgsl_3d0_pdata.chipid = ADRENO_CHIPID(3, 2, 0, 1);
else
kgsl_3d0_pdata.chipid = ADRENO_CHIPID(3, 2, 0, 0);
}
platform_device_register(&device_kgsl_3d0);
}
| gpl-2.0 |
systemdaemon/systemd | src/linux/drivers/net/ethernet/marvell/mvpp2.c | 495 | 181863 | /*
* Driver for Marvell PPv2 network controller for Armada 375 SoC.
*
* Copyright (C) 2014 Marvell
*
* Marcin Wojtas <mw@semihalf.com>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/platform_device.h>
#include <linux/skbuff.h>
#include <linux/inetdevice.h>
#include <linux/mbus.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/cpumask.h>
#include <linux/of.h>
#include <linux/of_irq.h>
#include <linux/of_mdio.h>
#include <linux/of_net.h>
#include <linux/of_address.h>
#include <linux/phy.h>
#include <linux/clk.h>
#include <uapi/linux/ppp_defs.h>
#include <net/ip.h>
#include <net/ipv6.h>
/* RX Fifo Registers */
#define MVPP2_RX_DATA_FIFO_SIZE_REG(port) (0x00 + 4 * (port))
#define MVPP2_RX_ATTR_FIFO_SIZE_REG(port) (0x20 + 4 * (port))
#define MVPP2_RX_MIN_PKT_SIZE_REG 0x60
#define MVPP2_RX_FIFO_INIT_REG 0x64
/* RX DMA Top Registers */
#define MVPP2_RX_CTRL_REG(port) (0x140 + 4 * (port))
#define MVPP2_RX_LOW_LATENCY_PKT_SIZE(s) (((s) & 0xfff) << 16)
#define MVPP2_RX_USE_PSEUDO_FOR_CSUM_MASK BIT(31)
#define MVPP2_POOL_BUF_SIZE_REG(pool) (0x180 + 4 * (pool))
#define MVPP2_POOL_BUF_SIZE_OFFSET 5
#define MVPP2_RXQ_CONFIG_REG(rxq) (0x800 + 4 * (rxq))
#define MVPP2_SNOOP_PKT_SIZE_MASK 0x1ff
#define MVPP2_SNOOP_BUF_HDR_MASK BIT(9)
#define MVPP2_RXQ_POOL_SHORT_OFFS 20
#define MVPP2_RXQ_POOL_SHORT_MASK 0x700000
#define MVPP2_RXQ_POOL_LONG_OFFS 24
#define MVPP2_RXQ_POOL_LONG_MASK 0x7000000
#define MVPP2_RXQ_PACKET_OFFSET_OFFS 28
#define MVPP2_RXQ_PACKET_OFFSET_MASK 0x70000000
#define MVPP2_RXQ_DISABLE_MASK BIT(31)
/* Parser Registers */
#define MVPP2_PRS_INIT_LOOKUP_REG 0x1000
#define MVPP2_PRS_PORT_LU_MAX 0xf
#define MVPP2_PRS_PORT_LU_MASK(port) (0xff << ((port) * 4))
#define MVPP2_PRS_PORT_LU_VAL(port, val) ((val) << ((port) * 4))
#define MVPP2_PRS_INIT_OFFS_REG(port) (0x1004 + ((port) & 4))
#define MVPP2_PRS_INIT_OFF_MASK(port) (0x3f << (((port) % 4) * 8))
#define MVPP2_PRS_INIT_OFF_VAL(port, val) ((val) << (((port) % 4) * 8))
#define MVPP2_PRS_MAX_LOOP_REG(port) (0x100c + ((port) & 4))
#define MVPP2_PRS_MAX_LOOP_MASK(port) (0xff << (((port) % 4) * 8))
#define MVPP2_PRS_MAX_LOOP_VAL(port, val) ((val) << (((port) % 4) * 8))
#define MVPP2_PRS_TCAM_IDX_REG 0x1100
#define MVPP2_PRS_TCAM_DATA_REG(idx) (0x1104 + (idx) * 4)
#define MVPP2_PRS_TCAM_INV_MASK BIT(31)
#define MVPP2_PRS_SRAM_IDX_REG 0x1200
#define MVPP2_PRS_SRAM_DATA_REG(idx) (0x1204 + (idx) * 4)
#define MVPP2_PRS_TCAM_CTRL_REG 0x1230
#define MVPP2_PRS_TCAM_EN_MASK BIT(0)
/* Classifier Registers */
#define MVPP2_CLS_MODE_REG 0x1800
#define MVPP2_CLS_MODE_ACTIVE_MASK BIT(0)
#define MVPP2_CLS_PORT_WAY_REG 0x1810
#define MVPP2_CLS_PORT_WAY_MASK(port) (1 << (port))
#define MVPP2_CLS_LKP_INDEX_REG 0x1814
#define MVPP2_CLS_LKP_INDEX_WAY_OFFS 6
#define MVPP2_CLS_LKP_TBL_REG 0x1818
#define MVPP2_CLS_LKP_TBL_RXQ_MASK 0xff
#define MVPP2_CLS_LKP_TBL_LOOKUP_EN_MASK BIT(25)
#define MVPP2_CLS_FLOW_INDEX_REG 0x1820
#define MVPP2_CLS_FLOW_TBL0_REG 0x1824
#define MVPP2_CLS_FLOW_TBL1_REG 0x1828
#define MVPP2_CLS_FLOW_TBL2_REG 0x182c
#define MVPP2_CLS_OVERSIZE_RXQ_LOW_REG(port) (0x1980 + ((port) * 4))
#define MVPP2_CLS_OVERSIZE_RXQ_LOW_BITS 3
#define MVPP2_CLS_OVERSIZE_RXQ_LOW_MASK 0x7
#define MVPP2_CLS_SWFWD_P2HQ_REG(port) (0x19b0 + ((port) * 4))
#define MVPP2_CLS_SWFWD_PCTRL_REG 0x19d0
#define MVPP2_CLS_SWFWD_PCTRL_MASK(port) (1 << (port))
/* Descriptor Manager Top Registers */
#define MVPP2_RXQ_NUM_REG 0x2040
#define MVPP2_RXQ_DESC_ADDR_REG 0x2044
#define MVPP2_RXQ_DESC_SIZE_REG 0x2048
#define MVPP2_RXQ_DESC_SIZE_MASK 0x3ff0
#define MVPP2_RXQ_STATUS_UPDATE_REG(rxq) (0x3000 + 4 * (rxq))
#define MVPP2_RXQ_NUM_PROCESSED_OFFSET 0
#define MVPP2_RXQ_NUM_NEW_OFFSET 16
#define MVPP2_RXQ_STATUS_REG(rxq) (0x3400 + 4 * (rxq))
#define MVPP2_RXQ_OCCUPIED_MASK 0x3fff
#define MVPP2_RXQ_NON_OCCUPIED_OFFSET 16
#define MVPP2_RXQ_NON_OCCUPIED_MASK 0x3fff0000
#define MVPP2_RXQ_THRESH_REG 0x204c
#define MVPP2_OCCUPIED_THRESH_OFFSET 0
#define MVPP2_OCCUPIED_THRESH_MASK 0x3fff
#define MVPP2_RXQ_INDEX_REG 0x2050
#define MVPP2_TXQ_NUM_REG 0x2080
#define MVPP2_TXQ_DESC_ADDR_REG 0x2084
#define MVPP2_TXQ_DESC_SIZE_REG 0x2088
#define MVPP2_TXQ_DESC_SIZE_MASK 0x3ff0
#define MVPP2_AGGR_TXQ_UPDATE_REG 0x2090
#define MVPP2_TXQ_THRESH_REG 0x2094
#define MVPP2_TRANSMITTED_THRESH_OFFSET 16
#define MVPP2_TRANSMITTED_THRESH_MASK 0x3fff0000
#define MVPP2_TXQ_INDEX_REG 0x2098
#define MVPP2_TXQ_PREF_BUF_REG 0x209c
#define MVPP2_PREF_BUF_PTR(desc) ((desc) & 0xfff)
#define MVPP2_PREF_BUF_SIZE_4 (BIT(12) | BIT(13))
#define MVPP2_PREF_BUF_SIZE_16 (BIT(12) | BIT(14))
#define MVPP2_PREF_BUF_THRESH(val) ((val) << 17)
#define MVPP2_TXQ_DRAIN_EN_MASK BIT(31)
#define MVPP2_TXQ_PENDING_REG 0x20a0
#define MVPP2_TXQ_PENDING_MASK 0x3fff
#define MVPP2_TXQ_INT_STATUS_REG 0x20a4
#define MVPP2_TXQ_SENT_REG(txq) (0x3c00 + 4 * (txq))
#define MVPP2_TRANSMITTED_COUNT_OFFSET 16
#define MVPP2_TRANSMITTED_COUNT_MASK 0x3fff0000
#define MVPP2_TXQ_RSVD_REQ_REG 0x20b0
#define MVPP2_TXQ_RSVD_REQ_Q_OFFSET 16
#define MVPP2_TXQ_RSVD_RSLT_REG 0x20b4
#define MVPP2_TXQ_RSVD_RSLT_MASK 0x3fff
#define MVPP2_TXQ_RSVD_CLR_REG 0x20b8
#define MVPP2_TXQ_RSVD_CLR_OFFSET 16
#define MVPP2_AGGR_TXQ_DESC_ADDR_REG(cpu) (0x2100 + 4 * (cpu))
#define MVPP2_AGGR_TXQ_DESC_SIZE_REG(cpu) (0x2140 + 4 * (cpu))
#define MVPP2_AGGR_TXQ_DESC_SIZE_MASK 0x3ff0
#define MVPP2_AGGR_TXQ_STATUS_REG(cpu) (0x2180 + 4 * (cpu))
#define MVPP2_AGGR_TXQ_PENDING_MASK 0x3fff
#define MVPP2_AGGR_TXQ_INDEX_REG(cpu) (0x21c0 + 4 * (cpu))
/* MBUS bridge registers */
#define MVPP2_WIN_BASE(w) (0x4000 + ((w) << 2))
#define MVPP2_WIN_SIZE(w) (0x4020 + ((w) << 2))
#define MVPP2_WIN_REMAP(w) (0x4040 + ((w) << 2))
#define MVPP2_BASE_ADDR_ENABLE 0x4060
/* Interrupt Cause and Mask registers */
#define MVPP2_ISR_RX_THRESHOLD_REG(rxq) (0x5200 + 4 * (rxq))
#define MVPP2_ISR_RXQ_GROUP_REG(rxq) (0x5400 + 4 * (rxq))
#define MVPP2_ISR_ENABLE_REG(port) (0x5420 + 4 * (port))
#define MVPP2_ISR_ENABLE_INTERRUPT(mask) ((mask) & 0xffff)
#define MVPP2_ISR_DISABLE_INTERRUPT(mask) (((mask) << 16) & 0xffff0000)
#define MVPP2_ISR_RX_TX_CAUSE_REG(port) (0x5480 + 4 * (port))
#define MVPP2_CAUSE_RXQ_OCCUP_DESC_ALL_MASK 0xffff
#define MVPP2_CAUSE_TXQ_OCCUP_DESC_ALL_MASK 0xff0000
#define MVPP2_CAUSE_RX_FIFO_OVERRUN_MASK BIT(24)
#define MVPP2_CAUSE_FCS_ERR_MASK BIT(25)
#define MVPP2_CAUSE_TX_FIFO_UNDERRUN_MASK BIT(26)
#define MVPP2_CAUSE_TX_EXCEPTION_SUM_MASK BIT(29)
#define MVPP2_CAUSE_RX_EXCEPTION_SUM_MASK BIT(30)
#define MVPP2_CAUSE_MISC_SUM_MASK BIT(31)
#define MVPP2_ISR_RX_TX_MASK_REG(port) (0x54a0 + 4 * (port))
#define MVPP2_ISR_PON_RX_TX_MASK_REG 0x54bc
#define MVPP2_PON_CAUSE_RXQ_OCCUP_DESC_ALL_MASK 0xffff
#define MVPP2_PON_CAUSE_TXP_OCCUP_DESC_ALL_MASK 0x3fc00000
#define MVPP2_PON_CAUSE_MISC_SUM_MASK BIT(31)
#define MVPP2_ISR_MISC_CAUSE_REG 0x55b0
/* Buffer Manager registers */
#define MVPP2_BM_POOL_BASE_REG(pool) (0x6000 + ((pool) * 4))
#define MVPP2_BM_POOL_BASE_ADDR_MASK 0xfffff80
#define MVPP2_BM_POOL_SIZE_REG(pool) (0x6040 + ((pool) * 4))
#define MVPP2_BM_POOL_SIZE_MASK 0xfff0
#define MVPP2_BM_POOL_READ_PTR_REG(pool) (0x6080 + ((pool) * 4))
#define MVPP2_BM_POOL_GET_READ_PTR_MASK 0xfff0
#define MVPP2_BM_POOL_PTRS_NUM_REG(pool) (0x60c0 + ((pool) * 4))
#define MVPP2_BM_POOL_PTRS_NUM_MASK 0xfff0
#define MVPP2_BM_BPPI_READ_PTR_REG(pool) (0x6100 + ((pool) * 4))
#define MVPP2_BM_BPPI_PTRS_NUM_REG(pool) (0x6140 + ((pool) * 4))
#define MVPP2_BM_BPPI_PTR_NUM_MASK 0x7ff
#define MVPP2_BM_BPPI_PREFETCH_FULL_MASK BIT(16)
#define MVPP2_BM_POOL_CTRL_REG(pool) (0x6200 + ((pool) * 4))
#define MVPP2_BM_START_MASK BIT(0)
#define MVPP2_BM_STOP_MASK BIT(1)
#define MVPP2_BM_STATE_MASK BIT(4)
#define MVPP2_BM_LOW_THRESH_OFFS 8
#define MVPP2_BM_LOW_THRESH_MASK 0x7f00
#define MVPP2_BM_LOW_THRESH_VALUE(val) ((val) << \
MVPP2_BM_LOW_THRESH_OFFS)
#define MVPP2_BM_HIGH_THRESH_OFFS 16
#define MVPP2_BM_HIGH_THRESH_MASK 0x7f0000
#define MVPP2_BM_HIGH_THRESH_VALUE(val) ((val) << \
MVPP2_BM_HIGH_THRESH_OFFS)
#define MVPP2_BM_INTR_CAUSE_REG(pool) (0x6240 + ((pool) * 4))
#define MVPP2_BM_RELEASED_DELAY_MASK BIT(0)
#define MVPP2_BM_ALLOC_FAILED_MASK BIT(1)
#define MVPP2_BM_BPPE_EMPTY_MASK BIT(2)
#define MVPP2_BM_BPPE_FULL_MASK BIT(3)
#define MVPP2_BM_AVAILABLE_BP_LOW_MASK BIT(4)
#define MVPP2_BM_INTR_MASK_REG(pool) (0x6280 + ((pool) * 4))
#define MVPP2_BM_PHY_ALLOC_REG(pool) (0x6400 + ((pool) * 4))
#define MVPP2_BM_PHY_ALLOC_GRNTD_MASK BIT(0)
#define MVPP2_BM_VIRT_ALLOC_REG 0x6440
#define MVPP2_BM_PHY_RLS_REG(pool) (0x6480 + ((pool) * 4))
#define MVPP2_BM_PHY_RLS_MC_BUFF_MASK BIT(0)
#define MVPP2_BM_PHY_RLS_PRIO_EN_MASK BIT(1)
#define MVPP2_BM_PHY_RLS_GRNTD_MASK BIT(2)
#define MVPP2_BM_VIRT_RLS_REG 0x64c0
#define MVPP2_BM_MC_RLS_REG 0x64c4
#define MVPP2_BM_MC_ID_MASK 0xfff
#define MVPP2_BM_FORCE_RELEASE_MASK BIT(12)
/* TX Scheduler registers */
#define MVPP2_TXP_SCHED_PORT_INDEX_REG 0x8000
#define MVPP2_TXP_SCHED_Q_CMD_REG 0x8004
#define MVPP2_TXP_SCHED_ENQ_MASK 0xff
#define MVPP2_TXP_SCHED_DISQ_OFFSET 8
#define MVPP2_TXP_SCHED_CMD_1_REG 0x8010
#define MVPP2_TXP_SCHED_PERIOD_REG 0x8018
#define MVPP2_TXP_SCHED_MTU_REG 0x801c
#define MVPP2_TXP_MTU_MAX 0x7FFFF
#define MVPP2_TXP_SCHED_REFILL_REG 0x8020
#define MVPP2_TXP_REFILL_TOKENS_ALL_MASK 0x7ffff
#define MVPP2_TXP_REFILL_PERIOD_ALL_MASK 0x3ff00000
#define MVPP2_TXP_REFILL_PERIOD_MASK(v) ((v) << 20)
#define MVPP2_TXP_SCHED_TOKEN_SIZE_REG 0x8024
#define MVPP2_TXP_TOKEN_SIZE_MAX 0xffffffff
#define MVPP2_TXQ_SCHED_REFILL_REG(q) (0x8040 + ((q) << 2))
#define MVPP2_TXQ_REFILL_TOKENS_ALL_MASK 0x7ffff
#define MVPP2_TXQ_REFILL_PERIOD_ALL_MASK 0x3ff00000
#define MVPP2_TXQ_REFILL_PERIOD_MASK(v) ((v) << 20)
#define MVPP2_TXQ_SCHED_TOKEN_SIZE_REG(q) (0x8060 + ((q) << 2))
#define MVPP2_TXQ_TOKEN_SIZE_MAX 0x7fffffff
#define MVPP2_TXQ_SCHED_TOKEN_CNTR_REG(q) (0x8080 + ((q) << 2))
#define MVPP2_TXQ_TOKEN_CNTR_MAX 0xffffffff
/* TX general registers */
#define MVPP2_TX_SNOOP_REG 0x8800
#define MVPP2_TX_PORT_FLUSH_REG 0x8810
#define MVPP2_TX_PORT_FLUSH_MASK(port) (1 << (port))
/* LMS registers */
#define MVPP2_SRC_ADDR_MIDDLE 0x24
#define MVPP2_SRC_ADDR_HIGH 0x28
#define MVPP2_PHY_AN_CFG0_REG 0x34
#define MVPP2_PHY_AN_STOP_SMI0_MASK BIT(7)
#define MVPP2_MIB_COUNTERS_BASE(port) (0x1000 + ((port) >> 1) * \
0x400 + (port) * 0x400)
#define MVPP2_MIB_LATE_COLLISION 0x7c
#define MVPP2_ISR_SUM_MASK_REG 0x220c
#define MVPP2_MNG_EXTENDED_GLOBAL_CTRL_REG 0x305c
#define MVPP2_EXT_GLOBAL_CTRL_DEFAULT 0x27
/* Per-port registers */
#define MVPP2_GMAC_CTRL_0_REG 0x0
#define MVPP2_GMAC_PORT_EN_MASK BIT(0)
#define MVPP2_GMAC_MAX_RX_SIZE_OFFS 2
#define MVPP2_GMAC_MAX_RX_SIZE_MASK 0x7ffc
#define MVPP2_GMAC_MIB_CNTR_EN_MASK BIT(15)
#define MVPP2_GMAC_CTRL_1_REG 0x4
#define MVPP2_GMAC_PERIODIC_XON_EN_MASK BIT(1)
#define MVPP2_GMAC_GMII_LB_EN_MASK BIT(5)
#define MVPP2_GMAC_PCS_LB_EN_BIT 6
#define MVPP2_GMAC_PCS_LB_EN_MASK BIT(6)
#define MVPP2_GMAC_SA_LOW_OFFS 7
#define MVPP2_GMAC_CTRL_2_REG 0x8
#define MVPP2_GMAC_INBAND_AN_MASK BIT(0)
#define MVPP2_GMAC_PCS_ENABLE_MASK BIT(3)
#define MVPP2_GMAC_PORT_RGMII_MASK BIT(4)
#define MVPP2_GMAC_PORT_RESET_MASK BIT(6)
#define MVPP2_GMAC_AUTONEG_CONFIG 0xc
#define MVPP2_GMAC_FORCE_LINK_DOWN BIT(0)
#define MVPP2_GMAC_FORCE_LINK_PASS BIT(1)
#define MVPP2_GMAC_CONFIG_MII_SPEED BIT(5)
#define MVPP2_GMAC_CONFIG_GMII_SPEED BIT(6)
#define MVPP2_GMAC_AN_SPEED_EN BIT(7)
#define MVPP2_GMAC_FC_ADV_EN BIT(9)
#define MVPP2_GMAC_CONFIG_FULL_DUPLEX BIT(12)
#define MVPP2_GMAC_AN_DUPLEX_EN BIT(13)
#define MVPP2_GMAC_PORT_FIFO_CFG_1_REG 0x1c
#define MVPP2_GMAC_TX_FIFO_MIN_TH_OFFS 6
#define MVPP2_GMAC_TX_FIFO_MIN_TH_ALL_MASK 0x1fc0
#define MVPP2_GMAC_TX_FIFO_MIN_TH_MASK(v) (((v) << 6) & \
MVPP2_GMAC_TX_FIFO_MIN_TH_ALL_MASK)
#define MVPP2_CAUSE_TXQ_SENT_DESC_ALL_MASK 0xff
/* Descriptor ring Macros */
#define MVPP2_QUEUE_NEXT_DESC(q, index) \
(((index) < (q)->last_desc) ? ((index) + 1) : 0)
/* Various constants */
/* Coalescing */
#define MVPP2_TXDONE_COAL_PKTS_THRESH 15
#define MVPP2_RX_COAL_PKTS 32
#define MVPP2_RX_COAL_USEC 100
/* The two bytes Marvell header. Either contains a special value used
* by Marvell switches when a specific hardware mode is enabled (not
* supported by this driver) or is filled automatically by zeroes on
* the RX side. Those two bytes being at the front of the Ethernet
* header, they allow to have the IP header aligned on a 4 bytes
* boundary automatically: the hardware skips those two bytes on its
* own.
*/
#define MVPP2_MH_SIZE 2
#define MVPP2_ETH_TYPE_LEN 2
#define MVPP2_PPPOE_HDR_SIZE 8
#define MVPP2_VLAN_TAG_LEN 4
/* Lbtd 802.3 type */
#define MVPP2_IP_LBDT_TYPE 0xfffa
#define MVPP2_CPU_D_CACHE_LINE_SIZE 32
#define MVPP2_TX_CSUM_MAX_SIZE 9800
/* Timeout constants */
#define MVPP2_TX_DISABLE_TIMEOUT_MSEC 1000
#define MVPP2_TX_PENDING_TIMEOUT_MSEC 1000
#define MVPP2_TX_MTU_MAX 0x7ffff
/* Maximum number of T-CONTs of PON port */
#define MVPP2_MAX_TCONT 16
/* Maximum number of supported ports */
#define MVPP2_MAX_PORTS 4
/* Maximum number of TXQs used by single port */
#define MVPP2_MAX_TXQ 8
/* Maximum number of RXQs used by single port */
#define MVPP2_MAX_RXQ 8
/* Dfault number of RXQs in use */
#define MVPP2_DEFAULT_RXQ 4
/* Total number of RXQs available to all ports */
#define MVPP2_RXQ_TOTAL_NUM (MVPP2_MAX_PORTS * MVPP2_MAX_RXQ)
/* Max number of Rx descriptors */
#define MVPP2_MAX_RXD 128
/* Max number of Tx descriptors */
#define MVPP2_MAX_TXD 1024
/* Amount of Tx descriptors that can be reserved at once by CPU */
#define MVPP2_CPU_DESC_CHUNK 64
/* Max number of Tx descriptors in each aggregated queue */
#define MVPP2_AGGR_TXQ_SIZE 256
/* Descriptor aligned size */
#define MVPP2_DESC_ALIGNED_SIZE 32
/* Descriptor alignment mask */
#define MVPP2_TX_DESC_ALIGN (MVPP2_DESC_ALIGNED_SIZE - 1)
/* RX FIFO constants */
#define MVPP2_RX_FIFO_PORT_DATA_SIZE 0x2000
#define MVPP2_RX_FIFO_PORT_ATTR_SIZE 0x80
#define MVPP2_RX_FIFO_PORT_MIN_PKT 0x80
/* RX buffer constants */
#define MVPP2_SKB_SHINFO_SIZE \
SKB_DATA_ALIGN(sizeof(struct skb_shared_info))
#define MVPP2_RX_PKT_SIZE(mtu) \
ALIGN((mtu) + MVPP2_MH_SIZE + MVPP2_VLAN_TAG_LEN + \
ETH_HLEN + ETH_FCS_LEN, MVPP2_CPU_D_CACHE_LINE_SIZE)
#define MVPP2_RX_BUF_SIZE(pkt_size) ((pkt_size) + NET_SKB_PAD)
#define MVPP2_RX_TOTAL_SIZE(buf_size) ((buf_size) + MVPP2_SKB_SHINFO_SIZE)
#define MVPP2_RX_MAX_PKT_SIZE(total_size) \
((total_size) - NET_SKB_PAD - MVPP2_SKB_SHINFO_SIZE)
#define MVPP2_BIT_TO_BYTE(bit) ((bit) / 8)
/* IPv6 max L3 address size */
#define MVPP2_MAX_L3_ADDR_SIZE 16
/* Port flags */
#define MVPP2_F_LOOPBACK BIT(0)
/* Marvell tag types */
enum mvpp2_tag_type {
MVPP2_TAG_TYPE_NONE = 0,
MVPP2_TAG_TYPE_MH = 1,
MVPP2_TAG_TYPE_DSA = 2,
MVPP2_TAG_TYPE_EDSA = 3,
MVPP2_TAG_TYPE_VLAN = 4,
MVPP2_TAG_TYPE_LAST = 5
};
/* Parser constants */
#define MVPP2_PRS_TCAM_SRAM_SIZE 256
#define MVPP2_PRS_TCAM_WORDS 6
#define MVPP2_PRS_SRAM_WORDS 4
#define MVPP2_PRS_FLOW_ID_SIZE 64
#define MVPP2_PRS_FLOW_ID_MASK 0x3f
#define MVPP2_PRS_TCAM_ENTRY_INVALID 1
#define MVPP2_PRS_TCAM_DSA_TAGGED_BIT BIT(5)
#define MVPP2_PRS_IPV4_HEAD 0x40
#define MVPP2_PRS_IPV4_HEAD_MASK 0xf0
#define MVPP2_PRS_IPV4_MC 0xe0
#define MVPP2_PRS_IPV4_MC_MASK 0xf0
#define MVPP2_PRS_IPV4_BC_MASK 0xff
#define MVPP2_PRS_IPV4_IHL 0x5
#define MVPP2_PRS_IPV4_IHL_MASK 0xf
#define MVPP2_PRS_IPV6_MC 0xff
#define MVPP2_PRS_IPV6_MC_MASK 0xff
#define MVPP2_PRS_IPV6_HOP_MASK 0xff
#define MVPP2_PRS_TCAM_PROTO_MASK 0xff
#define MVPP2_PRS_TCAM_PROTO_MASK_L 0x3f
#define MVPP2_PRS_DBL_VLANS_MAX 100
/* Tcam structure:
* - lookup ID - 4 bits
* - port ID - 1 byte
* - additional information - 1 byte
* - header data - 8 bytes
* The fields are represented by MVPP2_PRS_TCAM_DATA_REG(5)->(0).
*/
#define MVPP2_PRS_AI_BITS 8
#define MVPP2_PRS_PORT_MASK 0xff
#define MVPP2_PRS_LU_MASK 0xf
#define MVPP2_PRS_TCAM_DATA_BYTE(offs) \
(((offs) - ((offs) % 2)) * 2 + ((offs) % 2))
#define MVPP2_PRS_TCAM_DATA_BYTE_EN(offs) \
(((offs) * 2) - ((offs) % 2) + 2)
#define MVPP2_PRS_TCAM_AI_BYTE 16
#define MVPP2_PRS_TCAM_PORT_BYTE 17
#define MVPP2_PRS_TCAM_LU_BYTE 20
#define MVPP2_PRS_TCAM_EN_OFFS(offs) ((offs) + 2)
#define MVPP2_PRS_TCAM_INV_WORD 5
/* Tcam entries ID */
#define MVPP2_PE_DROP_ALL 0
#define MVPP2_PE_FIRST_FREE_TID 1
#define MVPP2_PE_LAST_FREE_TID (MVPP2_PRS_TCAM_SRAM_SIZE - 31)
#define MVPP2_PE_IP6_EXT_PROTO_UN (MVPP2_PRS_TCAM_SRAM_SIZE - 30)
#define MVPP2_PE_MAC_MC_IP6 (MVPP2_PRS_TCAM_SRAM_SIZE - 29)
#define MVPP2_PE_IP6_ADDR_UN (MVPP2_PRS_TCAM_SRAM_SIZE - 28)
#define MVPP2_PE_IP4_ADDR_UN (MVPP2_PRS_TCAM_SRAM_SIZE - 27)
#define MVPP2_PE_LAST_DEFAULT_FLOW (MVPP2_PRS_TCAM_SRAM_SIZE - 26)
#define MVPP2_PE_FIRST_DEFAULT_FLOW (MVPP2_PRS_TCAM_SRAM_SIZE - 19)
#define MVPP2_PE_EDSA_TAGGED (MVPP2_PRS_TCAM_SRAM_SIZE - 18)
#define MVPP2_PE_EDSA_UNTAGGED (MVPP2_PRS_TCAM_SRAM_SIZE - 17)
#define MVPP2_PE_DSA_TAGGED (MVPP2_PRS_TCAM_SRAM_SIZE - 16)
#define MVPP2_PE_DSA_UNTAGGED (MVPP2_PRS_TCAM_SRAM_SIZE - 15)
#define MVPP2_PE_ETYPE_EDSA_TAGGED (MVPP2_PRS_TCAM_SRAM_SIZE - 14)
#define MVPP2_PE_ETYPE_EDSA_UNTAGGED (MVPP2_PRS_TCAM_SRAM_SIZE - 13)
#define MVPP2_PE_ETYPE_DSA_TAGGED (MVPP2_PRS_TCAM_SRAM_SIZE - 12)
#define MVPP2_PE_ETYPE_DSA_UNTAGGED (MVPP2_PRS_TCAM_SRAM_SIZE - 11)
#define MVPP2_PE_MH_DEFAULT (MVPP2_PRS_TCAM_SRAM_SIZE - 10)
#define MVPP2_PE_DSA_DEFAULT (MVPP2_PRS_TCAM_SRAM_SIZE - 9)
#define MVPP2_PE_IP6_PROTO_UN (MVPP2_PRS_TCAM_SRAM_SIZE - 8)
#define MVPP2_PE_IP4_PROTO_UN (MVPP2_PRS_TCAM_SRAM_SIZE - 7)
#define MVPP2_PE_ETH_TYPE_UN (MVPP2_PRS_TCAM_SRAM_SIZE - 6)
#define MVPP2_PE_VLAN_DBL (MVPP2_PRS_TCAM_SRAM_SIZE - 5)
#define MVPP2_PE_VLAN_NONE (MVPP2_PRS_TCAM_SRAM_SIZE - 4)
#define MVPP2_PE_MAC_MC_ALL (MVPP2_PRS_TCAM_SRAM_SIZE - 3)
#define MVPP2_PE_MAC_PROMISCUOUS (MVPP2_PRS_TCAM_SRAM_SIZE - 2)
#define MVPP2_PE_MAC_NON_PROMISCUOUS (MVPP2_PRS_TCAM_SRAM_SIZE - 1)
/* Sram structure
* The fields are represented by MVPP2_PRS_TCAM_DATA_REG(3)->(0).
*/
#define MVPP2_PRS_SRAM_RI_OFFS 0
#define MVPP2_PRS_SRAM_RI_WORD 0
#define MVPP2_PRS_SRAM_RI_CTRL_OFFS 32
#define MVPP2_PRS_SRAM_RI_CTRL_WORD 1
#define MVPP2_PRS_SRAM_RI_CTRL_BITS 32
#define MVPP2_PRS_SRAM_SHIFT_OFFS 64
#define MVPP2_PRS_SRAM_SHIFT_SIGN_BIT 72
#define MVPP2_PRS_SRAM_UDF_OFFS 73
#define MVPP2_PRS_SRAM_UDF_BITS 8
#define MVPP2_PRS_SRAM_UDF_MASK 0xff
#define MVPP2_PRS_SRAM_UDF_SIGN_BIT 81
#define MVPP2_PRS_SRAM_UDF_TYPE_OFFS 82
#define MVPP2_PRS_SRAM_UDF_TYPE_MASK 0x7
#define MVPP2_PRS_SRAM_UDF_TYPE_L3 1
#define MVPP2_PRS_SRAM_UDF_TYPE_L4 4
#define MVPP2_PRS_SRAM_OP_SEL_SHIFT_OFFS 85
#define MVPP2_PRS_SRAM_OP_SEL_SHIFT_MASK 0x3
#define MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD 1
#define MVPP2_PRS_SRAM_OP_SEL_SHIFT_IP4_ADD 2
#define MVPP2_PRS_SRAM_OP_SEL_SHIFT_IP6_ADD 3
#define MVPP2_PRS_SRAM_OP_SEL_UDF_OFFS 87
#define MVPP2_PRS_SRAM_OP_SEL_UDF_BITS 2
#define MVPP2_PRS_SRAM_OP_SEL_UDF_MASK 0x3
#define MVPP2_PRS_SRAM_OP_SEL_UDF_ADD 0
#define MVPP2_PRS_SRAM_OP_SEL_UDF_IP4_ADD 2
#define MVPP2_PRS_SRAM_OP_SEL_UDF_IP6_ADD 3
#define MVPP2_PRS_SRAM_OP_SEL_BASE_OFFS 89
#define MVPP2_PRS_SRAM_AI_OFFS 90
#define MVPP2_PRS_SRAM_AI_CTRL_OFFS 98
#define MVPP2_PRS_SRAM_AI_CTRL_BITS 8
#define MVPP2_PRS_SRAM_AI_MASK 0xff
#define MVPP2_PRS_SRAM_NEXT_LU_OFFS 106
#define MVPP2_PRS_SRAM_NEXT_LU_MASK 0xf
#define MVPP2_PRS_SRAM_LU_DONE_BIT 110
#define MVPP2_PRS_SRAM_LU_GEN_BIT 111
/* Sram result info bits assignment */
#define MVPP2_PRS_RI_MAC_ME_MASK 0x1
#define MVPP2_PRS_RI_DSA_MASK 0x2
#define MVPP2_PRS_RI_VLAN_MASK 0xc
#define MVPP2_PRS_RI_VLAN_NONE ~(BIT(2) | BIT(3))
#define MVPP2_PRS_RI_VLAN_SINGLE BIT(2)
#define MVPP2_PRS_RI_VLAN_DOUBLE BIT(3)
#define MVPP2_PRS_RI_VLAN_TRIPLE (BIT(2) | BIT(3))
#define MVPP2_PRS_RI_CPU_CODE_MASK 0x70
#define MVPP2_PRS_RI_CPU_CODE_RX_SPEC BIT(4)
#define MVPP2_PRS_RI_L2_CAST_MASK 0x600
#define MVPP2_PRS_RI_L2_UCAST ~(BIT(9) | BIT(10))
#define MVPP2_PRS_RI_L2_MCAST BIT(9)
#define MVPP2_PRS_RI_L2_BCAST BIT(10)
#define MVPP2_PRS_RI_PPPOE_MASK 0x800
#define MVPP2_PRS_RI_L3_PROTO_MASK 0x7000
#define MVPP2_PRS_RI_L3_UN ~(BIT(12) | BIT(13) | BIT(14))
#define MVPP2_PRS_RI_L3_IP4 BIT(12)
#define MVPP2_PRS_RI_L3_IP4_OPT BIT(13)
#define MVPP2_PRS_RI_L3_IP4_OTHER (BIT(12) | BIT(13))
#define MVPP2_PRS_RI_L3_IP6 BIT(14)
#define MVPP2_PRS_RI_L3_IP6_EXT (BIT(12) | BIT(14))
#define MVPP2_PRS_RI_L3_ARP (BIT(13) | BIT(14))
#define MVPP2_PRS_RI_L3_ADDR_MASK 0x18000
#define MVPP2_PRS_RI_L3_UCAST ~(BIT(15) | BIT(16))
#define MVPP2_PRS_RI_L3_MCAST BIT(15)
#define MVPP2_PRS_RI_L3_BCAST (BIT(15) | BIT(16))
#define MVPP2_PRS_RI_IP_FRAG_MASK 0x20000
#define MVPP2_PRS_RI_UDF3_MASK 0x300000
#define MVPP2_PRS_RI_UDF3_RX_SPECIAL BIT(21)
#define MVPP2_PRS_RI_L4_PROTO_MASK 0x1c00000
#define MVPP2_PRS_RI_L4_TCP BIT(22)
#define MVPP2_PRS_RI_L4_UDP BIT(23)
#define MVPP2_PRS_RI_L4_OTHER (BIT(22) | BIT(23))
#define MVPP2_PRS_RI_UDF7_MASK 0x60000000
#define MVPP2_PRS_RI_UDF7_IP6_LITE BIT(29)
#define MVPP2_PRS_RI_DROP_MASK 0x80000000
/* Sram additional info bits assignment */
#define MVPP2_PRS_IPV4_DIP_AI_BIT BIT(0)
#define MVPP2_PRS_IPV6_NO_EXT_AI_BIT BIT(0)
#define MVPP2_PRS_IPV6_EXT_AI_BIT BIT(1)
#define MVPP2_PRS_IPV6_EXT_AH_AI_BIT BIT(2)
#define MVPP2_PRS_IPV6_EXT_AH_LEN_AI_BIT BIT(3)
#define MVPP2_PRS_IPV6_EXT_AH_L4_AI_BIT BIT(4)
#define MVPP2_PRS_SINGLE_VLAN_AI 0
#define MVPP2_PRS_DBL_VLAN_AI_BIT BIT(7)
/* DSA/EDSA type */
#define MVPP2_PRS_TAGGED true
#define MVPP2_PRS_UNTAGGED false
#define MVPP2_PRS_EDSA true
#define MVPP2_PRS_DSA false
/* MAC entries, shadow udf */
enum mvpp2_prs_udf {
MVPP2_PRS_UDF_MAC_DEF,
MVPP2_PRS_UDF_MAC_RANGE,
MVPP2_PRS_UDF_L2_DEF,
MVPP2_PRS_UDF_L2_DEF_COPY,
MVPP2_PRS_UDF_L2_USER,
};
/* Lookup ID */
enum mvpp2_prs_lookup {
MVPP2_PRS_LU_MH,
MVPP2_PRS_LU_MAC,
MVPP2_PRS_LU_DSA,
MVPP2_PRS_LU_VLAN,
MVPP2_PRS_LU_L2,
MVPP2_PRS_LU_PPPOE,
MVPP2_PRS_LU_IP4,
MVPP2_PRS_LU_IP6,
MVPP2_PRS_LU_FLOWS,
MVPP2_PRS_LU_LAST,
};
/* L3 cast enum */
enum mvpp2_prs_l3_cast {
MVPP2_PRS_L3_UNI_CAST,
MVPP2_PRS_L3_MULTI_CAST,
MVPP2_PRS_L3_BROAD_CAST
};
/* Classifier constants */
#define MVPP2_CLS_FLOWS_TBL_SIZE 512
#define MVPP2_CLS_FLOWS_TBL_DATA_WORDS 3
#define MVPP2_CLS_LKP_TBL_SIZE 64
/* BM constants */
#define MVPP2_BM_POOLS_NUM 8
#define MVPP2_BM_LONG_BUF_NUM 1024
#define MVPP2_BM_SHORT_BUF_NUM 2048
#define MVPP2_BM_POOL_SIZE_MAX (16*1024 - MVPP2_BM_POOL_PTR_ALIGN/4)
#define MVPP2_BM_POOL_PTR_ALIGN 128
#define MVPP2_BM_SWF_LONG_POOL(port) ((port > 2) ? 2 : port)
#define MVPP2_BM_SWF_SHORT_POOL 3
/* BM cookie (32 bits) definition */
#define MVPP2_BM_COOKIE_POOL_OFFS 8
#define MVPP2_BM_COOKIE_CPU_OFFS 24
/* BM short pool packet size
* These value assure that for SWF the total number
* of bytes allocated for each buffer will be 512
*/
#define MVPP2_BM_SHORT_PKT_SIZE MVPP2_RX_MAX_PKT_SIZE(512)
enum mvpp2_bm_type {
MVPP2_BM_FREE,
MVPP2_BM_SWF_LONG,
MVPP2_BM_SWF_SHORT
};
/* Definitions */
/* Shared Packet Processor resources */
struct mvpp2 {
/* Shared registers' base addresses */
void __iomem *base;
void __iomem *lms_base;
/* Common clocks */
struct clk *pp_clk;
struct clk *gop_clk;
/* List of pointers to port structures */
struct mvpp2_port **port_list;
/* Aggregated TXQs */
struct mvpp2_tx_queue *aggr_txqs;
/* BM pools */
struct mvpp2_bm_pool *bm_pools;
/* PRS shadow table */
struct mvpp2_prs_shadow *prs_shadow;
/* PRS auxiliary table for double vlan entries control */
bool *prs_double_vlans;
/* Tclk value */
u32 tclk;
};
struct mvpp2_pcpu_stats {
struct u64_stats_sync syncp;
u64 rx_packets;
u64 rx_bytes;
u64 tx_packets;
u64 tx_bytes;
};
struct mvpp2_port {
u8 id;
int irq;
struct mvpp2 *priv;
/* Per-port registers' base address */
void __iomem *base;
struct mvpp2_rx_queue **rxqs;
struct mvpp2_tx_queue **txqs;
struct net_device *dev;
int pkt_size;
u32 pending_cause_rx;
struct napi_struct napi;
/* Flags */
unsigned long flags;
u16 tx_ring_size;
u16 rx_ring_size;
struct mvpp2_pcpu_stats __percpu *stats;
struct phy_device *phy_dev;
phy_interface_t phy_interface;
struct device_node *phy_node;
unsigned int link;
unsigned int duplex;
unsigned int speed;
struct mvpp2_bm_pool *pool_long;
struct mvpp2_bm_pool *pool_short;
/* Index of first port's physical RXQ */
u8 first_rxq;
};
/* The mvpp2_tx_desc and mvpp2_rx_desc structures describe the
* layout of the transmit and reception DMA descriptors, and their
* layout is therefore defined by the hardware design
*/
#define MVPP2_TXD_L3_OFF_SHIFT 0
#define MVPP2_TXD_IP_HLEN_SHIFT 8
#define MVPP2_TXD_L4_CSUM_FRAG BIT(13)
#define MVPP2_TXD_L4_CSUM_NOT BIT(14)
#define MVPP2_TXD_IP_CSUM_DISABLE BIT(15)
#define MVPP2_TXD_PADDING_DISABLE BIT(23)
#define MVPP2_TXD_L4_UDP BIT(24)
#define MVPP2_TXD_L3_IP6 BIT(26)
#define MVPP2_TXD_L_DESC BIT(28)
#define MVPP2_TXD_F_DESC BIT(29)
#define MVPP2_RXD_ERR_SUMMARY BIT(15)
#define MVPP2_RXD_ERR_CODE_MASK (BIT(13) | BIT(14))
#define MVPP2_RXD_ERR_CRC 0x0
#define MVPP2_RXD_ERR_OVERRUN BIT(13)
#define MVPP2_RXD_ERR_RESOURCE (BIT(13) | BIT(14))
#define MVPP2_RXD_BM_POOL_ID_OFFS 16
#define MVPP2_RXD_BM_POOL_ID_MASK (BIT(16) | BIT(17) | BIT(18))
#define MVPP2_RXD_HWF_SYNC BIT(21)
#define MVPP2_RXD_L4_CSUM_OK BIT(22)
#define MVPP2_RXD_IP4_HEADER_ERR BIT(24)
#define MVPP2_RXD_L4_TCP BIT(25)
#define MVPP2_RXD_L4_UDP BIT(26)
#define MVPP2_RXD_L3_IP4 BIT(28)
#define MVPP2_RXD_L3_IP6 BIT(30)
#define MVPP2_RXD_BUF_HDR BIT(31)
struct mvpp2_tx_desc {
u32 command; /* Options used by HW for packet transmitting.*/
u8 packet_offset; /* the offset from the buffer beginning */
u8 phys_txq; /* destination queue ID */
u16 data_size; /* data size of transmitted packet in bytes */
u32 buf_phys_addr; /* physical addr of transmitted buffer */
u32 buf_cookie; /* cookie for access to TX buffer in tx path */
u32 reserved1[3]; /* hw_cmd (for future use, BM, PON, PNC) */
u32 reserved2; /* reserved (for future use) */
};
struct mvpp2_rx_desc {
u32 status; /* info about received packet */
u16 reserved1; /* parser_info (for future use, PnC) */
u16 data_size; /* size of received packet in bytes */
u32 buf_phys_addr; /* physical address of the buffer */
u32 buf_cookie; /* cookie for access to RX buffer in rx path */
u16 reserved2; /* gem_port_id (for future use, PON) */
u16 reserved3; /* csum_l4 (for future use, PnC) */
u8 reserved4; /* bm_qset (for future use, BM) */
u8 reserved5;
u16 reserved6; /* classify_info (for future use, PnC) */
u32 reserved7; /* flow_id (for future use, PnC) */
u32 reserved8;
};
/* Per-CPU Tx queue control */
struct mvpp2_txq_pcpu {
int cpu;
/* Number of Tx DMA descriptors in the descriptor ring */
int size;
/* Number of currently used Tx DMA descriptor in the
* descriptor ring
*/
int count;
/* Number of Tx DMA descriptors reserved for each CPU */
int reserved_num;
/* Array of transmitted skb */
struct sk_buff **tx_skb;
/* Index of last TX DMA descriptor that was inserted */
int txq_put_index;
/* Index of the TX DMA descriptor to be cleaned up */
int txq_get_index;
};
struct mvpp2_tx_queue {
/* Physical number of this Tx queue */
u8 id;
/* Logical number of this Tx queue */
u8 log_id;
/* Number of Tx DMA descriptors in the descriptor ring */
int size;
/* Number of currently used Tx DMA descriptor in the descriptor ring */
int count;
/* Per-CPU control of physical Tx queues */
struct mvpp2_txq_pcpu __percpu *pcpu;
/* Array of transmitted skb */
struct sk_buff **tx_skb;
u32 done_pkts_coal;
/* Virtual address of thex Tx DMA descriptors array */
struct mvpp2_tx_desc *descs;
/* DMA address of the Tx DMA descriptors array */
dma_addr_t descs_phys;
/* Index of the last Tx DMA descriptor */
int last_desc;
/* Index of the next Tx DMA descriptor to process */
int next_desc_to_proc;
};
struct mvpp2_rx_queue {
/* RX queue number, in the range 0-31 for physical RXQs */
u8 id;
/* Num of rx descriptors in the rx descriptor ring */
int size;
u32 pkts_coal;
u32 time_coal;
/* Virtual address of the RX DMA descriptors array */
struct mvpp2_rx_desc *descs;
/* DMA address of the RX DMA descriptors array */
dma_addr_t descs_phys;
/* Index of the last RX DMA descriptor */
int last_desc;
/* Index of the next RX DMA descriptor to process */
int next_desc_to_proc;
/* ID of port to which physical RXQ is mapped */
int port;
/* Port's logic RXQ number to which physical RXQ is mapped */
int logic_rxq;
};
union mvpp2_prs_tcam_entry {
u32 word[MVPP2_PRS_TCAM_WORDS];
u8 byte[MVPP2_PRS_TCAM_WORDS * 4];
};
union mvpp2_prs_sram_entry {
u32 word[MVPP2_PRS_SRAM_WORDS];
u8 byte[MVPP2_PRS_SRAM_WORDS * 4];
};
struct mvpp2_prs_entry {
u32 index;
union mvpp2_prs_tcam_entry tcam;
union mvpp2_prs_sram_entry sram;
};
struct mvpp2_prs_shadow {
bool valid;
bool finish;
/* Lookup ID */
int lu;
/* User defined offset */
int udf;
/* Result info */
u32 ri;
u32 ri_mask;
};
struct mvpp2_cls_flow_entry {
u32 index;
u32 data[MVPP2_CLS_FLOWS_TBL_DATA_WORDS];
};
struct mvpp2_cls_lookup_entry {
u32 lkpid;
u32 way;
u32 data;
};
struct mvpp2_bm_pool {
/* Pool number in the range 0-7 */
int id;
enum mvpp2_bm_type type;
/* Buffer Pointers Pool External (BPPE) size */
int size;
/* Number of buffers for this pool */
int buf_num;
/* Pool buffer size */
int buf_size;
/* Packet size */
int pkt_size;
/* BPPE virtual base address */
u32 *virt_addr;
/* BPPE physical base address */
dma_addr_t phys_addr;
/* Ports using BM pool */
u32 port_map;
/* Occupied buffers indicator */
atomic_t in_use;
int in_use_thresh;
spinlock_t lock;
};
struct mvpp2_buff_hdr {
u32 next_buff_phys_addr;
u32 next_buff_virt_addr;
u16 byte_count;
u16 info;
u8 reserved1; /* bm_qset (for future use, BM) */
};
/* Buffer header info bits */
#define MVPP2_B_HDR_INFO_MC_ID_MASK 0xfff
#define MVPP2_B_HDR_INFO_MC_ID(info) ((info) & MVPP2_B_HDR_INFO_MC_ID_MASK)
#define MVPP2_B_HDR_INFO_LAST_OFFS 12
#define MVPP2_B_HDR_INFO_LAST_MASK BIT(12)
#define MVPP2_B_HDR_INFO_IS_LAST(info) \
((info & MVPP2_B_HDR_INFO_LAST_MASK) >> MVPP2_B_HDR_INFO_LAST_OFFS)
/* Static declaractions */
/* Number of RXQs used by single port */
static int rxq_number = MVPP2_DEFAULT_RXQ;
/* Number of TXQs used by single port */
static int txq_number = MVPP2_MAX_TXQ;
#define MVPP2_DRIVER_NAME "mvpp2"
#define MVPP2_DRIVER_VERSION "1.0"
/* Utility/helper methods */
static void mvpp2_write(struct mvpp2 *priv, u32 offset, u32 data)
{
writel(data, priv->base + offset);
}
static u32 mvpp2_read(struct mvpp2 *priv, u32 offset)
{
return readl(priv->base + offset);
}
static void mvpp2_txq_inc_get(struct mvpp2_txq_pcpu *txq_pcpu)
{
txq_pcpu->txq_get_index++;
if (txq_pcpu->txq_get_index == txq_pcpu->size)
txq_pcpu->txq_get_index = 0;
}
static void mvpp2_txq_inc_put(struct mvpp2_txq_pcpu *txq_pcpu,
struct sk_buff *skb)
{
txq_pcpu->tx_skb[txq_pcpu->txq_put_index] = skb;
txq_pcpu->txq_put_index++;
if (txq_pcpu->txq_put_index == txq_pcpu->size)
txq_pcpu->txq_put_index = 0;
}
/* Get number of physical egress port */
static inline int mvpp2_egress_port(struct mvpp2_port *port)
{
return MVPP2_MAX_TCONT + port->id;
}
/* Get number of physical TXQ */
static inline int mvpp2_txq_phys(int port, int txq)
{
return (MVPP2_MAX_TCONT + port) * MVPP2_MAX_TXQ + txq;
}
/* Parser configuration routines */
/* Update parser tcam and sram hw entries */
static int mvpp2_prs_hw_write(struct mvpp2 *priv, struct mvpp2_prs_entry *pe)
{
int i;
if (pe->index > MVPP2_PRS_TCAM_SRAM_SIZE - 1)
return -EINVAL;
/* Clear entry invalidation bit */
pe->tcam.word[MVPP2_PRS_TCAM_INV_WORD] &= ~MVPP2_PRS_TCAM_INV_MASK;
/* Write tcam index - indirect access */
mvpp2_write(priv, MVPP2_PRS_TCAM_IDX_REG, pe->index);
for (i = 0; i < MVPP2_PRS_TCAM_WORDS; i++)
mvpp2_write(priv, MVPP2_PRS_TCAM_DATA_REG(i), pe->tcam.word[i]);
/* Write sram index - indirect access */
mvpp2_write(priv, MVPP2_PRS_SRAM_IDX_REG, pe->index);
for (i = 0; i < MVPP2_PRS_SRAM_WORDS; i++)
mvpp2_write(priv, MVPP2_PRS_SRAM_DATA_REG(i), pe->sram.word[i]);
return 0;
}
/* Read tcam entry from hw */
static int mvpp2_prs_hw_read(struct mvpp2 *priv, struct mvpp2_prs_entry *pe)
{
int i;
if (pe->index > MVPP2_PRS_TCAM_SRAM_SIZE - 1)
return -EINVAL;
/* Write tcam index - indirect access */
mvpp2_write(priv, MVPP2_PRS_TCAM_IDX_REG, pe->index);
pe->tcam.word[MVPP2_PRS_TCAM_INV_WORD] = mvpp2_read(priv,
MVPP2_PRS_TCAM_DATA_REG(MVPP2_PRS_TCAM_INV_WORD));
if (pe->tcam.word[MVPP2_PRS_TCAM_INV_WORD] & MVPP2_PRS_TCAM_INV_MASK)
return MVPP2_PRS_TCAM_ENTRY_INVALID;
for (i = 0; i < MVPP2_PRS_TCAM_WORDS; i++)
pe->tcam.word[i] = mvpp2_read(priv, MVPP2_PRS_TCAM_DATA_REG(i));
/* Write sram index - indirect access */
mvpp2_write(priv, MVPP2_PRS_SRAM_IDX_REG, pe->index);
for (i = 0; i < MVPP2_PRS_SRAM_WORDS; i++)
pe->sram.word[i] = mvpp2_read(priv, MVPP2_PRS_SRAM_DATA_REG(i));
return 0;
}
/* Invalidate tcam hw entry */
static void mvpp2_prs_hw_inv(struct mvpp2 *priv, int index)
{
/* Write index - indirect access */
mvpp2_write(priv, MVPP2_PRS_TCAM_IDX_REG, index);
mvpp2_write(priv, MVPP2_PRS_TCAM_DATA_REG(MVPP2_PRS_TCAM_INV_WORD),
MVPP2_PRS_TCAM_INV_MASK);
}
/* Enable shadow table entry and set its lookup ID */
static void mvpp2_prs_shadow_set(struct mvpp2 *priv, int index, int lu)
{
priv->prs_shadow[index].valid = true;
priv->prs_shadow[index].lu = lu;
}
/* Update ri fields in shadow table entry */
static void mvpp2_prs_shadow_ri_set(struct mvpp2 *priv, int index,
unsigned int ri, unsigned int ri_mask)
{
priv->prs_shadow[index].ri_mask = ri_mask;
priv->prs_shadow[index].ri = ri;
}
/* Update lookup field in tcam sw entry */
static void mvpp2_prs_tcam_lu_set(struct mvpp2_prs_entry *pe, unsigned int lu)
{
int enable_off = MVPP2_PRS_TCAM_EN_OFFS(MVPP2_PRS_TCAM_LU_BYTE);
pe->tcam.byte[MVPP2_PRS_TCAM_LU_BYTE] = lu;
pe->tcam.byte[enable_off] = MVPP2_PRS_LU_MASK;
}
/* Update mask for single port in tcam sw entry */
static void mvpp2_prs_tcam_port_set(struct mvpp2_prs_entry *pe,
unsigned int port, bool add)
{
int enable_off = MVPP2_PRS_TCAM_EN_OFFS(MVPP2_PRS_TCAM_PORT_BYTE);
if (add)
pe->tcam.byte[enable_off] &= ~(1 << port);
else
pe->tcam.byte[enable_off] |= 1 << port;
}
/* Update port map in tcam sw entry */
static void mvpp2_prs_tcam_port_map_set(struct mvpp2_prs_entry *pe,
unsigned int ports)
{
unsigned char port_mask = MVPP2_PRS_PORT_MASK;
int enable_off = MVPP2_PRS_TCAM_EN_OFFS(MVPP2_PRS_TCAM_PORT_BYTE);
pe->tcam.byte[MVPP2_PRS_TCAM_PORT_BYTE] = 0;
pe->tcam.byte[enable_off] &= ~port_mask;
pe->tcam.byte[enable_off] |= ~ports & MVPP2_PRS_PORT_MASK;
}
/* Obtain port map from tcam sw entry */
static unsigned int mvpp2_prs_tcam_port_map_get(struct mvpp2_prs_entry *pe)
{
int enable_off = MVPP2_PRS_TCAM_EN_OFFS(MVPP2_PRS_TCAM_PORT_BYTE);
return ~(pe->tcam.byte[enable_off]) & MVPP2_PRS_PORT_MASK;
}
/* Set byte of data and its enable bits in tcam sw entry */
static void mvpp2_prs_tcam_data_byte_set(struct mvpp2_prs_entry *pe,
unsigned int offs, unsigned char byte,
unsigned char enable)
{
pe->tcam.byte[MVPP2_PRS_TCAM_DATA_BYTE(offs)] = byte;
pe->tcam.byte[MVPP2_PRS_TCAM_DATA_BYTE_EN(offs)] = enable;
}
/* Get byte of data and its enable bits from tcam sw entry */
static void mvpp2_prs_tcam_data_byte_get(struct mvpp2_prs_entry *pe,
unsigned int offs, unsigned char *byte,
unsigned char *enable)
{
*byte = pe->tcam.byte[MVPP2_PRS_TCAM_DATA_BYTE(offs)];
*enable = pe->tcam.byte[MVPP2_PRS_TCAM_DATA_BYTE_EN(offs)];
}
/* Compare tcam data bytes with a pattern */
static bool mvpp2_prs_tcam_data_cmp(struct mvpp2_prs_entry *pe, int offs,
u16 data)
{
int off = MVPP2_PRS_TCAM_DATA_BYTE(offs);
u16 tcam_data;
tcam_data = (8 << pe->tcam.byte[off + 1]) | pe->tcam.byte[off];
if (tcam_data != data)
return false;
return true;
}
/* Update ai bits in tcam sw entry */
static void mvpp2_prs_tcam_ai_update(struct mvpp2_prs_entry *pe,
unsigned int bits, unsigned int enable)
{
int i, ai_idx = MVPP2_PRS_TCAM_AI_BYTE;
for (i = 0; i < MVPP2_PRS_AI_BITS; i++) {
if (!(enable & BIT(i)))
continue;
if (bits & BIT(i))
pe->tcam.byte[ai_idx] |= 1 << i;
else
pe->tcam.byte[ai_idx] &= ~(1 << i);
}
pe->tcam.byte[MVPP2_PRS_TCAM_EN_OFFS(ai_idx)] |= enable;
}
/* Get ai bits from tcam sw entry */
static int mvpp2_prs_tcam_ai_get(struct mvpp2_prs_entry *pe)
{
return pe->tcam.byte[MVPP2_PRS_TCAM_AI_BYTE];
}
/* Set ethertype in tcam sw entry */
static void mvpp2_prs_match_etype(struct mvpp2_prs_entry *pe, int offset,
unsigned short ethertype)
{
mvpp2_prs_tcam_data_byte_set(pe, offset + 0, ethertype >> 8, 0xff);
mvpp2_prs_tcam_data_byte_set(pe, offset + 1, ethertype & 0xff, 0xff);
}
/* Set bits in sram sw entry */
static void mvpp2_prs_sram_bits_set(struct mvpp2_prs_entry *pe, int bit_num,
int val)
{
pe->sram.byte[MVPP2_BIT_TO_BYTE(bit_num)] |= (val << (bit_num % 8));
}
/* Clear bits in sram sw entry */
static void mvpp2_prs_sram_bits_clear(struct mvpp2_prs_entry *pe, int bit_num,
int val)
{
pe->sram.byte[MVPP2_BIT_TO_BYTE(bit_num)] &= ~(val << (bit_num % 8));
}
/* Update ri bits in sram sw entry */
static void mvpp2_prs_sram_ri_update(struct mvpp2_prs_entry *pe,
unsigned int bits, unsigned int mask)
{
unsigned int i;
for (i = 0; i < MVPP2_PRS_SRAM_RI_CTRL_BITS; i++) {
int ri_off = MVPP2_PRS_SRAM_RI_OFFS;
if (!(mask & BIT(i)))
continue;
if (bits & BIT(i))
mvpp2_prs_sram_bits_set(pe, ri_off + i, 1);
else
mvpp2_prs_sram_bits_clear(pe, ri_off + i, 1);
mvpp2_prs_sram_bits_set(pe, MVPP2_PRS_SRAM_RI_CTRL_OFFS + i, 1);
}
}
/* Obtain ri bits from sram sw entry */
static int mvpp2_prs_sram_ri_get(struct mvpp2_prs_entry *pe)
{
return pe->sram.word[MVPP2_PRS_SRAM_RI_WORD];
}
/* Update ai bits in sram sw entry */
static void mvpp2_prs_sram_ai_update(struct mvpp2_prs_entry *pe,
unsigned int bits, unsigned int mask)
{
unsigned int i;
int ai_off = MVPP2_PRS_SRAM_AI_OFFS;
for (i = 0; i < MVPP2_PRS_SRAM_AI_CTRL_BITS; i++) {
if (!(mask & BIT(i)))
continue;
if (bits & BIT(i))
mvpp2_prs_sram_bits_set(pe, ai_off + i, 1);
else
mvpp2_prs_sram_bits_clear(pe, ai_off + i, 1);
mvpp2_prs_sram_bits_set(pe, MVPP2_PRS_SRAM_AI_CTRL_OFFS + i, 1);
}
}
/* Read ai bits from sram sw entry */
static int mvpp2_prs_sram_ai_get(struct mvpp2_prs_entry *pe)
{
u8 bits;
int ai_off = MVPP2_BIT_TO_BYTE(MVPP2_PRS_SRAM_AI_OFFS);
int ai_en_off = ai_off + 1;
int ai_shift = MVPP2_PRS_SRAM_AI_OFFS % 8;
bits = (pe->sram.byte[ai_off] >> ai_shift) |
(pe->sram.byte[ai_en_off] << (8 - ai_shift));
return bits;
}
/* In sram sw entry set lookup ID field of the tcam key to be used in the next
* lookup interation
*/
static void mvpp2_prs_sram_next_lu_set(struct mvpp2_prs_entry *pe,
unsigned int lu)
{
int sram_next_off = MVPP2_PRS_SRAM_NEXT_LU_OFFS;
mvpp2_prs_sram_bits_clear(pe, sram_next_off,
MVPP2_PRS_SRAM_NEXT_LU_MASK);
mvpp2_prs_sram_bits_set(pe, sram_next_off, lu);
}
/* In the sram sw entry set sign and value of the next lookup offset
* and the offset value generated to the classifier
*/
static void mvpp2_prs_sram_shift_set(struct mvpp2_prs_entry *pe, int shift,
unsigned int op)
{
/* Set sign */
if (shift < 0) {
mvpp2_prs_sram_bits_set(pe, MVPP2_PRS_SRAM_SHIFT_SIGN_BIT, 1);
shift = 0 - shift;
} else {
mvpp2_prs_sram_bits_clear(pe, MVPP2_PRS_SRAM_SHIFT_SIGN_BIT, 1);
}
/* Set value */
pe->sram.byte[MVPP2_BIT_TO_BYTE(MVPP2_PRS_SRAM_SHIFT_OFFS)] =
(unsigned char)shift;
/* Reset and set operation */
mvpp2_prs_sram_bits_clear(pe, MVPP2_PRS_SRAM_OP_SEL_SHIFT_OFFS,
MVPP2_PRS_SRAM_OP_SEL_SHIFT_MASK);
mvpp2_prs_sram_bits_set(pe, MVPP2_PRS_SRAM_OP_SEL_SHIFT_OFFS, op);
/* Set base offset as current */
mvpp2_prs_sram_bits_clear(pe, MVPP2_PRS_SRAM_OP_SEL_BASE_OFFS, 1);
}
/* In the sram sw entry set sign and value of the user defined offset
* generated to the classifier
*/
static void mvpp2_prs_sram_offset_set(struct mvpp2_prs_entry *pe,
unsigned int type, int offset,
unsigned int op)
{
/* Set sign */
if (offset < 0) {
mvpp2_prs_sram_bits_set(pe, MVPP2_PRS_SRAM_UDF_SIGN_BIT, 1);
offset = 0 - offset;
} else {
mvpp2_prs_sram_bits_clear(pe, MVPP2_PRS_SRAM_UDF_SIGN_BIT, 1);
}
/* Set value */
mvpp2_prs_sram_bits_clear(pe, MVPP2_PRS_SRAM_UDF_OFFS,
MVPP2_PRS_SRAM_UDF_MASK);
mvpp2_prs_sram_bits_set(pe, MVPP2_PRS_SRAM_UDF_OFFS, offset);
pe->sram.byte[MVPP2_BIT_TO_BYTE(MVPP2_PRS_SRAM_UDF_OFFS +
MVPP2_PRS_SRAM_UDF_BITS)] &=
~(MVPP2_PRS_SRAM_UDF_MASK >> (8 - (MVPP2_PRS_SRAM_UDF_OFFS % 8)));
pe->sram.byte[MVPP2_BIT_TO_BYTE(MVPP2_PRS_SRAM_UDF_OFFS +
MVPP2_PRS_SRAM_UDF_BITS)] |=
(offset >> (8 - (MVPP2_PRS_SRAM_UDF_OFFS % 8)));
/* Set offset type */
mvpp2_prs_sram_bits_clear(pe, MVPP2_PRS_SRAM_UDF_TYPE_OFFS,
MVPP2_PRS_SRAM_UDF_TYPE_MASK);
mvpp2_prs_sram_bits_set(pe, MVPP2_PRS_SRAM_UDF_TYPE_OFFS, type);
/* Set offset operation */
mvpp2_prs_sram_bits_clear(pe, MVPP2_PRS_SRAM_OP_SEL_UDF_OFFS,
MVPP2_PRS_SRAM_OP_SEL_UDF_MASK);
mvpp2_prs_sram_bits_set(pe, MVPP2_PRS_SRAM_OP_SEL_UDF_OFFS, op);
pe->sram.byte[MVPP2_BIT_TO_BYTE(MVPP2_PRS_SRAM_OP_SEL_UDF_OFFS +
MVPP2_PRS_SRAM_OP_SEL_UDF_BITS)] &=
~(MVPP2_PRS_SRAM_OP_SEL_UDF_MASK >>
(8 - (MVPP2_PRS_SRAM_OP_SEL_UDF_OFFS % 8)));
pe->sram.byte[MVPP2_BIT_TO_BYTE(MVPP2_PRS_SRAM_OP_SEL_UDF_OFFS +
MVPP2_PRS_SRAM_OP_SEL_UDF_BITS)] |=
(op >> (8 - (MVPP2_PRS_SRAM_OP_SEL_UDF_OFFS % 8)));
/* Set base offset as current */
mvpp2_prs_sram_bits_clear(pe, MVPP2_PRS_SRAM_OP_SEL_BASE_OFFS, 1);
}
/* Find parser flow entry */
static struct mvpp2_prs_entry *mvpp2_prs_flow_find(struct mvpp2 *priv, int flow)
{
struct mvpp2_prs_entry *pe;
int tid;
pe = kzalloc(sizeof(*pe), GFP_KERNEL);
if (!pe)
return NULL;
mvpp2_prs_tcam_lu_set(pe, MVPP2_PRS_LU_FLOWS);
/* Go through the all entires with MVPP2_PRS_LU_FLOWS */
for (tid = MVPP2_PRS_TCAM_SRAM_SIZE - 1; tid >= 0; tid--) {
u8 bits;
if (!priv->prs_shadow[tid].valid ||
priv->prs_shadow[tid].lu != MVPP2_PRS_LU_FLOWS)
continue;
pe->index = tid;
mvpp2_prs_hw_read(priv, pe);
bits = mvpp2_prs_sram_ai_get(pe);
/* Sram store classification lookup ID in AI bits [5:0] */
if ((bits & MVPP2_PRS_FLOW_ID_MASK) == flow)
return pe;
}
kfree(pe);
return NULL;
}
/* Return first free tcam index, seeking from start to end */
static int mvpp2_prs_tcam_first_free(struct mvpp2 *priv, unsigned char start,
unsigned char end)
{
int tid;
if (start > end)
swap(start, end);
if (end >= MVPP2_PRS_TCAM_SRAM_SIZE)
end = MVPP2_PRS_TCAM_SRAM_SIZE - 1;
for (tid = start; tid <= end; tid++) {
if (!priv->prs_shadow[tid].valid)
return tid;
}
return -EINVAL;
}
/* Enable/disable dropping all mac da's */
static void mvpp2_prs_mac_drop_all_set(struct mvpp2 *priv, int port, bool add)
{
struct mvpp2_prs_entry pe;
if (priv->prs_shadow[MVPP2_PE_DROP_ALL].valid) {
/* Entry exist - update port only */
pe.index = MVPP2_PE_DROP_ALL;
mvpp2_prs_hw_read(priv, &pe);
} else {
/* Entry doesn't exist - create new */
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_MAC);
pe.index = MVPP2_PE_DROP_ALL;
/* Non-promiscuous mode for all ports - DROP unknown packets */
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_DROP_MASK,
MVPP2_PRS_RI_DROP_MASK);
mvpp2_prs_sram_bits_set(&pe, MVPP2_PRS_SRAM_LU_GEN_BIT, 1);
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_FLOWS);
/* Update shadow table */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_MAC);
/* Mask all ports */
mvpp2_prs_tcam_port_map_set(&pe, 0);
}
/* Update port mask */
mvpp2_prs_tcam_port_set(&pe, port, add);
mvpp2_prs_hw_write(priv, &pe);
}
/* Set port to promiscuous mode */
static void mvpp2_prs_mac_promisc_set(struct mvpp2 *priv, int port, bool add)
{
struct mvpp2_prs_entry pe;
/* Promiscous mode - Accept unknown packets */
if (priv->prs_shadow[MVPP2_PE_MAC_PROMISCUOUS].valid) {
/* Entry exist - update port only */
pe.index = MVPP2_PE_MAC_PROMISCUOUS;
mvpp2_prs_hw_read(priv, &pe);
} else {
/* Entry doesn't exist - create new */
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_MAC);
pe.index = MVPP2_PE_MAC_PROMISCUOUS;
/* Continue - set next lookup */
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_DSA);
/* Set result info bits */
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L2_UCAST,
MVPP2_PRS_RI_L2_CAST_MASK);
/* Shift to ethertype */
mvpp2_prs_sram_shift_set(&pe, 2 * ETH_ALEN,
MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
/* Mask all ports */
mvpp2_prs_tcam_port_map_set(&pe, 0);
/* Update shadow table */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_MAC);
}
/* Update port mask */
mvpp2_prs_tcam_port_set(&pe, port, add);
mvpp2_prs_hw_write(priv, &pe);
}
/* Accept multicast */
static void mvpp2_prs_mac_multi_set(struct mvpp2 *priv, int port, int index,
bool add)
{
struct mvpp2_prs_entry pe;
unsigned char da_mc;
/* Ethernet multicast address first byte is
* 0x01 for IPv4 and 0x33 for IPv6
*/
da_mc = (index == MVPP2_PE_MAC_MC_ALL) ? 0x01 : 0x33;
if (priv->prs_shadow[index].valid) {
/* Entry exist - update port only */
pe.index = index;
mvpp2_prs_hw_read(priv, &pe);
} else {
/* Entry doesn't exist - create new */
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_MAC);
pe.index = index;
/* Continue - set next lookup */
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_DSA);
/* Set result info bits */
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L2_MCAST,
MVPP2_PRS_RI_L2_CAST_MASK);
/* Update tcam entry data first byte */
mvpp2_prs_tcam_data_byte_set(&pe, 0, da_mc, 0xff);
/* Shift to ethertype */
mvpp2_prs_sram_shift_set(&pe, 2 * ETH_ALEN,
MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
/* Mask all ports */
mvpp2_prs_tcam_port_map_set(&pe, 0);
/* Update shadow table */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_MAC);
}
/* Update port mask */
mvpp2_prs_tcam_port_set(&pe, port, add);
mvpp2_prs_hw_write(priv, &pe);
}
/* Set entry for dsa packets */
static void mvpp2_prs_dsa_tag_set(struct mvpp2 *priv, int port, bool add,
bool tagged, bool extend)
{
struct mvpp2_prs_entry pe;
int tid, shift;
if (extend) {
tid = tagged ? MVPP2_PE_EDSA_TAGGED : MVPP2_PE_EDSA_UNTAGGED;
shift = 8;
} else {
tid = tagged ? MVPP2_PE_DSA_TAGGED : MVPP2_PE_DSA_UNTAGGED;
shift = 4;
}
if (priv->prs_shadow[tid].valid) {
/* Entry exist - update port only */
pe.index = tid;
mvpp2_prs_hw_read(priv, &pe);
} else {
/* Entry doesn't exist - create new */
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_DSA);
pe.index = tid;
/* Shift 4 bytes if DSA tag or 8 bytes in case of EDSA tag*/
mvpp2_prs_sram_shift_set(&pe, shift,
MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
/* Update shadow table */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_DSA);
if (tagged) {
/* Set tagged bit in DSA tag */
mvpp2_prs_tcam_data_byte_set(&pe, 0,
MVPP2_PRS_TCAM_DSA_TAGGED_BIT,
MVPP2_PRS_TCAM_DSA_TAGGED_BIT);
/* Clear all ai bits for next iteration */
mvpp2_prs_sram_ai_update(&pe, 0,
MVPP2_PRS_SRAM_AI_MASK);
/* If packet is tagged continue check vlans */
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_VLAN);
} else {
/* Set result info bits to 'no vlans' */
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_VLAN_NONE,
MVPP2_PRS_RI_VLAN_MASK);
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_L2);
}
/* Mask all ports */
mvpp2_prs_tcam_port_map_set(&pe, 0);
}
/* Update port mask */
mvpp2_prs_tcam_port_set(&pe, port, add);
mvpp2_prs_hw_write(priv, &pe);
}
/* Set entry for dsa ethertype */
static void mvpp2_prs_dsa_tag_ethertype_set(struct mvpp2 *priv, int port,
bool add, bool tagged, bool extend)
{
struct mvpp2_prs_entry pe;
int tid, shift, port_mask;
if (extend) {
tid = tagged ? MVPP2_PE_ETYPE_EDSA_TAGGED :
MVPP2_PE_ETYPE_EDSA_UNTAGGED;
port_mask = 0;
shift = 8;
} else {
tid = tagged ? MVPP2_PE_ETYPE_DSA_TAGGED :
MVPP2_PE_ETYPE_DSA_UNTAGGED;
port_mask = MVPP2_PRS_PORT_MASK;
shift = 4;
}
if (priv->prs_shadow[tid].valid) {
/* Entry exist - update port only */
pe.index = tid;
mvpp2_prs_hw_read(priv, &pe);
} else {
/* Entry doesn't exist - create new */
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_DSA);
pe.index = tid;
/* Set ethertype */
mvpp2_prs_match_etype(&pe, 0, ETH_P_EDSA);
mvpp2_prs_match_etype(&pe, 2, 0);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_DSA_MASK,
MVPP2_PRS_RI_DSA_MASK);
/* Shift ethertype + 2 byte reserved + tag*/
mvpp2_prs_sram_shift_set(&pe, 2 + MVPP2_ETH_TYPE_LEN + shift,
MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
/* Update shadow table */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_DSA);
if (tagged) {
/* Set tagged bit in DSA tag */
mvpp2_prs_tcam_data_byte_set(&pe,
MVPP2_ETH_TYPE_LEN + 2 + 3,
MVPP2_PRS_TCAM_DSA_TAGGED_BIT,
MVPP2_PRS_TCAM_DSA_TAGGED_BIT);
/* Clear all ai bits for next iteration */
mvpp2_prs_sram_ai_update(&pe, 0,
MVPP2_PRS_SRAM_AI_MASK);
/* If packet is tagged continue check vlans */
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_VLAN);
} else {
/* Set result info bits to 'no vlans' */
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_VLAN_NONE,
MVPP2_PRS_RI_VLAN_MASK);
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_L2);
}
/* Mask/unmask all ports, depending on dsa type */
mvpp2_prs_tcam_port_map_set(&pe, port_mask);
}
/* Update port mask */
mvpp2_prs_tcam_port_set(&pe, port, add);
mvpp2_prs_hw_write(priv, &pe);
}
/* Search for existing single/triple vlan entry */
static struct mvpp2_prs_entry *mvpp2_prs_vlan_find(struct mvpp2 *priv,
unsigned short tpid, int ai)
{
struct mvpp2_prs_entry *pe;
int tid;
pe = kzalloc(sizeof(*pe), GFP_KERNEL);
if (!pe)
return NULL;
mvpp2_prs_tcam_lu_set(pe, MVPP2_PRS_LU_VLAN);
/* Go through the all entries with MVPP2_PRS_LU_VLAN */
for (tid = MVPP2_PE_FIRST_FREE_TID;
tid <= MVPP2_PE_LAST_FREE_TID; tid++) {
unsigned int ri_bits, ai_bits;
bool match;
if (!priv->prs_shadow[tid].valid ||
priv->prs_shadow[tid].lu != MVPP2_PRS_LU_VLAN)
continue;
pe->index = tid;
mvpp2_prs_hw_read(priv, pe);
match = mvpp2_prs_tcam_data_cmp(pe, 0, swab16(tpid));
if (!match)
continue;
/* Get vlan type */
ri_bits = mvpp2_prs_sram_ri_get(pe);
ri_bits &= MVPP2_PRS_RI_VLAN_MASK;
/* Get current ai value from tcam */
ai_bits = mvpp2_prs_tcam_ai_get(pe);
/* Clear double vlan bit */
ai_bits &= ~MVPP2_PRS_DBL_VLAN_AI_BIT;
if (ai != ai_bits)
continue;
if (ri_bits == MVPP2_PRS_RI_VLAN_SINGLE ||
ri_bits == MVPP2_PRS_RI_VLAN_TRIPLE)
return pe;
}
kfree(pe);
return NULL;
}
/* Add/update single/triple vlan entry */
static int mvpp2_prs_vlan_add(struct mvpp2 *priv, unsigned short tpid, int ai,
unsigned int port_map)
{
struct mvpp2_prs_entry *pe;
int tid_aux, tid;
int ret = 0;
pe = mvpp2_prs_vlan_find(priv, tpid, ai);
if (!pe) {
/* Create new tcam entry */
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_LAST_FREE_TID,
MVPP2_PE_FIRST_FREE_TID);
if (tid < 0)
return tid;
pe = kzalloc(sizeof(*pe), GFP_KERNEL);
if (!pe)
return -ENOMEM;
/* Get last double vlan tid */
for (tid_aux = MVPP2_PE_LAST_FREE_TID;
tid_aux >= MVPP2_PE_FIRST_FREE_TID; tid_aux--) {
unsigned int ri_bits;
if (!priv->prs_shadow[tid_aux].valid ||
priv->prs_shadow[tid_aux].lu != MVPP2_PRS_LU_VLAN)
continue;
pe->index = tid_aux;
mvpp2_prs_hw_read(priv, pe);
ri_bits = mvpp2_prs_sram_ri_get(pe);
if ((ri_bits & MVPP2_PRS_RI_VLAN_MASK) ==
MVPP2_PRS_RI_VLAN_DOUBLE)
break;
}
if (tid <= tid_aux) {
ret = -EINVAL;
goto error;
}
memset(pe, 0 , sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(pe, MVPP2_PRS_LU_VLAN);
pe->index = tid;
mvpp2_prs_match_etype(pe, 0, tpid);
mvpp2_prs_sram_next_lu_set(pe, MVPP2_PRS_LU_L2);
/* Shift 4 bytes - skip 1 vlan tag */
mvpp2_prs_sram_shift_set(pe, MVPP2_VLAN_TAG_LEN,
MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
/* Clear all ai bits for next iteration */
mvpp2_prs_sram_ai_update(pe, 0, MVPP2_PRS_SRAM_AI_MASK);
if (ai == MVPP2_PRS_SINGLE_VLAN_AI) {
mvpp2_prs_sram_ri_update(pe, MVPP2_PRS_RI_VLAN_SINGLE,
MVPP2_PRS_RI_VLAN_MASK);
} else {
ai |= MVPP2_PRS_DBL_VLAN_AI_BIT;
mvpp2_prs_sram_ri_update(pe, MVPP2_PRS_RI_VLAN_TRIPLE,
MVPP2_PRS_RI_VLAN_MASK);
}
mvpp2_prs_tcam_ai_update(pe, ai, MVPP2_PRS_SRAM_AI_MASK);
mvpp2_prs_shadow_set(priv, pe->index, MVPP2_PRS_LU_VLAN);
}
/* Update ports' mask */
mvpp2_prs_tcam_port_map_set(pe, port_map);
mvpp2_prs_hw_write(priv, pe);
error:
kfree(pe);
return ret;
}
/* Get first free double vlan ai number */
static int mvpp2_prs_double_vlan_ai_free_get(struct mvpp2 *priv)
{
int i;
for (i = 1; i < MVPP2_PRS_DBL_VLANS_MAX; i++) {
if (!priv->prs_double_vlans[i])
return i;
}
return -EINVAL;
}
/* Search for existing double vlan entry */
static struct mvpp2_prs_entry *mvpp2_prs_double_vlan_find(struct mvpp2 *priv,
unsigned short tpid1,
unsigned short tpid2)
{
struct mvpp2_prs_entry *pe;
int tid;
pe = kzalloc(sizeof(*pe), GFP_KERNEL);
if (!pe)
return NULL;
mvpp2_prs_tcam_lu_set(pe, MVPP2_PRS_LU_VLAN);
/* Go through the all entries with MVPP2_PRS_LU_VLAN */
for (tid = MVPP2_PE_FIRST_FREE_TID;
tid <= MVPP2_PE_LAST_FREE_TID; tid++) {
unsigned int ri_mask;
bool match;
if (!priv->prs_shadow[tid].valid ||
priv->prs_shadow[tid].lu != MVPP2_PRS_LU_VLAN)
continue;
pe->index = tid;
mvpp2_prs_hw_read(priv, pe);
match = mvpp2_prs_tcam_data_cmp(pe, 0, swab16(tpid1))
&& mvpp2_prs_tcam_data_cmp(pe, 4, swab16(tpid2));
if (!match)
continue;
ri_mask = mvpp2_prs_sram_ri_get(pe) & MVPP2_PRS_RI_VLAN_MASK;
if (ri_mask == MVPP2_PRS_RI_VLAN_DOUBLE)
return pe;
}
kfree(pe);
return NULL;
}
/* Add or update double vlan entry */
static int mvpp2_prs_double_vlan_add(struct mvpp2 *priv, unsigned short tpid1,
unsigned short tpid2,
unsigned int port_map)
{
struct mvpp2_prs_entry *pe;
int tid_aux, tid, ai, ret = 0;
pe = mvpp2_prs_double_vlan_find(priv, tpid1, tpid2);
if (!pe) {
/* Create new tcam entry */
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
MVPP2_PE_LAST_FREE_TID);
if (tid < 0)
return tid;
pe = kzalloc(sizeof(*pe), GFP_KERNEL);
if (!pe)
return -ENOMEM;
/* Set ai value for new double vlan entry */
ai = mvpp2_prs_double_vlan_ai_free_get(priv);
if (ai < 0) {
ret = ai;
goto error;
}
/* Get first single/triple vlan tid */
for (tid_aux = MVPP2_PE_FIRST_FREE_TID;
tid_aux <= MVPP2_PE_LAST_FREE_TID; tid_aux++) {
unsigned int ri_bits;
if (!priv->prs_shadow[tid_aux].valid ||
priv->prs_shadow[tid_aux].lu != MVPP2_PRS_LU_VLAN)
continue;
pe->index = tid_aux;
mvpp2_prs_hw_read(priv, pe);
ri_bits = mvpp2_prs_sram_ri_get(pe);
ri_bits &= MVPP2_PRS_RI_VLAN_MASK;
if (ri_bits == MVPP2_PRS_RI_VLAN_SINGLE ||
ri_bits == MVPP2_PRS_RI_VLAN_TRIPLE)
break;
}
if (tid >= tid_aux) {
ret = -ERANGE;
goto error;
}
memset(pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(pe, MVPP2_PRS_LU_VLAN);
pe->index = tid;
priv->prs_double_vlans[ai] = true;
mvpp2_prs_match_etype(pe, 0, tpid1);
mvpp2_prs_match_etype(pe, 4, tpid2);
mvpp2_prs_sram_next_lu_set(pe, MVPP2_PRS_LU_VLAN);
/* Shift 8 bytes - skip 2 vlan tags */
mvpp2_prs_sram_shift_set(pe, 2 * MVPP2_VLAN_TAG_LEN,
MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
mvpp2_prs_sram_ri_update(pe, MVPP2_PRS_RI_VLAN_DOUBLE,
MVPP2_PRS_RI_VLAN_MASK);
mvpp2_prs_sram_ai_update(pe, ai | MVPP2_PRS_DBL_VLAN_AI_BIT,
MVPP2_PRS_SRAM_AI_MASK);
mvpp2_prs_shadow_set(priv, pe->index, MVPP2_PRS_LU_VLAN);
}
/* Update ports' mask */
mvpp2_prs_tcam_port_map_set(pe, port_map);
mvpp2_prs_hw_write(priv, pe);
error:
kfree(pe);
return ret;
}
/* IPv4 header parsing for fragmentation and L4 offset */
static int mvpp2_prs_ip4_proto(struct mvpp2 *priv, unsigned short proto,
unsigned int ri, unsigned int ri_mask)
{
struct mvpp2_prs_entry pe;
int tid;
if ((proto != IPPROTO_TCP) && (proto != IPPROTO_UDP) &&
(proto != IPPROTO_IGMP))
return -EINVAL;
/* Fragmented packet */
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
MVPP2_PE_LAST_FREE_TID);
if (tid < 0)
return tid;
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_IP4);
pe.index = tid;
/* Set next lu to IPv4 */
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_IP4);
mvpp2_prs_sram_shift_set(&pe, 12, MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
/* Set L4 offset */
mvpp2_prs_sram_offset_set(&pe, MVPP2_PRS_SRAM_UDF_TYPE_L4,
sizeof(struct iphdr) - 4,
MVPP2_PRS_SRAM_OP_SEL_UDF_ADD);
mvpp2_prs_sram_ai_update(&pe, MVPP2_PRS_IPV4_DIP_AI_BIT,
MVPP2_PRS_IPV4_DIP_AI_BIT);
mvpp2_prs_sram_ri_update(&pe, ri | MVPP2_PRS_RI_IP_FRAG_MASK,
ri_mask | MVPP2_PRS_RI_IP_FRAG_MASK);
mvpp2_prs_tcam_data_byte_set(&pe, 5, proto, MVPP2_PRS_TCAM_PROTO_MASK);
mvpp2_prs_tcam_ai_update(&pe, 0, MVPP2_PRS_IPV4_DIP_AI_BIT);
/* Unmask all ports */
mvpp2_prs_tcam_port_map_set(&pe, MVPP2_PRS_PORT_MASK);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_IP4);
mvpp2_prs_hw_write(priv, &pe);
/* Not fragmented packet */
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
MVPP2_PE_LAST_FREE_TID);
if (tid < 0)
return tid;
pe.index = tid;
/* Clear ri before updating */
pe.sram.word[MVPP2_PRS_SRAM_RI_WORD] = 0x0;
pe.sram.word[MVPP2_PRS_SRAM_RI_CTRL_WORD] = 0x0;
mvpp2_prs_sram_ri_update(&pe, ri, ri_mask);
mvpp2_prs_tcam_data_byte_set(&pe, 2, 0x00, MVPP2_PRS_TCAM_PROTO_MASK_L);
mvpp2_prs_tcam_data_byte_set(&pe, 3, 0x00, MVPP2_PRS_TCAM_PROTO_MASK);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_IP4);
mvpp2_prs_hw_write(priv, &pe);
return 0;
}
/* IPv4 L3 multicast or broadcast */
static int mvpp2_prs_ip4_cast(struct mvpp2 *priv, unsigned short l3_cast)
{
struct mvpp2_prs_entry pe;
int mask, tid;
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
MVPP2_PE_LAST_FREE_TID);
if (tid < 0)
return tid;
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_IP4);
pe.index = tid;
switch (l3_cast) {
case MVPP2_PRS_L3_MULTI_CAST:
mvpp2_prs_tcam_data_byte_set(&pe, 0, MVPP2_PRS_IPV4_MC,
MVPP2_PRS_IPV4_MC_MASK);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L3_MCAST,
MVPP2_PRS_RI_L3_ADDR_MASK);
break;
case MVPP2_PRS_L3_BROAD_CAST:
mask = MVPP2_PRS_IPV4_BC_MASK;
mvpp2_prs_tcam_data_byte_set(&pe, 0, mask, mask);
mvpp2_prs_tcam_data_byte_set(&pe, 1, mask, mask);
mvpp2_prs_tcam_data_byte_set(&pe, 2, mask, mask);
mvpp2_prs_tcam_data_byte_set(&pe, 3, mask, mask);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L3_BCAST,
MVPP2_PRS_RI_L3_ADDR_MASK);
break;
default:
return -EINVAL;
}
/* Finished: go to flowid generation */
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_FLOWS);
mvpp2_prs_sram_bits_set(&pe, MVPP2_PRS_SRAM_LU_GEN_BIT, 1);
mvpp2_prs_tcam_ai_update(&pe, MVPP2_PRS_IPV4_DIP_AI_BIT,
MVPP2_PRS_IPV4_DIP_AI_BIT);
/* Unmask all ports */
mvpp2_prs_tcam_port_map_set(&pe, MVPP2_PRS_PORT_MASK);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_IP4);
mvpp2_prs_hw_write(priv, &pe);
return 0;
}
/* Set entries for protocols over IPv6 */
static int mvpp2_prs_ip6_proto(struct mvpp2 *priv, unsigned short proto,
unsigned int ri, unsigned int ri_mask)
{
struct mvpp2_prs_entry pe;
int tid;
if ((proto != IPPROTO_TCP) && (proto != IPPROTO_UDP) &&
(proto != IPPROTO_ICMPV6) && (proto != IPPROTO_IPIP))
return -EINVAL;
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
MVPP2_PE_LAST_FREE_TID);
if (tid < 0)
return tid;
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_IP6);
pe.index = tid;
/* Finished: go to flowid generation */
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_FLOWS);
mvpp2_prs_sram_bits_set(&pe, MVPP2_PRS_SRAM_LU_GEN_BIT, 1);
mvpp2_prs_sram_ri_update(&pe, ri, ri_mask);
mvpp2_prs_sram_offset_set(&pe, MVPP2_PRS_SRAM_UDF_TYPE_L4,
sizeof(struct ipv6hdr) - 6,
MVPP2_PRS_SRAM_OP_SEL_UDF_ADD);
mvpp2_prs_tcam_data_byte_set(&pe, 0, proto, MVPP2_PRS_TCAM_PROTO_MASK);
mvpp2_prs_tcam_ai_update(&pe, MVPP2_PRS_IPV6_NO_EXT_AI_BIT,
MVPP2_PRS_IPV6_NO_EXT_AI_BIT);
/* Unmask all ports */
mvpp2_prs_tcam_port_map_set(&pe, MVPP2_PRS_PORT_MASK);
/* Write HW */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_IP6);
mvpp2_prs_hw_write(priv, &pe);
return 0;
}
/* IPv6 L3 multicast entry */
static int mvpp2_prs_ip6_cast(struct mvpp2 *priv, unsigned short l3_cast)
{
struct mvpp2_prs_entry pe;
int tid;
if (l3_cast != MVPP2_PRS_L3_MULTI_CAST)
return -EINVAL;
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
MVPP2_PE_LAST_FREE_TID);
if (tid < 0)
return tid;
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_IP6);
pe.index = tid;
/* Finished: go to flowid generation */
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_IP6);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L3_MCAST,
MVPP2_PRS_RI_L3_ADDR_MASK);
mvpp2_prs_sram_ai_update(&pe, MVPP2_PRS_IPV6_NO_EXT_AI_BIT,
MVPP2_PRS_IPV6_NO_EXT_AI_BIT);
/* Shift back to IPv6 NH */
mvpp2_prs_sram_shift_set(&pe, -18, MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
mvpp2_prs_tcam_data_byte_set(&pe, 0, MVPP2_PRS_IPV6_MC,
MVPP2_PRS_IPV6_MC_MASK);
mvpp2_prs_tcam_ai_update(&pe, 0, MVPP2_PRS_IPV6_NO_EXT_AI_BIT);
/* Unmask all ports */
mvpp2_prs_tcam_port_map_set(&pe, MVPP2_PRS_PORT_MASK);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_IP6);
mvpp2_prs_hw_write(priv, &pe);
return 0;
}
/* Parser per-port initialization */
static void mvpp2_prs_hw_port_init(struct mvpp2 *priv, int port, int lu_first,
int lu_max, int offset)
{
u32 val;
/* Set lookup ID */
val = mvpp2_read(priv, MVPP2_PRS_INIT_LOOKUP_REG);
val &= ~MVPP2_PRS_PORT_LU_MASK(port);
val |= MVPP2_PRS_PORT_LU_VAL(port, lu_first);
mvpp2_write(priv, MVPP2_PRS_INIT_LOOKUP_REG, val);
/* Set maximum number of loops for packet received from port */
val = mvpp2_read(priv, MVPP2_PRS_MAX_LOOP_REG(port));
val &= ~MVPP2_PRS_MAX_LOOP_MASK(port);
val |= MVPP2_PRS_MAX_LOOP_VAL(port, lu_max);
mvpp2_write(priv, MVPP2_PRS_MAX_LOOP_REG(port), val);
/* Set initial offset for packet header extraction for the first
* searching loop
*/
val = mvpp2_read(priv, MVPP2_PRS_INIT_OFFS_REG(port));
val &= ~MVPP2_PRS_INIT_OFF_MASK(port);
val |= MVPP2_PRS_INIT_OFF_VAL(port, offset);
mvpp2_write(priv, MVPP2_PRS_INIT_OFFS_REG(port), val);
}
/* Default flow entries initialization for all ports */
static void mvpp2_prs_def_flow_init(struct mvpp2 *priv)
{
struct mvpp2_prs_entry pe;
int port;
for (port = 0; port < MVPP2_MAX_PORTS; port++) {
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_FLOWS);
pe.index = MVPP2_PE_FIRST_DEFAULT_FLOW - port;
/* Mask all ports */
mvpp2_prs_tcam_port_map_set(&pe, 0);
/* Set flow ID*/
mvpp2_prs_sram_ai_update(&pe, port, MVPP2_PRS_FLOW_ID_MASK);
mvpp2_prs_sram_bits_set(&pe, MVPP2_PRS_SRAM_LU_DONE_BIT, 1);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_FLOWS);
mvpp2_prs_hw_write(priv, &pe);
}
}
/* Set default entry for Marvell Header field */
static void mvpp2_prs_mh_init(struct mvpp2 *priv)
{
struct mvpp2_prs_entry pe;
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
pe.index = MVPP2_PE_MH_DEFAULT;
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_MH);
mvpp2_prs_sram_shift_set(&pe, MVPP2_MH_SIZE,
MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_MAC);
/* Unmask all ports */
mvpp2_prs_tcam_port_map_set(&pe, MVPP2_PRS_PORT_MASK);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_MH);
mvpp2_prs_hw_write(priv, &pe);
}
/* Set default entires (place holder) for promiscuous, non-promiscuous and
* multicast MAC addresses
*/
static void mvpp2_prs_mac_init(struct mvpp2 *priv)
{
struct mvpp2_prs_entry pe;
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
/* Non-promiscuous mode for all ports - DROP unknown packets */
pe.index = MVPP2_PE_MAC_NON_PROMISCUOUS;
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_MAC);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_DROP_MASK,
MVPP2_PRS_RI_DROP_MASK);
mvpp2_prs_sram_bits_set(&pe, MVPP2_PRS_SRAM_LU_GEN_BIT, 1);
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_FLOWS);
/* Unmask all ports */
mvpp2_prs_tcam_port_map_set(&pe, MVPP2_PRS_PORT_MASK);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_MAC);
mvpp2_prs_hw_write(priv, &pe);
/* place holders only - no ports */
mvpp2_prs_mac_drop_all_set(priv, 0, false);
mvpp2_prs_mac_promisc_set(priv, 0, false);
mvpp2_prs_mac_multi_set(priv, MVPP2_PE_MAC_MC_ALL, 0, false);
mvpp2_prs_mac_multi_set(priv, MVPP2_PE_MAC_MC_IP6, 0, false);
}
/* Set default entries for various types of dsa packets */
static void mvpp2_prs_dsa_init(struct mvpp2 *priv)
{
struct mvpp2_prs_entry pe;
/* None tagged EDSA entry - place holder */
mvpp2_prs_dsa_tag_set(priv, 0, false, MVPP2_PRS_UNTAGGED,
MVPP2_PRS_EDSA);
/* Tagged EDSA entry - place holder */
mvpp2_prs_dsa_tag_set(priv, 0, false, MVPP2_PRS_TAGGED, MVPP2_PRS_EDSA);
/* None tagged DSA entry - place holder */
mvpp2_prs_dsa_tag_set(priv, 0, false, MVPP2_PRS_UNTAGGED,
MVPP2_PRS_DSA);
/* Tagged DSA entry - place holder */
mvpp2_prs_dsa_tag_set(priv, 0, false, MVPP2_PRS_TAGGED, MVPP2_PRS_DSA);
/* None tagged EDSA ethertype entry - place holder*/
mvpp2_prs_dsa_tag_ethertype_set(priv, 0, false,
MVPP2_PRS_UNTAGGED, MVPP2_PRS_EDSA);
/* Tagged EDSA ethertype entry - place holder*/
mvpp2_prs_dsa_tag_ethertype_set(priv, 0, false,
MVPP2_PRS_TAGGED, MVPP2_PRS_EDSA);
/* None tagged DSA ethertype entry */
mvpp2_prs_dsa_tag_ethertype_set(priv, 0, true,
MVPP2_PRS_UNTAGGED, MVPP2_PRS_DSA);
/* Tagged DSA ethertype entry */
mvpp2_prs_dsa_tag_ethertype_set(priv, 0, true,
MVPP2_PRS_TAGGED, MVPP2_PRS_DSA);
/* Set default entry, in case DSA or EDSA tag not found */
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_DSA);
pe.index = MVPP2_PE_DSA_DEFAULT;
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_VLAN);
/* Shift 0 bytes */
mvpp2_prs_sram_shift_set(&pe, 0, MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_MAC);
/* Clear all sram ai bits for next iteration */
mvpp2_prs_sram_ai_update(&pe, 0, MVPP2_PRS_SRAM_AI_MASK);
/* Unmask all ports */
mvpp2_prs_tcam_port_map_set(&pe, MVPP2_PRS_PORT_MASK);
mvpp2_prs_hw_write(priv, &pe);
}
/* Match basic ethertypes */
static int mvpp2_prs_etype_init(struct mvpp2 *priv)
{
struct mvpp2_prs_entry pe;
int tid;
/* Ethertype: PPPoE */
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
MVPP2_PE_LAST_FREE_TID);
if (tid < 0)
return tid;
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_L2);
pe.index = tid;
mvpp2_prs_match_etype(&pe, 0, ETH_P_PPP_SES);
mvpp2_prs_sram_shift_set(&pe, MVPP2_PPPOE_HDR_SIZE,
MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_PPPOE);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_PPPOE_MASK,
MVPP2_PRS_RI_PPPOE_MASK);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_L2);
priv->prs_shadow[pe.index].udf = MVPP2_PRS_UDF_L2_DEF;
priv->prs_shadow[pe.index].finish = false;
mvpp2_prs_shadow_ri_set(priv, pe.index, MVPP2_PRS_RI_PPPOE_MASK,
MVPP2_PRS_RI_PPPOE_MASK);
mvpp2_prs_hw_write(priv, &pe);
/* Ethertype: ARP */
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
MVPP2_PE_LAST_FREE_TID);
if (tid < 0)
return tid;
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_L2);
pe.index = tid;
mvpp2_prs_match_etype(&pe, 0, ETH_P_ARP);
/* Generate flow in the next iteration*/
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_FLOWS);
mvpp2_prs_sram_bits_set(&pe, MVPP2_PRS_SRAM_LU_GEN_BIT, 1);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L3_ARP,
MVPP2_PRS_RI_L3_PROTO_MASK);
/* Set L3 offset */
mvpp2_prs_sram_offset_set(&pe, MVPP2_PRS_SRAM_UDF_TYPE_L3,
MVPP2_ETH_TYPE_LEN,
MVPP2_PRS_SRAM_OP_SEL_UDF_ADD);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_L2);
priv->prs_shadow[pe.index].udf = MVPP2_PRS_UDF_L2_DEF;
priv->prs_shadow[pe.index].finish = true;
mvpp2_prs_shadow_ri_set(priv, pe.index, MVPP2_PRS_RI_L3_ARP,
MVPP2_PRS_RI_L3_PROTO_MASK);
mvpp2_prs_hw_write(priv, &pe);
/* Ethertype: LBTD */
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
MVPP2_PE_LAST_FREE_TID);
if (tid < 0)
return tid;
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_L2);
pe.index = tid;
mvpp2_prs_match_etype(&pe, 0, MVPP2_IP_LBDT_TYPE);
/* Generate flow in the next iteration*/
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_FLOWS);
mvpp2_prs_sram_bits_set(&pe, MVPP2_PRS_SRAM_LU_GEN_BIT, 1);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_CPU_CODE_RX_SPEC |
MVPP2_PRS_RI_UDF3_RX_SPECIAL,
MVPP2_PRS_RI_CPU_CODE_MASK |
MVPP2_PRS_RI_UDF3_MASK);
/* Set L3 offset */
mvpp2_prs_sram_offset_set(&pe, MVPP2_PRS_SRAM_UDF_TYPE_L3,
MVPP2_ETH_TYPE_LEN,
MVPP2_PRS_SRAM_OP_SEL_UDF_ADD);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_L2);
priv->prs_shadow[pe.index].udf = MVPP2_PRS_UDF_L2_DEF;
priv->prs_shadow[pe.index].finish = true;
mvpp2_prs_shadow_ri_set(priv, pe.index, MVPP2_PRS_RI_CPU_CODE_RX_SPEC |
MVPP2_PRS_RI_UDF3_RX_SPECIAL,
MVPP2_PRS_RI_CPU_CODE_MASK |
MVPP2_PRS_RI_UDF3_MASK);
mvpp2_prs_hw_write(priv, &pe);
/* Ethertype: IPv4 without options */
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
MVPP2_PE_LAST_FREE_TID);
if (tid < 0)
return tid;
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_L2);
pe.index = tid;
mvpp2_prs_match_etype(&pe, 0, ETH_P_IP);
mvpp2_prs_tcam_data_byte_set(&pe, MVPP2_ETH_TYPE_LEN,
MVPP2_PRS_IPV4_HEAD | MVPP2_PRS_IPV4_IHL,
MVPP2_PRS_IPV4_HEAD_MASK |
MVPP2_PRS_IPV4_IHL_MASK);
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_IP4);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L3_IP4,
MVPP2_PRS_RI_L3_PROTO_MASK);
/* Skip eth_type + 4 bytes of IP header */
mvpp2_prs_sram_shift_set(&pe, MVPP2_ETH_TYPE_LEN + 4,
MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
/* Set L3 offset */
mvpp2_prs_sram_offset_set(&pe, MVPP2_PRS_SRAM_UDF_TYPE_L3,
MVPP2_ETH_TYPE_LEN,
MVPP2_PRS_SRAM_OP_SEL_UDF_ADD);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_L2);
priv->prs_shadow[pe.index].udf = MVPP2_PRS_UDF_L2_DEF;
priv->prs_shadow[pe.index].finish = false;
mvpp2_prs_shadow_ri_set(priv, pe.index, MVPP2_PRS_RI_L3_IP4,
MVPP2_PRS_RI_L3_PROTO_MASK);
mvpp2_prs_hw_write(priv, &pe);
/* Ethertype: IPv4 with options */
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
MVPP2_PE_LAST_FREE_TID);
if (tid < 0)
return tid;
pe.index = tid;
/* Clear tcam data before updating */
pe.tcam.byte[MVPP2_PRS_TCAM_DATA_BYTE(MVPP2_ETH_TYPE_LEN)] = 0x0;
pe.tcam.byte[MVPP2_PRS_TCAM_DATA_BYTE_EN(MVPP2_ETH_TYPE_LEN)] = 0x0;
mvpp2_prs_tcam_data_byte_set(&pe, MVPP2_ETH_TYPE_LEN,
MVPP2_PRS_IPV4_HEAD,
MVPP2_PRS_IPV4_HEAD_MASK);
/* Clear ri before updating */
pe.sram.word[MVPP2_PRS_SRAM_RI_WORD] = 0x0;
pe.sram.word[MVPP2_PRS_SRAM_RI_CTRL_WORD] = 0x0;
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L3_IP4_OPT,
MVPP2_PRS_RI_L3_PROTO_MASK);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_L2);
priv->prs_shadow[pe.index].udf = MVPP2_PRS_UDF_L2_DEF;
priv->prs_shadow[pe.index].finish = false;
mvpp2_prs_shadow_ri_set(priv, pe.index, MVPP2_PRS_RI_L3_IP4_OPT,
MVPP2_PRS_RI_L3_PROTO_MASK);
mvpp2_prs_hw_write(priv, &pe);
/* Ethertype: IPv6 without options */
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
MVPP2_PE_LAST_FREE_TID);
if (tid < 0)
return tid;
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_L2);
pe.index = tid;
mvpp2_prs_match_etype(&pe, 0, ETH_P_IPV6);
/* Skip DIP of IPV6 header */
mvpp2_prs_sram_shift_set(&pe, MVPP2_ETH_TYPE_LEN + 8 +
MVPP2_MAX_L3_ADDR_SIZE,
MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_IP6);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L3_IP6,
MVPP2_PRS_RI_L3_PROTO_MASK);
/* Set L3 offset */
mvpp2_prs_sram_offset_set(&pe, MVPP2_PRS_SRAM_UDF_TYPE_L3,
MVPP2_ETH_TYPE_LEN,
MVPP2_PRS_SRAM_OP_SEL_UDF_ADD);
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_L2);
priv->prs_shadow[pe.index].udf = MVPP2_PRS_UDF_L2_DEF;
priv->prs_shadow[pe.index].finish = false;
mvpp2_prs_shadow_ri_set(priv, pe.index, MVPP2_PRS_RI_L3_IP6,
MVPP2_PRS_RI_L3_PROTO_MASK);
mvpp2_prs_hw_write(priv, &pe);
/* Default entry for MVPP2_PRS_LU_L2 - Unknown ethtype */
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_L2);
pe.index = MVPP2_PE_ETH_TYPE_UN;
/* Unmask all ports */
mvpp2_prs_tcam_port_map_set(&pe, MVPP2_PRS_PORT_MASK);
/* Generate flow in the next iteration*/
mvpp2_prs_sram_bits_set(&pe, MVPP2_PRS_SRAM_LU_GEN_BIT, 1);
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_FLOWS);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L3_UN,
MVPP2_PRS_RI_L3_PROTO_MASK);
/* Set L3 offset even it's unknown L3 */
mvpp2_prs_sram_offset_set(&pe, MVPP2_PRS_SRAM_UDF_TYPE_L3,
MVPP2_ETH_TYPE_LEN,
MVPP2_PRS_SRAM_OP_SEL_UDF_ADD);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_L2);
priv->prs_shadow[pe.index].udf = MVPP2_PRS_UDF_L2_DEF;
priv->prs_shadow[pe.index].finish = true;
mvpp2_prs_shadow_ri_set(priv, pe.index, MVPP2_PRS_RI_L3_UN,
MVPP2_PRS_RI_L3_PROTO_MASK);
mvpp2_prs_hw_write(priv, &pe);
return 0;
}
/* Configure vlan entries and detect up to 2 successive VLAN tags.
* Possible options:
* 0x8100, 0x88A8
* 0x8100, 0x8100
* 0x8100
* 0x88A8
*/
static int mvpp2_prs_vlan_init(struct platform_device *pdev, struct mvpp2 *priv)
{
struct mvpp2_prs_entry pe;
int err;
priv->prs_double_vlans = devm_kcalloc(&pdev->dev, sizeof(bool),
MVPP2_PRS_DBL_VLANS_MAX,
GFP_KERNEL);
if (!priv->prs_double_vlans)
return -ENOMEM;
/* Double VLAN: 0x8100, 0x88A8 */
err = mvpp2_prs_double_vlan_add(priv, ETH_P_8021Q, ETH_P_8021AD,
MVPP2_PRS_PORT_MASK);
if (err)
return err;
/* Double VLAN: 0x8100, 0x8100 */
err = mvpp2_prs_double_vlan_add(priv, ETH_P_8021Q, ETH_P_8021Q,
MVPP2_PRS_PORT_MASK);
if (err)
return err;
/* Single VLAN: 0x88a8 */
err = mvpp2_prs_vlan_add(priv, ETH_P_8021AD, MVPP2_PRS_SINGLE_VLAN_AI,
MVPP2_PRS_PORT_MASK);
if (err)
return err;
/* Single VLAN: 0x8100 */
err = mvpp2_prs_vlan_add(priv, ETH_P_8021Q, MVPP2_PRS_SINGLE_VLAN_AI,
MVPP2_PRS_PORT_MASK);
if (err)
return err;
/* Set default double vlan entry */
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_VLAN);
pe.index = MVPP2_PE_VLAN_DBL;
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_L2);
/* Clear ai for next iterations */
mvpp2_prs_sram_ai_update(&pe, 0, MVPP2_PRS_SRAM_AI_MASK);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_VLAN_DOUBLE,
MVPP2_PRS_RI_VLAN_MASK);
mvpp2_prs_tcam_ai_update(&pe, MVPP2_PRS_DBL_VLAN_AI_BIT,
MVPP2_PRS_DBL_VLAN_AI_BIT);
/* Unmask all ports */
mvpp2_prs_tcam_port_map_set(&pe, MVPP2_PRS_PORT_MASK);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_VLAN);
mvpp2_prs_hw_write(priv, &pe);
/* Set default vlan none entry */
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_VLAN);
pe.index = MVPP2_PE_VLAN_NONE;
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_L2);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_VLAN_NONE,
MVPP2_PRS_RI_VLAN_MASK);
/* Unmask all ports */
mvpp2_prs_tcam_port_map_set(&pe, MVPP2_PRS_PORT_MASK);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_VLAN);
mvpp2_prs_hw_write(priv, &pe);
return 0;
}
/* Set entries for PPPoE ethertype */
static int mvpp2_prs_pppoe_init(struct mvpp2 *priv)
{
struct mvpp2_prs_entry pe;
int tid;
/* IPv4 over PPPoE with options */
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
MVPP2_PE_LAST_FREE_TID);
if (tid < 0)
return tid;
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_PPPOE);
pe.index = tid;
mvpp2_prs_match_etype(&pe, 0, PPP_IP);
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_IP4);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L3_IP4_OPT,
MVPP2_PRS_RI_L3_PROTO_MASK);
/* Skip eth_type + 4 bytes of IP header */
mvpp2_prs_sram_shift_set(&pe, MVPP2_ETH_TYPE_LEN + 4,
MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
/* Set L3 offset */
mvpp2_prs_sram_offset_set(&pe, MVPP2_PRS_SRAM_UDF_TYPE_L3,
MVPP2_ETH_TYPE_LEN,
MVPP2_PRS_SRAM_OP_SEL_UDF_ADD);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_PPPOE);
mvpp2_prs_hw_write(priv, &pe);
/* IPv4 over PPPoE without options */
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
MVPP2_PE_LAST_FREE_TID);
if (tid < 0)
return tid;
pe.index = tid;
mvpp2_prs_tcam_data_byte_set(&pe, MVPP2_ETH_TYPE_LEN,
MVPP2_PRS_IPV4_HEAD | MVPP2_PRS_IPV4_IHL,
MVPP2_PRS_IPV4_HEAD_MASK |
MVPP2_PRS_IPV4_IHL_MASK);
/* Clear ri before updating */
pe.sram.word[MVPP2_PRS_SRAM_RI_WORD] = 0x0;
pe.sram.word[MVPP2_PRS_SRAM_RI_CTRL_WORD] = 0x0;
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L3_IP4,
MVPP2_PRS_RI_L3_PROTO_MASK);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_PPPOE);
mvpp2_prs_hw_write(priv, &pe);
/* IPv6 over PPPoE */
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
MVPP2_PE_LAST_FREE_TID);
if (tid < 0)
return tid;
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_PPPOE);
pe.index = tid;
mvpp2_prs_match_etype(&pe, 0, PPP_IPV6);
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_IP6);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L3_IP6,
MVPP2_PRS_RI_L3_PROTO_MASK);
/* Skip eth_type + 4 bytes of IPv6 header */
mvpp2_prs_sram_shift_set(&pe, MVPP2_ETH_TYPE_LEN + 4,
MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
/* Set L3 offset */
mvpp2_prs_sram_offset_set(&pe, MVPP2_PRS_SRAM_UDF_TYPE_L3,
MVPP2_ETH_TYPE_LEN,
MVPP2_PRS_SRAM_OP_SEL_UDF_ADD);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_PPPOE);
mvpp2_prs_hw_write(priv, &pe);
/* Non-IP over PPPoE */
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
MVPP2_PE_LAST_FREE_TID);
if (tid < 0)
return tid;
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_PPPOE);
pe.index = tid;
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L3_UN,
MVPP2_PRS_RI_L3_PROTO_MASK);
/* Finished: go to flowid generation */
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_FLOWS);
mvpp2_prs_sram_bits_set(&pe, MVPP2_PRS_SRAM_LU_GEN_BIT, 1);
/* Set L3 offset even if it's unknown L3 */
mvpp2_prs_sram_offset_set(&pe, MVPP2_PRS_SRAM_UDF_TYPE_L3,
MVPP2_ETH_TYPE_LEN,
MVPP2_PRS_SRAM_OP_SEL_UDF_ADD);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_PPPOE);
mvpp2_prs_hw_write(priv, &pe);
return 0;
}
/* Initialize entries for IPv4 */
static int mvpp2_prs_ip4_init(struct mvpp2 *priv)
{
struct mvpp2_prs_entry pe;
int err;
/* Set entries for TCP, UDP and IGMP over IPv4 */
err = mvpp2_prs_ip4_proto(priv, IPPROTO_TCP, MVPP2_PRS_RI_L4_TCP,
MVPP2_PRS_RI_L4_PROTO_MASK);
if (err)
return err;
err = mvpp2_prs_ip4_proto(priv, IPPROTO_UDP, MVPP2_PRS_RI_L4_UDP,
MVPP2_PRS_RI_L4_PROTO_MASK);
if (err)
return err;
err = mvpp2_prs_ip4_proto(priv, IPPROTO_IGMP,
MVPP2_PRS_RI_CPU_CODE_RX_SPEC |
MVPP2_PRS_RI_UDF3_RX_SPECIAL,
MVPP2_PRS_RI_CPU_CODE_MASK |
MVPP2_PRS_RI_UDF3_MASK);
if (err)
return err;
/* IPv4 Broadcast */
err = mvpp2_prs_ip4_cast(priv, MVPP2_PRS_L3_BROAD_CAST);
if (err)
return err;
/* IPv4 Multicast */
err = mvpp2_prs_ip4_cast(priv, MVPP2_PRS_L3_MULTI_CAST);
if (err)
return err;
/* Default IPv4 entry for unknown protocols */
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_IP4);
pe.index = MVPP2_PE_IP4_PROTO_UN;
/* Set next lu to IPv4 */
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_IP4);
mvpp2_prs_sram_shift_set(&pe, 12, MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
/* Set L4 offset */
mvpp2_prs_sram_offset_set(&pe, MVPP2_PRS_SRAM_UDF_TYPE_L4,
sizeof(struct iphdr) - 4,
MVPP2_PRS_SRAM_OP_SEL_UDF_ADD);
mvpp2_prs_sram_ai_update(&pe, MVPP2_PRS_IPV4_DIP_AI_BIT,
MVPP2_PRS_IPV4_DIP_AI_BIT);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L4_OTHER,
MVPP2_PRS_RI_L4_PROTO_MASK);
mvpp2_prs_tcam_ai_update(&pe, 0, MVPP2_PRS_IPV4_DIP_AI_BIT);
/* Unmask all ports */
mvpp2_prs_tcam_port_map_set(&pe, MVPP2_PRS_PORT_MASK);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_IP4);
mvpp2_prs_hw_write(priv, &pe);
/* Default IPv4 entry for unicast address */
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_IP4);
pe.index = MVPP2_PE_IP4_ADDR_UN;
/* Finished: go to flowid generation */
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_FLOWS);
mvpp2_prs_sram_bits_set(&pe, MVPP2_PRS_SRAM_LU_GEN_BIT, 1);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L3_UCAST,
MVPP2_PRS_RI_L3_ADDR_MASK);
mvpp2_prs_tcam_ai_update(&pe, MVPP2_PRS_IPV4_DIP_AI_BIT,
MVPP2_PRS_IPV4_DIP_AI_BIT);
/* Unmask all ports */
mvpp2_prs_tcam_port_map_set(&pe, MVPP2_PRS_PORT_MASK);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_IP4);
mvpp2_prs_hw_write(priv, &pe);
return 0;
}
/* Initialize entries for IPv6 */
static int mvpp2_prs_ip6_init(struct mvpp2 *priv)
{
struct mvpp2_prs_entry pe;
int tid, err;
/* Set entries for TCP, UDP and ICMP over IPv6 */
err = mvpp2_prs_ip6_proto(priv, IPPROTO_TCP,
MVPP2_PRS_RI_L4_TCP,
MVPP2_PRS_RI_L4_PROTO_MASK);
if (err)
return err;
err = mvpp2_prs_ip6_proto(priv, IPPROTO_UDP,
MVPP2_PRS_RI_L4_UDP,
MVPP2_PRS_RI_L4_PROTO_MASK);
if (err)
return err;
err = mvpp2_prs_ip6_proto(priv, IPPROTO_ICMPV6,
MVPP2_PRS_RI_CPU_CODE_RX_SPEC |
MVPP2_PRS_RI_UDF3_RX_SPECIAL,
MVPP2_PRS_RI_CPU_CODE_MASK |
MVPP2_PRS_RI_UDF3_MASK);
if (err)
return err;
/* IPv4 is the last header. This is similar case as 6-TCP or 17-UDP */
/* Result Info: UDF7=1, DS lite */
err = mvpp2_prs_ip6_proto(priv, IPPROTO_IPIP,
MVPP2_PRS_RI_UDF7_IP6_LITE,
MVPP2_PRS_RI_UDF7_MASK);
if (err)
return err;
/* IPv6 multicast */
err = mvpp2_prs_ip6_cast(priv, MVPP2_PRS_L3_MULTI_CAST);
if (err)
return err;
/* Entry for checking hop limit */
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
MVPP2_PE_LAST_FREE_TID);
if (tid < 0)
return tid;
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_IP6);
pe.index = tid;
/* Finished: go to flowid generation */
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_FLOWS);
mvpp2_prs_sram_bits_set(&pe, MVPP2_PRS_SRAM_LU_GEN_BIT, 1);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L3_UN |
MVPP2_PRS_RI_DROP_MASK,
MVPP2_PRS_RI_L3_PROTO_MASK |
MVPP2_PRS_RI_DROP_MASK);
mvpp2_prs_tcam_data_byte_set(&pe, 1, 0x00, MVPP2_PRS_IPV6_HOP_MASK);
mvpp2_prs_tcam_ai_update(&pe, MVPP2_PRS_IPV6_NO_EXT_AI_BIT,
MVPP2_PRS_IPV6_NO_EXT_AI_BIT);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_IP4);
mvpp2_prs_hw_write(priv, &pe);
/* Default IPv6 entry for unknown protocols */
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_IP6);
pe.index = MVPP2_PE_IP6_PROTO_UN;
/* Finished: go to flowid generation */
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_FLOWS);
mvpp2_prs_sram_bits_set(&pe, MVPP2_PRS_SRAM_LU_GEN_BIT, 1);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L4_OTHER,
MVPP2_PRS_RI_L4_PROTO_MASK);
/* Set L4 offset relatively to our current place */
mvpp2_prs_sram_offset_set(&pe, MVPP2_PRS_SRAM_UDF_TYPE_L4,
sizeof(struct ipv6hdr) - 4,
MVPP2_PRS_SRAM_OP_SEL_UDF_ADD);
mvpp2_prs_tcam_ai_update(&pe, MVPP2_PRS_IPV6_NO_EXT_AI_BIT,
MVPP2_PRS_IPV6_NO_EXT_AI_BIT);
/* Unmask all ports */
mvpp2_prs_tcam_port_map_set(&pe, MVPP2_PRS_PORT_MASK);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_IP4);
mvpp2_prs_hw_write(priv, &pe);
/* Default IPv6 entry for unknown ext protocols */
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_IP6);
pe.index = MVPP2_PE_IP6_EXT_PROTO_UN;
/* Finished: go to flowid generation */
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_FLOWS);
mvpp2_prs_sram_bits_set(&pe, MVPP2_PRS_SRAM_LU_GEN_BIT, 1);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L4_OTHER,
MVPP2_PRS_RI_L4_PROTO_MASK);
mvpp2_prs_tcam_ai_update(&pe, MVPP2_PRS_IPV6_EXT_AI_BIT,
MVPP2_PRS_IPV6_EXT_AI_BIT);
/* Unmask all ports */
mvpp2_prs_tcam_port_map_set(&pe, MVPP2_PRS_PORT_MASK);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_IP4);
mvpp2_prs_hw_write(priv, &pe);
/* Default IPv6 entry for unicast address */
memset(&pe, 0, sizeof(struct mvpp2_prs_entry));
mvpp2_prs_tcam_lu_set(&pe, MVPP2_PRS_LU_IP6);
pe.index = MVPP2_PE_IP6_ADDR_UN;
/* Finished: go to IPv6 again */
mvpp2_prs_sram_next_lu_set(&pe, MVPP2_PRS_LU_IP6);
mvpp2_prs_sram_ri_update(&pe, MVPP2_PRS_RI_L3_UCAST,
MVPP2_PRS_RI_L3_ADDR_MASK);
mvpp2_prs_sram_ai_update(&pe, MVPP2_PRS_IPV6_NO_EXT_AI_BIT,
MVPP2_PRS_IPV6_NO_EXT_AI_BIT);
/* Shift back to IPV6 NH */
mvpp2_prs_sram_shift_set(&pe, -18, MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
mvpp2_prs_tcam_ai_update(&pe, 0, MVPP2_PRS_IPV6_NO_EXT_AI_BIT);
/* Unmask all ports */
mvpp2_prs_tcam_port_map_set(&pe, MVPP2_PRS_PORT_MASK);
/* Update shadow table and hw entry */
mvpp2_prs_shadow_set(priv, pe.index, MVPP2_PRS_LU_IP6);
mvpp2_prs_hw_write(priv, &pe);
return 0;
}
/* Parser default initialization */
static int mvpp2_prs_default_init(struct platform_device *pdev,
struct mvpp2 *priv)
{
int err, index, i;
/* Enable tcam table */
mvpp2_write(priv, MVPP2_PRS_TCAM_CTRL_REG, MVPP2_PRS_TCAM_EN_MASK);
/* Clear all tcam and sram entries */
for (index = 0; index < MVPP2_PRS_TCAM_SRAM_SIZE; index++) {
mvpp2_write(priv, MVPP2_PRS_TCAM_IDX_REG, index);
for (i = 0; i < MVPP2_PRS_TCAM_WORDS; i++)
mvpp2_write(priv, MVPP2_PRS_TCAM_DATA_REG(i), 0);
mvpp2_write(priv, MVPP2_PRS_SRAM_IDX_REG, index);
for (i = 0; i < MVPP2_PRS_SRAM_WORDS; i++)
mvpp2_write(priv, MVPP2_PRS_SRAM_DATA_REG(i), 0);
}
/* Invalidate all tcam entries */
for (index = 0; index < MVPP2_PRS_TCAM_SRAM_SIZE; index++)
mvpp2_prs_hw_inv(priv, index);
priv->prs_shadow = devm_kcalloc(&pdev->dev, MVPP2_PRS_TCAM_SRAM_SIZE,
sizeof(struct mvpp2_prs_shadow),
GFP_KERNEL);
if (!priv->prs_shadow)
return -ENOMEM;
/* Always start from lookup = 0 */
for (index = 0; index < MVPP2_MAX_PORTS; index++)
mvpp2_prs_hw_port_init(priv, index, MVPP2_PRS_LU_MH,
MVPP2_PRS_PORT_LU_MAX, 0);
mvpp2_prs_def_flow_init(priv);
mvpp2_prs_mh_init(priv);
mvpp2_prs_mac_init(priv);
mvpp2_prs_dsa_init(priv);
err = mvpp2_prs_etype_init(priv);
if (err)
return err;
err = mvpp2_prs_vlan_init(pdev, priv);
if (err)
return err;
err = mvpp2_prs_pppoe_init(priv);
if (err)
return err;
err = mvpp2_prs_ip6_init(priv);
if (err)
return err;
err = mvpp2_prs_ip4_init(priv);
if (err)
return err;
return 0;
}
/* Compare MAC DA with tcam entry data */
static bool mvpp2_prs_mac_range_equals(struct mvpp2_prs_entry *pe,
const u8 *da, unsigned char *mask)
{
unsigned char tcam_byte, tcam_mask;
int index;
for (index = 0; index < ETH_ALEN; index++) {
mvpp2_prs_tcam_data_byte_get(pe, index, &tcam_byte, &tcam_mask);
if (tcam_mask != mask[index])
return false;
if ((tcam_mask & tcam_byte) != (da[index] & mask[index]))
return false;
}
return true;
}
/* Find tcam entry with matched pair <MAC DA, port> */
static struct mvpp2_prs_entry *
mvpp2_prs_mac_da_range_find(struct mvpp2 *priv, int pmap, const u8 *da,
unsigned char *mask, int udf_type)
{
struct mvpp2_prs_entry *pe;
int tid;
pe = kzalloc(sizeof(*pe), GFP_KERNEL);
if (!pe)
return NULL;
mvpp2_prs_tcam_lu_set(pe, MVPP2_PRS_LU_MAC);
/* Go through the all entires with MVPP2_PRS_LU_MAC */
for (tid = MVPP2_PE_FIRST_FREE_TID;
tid <= MVPP2_PE_LAST_FREE_TID; tid++) {
unsigned int entry_pmap;
if (!priv->prs_shadow[tid].valid ||
(priv->prs_shadow[tid].lu != MVPP2_PRS_LU_MAC) ||
(priv->prs_shadow[tid].udf != udf_type))
continue;
pe->index = tid;
mvpp2_prs_hw_read(priv, pe);
entry_pmap = mvpp2_prs_tcam_port_map_get(pe);
if (mvpp2_prs_mac_range_equals(pe, da, mask) &&
entry_pmap == pmap)
return pe;
}
kfree(pe);
return NULL;
}
/* Update parser's mac da entry */
static int mvpp2_prs_mac_da_accept(struct mvpp2 *priv, int port,
const u8 *da, bool add)
{
struct mvpp2_prs_entry *pe;
unsigned int pmap, len, ri;
unsigned char mask[ETH_ALEN] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
int tid;
/* Scan TCAM and see if entry with this <MAC DA, port> already exist */
pe = mvpp2_prs_mac_da_range_find(priv, (1 << port), da, mask,
MVPP2_PRS_UDF_MAC_DEF);
/* No such entry */
if (!pe) {
if (!add)
return 0;
/* Create new TCAM entry */
/* Find first range mac entry*/
for (tid = MVPP2_PE_FIRST_FREE_TID;
tid <= MVPP2_PE_LAST_FREE_TID; tid++)
if (priv->prs_shadow[tid].valid &&
(priv->prs_shadow[tid].lu == MVPP2_PRS_LU_MAC) &&
(priv->prs_shadow[tid].udf ==
MVPP2_PRS_UDF_MAC_RANGE))
break;
/* Go through the all entries from first to last */
tid = mvpp2_prs_tcam_first_free(priv, MVPP2_PE_FIRST_FREE_TID,
tid - 1);
if (tid < 0)
return tid;
pe = kzalloc(sizeof(*pe), GFP_KERNEL);
if (!pe)
return -1;
mvpp2_prs_tcam_lu_set(pe, MVPP2_PRS_LU_MAC);
pe->index = tid;
/* Mask all ports */
mvpp2_prs_tcam_port_map_set(pe, 0);
}
/* Update port mask */
mvpp2_prs_tcam_port_set(pe, port, add);
/* Invalidate the entry if no ports are left enabled */
pmap = mvpp2_prs_tcam_port_map_get(pe);
if (pmap == 0) {
if (add) {
kfree(pe);
return -1;
}
mvpp2_prs_hw_inv(priv, pe->index);
priv->prs_shadow[pe->index].valid = false;
kfree(pe);
return 0;
}
/* Continue - set next lookup */
mvpp2_prs_sram_next_lu_set(pe, MVPP2_PRS_LU_DSA);
/* Set match on DA */
len = ETH_ALEN;
while (len--)
mvpp2_prs_tcam_data_byte_set(pe, len, da[len], 0xff);
/* Set result info bits */
if (is_broadcast_ether_addr(da))
ri = MVPP2_PRS_RI_L2_BCAST;
else if (is_multicast_ether_addr(da))
ri = MVPP2_PRS_RI_L2_MCAST;
else
ri = MVPP2_PRS_RI_L2_UCAST | MVPP2_PRS_RI_MAC_ME_MASK;
mvpp2_prs_sram_ri_update(pe, ri, MVPP2_PRS_RI_L2_CAST_MASK |
MVPP2_PRS_RI_MAC_ME_MASK);
mvpp2_prs_shadow_ri_set(priv, pe->index, ri, MVPP2_PRS_RI_L2_CAST_MASK |
MVPP2_PRS_RI_MAC_ME_MASK);
/* Shift to ethertype */
mvpp2_prs_sram_shift_set(pe, 2 * ETH_ALEN,
MVPP2_PRS_SRAM_OP_SEL_SHIFT_ADD);
/* Update shadow table and hw entry */
priv->prs_shadow[pe->index].udf = MVPP2_PRS_UDF_MAC_DEF;
mvpp2_prs_shadow_set(priv, pe->index, MVPP2_PRS_LU_MAC);
mvpp2_prs_hw_write(priv, pe);
kfree(pe);
return 0;
}
static int mvpp2_prs_update_mac_da(struct net_device *dev, const u8 *da)
{
struct mvpp2_port *port = netdev_priv(dev);
int err;
/* Remove old parser entry */
err = mvpp2_prs_mac_da_accept(port->priv, port->id, dev->dev_addr,
false);
if (err)
return err;
/* Add new parser entry */
err = mvpp2_prs_mac_da_accept(port->priv, port->id, da, true);
if (err)
return err;
/* Set addr in the device */
ether_addr_copy(dev->dev_addr, da);
return 0;
}
/* Delete all port's multicast simple (not range) entries */
static void mvpp2_prs_mcast_del_all(struct mvpp2 *priv, int port)
{
struct mvpp2_prs_entry pe;
int index, tid;
for (tid = MVPP2_PE_FIRST_FREE_TID;
tid <= MVPP2_PE_LAST_FREE_TID; tid++) {
unsigned char da[ETH_ALEN], da_mask[ETH_ALEN];
if (!priv->prs_shadow[tid].valid ||
(priv->prs_shadow[tid].lu != MVPP2_PRS_LU_MAC) ||
(priv->prs_shadow[tid].udf != MVPP2_PRS_UDF_MAC_DEF))
continue;
/* Only simple mac entries */
pe.index = tid;
mvpp2_prs_hw_read(priv, &pe);
/* Read mac addr from entry */
for (index = 0; index < ETH_ALEN; index++)
mvpp2_prs_tcam_data_byte_get(&pe, index, &da[index],
&da_mask[index]);
if (is_multicast_ether_addr(da) && !is_broadcast_ether_addr(da))
/* Delete this entry */
mvpp2_prs_mac_da_accept(priv, port, da, false);
}
}
static int mvpp2_prs_tag_mode_set(struct mvpp2 *priv, int port, int type)
{
switch (type) {
case MVPP2_TAG_TYPE_EDSA:
/* Add port to EDSA entries */
mvpp2_prs_dsa_tag_set(priv, port, true,
MVPP2_PRS_TAGGED, MVPP2_PRS_EDSA);
mvpp2_prs_dsa_tag_set(priv, port, true,
MVPP2_PRS_UNTAGGED, MVPP2_PRS_EDSA);
/* Remove port from DSA entries */
mvpp2_prs_dsa_tag_set(priv, port, false,
MVPP2_PRS_TAGGED, MVPP2_PRS_DSA);
mvpp2_prs_dsa_tag_set(priv, port, false,
MVPP2_PRS_UNTAGGED, MVPP2_PRS_DSA);
break;
case MVPP2_TAG_TYPE_DSA:
/* Add port to DSA entries */
mvpp2_prs_dsa_tag_set(priv, port, true,
MVPP2_PRS_TAGGED, MVPP2_PRS_DSA);
mvpp2_prs_dsa_tag_set(priv, port, true,
MVPP2_PRS_UNTAGGED, MVPP2_PRS_DSA);
/* Remove port from EDSA entries */
mvpp2_prs_dsa_tag_set(priv, port, false,
MVPP2_PRS_TAGGED, MVPP2_PRS_EDSA);
mvpp2_prs_dsa_tag_set(priv, port, false,
MVPP2_PRS_UNTAGGED, MVPP2_PRS_EDSA);
break;
case MVPP2_TAG_TYPE_MH:
case MVPP2_TAG_TYPE_NONE:
/* Remove port form EDSA and DSA entries */
mvpp2_prs_dsa_tag_set(priv, port, false,
MVPP2_PRS_TAGGED, MVPP2_PRS_DSA);
mvpp2_prs_dsa_tag_set(priv, port, false,
MVPP2_PRS_UNTAGGED, MVPP2_PRS_DSA);
mvpp2_prs_dsa_tag_set(priv, port, false,
MVPP2_PRS_TAGGED, MVPP2_PRS_EDSA);
mvpp2_prs_dsa_tag_set(priv, port, false,
MVPP2_PRS_UNTAGGED, MVPP2_PRS_EDSA);
break;
default:
if ((type < 0) || (type > MVPP2_TAG_TYPE_EDSA))
return -EINVAL;
}
return 0;
}
/* Set prs flow for the port */
static int mvpp2_prs_def_flow(struct mvpp2_port *port)
{
struct mvpp2_prs_entry *pe;
int tid;
pe = mvpp2_prs_flow_find(port->priv, port->id);
/* Such entry not exist */
if (!pe) {
/* Go through the all entires from last to first */
tid = mvpp2_prs_tcam_first_free(port->priv,
MVPP2_PE_LAST_FREE_TID,
MVPP2_PE_FIRST_FREE_TID);
if (tid < 0)
return tid;
pe = kzalloc(sizeof(*pe), GFP_KERNEL);
if (!pe)
return -ENOMEM;
mvpp2_prs_tcam_lu_set(pe, MVPP2_PRS_LU_FLOWS);
pe->index = tid;
/* Set flow ID*/
mvpp2_prs_sram_ai_update(pe, port->id, MVPP2_PRS_FLOW_ID_MASK);
mvpp2_prs_sram_bits_set(pe, MVPP2_PRS_SRAM_LU_DONE_BIT, 1);
/* Update shadow table */
mvpp2_prs_shadow_set(port->priv, pe->index, MVPP2_PRS_LU_FLOWS);
}
mvpp2_prs_tcam_port_map_set(pe, (1 << port->id));
mvpp2_prs_hw_write(port->priv, pe);
kfree(pe);
return 0;
}
/* Classifier configuration routines */
/* Update classification flow table registers */
static void mvpp2_cls_flow_write(struct mvpp2 *priv,
struct mvpp2_cls_flow_entry *fe)
{
mvpp2_write(priv, MVPP2_CLS_FLOW_INDEX_REG, fe->index);
mvpp2_write(priv, MVPP2_CLS_FLOW_TBL0_REG, fe->data[0]);
mvpp2_write(priv, MVPP2_CLS_FLOW_TBL1_REG, fe->data[1]);
mvpp2_write(priv, MVPP2_CLS_FLOW_TBL2_REG, fe->data[2]);
}
/* Update classification lookup table register */
static void mvpp2_cls_lookup_write(struct mvpp2 *priv,
struct mvpp2_cls_lookup_entry *le)
{
u32 val;
val = (le->way << MVPP2_CLS_LKP_INDEX_WAY_OFFS) | le->lkpid;
mvpp2_write(priv, MVPP2_CLS_LKP_INDEX_REG, val);
mvpp2_write(priv, MVPP2_CLS_LKP_TBL_REG, le->data);
}
/* Classifier default initialization */
static void mvpp2_cls_init(struct mvpp2 *priv)
{
struct mvpp2_cls_lookup_entry le;
struct mvpp2_cls_flow_entry fe;
int index;
/* Enable classifier */
mvpp2_write(priv, MVPP2_CLS_MODE_REG, MVPP2_CLS_MODE_ACTIVE_MASK);
/* Clear classifier flow table */
memset(&fe.data, 0, MVPP2_CLS_FLOWS_TBL_DATA_WORDS);
for (index = 0; index < MVPP2_CLS_FLOWS_TBL_SIZE; index++) {
fe.index = index;
mvpp2_cls_flow_write(priv, &fe);
}
/* Clear classifier lookup table */
le.data = 0;
for (index = 0; index < MVPP2_CLS_LKP_TBL_SIZE; index++) {
le.lkpid = index;
le.way = 0;
mvpp2_cls_lookup_write(priv, &le);
le.way = 1;
mvpp2_cls_lookup_write(priv, &le);
}
}
static void mvpp2_cls_port_config(struct mvpp2_port *port)
{
struct mvpp2_cls_lookup_entry le;
u32 val;
/* Set way for the port */
val = mvpp2_read(port->priv, MVPP2_CLS_PORT_WAY_REG);
val &= ~MVPP2_CLS_PORT_WAY_MASK(port->id);
mvpp2_write(port->priv, MVPP2_CLS_PORT_WAY_REG, val);
/* Pick the entry to be accessed in lookup ID decoding table
* according to the way and lkpid.
*/
le.lkpid = port->id;
le.way = 0;
le.data = 0;
/* Set initial CPU queue for receiving packets */
le.data &= ~MVPP2_CLS_LKP_TBL_RXQ_MASK;
le.data |= port->first_rxq;
/* Disable classification engines */
le.data &= ~MVPP2_CLS_LKP_TBL_LOOKUP_EN_MASK;
/* Update lookup ID table entry */
mvpp2_cls_lookup_write(port->priv, &le);
}
/* Set CPU queue number for oversize packets */
static void mvpp2_cls_oversize_rxq_set(struct mvpp2_port *port)
{
u32 val;
mvpp2_write(port->priv, MVPP2_CLS_OVERSIZE_RXQ_LOW_REG(port->id),
port->first_rxq & MVPP2_CLS_OVERSIZE_RXQ_LOW_MASK);
mvpp2_write(port->priv, MVPP2_CLS_SWFWD_P2HQ_REG(port->id),
(port->first_rxq >> MVPP2_CLS_OVERSIZE_RXQ_LOW_BITS));
val = mvpp2_read(port->priv, MVPP2_CLS_SWFWD_PCTRL_REG);
val |= MVPP2_CLS_SWFWD_PCTRL_MASK(port->id);
mvpp2_write(port->priv, MVPP2_CLS_SWFWD_PCTRL_REG, val);
}
/* Buffer Manager configuration routines */
/* Create pool */
static int mvpp2_bm_pool_create(struct platform_device *pdev,
struct mvpp2 *priv,
struct mvpp2_bm_pool *bm_pool, int size)
{
int size_bytes;
u32 val;
size_bytes = sizeof(u32) * size;
bm_pool->virt_addr = dma_alloc_coherent(&pdev->dev, size_bytes,
&bm_pool->phys_addr,
GFP_KERNEL);
if (!bm_pool->virt_addr)
return -ENOMEM;
if (!IS_ALIGNED((u32)bm_pool->virt_addr, MVPP2_BM_POOL_PTR_ALIGN)) {
dma_free_coherent(&pdev->dev, size_bytes, bm_pool->virt_addr,
bm_pool->phys_addr);
dev_err(&pdev->dev, "BM pool %d is not %d bytes aligned\n",
bm_pool->id, MVPP2_BM_POOL_PTR_ALIGN);
return -ENOMEM;
}
mvpp2_write(priv, MVPP2_BM_POOL_BASE_REG(bm_pool->id),
bm_pool->phys_addr);
mvpp2_write(priv, MVPP2_BM_POOL_SIZE_REG(bm_pool->id), size);
val = mvpp2_read(priv, MVPP2_BM_POOL_CTRL_REG(bm_pool->id));
val |= MVPP2_BM_START_MASK;
mvpp2_write(priv, MVPP2_BM_POOL_CTRL_REG(bm_pool->id), val);
bm_pool->type = MVPP2_BM_FREE;
bm_pool->size = size;
bm_pool->pkt_size = 0;
bm_pool->buf_num = 0;
atomic_set(&bm_pool->in_use, 0);
spin_lock_init(&bm_pool->lock);
return 0;
}
/* Set pool buffer size */
static void mvpp2_bm_pool_bufsize_set(struct mvpp2 *priv,
struct mvpp2_bm_pool *bm_pool,
int buf_size)
{
u32 val;
bm_pool->buf_size = buf_size;
val = ALIGN(buf_size, 1 << MVPP2_POOL_BUF_SIZE_OFFSET);
mvpp2_write(priv, MVPP2_POOL_BUF_SIZE_REG(bm_pool->id), val);
}
/* Free all buffers from the pool */
static void mvpp2_bm_bufs_free(struct mvpp2 *priv, struct mvpp2_bm_pool *bm_pool)
{
int i;
for (i = 0; i < bm_pool->buf_num; i++) {
u32 vaddr;
/* Get buffer virtual adress (indirect access) */
mvpp2_read(priv, MVPP2_BM_PHY_ALLOC_REG(bm_pool->id));
vaddr = mvpp2_read(priv, MVPP2_BM_VIRT_ALLOC_REG);
if (!vaddr)
break;
dev_kfree_skb_any((struct sk_buff *)vaddr);
}
/* Update BM driver with number of buffers removed from pool */
bm_pool->buf_num -= i;
}
/* Cleanup pool */
static int mvpp2_bm_pool_destroy(struct platform_device *pdev,
struct mvpp2 *priv,
struct mvpp2_bm_pool *bm_pool)
{
u32 val;
mvpp2_bm_bufs_free(priv, bm_pool);
if (bm_pool->buf_num) {
WARN(1, "cannot free all buffers in pool %d\n", bm_pool->id);
return 0;
}
val = mvpp2_read(priv, MVPP2_BM_POOL_CTRL_REG(bm_pool->id));
val |= MVPP2_BM_STOP_MASK;
mvpp2_write(priv, MVPP2_BM_POOL_CTRL_REG(bm_pool->id), val);
dma_free_coherent(&pdev->dev, sizeof(u32) * bm_pool->size,
bm_pool->virt_addr,
bm_pool->phys_addr);
return 0;
}
static int mvpp2_bm_pools_init(struct platform_device *pdev,
struct mvpp2 *priv)
{
int i, err, size;
struct mvpp2_bm_pool *bm_pool;
/* Create all pools with maximum size */
size = MVPP2_BM_POOL_SIZE_MAX;
for (i = 0; i < MVPP2_BM_POOLS_NUM; i++) {
bm_pool = &priv->bm_pools[i];
bm_pool->id = i;
err = mvpp2_bm_pool_create(pdev, priv, bm_pool, size);
if (err)
goto err_unroll_pools;
mvpp2_bm_pool_bufsize_set(priv, bm_pool, 0);
}
return 0;
err_unroll_pools:
dev_err(&pdev->dev, "failed to create BM pool %d, size %d\n", i, size);
for (i = i - 1; i >= 0; i--)
mvpp2_bm_pool_destroy(pdev, priv, &priv->bm_pools[i]);
return err;
}
static int mvpp2_bm_init(struct platform_device *pdev, struct mvpp2 *priv)
{
int i, err;
for (i = 0; i < MVPP2_BM_POOLS_NUM; i++) {
/* Mask BM all interrupts */
mvpp2_write(priv, MVPP2_BM_INTR_MASK_REG(i), 0);
/* Clear BM cause register */
mvpp2_write(priv, MVPP2_BM_INTR_CAUSE_REG(i), 0);
}
/* Allocate and initialize BM pools */
priv->bm_pools = devm_kcalloc(&pdev->dev, MVPP2_BM_POOLS_NUM,
sizeof(struct mvpp2_bm_pool), GFP_KERNEL);
if (!priv->bm_pools)
return -ENOMEM;
err = mvpp2_bm_pools_init(pdev, priv);
if (err < 0)
return err;
return 0;
}
/* Attach long pool to rxq */
static void mvpp2_rxq_long_pool_set(struct mvpp2_port *port,
int lrxq, int long_pool)
{
u32 val;
int prxq;
/* Get queue physical ID */
prxq = port->rxqs[lrxq]->id;
val = mvpp2_read(port->priv, MVPP2_RXQ_CONFIG_REG(prxq));
val &= ~MVPP2_RXQ_POOL_LONG_MASK;
val |= ((long_pool << MVPP2_RXQ_POOL_LONG_OFFS) &
MVPP2_RXQ_POOL_LONG_MASK);
mvpp2_write(port->priv, MVPP2_RXQ_CONFIG_REG(prxq), val);
}
/* Attach short pool to rxq */
static void mvpp2_rxq_short_pool_set(struct mvpp2_port *port,
int lrxq, int short_pool)
{
u32 val;
int prxq;
/* Get queue physical ID */
prxq = port->rxqs[lrxq]->id;
val = mvpp2_read(port->priv, MVPP2_RXQ_CONFIG_REG(prxq));
val &= ~MVPP2_RXQ_POOL_SHORT_MASK;
val |= ((short_pool << MVPP2_RXQ_POOL_SHORT_OFFS) &
MVPP2_RXQ_POOL_SHORT_MASK);
mvpp2_write(port->priv, MVPP2_RXQ_CONFIG_REG(prxq), val);
}
/* Allocate skb for BM pool */
static struct sk_buff *mvpp2_skb_alloc(struct mvpp2_port *port,
struct mvpp2_bm_pool *bm_pool,
dma_addr_t *buf_phys_addr,
gfp_t gfp_mask)
{
struct sk_buff *skb;
dma_addr_t phys_addr;
skb = __dev_alloc_skb(bm_pool->pkt_size, gfp_mask);
if (!skb)
return NULL;
phys_addr = dma_map_single(port->dev->dev.parent, skb->head,
MVPP2_RX_BUF_SIZE(bm_pool->pkt_size),
DMA_FROM_DEVICE);
if (unlikely(dma_mapping_error(port->dev->dev.parent, phys_addr))) {
dev_kfree_skb_any(skb);
return NULL;
}
*buf_phys_addr = phys_addr;
return skb;
}
/* Set pool number in a BM cookie */
static inline u32 mvpp2_bm_cookie_pool_set(u32 cookie, int pool)
{
u32 bm;
bm = cookie & ~(0xFF << MVPP2_BM_COOKIE_POOL_OFFS);
bm |= ((pool & 0xFF) << MVPP2_BM_COOKIE_POOL_OFFS);
return bm;
}
/* Get pool number from a BM cookie */
static inline int mvpp2_bm_cookie_pool_get(u32 cookie)
{
return (cookie >> MVPP2_BM_COOKIE_POOL_OFFS) & 0xFF;
}
/* Release buffer to BM */
static inline void mvpp2_bm_pool_put(struct mvpp2_port *port, int pool,
u32 buf_phys_addr, u32 buf_virt_addr)
{
mvpp2_write(port->priv, MVPP2_BM_VIRT_RLS_REG, buf_virt_addr);
mvpp2_write(port->priv, MVPP2_BM_PHY_RLS_REG(pool), buf_phys_addr);
}
/* Release multicast buffer */
static void mvpp2_bm_pool_mc_put(struct mvpp2_port *port, int pool,
u32 buf_phys_addr, u32 buf_virt_addr,
int mc_id)
{
u32 val = 0;
val |= (mc_id & MVPP2_BM_MC_ID_MASK);
mvpp2_write(port->priv, MVPP2_BM_MC_RLS_REG, val);
mvpp2_bm_pool_put(port, pool,
buf_phys_addr | MVPP2_BM_PHY_RLS_MC_BUFF_MASK,
buf_virt_addr);
}
/* Refill BM pool */
static void mvpp2_pool_refill(struct mvpp2_port *port, u32 bm,
u32 phys_addr, u32 cookie)
{
int pool = mvpp2_bm_cookie_pool_get(bm);
mvpp2_bm_pool_put(port, pool, phys_addr, cookie);
}
/* Allocate buffers for the pool */
static int mvpp2_bm_bufs_add(struct mvpp2_port *port,
struct mvpp2_bm_pool *bm_pool, int buf_num)
{
struct sk_buff *skb;
int i, buf_size, total_size;
u32 bm;
dma_addr_t phys_addr;
buf_size = MVPP2_RX_BUF_SIZE(bm_pool->pkt_size);
total_size = MVPP2_RX_TOTAL_SIZE(buf_size);
if (buf_num < 0 ||
(buf_num + bm_pool->buf_num > bm_pool->size)) {
netdev_err(port->dev,
"cannot allocate %d buffers for pool %d\n",
buf_num, bm_pool->id);
return 0;
}
bm = mvpp2_bm_cookie_pool_set(0, bm_pool->id);
for (i = 0; i < buf_num; i++) {
skb = mvpp2_skb_alloc(port, bm_pool, &phys_addr, GFP_KERNEL);
if (!skb)
break;
mvpp2_pool_refill(port, bm, (u32)phys_addr, (u32)skb);
}
/* Update BM driver with number of buffers added to pool */
bm_pool->buf_num += i;
bm_pool->in_use_thresh = bm_pool->buf_num / 4;
netdev_dbg(port->dev,
"%s pool %d: pkt_size=%4d, buf_size=%4d, total_size=%4d\n",
bm_pool->type == MVPP2_BM_SWF_SHORT ? "short" : " long",
bm_pool->id, bm_pool->pkt_size, buf_size, total_size);
netdev_dbg(port->dev,
"%s pool %d: %d of %d buffers added\n",
bm_pool->type == MVPP2_BM_SWF_SHORT ? "short" : " long",
bm_pool->id, i, buf_num);
return i;
}
/* Notify the driver that BM pool is being used as specific type and return the
* pool pointer on success
*/
static struct mvpp2_bm_pool *
mvpp2_bm_pool_use(struct mvpp2_port *port, int pool, enum mvpp2_bm_type type,
int pkt_size)
{
unsigned long flags = 0;
struct mvpp2_bm_pool *new_pool = &port->priv->bm_pools[pool];
int num;
if (new_pool->type != MVPP2_BM_FREE && new_pool->type != type) {
netdev_err(port->dev, "mixing pool types is forbidden\n");
return NULL;
}
spin_lock_irqsave(&new_pool->lock, flags);
if (new_pool->type == MVPP2_BM_FREE)
new_pool->type = type;
/* Allocate buffers in case BM pool is used as long pool, but packet
* size doesn't match MTU or BM pool hasn't being used yet
*/
if (((type == MVPP2_BM_SWF_LONG) && (pkt_size > new_pool->pkt_size)) ||
(new_pool->pkt_size == 0)) {
int pkts_num;
/* Set default buffer number or free all the buffers in case
* the pool is not empty
*/
pkts_num = new_pool->buf_num;
if (pkts_num == 0)
pkts_num = type == MVPP2_BM_SWF_LONG ?
MVPP2_BM_LONG_BUF_NUM :
MVPP2_BM_SHORT_BUF_NUM;
else
mvpp2_bm_bufs_free(port->priv, new_pool);
new_pool->pkt_size = pkt_size;
/* Allocate buffers for this pool */
num = mvpp2_bm_bufs_add(port, new_pool, pkts_num);
if (num != pkts_num) {
WARN(1, "pool %d: %d of %d allocated\n",
new_pool->id, num, pkts_num);
/* We need to undo the bufs_add() allocations */
spin_unlock_irqrestore(&new_pool->lock, flags);
return NULL;
}
}
mvpp2_bm_pool_bufsize_set(port->priv, new_pool,
MVPP2_RX_BUF_SIZE(new_pool->pkt_size));
spin_unlock_irqrestore(&new_pool->lock, flags);
return new_pool;
}
/* Initialize pools for swf */
static int mvpp2_swf_bm_pool_init(struct mvpp2_port *port)
{
unsigned long flags = 0;
int rxq;
if (!port->pool_long) {
port->pool_long =
mvpp2_bm_pool_use(port, MVPP2_BM_SWF_LONG_POOL(port->id),
MVPP2_BM_SWF_LONG,
port->pkt_size);
if (!port->pool_long)
return -ENOMEM;
spin_lock_irqsave(&port->pool_long->lock, flags);
port->pool_long->port_map |= (1 << port->id);
spin_unlock_irqrestore(&port->pool_long->lock, flags);
for (rxq = 0; rxq < rxq_number; rxq++)
mvpp2_rxq_long_pool_set(port, rxq, port->pool_long->id);
}
if (!port->pool_short) {
port->pool_short =
mvpp2_bm_pool_use(port, MVPP2_BM_SWF_SHORT_POOL,
MVPP2_BM_SWF_SHORT,
MVPP2_BM_SHORT_PKT_SIZE);
if (!port->pool_short)
return -ENOMEM;
spin_lock_irqsave(&port->pool_short->lock, flags);
port->pool_short->port_map |= (1 << port->id);
spin_unlock_irqrestore(&port->pool_short->lock, flags);
for (rxq = 0; rxq < rxq_number; rxq++)
mvpp2_rxq_short_pool_set(port, rxq,
port->pool_short->id);
}
return 0;
}
static int mvpp2_bm_update_mtu(struct net_device *dev, int mtu)
{
struct mvpp2_port *port = netdev_priv(dev);
struct mvpp2_bm_pool *port_pool = port->pool_long;
int num, pkts_num = port_pool->buf_num;
int pkt_size = MVPP2_RX_PKT_SIZE(mtu);
/* Update BM pool with new buffer size */
mvpp2_bm_bufs_free(port->priv, port_pool);
if (port_pool->buf_num) {
WARN(1, "cannot free all buffers in pool %d\n", port_pool->id);
return -EIO;
}
port_pool->pkt_size = pkt_size;
num = mvpp2_bm_bufs_add(port, port_pool, pkts_num);
if (num != pkts_num) {
WARN(1, "pool %d: %d of %d allocated\n",
port_pool->id, num, pkts_num);
return -EIO;
}
mvpp2_bm_pool_bufsize_set(port->priv, port_pool,
MVPP2_RX_BUF_SIZE(port_pool->pkt_size));
dev->mtu = mtu;
netdev_update_features(dev);
return 0;
}
static inline void mvpp2_interrupts_enable(struct mvpp2_port *port)
{
int cpu, cpu_mask = 0;
for_each_present_cpu(cpu)
cpu_mask |= 1 << cpu;
mvpp2_write(port->priv, MVPP2_ISR_ENABLE_REG(port->id),
MVPP2_ISR_ENABLE_INTERRUPT(cpu_mask));
}
static inline void mvpp2_interrupts_disable(struct mvpp2_port *port)
{
int cpu, cpu_mask = 0;
for_each_present_cpu(cpu)
cpu_mask |= 1 << cpu;
mvpp2_write(port->priv, MVPP2_ISR_ENABLE_REG(port->id),
MVPP2_ISR_DISABLE_INTERRUPT(cpu_mask));
}
/* Mask the current CPU's Rx/Tx interrupts */
static void mvpp2_interrupts_mask(void *arg)
{
struct mvpp2_port *port = arg;
mvpp2_write(port->priv, MVPP2_ISR_RX_TX_MASK_REG(port->id), 0);
}
/* Unmask the current CPU's Rx/Tx interrupts */
static void mvpp2_interrupts_unmask(void *arg)
{
struct mvpp2_port *port = arg;
mvpp2_write(port->priv, MVPP2_ISR_RX_TX_MASK_REG(port->id),
(MVPP2_CAUSE_MISC_SUM_MASK |
MVPP2_CAUSE_TXQ_OCCUP_DESC_ALL_MASK |
MVPP2_CAUSE_RXQ_OCCUP_DESC_ALL_MASK));
}
/* Port configuration routines */
static void mvpp2_port_mii_set(struct mvpp2_port *port)
{
u32 val;
val = readl(port->base + MVPP2_GMAC_CTRL_2_REG);
switch (port->phy_interface) {
case PHY_INTERFACE_MODE_SGMII:
val |= MVPP2_GMAC_INBAND_AN_MASK;
break;
case PHY_INTERFACE_MODE_RGMII:
val |= MVPP2_GMAC_PORT_RGMII_MASK;
default:
val &= ~MVPP2_GMAC_PCS_ENABLE_MASK;
}
writel(val, port->base + MVPP2_GMAC_CTRL_2_REG);
}
static void mvpp2_port_fc_adv_enable(struct mvpp2_port *port)
{
u32 val;
val = readl(port->base + MVPP2_GMAC_AUTONEG_CONFIG);
val |= MVPP2_GMAC_FC_ADV_EN;
writel(val, port->base + MVPP2_GMAC_AUTONEG_CONFIG);
}
static void mvpp2_port_enable(struct mvpp2_port *port)
{
u32 val;
val = readl(port->base + MVPP2_GMAC_CTRL_0_REG);
val |= MVPP2_GMAC_PORT_EN_MASK;
val |= MVPP2_GMAC_MIB_CNTR_EN_MASK;
writel(val, port->base + MVPP2_GMAC_CTRL_0_REG);
}
static void mvpp2_port_disable(struct mvpp2_port *port)
{
u32 val;
val = readl(port->base + MVPP2_GMAC_CTRL_0_REG);
val &= ~(MVPP2_GMAC_PORT_EN_MASK);
writel(val, port->base + MVPP2_GMAC_CTRL_0_REG);
}
/* Set IEEE 802.3x Flow Control Xon Packet Transmission Mode */
static void mvpp2_port_periodic_xon_disable(struct mvpp2_port *port)
{
u32 val;
val = readl(port->base + MVPP2_GMAC_CTRL_1_REG) &
~MVPP2_GMAC_PERIODIC_XON_EN_MASK;
writel(val, port->base + MVPP2_GMAC_CTRL_1_REG);
}
/* Configure loopback port */
static void mvpp2_port_loopback_set(struct mvpp2_port *port)
{
u32 val;
val = readl(port->base + MVPP2_GMAC_CTRL_1_REG);
if (port->speed == 1000)
val |= MVPP2_GMAC_GMII_LB_EN_MASK;
else
val &= ~MVPP2_GMAC_GMII_LB_EN_MASK;
if (port->phy_interface == PHY_INTERFACE_MODE_SGMII)
val |= MVPP2_GMAC_PCS_LB_EN_MASK;
else
val &= ~MVPP2_GMAC_PCS_LB_EN_MASK;
writel(val, port->base + MVPP2_GMAC_CTRL_1_REG);
}
static void mvpp2_port_reset(struct mvpp2_port *port)
{
u32 val;
val = readl(port->base + MVPP2_GMAC_CTRL_2_REG) &
~MVPP2_GMAC_PORT_RESET_MASK;
writel(val, port->base + MVPP2_GMAC_CTRL_2_REG);
while (readl(port->base + MVPP2_GMAC_CTRL_2_REG) &
MVPP2_GMAC_PORT_RESET_MASK)
continue;
}
/* Change maximum receive size of the port */
static inline void mvpp2_gmac_max_rx_size_set(struct mvpp2_port *port)
{
u32 val;
val = readl(port->base + MVPP2_GMAC_CTRL_0_REG);
val &= ~MVPP2_GMAC_MAX_RX_SIZE_MASK;
val |= (((port->pkt_size - MVPP2_MH_SIZE) / 2) <<
MVPP2_GMAC_MAX_RX_SIZE_OFFS);
writel(val, port->base + MVPP2_GMAC_CTRL_0_REG);
}
/* Set defaults to the MVPP2 port */
static void mvpp2_defaults_set(struct mvpp2_port *port)
{
int tx_port_num, val, queue, ptxq, lrxq;
/* Configure port to loopback if needed */
if (port->flags & MVPP2_F_LOOPBACK)
mvpp2_port_loopback_set(port);
/* Update TX FIFO MIN Threshold */
val = readl(port->base + MVPP2_GMAC_PORT_FIFO_CFG_1_REG);
val &= ~MVPP2_GMAC_TX_FIFO_MIN_TH_ALL_MASK;
/* Min. TX threshold must be less than minimal packet length */
val |= MVPP2_GMAC_TX_FIFO_MIN_TH_MASK(64 - 4 - 2);
writel(val, port->base + MVPP2_GMAC_PORT_FIFO_CFG_1_REG);
/* Disable Legacy WRR, Disable EJP, Release from reset */
tx_port_num = mvpp2_egress_port(port);
mvpp2_write(port->priv, MVPP2_TXP_SCHED_PORT_INDEX_REG,
tx_port_num);
mvpp2_write(port->priv, MVPP2_TXP_SCHED_CMD_1_REG, 0);
/* Close bandwidth for all queues */
for (queue = 0; queue < MVPP2_MAX_TXQ; queue++) {
ptxq = mvpp2_txq_phys(port->id, queue);
mvpp2_write(port->priv,
MVPP2_TXQ_SCHED_TOKEN_CNTR_REG(ptxq), 0);
}
/* Set refill period to 1 usec, refill tokens
* and bucket size to maximum
*/
mvpp2_write(port->priv, MVPP2_TXP_SCHED_PERIOD_REG,
port->priv->tclk / USEC_PER_SEC);
val = mvpp2_read(port->priv, MVPP2_TXP_SCHED_REFILL_REG);
val &= ~MVPP2_TXP_REFILL_PERIOD_ALL_MASK;
val |= MVPP2_TXP_REFILL_PERIOD_MASK(1);
val |= MVPP2_TXP_REFILL_TOKENS_ALL_MASK;
mvpp2_write(port->priv, MVPP2_TXP_SCHED_REFILL_REG, val);
val = MVPP2_TXP_TOKEN_SIZE_MAX;
mvpp2_write(port->priv, MVPP2_TXP_SCHED_TOKEN_SIZE_REG, val);
/* Set MaximumLowLatencyPacketSize value to 256 */
mvpp2_write(port->priv, MVPP2_RX_CTRL_REG(port->id),
MVPP2_RX_USE_PSEUDO_FOR_CSUM_MASK |
MVPP2_RX_LOW_LATENCY_PKT_SIZE(256));
/* Enable Rx cache snoop */
for (lrxq = 0; lrxq < rxq_number; lrxq++) {
queue = port->rxqs[lrxq]->id;
val = mvpp2_read(port->priv, MVPP2_RXQ_CONFIG_REG(queue));
val |= MVPP2_SNOOP_PKT_SIZE_MASK |
MVPP2_SNOOP_BUF_HDR_MASK;
mvpp2_write(port->priv, MVPP2_RXQ_CONFIG_REG(queue), val);
}
/* At default, mask all interrupts to all present cpus */
mvpp2_interrupts_disable(port);
}
/* Enable/disable receiving packets */
static void mvpp2_ingress_enable(struct mvpp2_port *port)
{
u32 val;
int lrxq, queue;
for (lrxq = 0; lrxq < rxq_number; lrxq++) {
queue = port->rxqs[lrxq]->id;
val = mvpp2_read(port->priv, MVPP2_RXQ_CONFIG_REG(queue));
val &= ~MVPP2_RXQ_DISABLE_MASK;
mvpp2_write(port->priv, MVPP2_RXQ_CONFIG_REG(queue), val);
}
}
static void mvpp2_ingress_disable(struct mvpp2_port *port)
{
u32 val;
int lrxq, queue;
for (lrxq = 0; lrxq < rxq_number; lrxq++) {
queue = port->rxqs[lrxq]->id;
val = mvpp2_read(port->priv, MVPP2_RXQ_CONFIG_REG(queue));
val |= MVPP2_RXQ_DISABLE_MASK;
mvpp2_write(port->priv, MVPP2_RXQ_CONFIG_REG(queue), val);
}
}
/* Enable transmit via physical egress queue
* - HW starts take descriptors from DRAM
*/
static void mvpp2_egress_enable(struct mvpp2_port *port)
{
u32 qmap;
int queue;
int tx_port_num = mvpp2_egress_port(port);
/* Enable all initialized TXs. */
qmap = 0;
for (queue = 0; queue < txq_number; queue++) {
struct mvpp2_tx_queue *txq = port->txqs[queue];
if (txq->descs != NULL)
qmap |= (1 << queue);
}
mvpp2_write(port->priv, MVPP2_TXP_SCHED_PORT_INDEX_REG, tx_port_num);
mvpp2_write(port->priv, MVPP2_TXP_SCHED_Q_CMD_REG, qmap);
}
/* Disable transmit via physical egress queue
* - HW doesn't take descriptors from DRAM
*/
static void mvpp2_egress_disable(struct mvpp2_port *port)
{
u32 reg_data;
int delay;
int tx_port_num = mvpp2_egress_port(port);
/* Issue stop command for active channels only */
mvpp2_write(port->priv, MVPP2_TXP_SCHED_PORT_INDEX_REG, tx_port_num);
reg_data = (mvpp2_read(port->priv, MVPP2_TXP_SCHED_Q_CMD_REG)) &
MVPP2_TXP_SCHED_ENQ_MASK;
if (reg_data != 0)
mvpp2_write(port->priv, MVPP2_TXP_SCHED_Q_CMD_REG,
(reg_data << MVPP2_TXP_SCHED_DISQ_OFFSET));
/* Wait for all Tx activity to terminate. */
delay = 0;
do {
if (delay >= MVPP2_TX_DISABLE_TIMEOUT_MSEC) {
netdev_warn(port->dev,
"Tx stop timed out, status=0x%08x\n",
reg_data);
break;
}
mdelay(1);
delay++;
/* Check port TX Command register that all
* Tx queues are stopped
*/
reg_data = mvpp2_read(port->priv, MVPP2_TXP_SCHED_Q_CMD_REG);
} while (reg_data & MVPP2_TXP_SCHED_ENQ_MASK);
}
/* Rx descriptors helper methods */
/* Get number of Rx descriptors occupied by received packets */
static inline int
mvpp2_rxq_received(struct mvpp2_port *port, int rxq_id)
{
u32 val = mvpp2_read(port->priv, MVPP2_RXQ_STATUS_REG(rxq_id));
return val & MVPP2_RXQ_OCCUPIED_MASK;
}
/* Update Rx queue status with the number of occupied and available
* Rx descriptor slots.
*/
static inline void
mvpp2_rxq_status_update(struct mvpp2_port *port, int rxq_id,
int used_count, int free_count)
{
/* Decrement the number of used descriptors and increment count
* increment the number of free descriptors.
*/
u32 val = used_count | (free_count << MVPP2_RXQ_NUM_NEW_OFFSET);
mvpp2_write(port->priv, MVPP2_RXQ_STATUS_UPDATE_REG(rxq_id), val);
}
/* Get pointer to next RX descriptor to be processed by SW */
static inline struct mvpp2_rx_desc *
mvpp2_rxq_next_desc_get(struct mvpp2_rx_queue *rxq)
{
int rx_desc = rxq->next_desc_to_proc;
rxq->next_desc_to_proc = MVPP2_QUEUE_NEXT_DESC(rxq, rx_desc);
prefetch(rxq->descs + rxq->next_desc_to_proc);
return rxq->descs + rx_desc;
}
/* Set rx queue offset */
static void mvpp2_rxq_offset_set(struct mvpp2_port *port,
int prxq, int offset)
{
u32 val;
/* Convert offset from bytes to units of 32 bytes */
offset = offset >> 5;
val = mvpp2_read(port->priv, MVPP2_RXQ_CONFIG_REG(prxq));
val &= ~MVPP2_RXQ_PACKET_OFFSET_MASK;
/* Offset is in */
val |= ((offset << MVPP2_RXQ_PACKET_OFFSET_OFFS) &
MVPP2_RXQ_PACKET_OFFSET_MASK);
mvpp2_write(port->priv, MVPP2_RXQ_CONFIG_REG(prxq), val);
}
/* Obtain BM cookie information from descriptor */
static u32 mvpp2_bm_cookie_build(struct mvpp2_rx_desc *rx_desc)
{
int pool = (rx_desc->status & MVPP2_RXD_BM_POOL_ID_MASK) >>
MVPP2_RXD_BM_POOL_ID_OFFS;
int cpu = smp_processor_id();
return ((pool & 0xFF) << MVPP2_BM_COOKIE_POOL_OFFS) |
((cpu & 0xFF) << MVPP2_BM_COOKIE_CPU_OFFS);
}
/* Tx descriptors helper methods */
/* Get number of Tx descriptors waiting to be transmitted by HW */
static int mvpp2_txq_pend_desc_num_get(struct mvpp2_port *port,
struct mvpp2_tx_queue *txq)
{
u32 val;
mvpp2_write(port->priv, MVPP2_TXQ_NUM_REG, txq->id);
val = mvpp2_read(port->priv, MVPP2_TXQ_PENDING_REG);
return val & MVPP2_TXQ_PENDING_MASK;
}
/* Get pointer to next Tx descriptor to be processed (send) by HW */
static struct mvpp2_tx_desc *
mvpp2_txq_next_desc_get(struct mvpp2_tx_queue *txq)
{
int tx_desc = txq->next_desc_to_proc;
txq->next_desc_to_proc = MVPP2_QUEUE_NEXT_DESC(txq, tx_desc);
return txq->descs + tx_desc;
}
/* Update HW with number of aggregated Tx descriptors to be sent */
static void mvpp2_aggr_txq_pend_desc_add(struct mvpp2_port *port, int pending)
{
/* aggregated access - relevant TXQ number is written in TX desc */
mvpp2_write(port->priv, MVPP2_AGGR_TXQ_UPDATE_REG, pending);
}
/* Check if there are enough free descriptors in aggregated txq.
* If not, update the number of occupied descriptors and repeat the check.
*/
static int mvpp2_aggr_desc_num_check(struct mvpp2 *priv,
struct mvpp2_tx_queue *aggr_txq, int num)
{
if ((aggr_txq->count + num) > aggr_txq->size) {
/* Update number of occupied aggregated Tx descriptors */
int cpu = smp_processor_id();
u32 val = mvpp2_read(priv, MVPP2_AGGR_TXQ_STATUS_REG(cpu));
aggr_txq->count = val & MVPP2_AGGR_TXQ_PENDING_MASK;
}
if ((aggr_txq->count + num) > aggr_txq->size)
return -ENOMEM;
return 0;
}
/* Reserved Tx descriptors allocation request */
static int mvpp2_txq_alloc_reserved_desc(struct mvpp2 *priv,
struct mvpp2_tx_queue *txq, int num)
{
u32 val;
val = (txq->id << MVPP2_TXQ_RSVD_REQ_Q_OFFSET) | num;
mvpp2_write(priv, MVPP2_TXQ_RSVD_REQ_REG, val);
val = mvpp2_read(priv, MVPP2_TXQ_RSVD_RSLT_REG);
return val & MVPP2_TXQ_RSVD_RSLT_MASK;
}
/* Check if there are enough reserved descriptors for transmission.
* If not, request chunk of reserved descriptors and check again.
*/
static int mvpp2_txq_reserved_desc_num_proc(struct mvpp2 *priv,
struct mvpp2_tx_queue *txq,
struct mvpp2_txq_pcpu *txq_pcpu,
int num)
{
int req, cpu, desc_count;
if (txq_pcpu->reserved_num >= num)
return 0;
/* Not enough descriptors reserved! Update the reserved descriptor
* count and check again.
*/
desc_count = 0;
/* Compute total of used descriptors */
for_each_present_cpu(cpu) {
struct mvpp2_txq_pcpu *txq_pcpu_aux;
txq_pcpu_aux = per_cpu_ptr(txq->pcpu, cpu);
desc_count += txq_pcpu_aux->count;
desc_count += txq_pcpu_aux->reserved_num;
}
req = max(MVPP2_CPU_DESC_CHUNK, num - txq_pcpu->reserved_num);
desc_count += req;
if (desc_count >
(txq->size - (num_present_cpus() * MVPP2_CPU_DESC_CHUNK)))
return -ENOMEM;
txq_pcpu->reserved_num += mvpp2_txq_alloc_reserved_desc(priv, txq, req);
/* OK, the descriptor cound has been updated: check again. */
if (txq_pcpu->reserved_num < num)
return -ENOMEM;
return 0;
}
/* Release the last allocated Tx descriptor. Useful to handle DMA
* mapping failures in the Tx path.
*/
static void mvpp2_txq_desc_put(struct mvpp2_tx_queue *txq)
{
if (txq->next_desc_to_proc == 0)
txq->next_desc_to_proc = txq->last_desc - 1;
else
txq->next_desc_to_proc--;
}
/* Set Tx descriptors fields relevant for CSUM calculation */
static u32 mvpp2_txq_desc_csum(int l3_offs, int l3_proto,
int ip_hdr_len, int l4_proto)
{
u32 command;
/* fields: L3_offset, IP_hdrlen, L3_type, G_IPv4_chk,
* G_L4_chk, L4_type required only for checksum calculation
*/
command = (l3_offs << MVPP2_TXD_L3_OFF_SHIFT);
command |= (ip_hdr_len << MVPP2_TXD_IP_HLEN_SHIFT);
command |= MVPP2_TXD_IP_CSUM_DISABLE;
if (l3_proto == swab16(ETH_P_IP)) {
command &= ~MVPP2_TXD_IP_CSUM_DISABLE; /* enable IPv4 csum */
command &= ~MVPP2_TXD_L3_IP6; /* enable IPv4 */
} else {
command |= MVPP2_TXD_L3_IP6; /* enable IPv6 */
}
if (l4_proto == IPPROTO_TCP) {
command &= ~MVPP2_TXD_L4_UDP; /* enable TCP */
command &= ~MVPP2_TXD_L4_CSUM_FRAG; /* generate L4 csum */
} else if (l4_proto == IPPROTO_UDP) {
command |= MVPP2_TXD_L4_UDP; /* enable UDP */
command &= ~MVPP2_TXD_L4_CSUM_FRAG; /* generate L4 csum */
} else {
command |= MVPP2_TXD_L4_CSUM_NOT;
}
return command;
}
/* Get number of sent descriptors and decrement counter.
* The number of sent descriptors is returned.
* Per-CPU access
*/
static inline int mvpp2_txq_sent_desc_proc(struct mvpp2_port *port,
struct mvpp2_tx_queue *txq)
{
u32 val;
/* Reading status reg resets transmitted descriptor counter */
val = mvpp2_read(port->priv, MVPP2_TXQ_SENT_REG(txq->id));
return (val & MVPP2_TRANSMITTED_COUNT_MASK) >>
MVPP2_TRANSMITTED_COUNT_OFFSET;
}
static void mvpp2_txq_sent_counter_clear(void *arg)
{
struct mvpp2_port *port = arg;
int queue;
for (queue = 0; queue < txq_number; queue++) {
int id = port->txqs[queue]->id;
mvpp2_read(port->priv, MVPP2_TXQ_SENT_REG(id));
}
}
/* Set max sizes for Tx queues */
static void mvpp2_txp_max_tx_size_set(struct mvpp2_port *port)
{
u32 val, size, mtu;
int txq, tx_port_num;
mtu = port->pkt_size * 8;
if (mtu > MVPP2_TXP_MTU_MAX)
mtu = MVPP2_TXP_MTU_MAX;
/* WA for wrong Token bucket update: Set MTU value = 3*real MTU value */
mtu = 3 * mtu;
/* Indirect access to registers */
tx_port_num = mvpp2_egress_port(port);
mvpp2_write(port->priv, MVPP2_TXP_SCHED_PORT_INDEX_REG, tx_port_num);
/* Set MTU */
val = mvpp2_read(port->priv, MVPP2_TXP_SCHED_MTU_REG);
val &= ~MVPP2_TXP_MTU_MAX;
val |= mtu;
mvpp2_write(port->priv, MVPP2_TXP_SCHED_MTU_REG, val);
/* TXP token size and all TXQs token size must be larger that MTU */
val = mvpp2_read(port->priv, MVPP2_TXP_SCHED_TOKEN_SIZE_REG);
size = val & MVPP2_TXP_TOKEN_SIZE_MAX;
if (size < mtu) {
size = mtu;
val &= ~MVPP2_TXP_TOKEN_SIZE_MAX;
val |= size;
mvpp2_write(port->priv, MVPP2_TXP_SCHED_TOKEN_SIZE_REG, val);
}
for (txq = 0; txq < txq_number; txq++) {
val = mvpp2_read(port->priv,
MVPP2_TXQ_SCHED_TOKEN_SIZE_REG(txq));
size = val & MVPP2_TXQ_TOKEN_SIZE_MAX;
if (size < mtu) {
size = mtu;
val &= ~MVPP2_TXQ_TOKEN_SIZE_MAX;
val |= size;
mvpp2_write(port->priv,
MVPP2_TXQ_SCHED_TOKEN_SIZE_REG(txq),
val);
}
}
}
/* Set the number of packets that will be received before Rx interrupt
* will be generated by HW.
*/
static void mvpp2_rx_pkts_coal_set(struct mvpp2_port *port,
struct mvpp2_rx_queue *rxq, u32 pkts)
{
u32 val;
val = (pkts & MVPP2_OCCUPIED_THRESH_MASK);
mvpp2_write(port->priv, MVPP2_RXQ_NUM_REG, rxq->id);
mvpp2_write(port->priv, MVPP2_RXQ_THRESH_REG, val);
rxq->pkts_coal = pkts;
}
/* Set the time delay in usec before Rx interrupt */
static void mvpp2_rx_time_coal_set(struct mvpp2_port *port,
struct mvpp2_rx_queue *rxq, u32 usec)
{
u32 val;
val = (port->priv->tclk / USEC_PER_SEC) * usec;
mvpp2_write(port->priv, MVPP2_ISR_RX_THRESHOLD_REG(rxq->id), val);
rxq->time_coal = usec;
}
/* Set threshold for TX_DONE pkts coalescing */
static void mvpp2_tx_done_pkts_coal_set(void *arg)
{
struct mvpp2_port *port = arg;
int queue;
u32 val;
for (queue = 0; queue < txq_number; queue++) {
struct mvpp2_tx_queue *txq = port->txqs[queue];
val = (txq->done_pkts_coal << MVPP2_TRANSMITTED_THRESH_OFFSET) &
MVPP2_TRANSMITTED_THRESH_MASK;
mvpp2_write(port->priv, MVPP2_TXQ_NUM_REG, txq->id);
mvpp2_write(port->priv, MVPP2_TXQ_THRESH_REG, val);
}
}
/* Free Tx queue skbuffs */
static void mvpp2_txq_bufs_free(struct mvpp2_port *port,
struct mvpp2_tx_queue *txq,
struct mvpp2_txq_pcpu *txq_pcpu, int num)
{
int i;
for (i = 0; i < num; i++) {
struct mvpp2_tx_desc *tx_desc = txq->descs +
txq_pcpu->txq_get_index;
struct sk_buff *skb = txq_pcpu->tx_skb[txq_pcpu->txq_get_index];
mvpp2_txq_inc_get(txq_pcpu);
if (!skb)
continue;
dma_unmap_single(port->dev->dev.parent, tx_desc->buf_phys_addr,
tx_desc->data_size, DMA_TO_DEVICE);
dev_kfree_skb_any(skb);
}
}
static inline struct mvpp2_rx_queue *mvpp2_get_rx_queue(struct mvpp2_port *port,
u32 cause)
{
int queue = fls(cause) - 1;
return port->rxqs[queue];
}
static inline struct mvpp2_tx_queue *mvpp2_get_tx_queue(struct mvpp2_port *port,
u32 cause)
{
int queue = fls(cause >> 16) - 1;
return port->txqs[queue];
}
/* Handle end of transmission */
static void mvpp2_txq_done(struct mvpp2_port *port, struct mvpp2_tx_queue *txq,
struct mvpp2_txq_pcpu *txq_pcpu)
{
struct netdev_queue *nq = netdev_get_tx_queue(port->dev, txq->log_id);
int tx_done;
if (txq_pcpu->cpu != smp_processor_id())
netdev_err(port->dev, "wrong cpu on the end of Tx processing\n");
tx_done = mvpp2_txq_sent_desc_proc(port, txq);
if (!tx_done)
return;
mvpp2_txq_bufs_free(port, txq, txq_pcpu, tx_done);
txq_pcpu->count -= tx_done;
if (netif_tx_queue_stopped(nq))
if (txq_pcpu->size - txq_pcpu->count >= MAX_SKB_FRAGS + 1)
netif_tx_wake_queue(nq);
}
/* Rx/Tx queue initialization/cleanup methods */
/* Allocate and initialize descriptors for aggr TXQ */
static int mvpp2_aggr_txq_init(struct platform_device *pdev,
struct mvpp2_tx_queue *aggr_txq,
int desc_num, int cpu,
struct mvpp2 *priv)
{
/* Allocate memory for TX descriptors */
aggr_txq->descs = dma_alloc_coherent(&pdev->dev,
desc_num * MVPP2_DESC_ALIGNED_SIZE,
&aggr_txq->descs_phys, GFP_KERNEL);
if (!aggr_txq->descs)
return -ENOMEM;
/* Make sure descriptor address is cache line size aligned */
BUG_ON(aggr_txq->descs !=
PTR_ALIGN(aggr_txq->descs, MVPP2_CPU_D_CACHE_LINE_SIZE));
aggr_txq->last_desc = aggr_txq->size - 1;
/* Aggr TXQ no reset WA */
aggr_txq->next_desc_to_proc = mvpp2_read(priv,
MVPP2_AGGR_TXQ_INDEX_REG(cpu));
/* Set Tx descriptors queue starting address */
/* indirect access */
mvpp2_write(priv, MVPP2_AGGR_TXQ_DESC_ADDR_REG(cpu),
aggr_txq->descs_phys);
mvpp2_write(priv, MVPP2_AGGR_TXQ_DESC_SIZE_REG(cpu), desc_num);
return 0;
}
/* Create a specified Rx queue */
static int mvpp2_rxq_init(struct mvpp2_port *port,
struct mvpp2_rx_queue *rxq)
{
rxq->size = port->rx_ring_size;
/* Allocate memory for RX descriptors */
rxq->descs = dma_alloc_coherent(port->dev->dev.parent,
rxq->size * MVPP2_DESC_ALIGNED_SIZE,
&rxq->descs_phys, GFP_KERNEL);
if (!rxq->descs)
return -ENOMEM;
BUG_ON(rxq->descs !=
PTR_ALIGN(rxq->descs, MVPP2_CPU_D_CACHE_LINE_SIZE));
rxq->last_desc = rxq->size - 1;
/* Zero occupied and non-occupied counters - direct access */
mvpp2_write(port->priv, MVPP2_RXQ_STATUS_REG(rxq->id), 0);
/* Set Rx descriptors queue starting address - indirect access */
mvpp2_write(port->priv, MVPP2_RXQ_NUM_REG, rxq->id);
mvpp2_write(port->priv, MVPP2_RXQ_DESC_ADDR_REG, rxq->descs_phys);
mvpp2_write(port->priv, MVPP2_RXQ_DESC_SIZE_REG, rxq->size);
mvpp2_write(port->priv, MVPP2_RXQ_INDEX_REG, 0);
/* Set Offset */
mvpp2_rxq_offset_set(port, rxq->id, NET_SKB_PAD);
/* Set coalescing pkts and time */
mvpp2_rx_pkts_coal_set(port, rxq, rxq->pkts_coal);
mvpp2_rx_time_coal_set(port, rxq, rxq->time_coal);
/* Add number of descriptors ready for receiving packets */
mvpp2_rxq_status_update(port, rxq->id, 0, rxq->size);
return 0;
}
/* Push packets received by the RXQ to BM pool */
static void mvpp2_rxq_drop_pkts(struct mvpp2_port *port,
struct mvpp2_rx_queue *rxq)
{
int rx_received, i;
rx_received = mvpp2_rxq_received(port, rxq->id);
if (!rx_received)
return;
for (i = 0; i < rx_received; i++) {
struct mvpp2_rx_desc *rx_desc = mvpp2_rxq_next_desc_get(rxq);
u32 bm = mvpp2_bm_cookie_build(rx_desc);
mvpp2_pool_refill(port, bm, rx_desc->buf_phys_addr,
rx_desc->buf_cookie);
}
mvpp2_rxq_status_update(port, rxq->id, rx_received, rx_received);
}
/* Cleanup Rx queue */
static void mvpp2_rxq_deinit(struct mvpp2_port *port,
struct mvpp2_rx_queue *rxq)
{
mvpp2_rxq_drop_pkts(port, rxq);
if (rxq->descs)
dma_free_coherent(port->dev->dev.parent,
rxq->size * MVPP2_DESC_ALIGNED_SIZE,
rxq->descs,
rxq->descs_phys);
rxq->descs = NULL;
rxq->last_desc = 0;
rxq->next_desc_to_proc = 0;
rxq->descs_phys = 0;
/* Clear Rx descriptors queue starting address and size;
* free descriptor number
*/
mvpp2_write(port->priv, MVPP2_RXQ_STATUS_REG(rxq->id), 0);
mvpp2_write(port->priv, MVPP2_RXQ_NUM_REG, rxq->id);
mvpp2_write(port->priv, MVPP2_RXQ_DESC_ADDR_REG, 0);
mvpp2_write(port->priv, MVPP2_RXQ_DESC_SIZE_REG, 0);
}
/* Create and initialize a Tx queue */
static int mvpp2_txq_init(struct mvpp2_port *port,
struct mvpp2_tx_queue *txq)
{
u32 val;
int cpu, desc, desc_per_txq, tx_port_num;
struct mvpp2_txq_pcpu *txq_pcpu;
txq->size = port->tx_ring_size;
/* Allocate memory for Tx descriptors */
txq->descs = dma_alloc_coherent(port->dev->dev.parent,
txq->size * MVPP2_DESC_ALIGNED_SIZE,
&txq->descs_phys, GFP_KERNEL);
if (!txq->descs)
return -ENOMEM;
/* Make sure descriptor address is cache line size aligned */
BUG_ON(txq->descs !=
PTR_ALIGN(txq->descs, MVPP2_CPU_D_CACHE_LINE_SIZE));
txq->last_desc = txq->size - 1;
/* Set Tx descriptors queue starting address - indirect access */
mvpp2_write(port->priv, MVPP2_TXQ_NUM_REG, txq->id);
mvpp2_write(port->priv, MVPP2_TXQ_DESC_ADDR_REG, txq->descs_phys);
mvpp2_write(port->priv, MVPP2_TXQ_DESC_SIZE_REG, txq->size &
MVPP2_TXQ_DESC_SIZE_MASK);
mvpp2_write(port->priv, MVPP2_TXQ_INDEX_REG, 0);
mvpp2_write(port->priv, MVPP2_TXQ_RSVD_CLR_REG,
txq->id << MVPP2_TXQ_RSVD_CLR_OFFSET);
val = mvpp2_read(port->priv, MVPP2_TXQ_PENDING_REG);
val &= ~MVPP2_TXQ_PENDING_MASK;
mvpp2_write(port->priv, MVPP2_TXQ_PENDING_REG, val);
/* Calculate base address in prefetch buffer. We reserve 16 descriptors
* for each existing TXQ.
* TCONTS for PON port must be continuous from 0 to MVPP2_MAX_TCONT
* GBE ports assumed to be continious from 0 to MVPP2_MAX_PORTS
*/
desc_per_txq = 16;
desc = (port->id * MVPP2_MAX_TXQ * desc_per_txq) +
(txq->log_id * desc_per_txq);
mvpp2_write(port->priv, MVPP2_TXQ_PREF_BUF_REG,
MVPP2_PREF_BUF_PTR(desc) | MVPP2_PREF_BUF_SIZE_16 |
MVPP2_PREF_BUF_THRESH(desc_per_txq/2));
/* WRR / EJP configuration - indirect access */
tx_port_num = mvpp2_egress_port(port);
mvpp2_write(port->priv, MVPP2_TXP_SCHED_PORT_INDEX_REG, tx_port_num);
val = mvpp2_read(port->priv, MVPP2_TXQ_SCHED_REFILL_REG(txq->log_id));
val &= ~MVPP2_TXQ_REFILL_PERIOD_ALL_MASK;
val |= MVPP2_TXQ_REFILL_PERIOD_MASK(1);
val |= MVPP2_TXQ_REFILL_TOKENS_ALL_MASK;
mvpp2_write(port->priv, MVPP2_TXQ_SCHED_REFILL_REG(txq->log_id), val);
val = MVPP2_TXQ_TOKEN_SIZE_MAX;
mvpp2_write(port->priv, MVPP2_TXQ_SCHED_TOKEN_SIZE_REG(txq->log_id),
val);
for_each_present_cpu(cpu) {
txq_pcpu = per_cpu_ptr(txq->pcpu, cpu);
txq_pcpu->size = txq->size;
txq_pcpu->tx_skb = kmalloc(txq_pcpu->size *
sizeof(*txq_pcpu->tx_skb),
GFP_KERNEL);
if (!txq_pcpu->tx_skb) {
dma_free_coherent(port->dev->dev.parent,
txq->size * MVPP2_DESC_ALIGNED_SIZE,
txq->descs, txq->descs_phys);
return -ENOMEM;
}
txq_pcpu->count = 0;
txq_pcpu->reserved_num = 0;
txq_pcpu->txq_put_index = 0;
txq_pcpu->txq_get_index = 0;
}
return 0;
}
/* Free allocated TXQ resources */
static void mvpp2_txq_deinit(struct mvpp2_port *port,
struct mvpp2_tx_queue *txq)
{
struct mvpp2_txq_pcpu *txq_pcpu;
int cpu;
for_each_present_cpu(cpu) {
txq_pcpu = per_cpu_ptr(txq->pcpu, cpu);
kfree(txq_pcpu->tx_skb);
}
if (txq->descs)
dma_free_coherent(port->dev->dev.parent,
txq->size * MVPP2_DESC_ALIGNED_SIZE,
txq->descs, txq->descs_phys);
txq->descs = NULL;
txq->last_desc = 0;
txq->next_desc_to_proc = 0;
txq->descs_phys = 0;
/* Set minimum bandwidth for disabled TXQs */
mvpp2_write(port->priv, MVPP2_TXQ_SCHED_TOKEN_CNTR_REG(txq->id), 0);
/* Set Tx descriptors queue starting address and size */
mvpp2_write(port->priv, MVPP2_TXQ_NUM_REG, txq->id);
mvpp2_write(port->priv, MVPP2_TXQ_DESC_ADDR_REG, 0);
mvpp2_write(port->priv, MVPP2_TXQ_DESC_SIZE_REG, 0);
}
/* Cleanup Tx ports */
static void mvpp2_txq_clean(struct mvpp2_port *port, struct mvpp2_tx_queue *txq)
{
struct mvpp2_txq_pcpu *txq_pcpu;
int delay, pending, cpu;
u32 val;
mvpp2_write(port->priv, MVPP2_TXQ_NUM_REG, txq->id);
val = mvpp2_read(port->priv, MVPP2_TXQ_PREF_BUF_REG);
val |= MVPP2_TXQ_DRAIN_EN_MASK;
mvpp2_write(port->priv, MVPP2_TXQ_PREF_BUF_REG, val);
/* The napi queue has been stopped so wait for all packets
* to be transmitted.
*/
delay = 0;
do {
if (delay >= MVPP2_TX_PENDING_TIMEOUT_MSEC) {
netdev_warn(port->dev,
"port %d: cleaning queue %d timed out\n",
port->id, txq->log_id);
break;
}
mdelay(1);
delay++;
pending = mvpp2_txq_pend_desc_num_get(port, txq);
} while (pending);
val &= ~MVPP2_TXQ_DRAIN_EN_MASK;
mvpp2_write(port->priv, MVPP2_TXQ_PREF_BUF_REG, val);
for_each_present_cpu(cpu) {
txq_pcpu = per_cpu_ptr(txq->pcpu, cpu);
/* Release all packets */
mvpp2_txq_bufs_free(port, txq, txq_pcpu, txq_pcpu->count);
/* Reset queue */
txq_pcpu->count = 0;
txq_pcpu->txq_put_index = 0;
txq_pcpu->txq_get_index = 0;
}
}
/* Cleanup all Tx queues */
static void mvpp2_cleanup_txqs(struct mvpp2_port *port)
{
struct mvpp2_tx_queue *txq;
int queue;
u32 val;
val = mvpp2_read(port->priv, MVPP2_TX_PORT_FLUSH_REG);
/* Reset Tx ports and delete Tx queues */
val |= MVPP2_TX_PORT_FLUSH_MASK(port->id);
mvpp2_write(port->priv, MVPP2_TX_PORT_FLUSH_REG, val);
for (queue = 0; queue < txq_number; queue++) {
txq = port->txqs[queue];
mvpp2_txq_clean(port, txq);
mvpp2_txq_deinit(port, txq);
}
on_each_cpu(mvpp2_txq_sent_counter_clear, port, 1);
val &= ~MVPP2_TX_PORT_FLUSH_MASK(port->id);
mvpp2_write(port->priv, MVPP2_TX_PORT_FLUSH_REG, val);
}
/* Cleanup all Rx queues */
static void mvpp2_cleanup_rxqs(struct mvpp2_port *port)
{
int queue;
for (queue = 0; queue < rxq_number; queue++)
mvpp2_rxq_deinit(port, port->rxqs[queue]);
}
/* Init all Rx queues for port */
static int mvpp2_setup_rxqs(struct mvpp2_port *port)
{
int queue, err;
for (queue = 0; queue < rxq_number; queue++) {
err = mvpp2_rxq_init(port, port->rxqs[queue]);
if (err)
goto err_cleanup;
}
return 0;
err_cleanup:
mvpp2_cleanup_rxqs(port);
return err;
}
/* Init all tx queues for port */
static int mvpp2_setup_txqs(struct mvpp2_port *port)
{
struct mvpp2_tx_queue *txq;
int queue, err;
for (queue = 0; queue < txq_number; queue++) {
txq = port->txqs[queue];
err = mvpp2_txq_init(port, txq);
if (err)
goto err_cleanup;
}
on_each_cpu(mvpp2_tx_done_pkts_coal_set, port, 1);
on_each_cpu(mvpp2_txq_sent_counter_clear, port, 1);
return 0;
err_cleanup:
mvpp2_cleanup_txqs(port);
return err;
}
/* The callback for per-port interrupt */
static irqreturn_t mvpp2_isr(int irq, void *dev_id)
{
struct mvpp2_port *port = (struct mvpp2_port *)dev_id;
mvpp2_interrupts_disable(port);
napi_schedule(&port->napi);
return IRQ_HANDLED;
}
/* Adjust link */
static void mvpp2_link_event(struct net_device *dev)
{
struct mvpp2_port *port = netdev_priv(dev);
struct phy_device *phydev = port->phy_dev;
int status_change = 0;
u32 val;
if (phydev->link) {
if ((port->speed != phydev->speed) ||
(port->duplex != phydev->duplex)) {
u32 val;
val = readl(port->base + MVPP2_GMAC_AUTONEG_CONFIG);
val &= ~(MVPP2_GMAC_CONFIG_MII_SPEED |
MVPP2_GMAC_CONFIG_GMII_SPEED |
MVPP2_GMAC_CONFIG_FULL_DUPLEX |
MVPP2_GMAC_AN_SPEED_EN |
MVPP2_GMAC_AN_DUPLEX_EN);
if (phydev->duplex)
val |= MVPP2_GMAC_CONFIG_FULL_DUPLEX;
if (phydev->speed == SPEED_1000)
val |= MVPP2_GMAC_CONFIG_GMII_SPEED;
else if (phydev->speed == SPEED_100)
val |= MVPP2_GMAC_CONFIG_MII_SPEED;
writel(val, port->base + MVPP2_GMAC_AUTONEG_CONFIG);
port->duplex = phydev->duplex;
port->speed = phydev->speed;
}
}
if (phydev->link != port->link) {
if (!phydev->link) {
port->duplex = -1;
port->speed = 0;
}
port->link = phydev->link;
status_change = 1;
}
if (status_change) {
if (phydev->link) {
val = readl(port->base + MVPP2_GMAC_AUTONEG_CONFIG);
val |= (MVPP2_GMAC_FORCE_LINK_PASS |
MVPP2_GMAC_FORCE_LINK_DOWN);
writel(val, port->base + MVPP2_GMAC_AUTONEG_CONFIG);
mvpp2_egress_enable(port);
mvpp2_ingress_enable(port);
} else {
mvpp2_ingress_disable(port);
mvpp2_egress_disable(port);
}
phy_print_status(phydev);
}
}
/* Main RX/TX processing routines */
/* Display more error info */
static void mvpp2_rx_error(struct mvpp2_port *port,
struct mvpp2_rx_desc *rx_desc)
{
u32 status = rx_desc->status;
switch (status & MVPP2_RXD_ERR_CODE_MASK) {
case MVPP2_RXD_ERR_CRC:
netdev_err(port->dev, "bad rx status %08x (crc error), size=%d\n",
status, rx_desc->data_size);
break;
case MVPP2_RXD_ERR_OVERRUN:
netdev_err(port->dev, "bad rx status %08x (overrun error), size=%d\n",
status, rx_desc->data_size);
break;
case MVPP2_RXD_ERR_RESOURCE:
netdev_err(port->dev, "bad rx status %08x (resource error), size=%d\n",
status, rx_desc->data_size);
break;
}
}
/* Handle RX checksum offload */
static void mvpp2_rx_csum(struct mvpp2_port *port, u32 status,
struct sk_buff *skb)
{
if (((status & MVPP2_RXD_L3_IP4) &&
!(status & MVPP2_RXD_IP4_HEADER_ERR)) ||
(status & MVPP2_RXD_L3_IP6))
if (((status & MVPP2_RXD_L4_UDP) ||
(status & MVPP2_RXD_L4_TCP)) &&
(status & MVPP2_RXD_L4_CSUM_OK)) {
skb->csum = 0;
skb->ip_summed = CHECKSUM_UNNECESSARY;
return;
}
skb->ip_summed = CHECKSUM_NONE;
}
/* Reuse skb if possible, or allocate a new skb and add it to BM pool */
static int mvpp2_rx_refill(struct mvpp2_port *port,
struct mvpp2_bm_pool *bm_pool,
u32 bm, int is_recycle)
{
struct sk_buff *skb;
dma_addr_t phys_addr;
if (is_recycle &&
(atomic_read(&bm_pool->in_use) < bm_pool->in_use_thresh))
return 0;
/* No recycle or too many buffers are in use, so allocate a new skb */
skb = mvpp2_skb_alloc(port, bm_pool, &phys_addr, GFP_ATOMIC);
if (!skb)
return -ENOMEM;
mvpp2_pool_refill(port, bm, (u32)phys_addr, (u32)skb);
atomic_dec(&bm_pool->in_use);
return 0;
}
/* Handle tx checksum */
static u32 mvpp2_skb_tx_csum(struct mvpp2_port *port, struct sk_buff *skb)
{
if (skb->ip_summed == CHECKSUM_PARTIAL) {
int ip_hdr_len = 0;
u8 l4_proto;
if (skb->protocol == htons(ETH_P_IP)) {
struct iphdr *ip4h = ip_hdr(skb);
/* Calculate IPv4 checksum and L4 checksum */
ip_hdr_len = ip4h->ihl;
l4_proto = ip4h->protocol;
} else if (skb->protocol == htons(ETH_P_IPV6)) {
struct ipv6hdr *ip6h = ipv6_hdr(skb);
/* Read l4_protocol from one of IPv6 extra headers */
if (skb_network_header_len(skb) > 0)
ip_hdr_len = (skb_network_header_len(skb) >> 2);
l4_proto = ip6h->nexthdr;
} else {
return MVPP2_TXD_L4_CSUM_NOT;
}
return mvpp2_txq_desc_csum(skb_network_offset(skb),
skb->protocol, ip_hdr_len, l4_proto);
}
return MVPP2_TXD_L4_CSUM_NOT | MVPP2_TXD_IP_CSUM_DISABLE;
}
static void mvpp2_buff_hdr_rx(struct mvpp2_port *port,
struct mvpp2_rx_desc *rx_desc)
{
struct mvpp2_buff_hdr *buff_hdr;
struct sk_buff *skb;
u32 rx_status = rx_desc->status;
u32 buff_phys_addr;
u32 buff_virt_addr;
u32 buff_phys_addr_next;
u32 buff_virt_addr_next;
int mc_id;
int pool_id;
pool_id = (rx_status & MVPP2_RXD_BM_POOL_ID_MASK) >>
MVPP2_RXD_BM_POOL_ID_OFFS;
buff_phys_addr = rx_desc->buf_phys_addr;
buff_virt_addr = rx_desc->buf_cookie;
do {
skb = (struct sk_buff *)buff_virt_addr;
buff_hdr = (struct mvpp2_buff_hdr *)skb->head;
mc_id = MVPP2_B_HDR_INFO_MC_ID(buff_hdr->info);
buff_phys_addr_next = buff_hdr->next_buff_phys_addr;
buff_virt_addr_next = buff_hdr->next_buff_virt_addr;
/* Release buffer */
mvpp2_bm_pool_mc_put(port, pool_id, buff_phys_addr,
buff_virt_addr, mc_id);
buff_phys_addr = buff_phys_addr_next;
buff_virt_addr = buff_virt_addr_next;
} while (!MVPP2_B_HDR_INFO_IS_LAST(buff_hdr->info));
}
/* Main rx processing */
static int mvpp2_rx(struct mvpp2_port *port, int rx_todo,
struct mvpp2_rx_queue *rxq)
{
struct net_device *dev = port->dev;
int rx_received, rx_filled, i;
u32 rcvd_pkts = 0;
u32 rcvd_bytes = 0;
/* Get number of received packets and clamp the to-do */
rx_received = mvpp2_rxq_received(port, rxq->id);
if (rx_todo > rx_received)
rx_todo = rx_received;
rx_filled = 0;
for (i = 0; i < rx_todo; i++) {
struct mvpp2_rx_desc *rx_desc = mvpp2_rxq_next_desc_get(rxq);
struct mvpp2_bm_pool *bm_pool;
struct sk_buff *skb;
u32 bm, rx_status;
int pool, rx_bytes, err;
rx_filled++;
rx_status = rx_desc->status;
rx_bytes = rx_desc->data_size - MVPP2_MH_SIZE;
bm = mvpp2_bm_cookie_build(rx_desc);
pool = mvpp2_bm_cookie_pool_get(bm);
bm_pool = &port->priv->bm_pools[pool];
/* Check if buffer header is used */
if (rx_status & MVPP2_RXD_BUF_HDR) {
mvpp2_buff_hdr_rx(port, rx_desc);
continue;
}
/* In case of an error, release the requested buffer pointer
* to the Buffer Manager. This request process is controlled
* by the hardware, and the information about the buffer is
* comprised by the RX descriptor.
*/
if (rx_status & MVPP2_RXD_ERR_SUMMARY) {
dev->stats.rx_errors++;
mvpp2_rx_error(port, rx_desc);
mvpp2_pool_refill(port, bm, rx_desc->buf_phys_addr,
rx_desc->buf_cookie);
continue;
}
skb = (struct sk_buff *)rx_desc->buf_cookie;
rcvd_pkts++;
rcvd_bytes += rx_bytes;
atomic_inc(&bm_pool->in_use);
skb_reserve(skb, MVPP2_MH_SIZE);
skb_put(skb, rx_bytes);
skb->protocol = eth_type_trans(skb, dev);
mvpp2_rx_csum(port, rx_status, skb);
napi_gro_receive(&port->napi, skb);
err = mvpp2_rx_refill(port, bm_pool, bm, 0);
if (err) {
netdev_err(port->dev, "failed to refill BM pools\n");
rx_filled--;
}
}
if (rcvd_pkts) {
struct mvpp2_pcpu_stats *stats = this_cpu_ptr(port->stats);
u64_stats_update_begin(&stats->syncp);
stats->rx_packets += rcvd_pkts;
stats->rx_bytes += rcvd_bytes;
u64_stats_update_end(&stats->syncp);
}
/* Update Rx queue management counters */
wmb();
mvpp2_rxq_status_update(port, rxq->id, rx_todo, rx_filled);
return rx_todo;
}
static inline void
tx_desc_unmap_put(struct device *dev, struct mvpp2_tx_queue *txq,
struct mvpp2_tx_desc *desc)
{
dma_unmap_single(dev, desc->buf_phys_addr,
desc->data_size, DMA_TO_DEVICE);
mvpp2_txq_desc_put(txq);
}
/* Handle tx fragmentation processing */
static int mvpp2_tx_frag_process(struct mvpp2_port *port, struct sk_buff *skb,
struct mvpp2_tx_queue *aggr_txq,
struct mvpp2_tx_queue *txq)
{
struct mvpp2_txq_pcpu *txq_pcpu = this_cpu_ptr(txq->pcpu);
struct mvpp2_tx_desc *tx_desc;
int i;
dma_addr_t buf_phys_addr;
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
void *addr = page_address(frag->page.p) + frag->page_offset;
tx_desc = mvpp2_txq_next_desc_get(aggr_txq);
tx_desc->phys_txq = txq->id;
tx_desc->data_size = frag->size;
buf_phys_addr = dma_map_single(port->dev->dev.parent, addr,
tx_desc->data_size,
DMA_TO_DEVICE);
if (dma_mapping_error(port->dev->dev.parent, buf_phys_addr)) {
mvpp2_txq_desc_put(txq);
goto error;
}
tx_desc->packet_offset = buf_phys_addr & MVPP2_TX_DESC_ALIGN;
tx_desc->buf_phys_addr = buf_phys_addr & (~MVPP2_TX_DESC_ALIGN);
if (i == (skb_shinfo(skb)->nr_frags - 1)) {
/* Last descriptor */
tx_desc->command = MVPP2_TXD_L_DESC;
mvpp2_txq_inc_put(txq_pcpu, skb);
} else {
/* Descriptor in the middle: Not First, Not Last */
tx_desc->command = 0;
mvpp2_txq_inc_put(txq_pcpu, NULL);
}
}
return 0;
error:
/* Release all descriptors that were used to map fragments of
* this packet, as well as the corresponding DMA mappings
*/
for (i = i - 1; i >= 0; i--) {
tx_desc = txq->descs + i;
tx_desc_unmap_put(port->dev->dev.parent, txq, tx_desc);
}
return -ENOMEM;
}
/* Main tx processing */
static int mvpp2_tx(struct sk_buff *skb, struct net_device *dev)
{
struct mvpp2_port *port = netdev_priv(dev);
struct mvpp2_tx_queue *txq, *aggr_txq;
struct mvpp2_txq_pcpu *txq_pcpu;
struct mvpp2_tx_desc *tx_desc;
dma_addr_t buf_phys_addr;
int frags = 0;
u16 txq_id;
u32 tx_cmd;
txq_id = skb_get_queue_mapping(skb);
txq = port->txqs[txq_id];
txq_pcpu = this_cpu_ptr(txq->pcpu);
aggr_txq = &port->priv->aggr_txqs[smp_processor_id()];
frags = skb_shinfo(skb)->nr_frags + 1;
/* Check number of available descriptors */
if (mvpp2_aggr_desc_num_check(port->priv, aggr_txq, frags) ||
mvpp2_txq_reserved_desc_num_proc(port->priv, txq,
txq_pcpu, frags)) {
frags = 0;
goto out;
}
/* Get a descriptor for the first part of the packet */
tx_desc = mvpp2_txq_next_desc_get(aggr_txq);
tx_desc->phys_txq = txq->id;
tx_desc->data_size = skb_headlen(skb);
buf_phys_addr = dma_map_single(dev->dev.parent, skb->data,
tx_desc->data_size, DMA_TO_DEVICE);
if (unlikely(dma_mapping_error(dev->dev.parent, buf_phys_addr))) {
mvpp2_txq_desc_put(txq);
frags = 0;
goto out;
}
tx_desc->packet_offset = buf_phys_addr & MVPP2_TX_DESC_ALIGN;
tx_desc->buf_phys_addr = buf_phys_addr & ~MVPP2_TX_DESC_ALIGN;
tx_cmd = mvpp2_skb_tx_csum(port, skb);
if (frags == 1) {
/* First and Last descriptor */
tx_cmd |= MVPP2_TXD_F_DESC | MVPP2_TXD_L_DESC;
tx_desc->command = tx_cmd;
mvpp2_txq_inc_put(txq_pcpu, skb);
} else {
/* First but not Last */
tx_cmd |= MVPP2_TXD_F_DESC | MVPP2_TXD_PADDING_DISABLE;
tx_desc->command = tx_cmd;
mvpp2_txq_inc_put(txq_pcpu, NULL);
/* Continue with other skb fragments */
if (mvpp2_tx_frag_process(port, skb, aggr_txq, txq)) {
tx_desc_unmap_put(port->dev->dev.parent, txq, tx_desc);
frags = 0;
goto out;
}
}
txq_pcpu->reserved_num -= frags;
txq_pcpu->count += frags;
aggr_txq->count += frags;
/* Enable transmit */
wmb();
mvpp2_aggr_txq_pend_desc_add(port, frags);
if (txq_pcpu->size - txq_pcpu->count < MAX_SKB_FRAGS + 1) {
struct netdev_queue *nq = netdev_get_tx_queue(dev, txq_id);
netif_tx_stop_queue(nq);
}
out:
if (frags > 0) {
struct mvpp2_pcpu_stats *stats = this_cpu_ptr(port->stats);
u64_stats_update_begin(&stats->syncp);
stats->tx_packets++;
stats->tx_bytes += skb->len;
u64_stats_update_end(&stats->syncp);
} else {
dev->stats.tx_dropped++;
dev_kfree_skb_any(skb);
}
return NETDEV_TX_OK;
}
static inline void mvpp2_cause_error(struct net_device *dev, int cause)
{
if (cause & MVPP2_CAUSE_FCS_ERR_MASK)
netdev_err(dev, "FCS error\n");
if (cause & MVPP2_CAUSE_RX_FIFO_OVERRUN_MASK)
netdev_err(dev, "rx fifo overrun error\n");
if (cause & MVPP2_CAUSE_TX_FIFO_UNDERRUN_MASK)
netdev_err(dev, "tx fifo underrun error\n");
}
static void mvpp2_txq_done_percpu(void *arg)
{
struct mvpp2_port *port = arg;
u32 cause_rx_tx, cause_tx, cause_misc;
/* Rx/Tx cause register
*
* Bits 0-15: each bit indicates received packets on the Rx queue
* (bit 0 is for Rx queue 0).
*
* Bits 16-23: each bit indicates transmitted packets on the Tx queue
* (bit 16 is for Tx queue 0).
*
* Each CPU has its own Rx/Tx cause register
*/
cause_rx_tx = mvpp2_read(port->priv,
MVPP2_ISR_RX_TX_CAUSE_REG(port->id));
cause_tx = cause_rx_tx & MVPP2_CAUSE_TXQ_OCCUP_DESC_ALL_MASK;
cause_misc = cause_rx_tx & MVPP2_CAUSE_MISC_SUM_MASK;
if (cause_misc) {
mvpp2_cause_error(port->dev, cause_misc);
/* Clear the cause register */
mvpp2_write(port->priv, MVPP2_ISR_MISC_CAUSE_REG, 0);
mvpp2_write(port->priv, MVPP2_ISR_RX_TX_CAUSE_REG(port->id),
cause_rx_tx & ~MVPP2_CAUSE_MISC_SUM_MASK);
}
/* Release TX descriptors */
if (cause_tx) {
struct mvpp2_tx_queue *txq = mvpp2_get_tx_queue(port, cause_tx);
struct mvpp2_txq_pcpu *txq_pcpu = this_cpu_ptr(txq->pcpu);
if (txq_pcpu->count)
mvpp2_txq_done(port, txq, txq_pcpu);
}
}
static int mvpp2_poll(struct napi_struct *napi, int budget)
{
u32 cause_rx_tx, cause_rx;
int rx_done = 0;
struct mvpp2_port *port = netdev_priv(napi->dev);
on_each_cpu(mvpp2_txq_done_percpu, port, 1);
cause_rx_tx = mvpp2_read(port->priv,
MVPP2_ISR_RX_TX_CAUSE_REG(port->id));
cause_rx = cause_rx_tx & MVPP2_CAUSE_RXQ_OCCUP_DESC_ALL_MASK;
/* Process RX packets */
cause_rx |= port->pending_cause_rx;
while (cause_rx && budget > 0) {
int count;
struct mvpp2_rx_queue *rxq;
rxq = mvpp2_get_rx_queue(port, cause_rx);
if (!rxq)
break;
count = mvpp2_rx(port, budget, rxq);
rx_done += count;
budget -= count;
if (budget > 0) {
/* Clear the bit associated to this Rx queue
* so that next iteration will continue from
* the next Rx queue.
*/
cause_rx &= ~(1 << rxq->logic_rxq);
}
}
if (budget > 0) {
cause_rx = 0;
napi_complete(napi);
mvpp2_interrupts_enable(port);
}
port->pending_cause_rx = cause_rx;
return rx_done;
}
/* Set hw internals when starting port */
static void mvpp2_start_dev(struct mvpp2_port *port)
{
mvpp2_gmac_max_rx_size_set(port);
mvpp2_txp_max_tx_size_set(port);
napi_enable(&port->napi);
/* Enable interrupts on all CPUs */
mvpp2_interrupts_enable(port);
mvpp2_port_enable(port);
phy_start(port->phy_dev);
netif_tx_start_all_queues(port->dev);
}
/* Set hw internals when stopping port */
static void mvpp2_stop_dev(struct mvpp2_port *port)
{
/* Stop new packets from arriving to RXQs */
mvpp2_ingress_disable(port);
mdelay(10);
/* Disable interrupts on all CPUs */
mvpp2_interrupts_disable(port);
napi_disable(&port->napi);
netif_carrier_off(port->dev);
netif_tx_stop_all_queues(port->dev);
mvpp2_egress_disable(port);
mvpp2_port_disable(port);
phy_stop(port->phy_dev);
}
/* Return positive if MTU is valid */
static inline int mvpp2_check_mtu_valid(struct net_device *dev, int mtu)
{
if (mtu < 68) {
netdev_err(dev, "cannot change mtu to less than 68\n");
return -EINVAL;
}
/* 9676 == 9700 - 20 and rounding to 8 */
if (mtu > 9676) {
netdev_info(dev, "illegal MTU value %d, round to 9676\n", mtu);
mtu = 9676;
}
if (!IS_ALIGNED(MVPP2_RX_PKT_SIZE(mtu), 8)) {
netdev_info(dev, "illegal MTU value %d, round to %d\n", mtu,
ALIGN(MVPP2_RX_PKT_SIZE(mtu), 8));
mtu = ALIGN(MVPP2_RX_PKT_SIZE(mtu), 8);
}
return mtu;
}
static int mvpp2_check_ringparam_valid(struct net_device *dev,
struct ethtool_ringparam *ring)
{
u16 new_rx_pending = ring->rx_pending;
u16 new_tx_pending = ring->tx_pending;
if (ring->rx_pending == 0 || ring->tx_pending == 0)
return -EINVAL;
if (ring->rx_pending > MVPP2_MAX_RXD)
new_rx_pending = MVPP2_MAX_RXD;
else if (!IS_ALIGNED(ring->rx_pending, 16))
new_rx_pending = ALIGN(ring->rx_pending, 16);
if (ring->tx_pending > MVPP2_MAX_TXD)
new_tx_pending = MVPP2_MAX_TXD;
else if (!IS_ALIGNED(ring->tx_pending, 32))
new_tx_pending = ALIGN(ring->tx_pending, 32);
if (ring->rx_pending != new_rx_pending) {
netdev_info(dev, "illegal Rx ring size value %d, round to %d\n",
ring->rx_pending, new_rx_pending);
ring->rx_pending = new_rx_pending;
}
if (ring->tx_pending != new_tx_pending) {
netdev_info(dev, "illegal Tx ring size value %d, round to %d\n",
ring->tx_pending, new_tx_pending);
ring->tx_pending = new_tx_pending;
}
return 0;
}
static void mvpp2_get_mac_address(struct mvpp2_port *port, unsigned char *addr)
{
u32 mac_addr_l, mac_addr_m, mac_addr_h;
mac_addr_l = readl(port->base + MVPP2_GMAC_CTRL_1_REG);
mac_addr_m = readl(port->priv->lms_base + MVPP2_SRC_ADDR_MIDDLE);
mac_addr_h = readl(port->priv->lms_base + MVPP2_SRC_ADDR_HIGH);
addr[0] = (mac_addr_h >> 24) & 0xFF;
addr[1] = (mac_addr_h >> 16) & 0xFF;
addr[2] = (mac_addr_h >> 8) & 0xFF;
addr[3] = mac_addr_h & 0xFF;
addr[4] = mac_addr_m & 0xFF;
addr[5] = (mac_addr_l >> MVPP2_GMAC_SA_LOW_OFFS) & 0xFF;
}
static int mvpp2_phy_connect(struct mvpp2_port *port)
{
struct phy_device *phy_dev;
phy_dev = of_phy_connect(port->dev, port->phy_node, mvpp2_link_event, 0,
port->phy_interface);
if (!phy_dev) {
netdev_err(port->dev, "cannot connect to phy\n");
return -ENODEV;
}
phy_dev->supported &= PHY_GBIT_FEATURES;
phy_dev->advertising = phy_dev->supported;
port->phy_dev = phy_dev;
port->link = 0;
port->duplex = 0;
port->speed = 0;
return 0;
}
static void mvpp2_phy_disconnect(struct mvpp2_port *port)
{
phy_disconnect(port->phy_dev);
port->phy_dev = NULL;
}
static int mvpp2_open(struct net_device *dev)
{
struct mvpp2_port *port = netdev_priv(dev);
unsigned char mac_bcast[ETH_ALEN] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
int err;
err = mvpp2_prs_mac_da_accept(port->priv, port->id, mac_bcast, true);
if (err) {
netdev_err(dev, "mvpp2_prs_mac_da_accept BC failed\n");
return err;
}
err = mvpp2_prs_mac_da_accept(port->priv, port->id,
dev->dev_addr, true);
if (err) {
netdev_err(dev, "mvpp2_prs_mac_da_accept MC failed\n");
return err;
}
err = mvpp2_prs_tag_mode_set(port->priv, port->id, MVPP2_TAG_TYPE_MH);
if (err) {
netdev_err(dev, "mvpp2_prs_tag_mode_set failed\n");
return err;
}
err = mvpp2_prs_def_flow(port);
if (err) {
netdev_err(dev, "mvpp2_prs_def_flow failed\n");
return err;
}
/* Allocate the Rx/Tx queues */
err = mvpp2_setup_rxqs(port);
if (err) {
netdev_err(port->dev, "cannot allocate Rx queues\n");
return err;
}
err = mvpp2_setup_txqs(port);
if (err) {
netdev_err(port->dev, "cannot allocate Tx queues\n");
goto err_cleanup_rxqs;
}
err = request_irq(port->irq, mvpp2_isr, 0, dev->name, port);
if (err) {
netdev_err(port->dev, "cannot request IRQ %d\n", port->irq);
goto err_cleanup_txqs;
}
/* In default link is down */
netif_carrier_off(port->dev);
err = mvpp2_phy_connect(port);
if (err < 0)
goto err_free_irq;
/* Unmask interrupts on all CPUs */
on_each_cpu(mvpp2_interrupts_unmask, port, 1);
mvpp2_start_dev(port);
return 0;
err_free_irq:
free_irq(port->irq, port);
err_cleanup_txqs:
mvpp2_cleanup_txqs(port);
err_cleanup_rxqs:
mvpp2_cleanup_rxqs(port);
return err;
}
static int mvpp2_stop(struct net_device *dev)
{
struct mvpp2_port *port = netdev_priv(dev);
mvpp2_stop_dev(port);
mvpp2_phy_disconnect(port);
/* Mask interrupts on all CPUs */
on_each_cpu(mvpp2_interrupts_mask, port, 1);
free_irq(port->irq, port);
mvpp2_cleanup_rxqs(port);
mvpp2_cleanup_txqs(port);
return 0;
}
static void mvpp2_set_rx_mode(struct net_device *dev)
{
struct mvpp2_port *port = netdev_priv(dev);
struct mvpp2 *priv = port->priv;
struct netdev_hw_addr *ha;
int id = port->id;
bool allmulti = dev->flags & IFF_ALLMULTI;
mvpp2_prs_mac_promisc_set(priv, id, dev->flags & IFF_PROMISC);
mvpp2_prs_mac_multi_set(priv, id, MVPP2_PE_MAC_MC_ALL, allmulti);
mvpp2_prs_mac_multi_set(priv, id, MVPP2_PE_MAC_MC_IP6, allmulti);
/* Remove all port->id's mcast enries */
mvpp2_prs_mcast_del_all(priv, id);
if (allmulti && !netdev_mc_empty(dev)) {
netdev_for_each_mc_addr(ha, dev)
mvpp2_prs_mac_da_accept(priv, id, ha->addr, true);
}
}
static int mvpp2_set_mac_address(struct net_device *dev, void *p)
{
struct mvpp2_port *port = netdev_priv(dev);
const struct sockaddr *addr = p;
int err;
if (!is_valid_ether_addr(addr->sa_data)) {
err = -EADDRNOTAVAIL;
goto error;
}
if (!netif_running(dev)) {
err = mvpp2_prs_update_mac_da(dev, addr->sa_data);
if (!err)
return 0;
/* Reconfigure parser to accept the original MAC address */
err = mvpp2_prs_update_mac_da(dev, dev->dev_addr);
if (err)
goto error;
}
mvpp2_stop_dev(port);
err = mvpp2_prs_update_mac_da(dev, addr->sa_data);
if (!err)
goto out_start;
/* Reconfigure parser accept the original MAC address */
err = mvpp2_prs_update_mac_da(dev, dev->dev_addr);
if (err)
goto error;
out_start:
mvpp2_start_dev(port);
mvpp2_egress_enable(port);
mvpp2_ingress_enable(port);
return 0;
error:
netdev_err(dev, "fail to change MAC address\n");
return err;
}
static int mvpp2_change_mtu(struct net_device *dev, int mtu)
{
struct mvpp2_port *port = netdev_priv(dev);
int err;
mtu = mvpp2_check_mtu_valid(dev, mtu);
if (mtu < 0) {
err = mtu;
goto error;
}
if (!netif_running(dev)) {
err = mvpp2_bm_update_mtu(dev, mtu);
if (!err) {
port->pkt_size = MVPP2_RX_PKT_SIZE(mtu);
return 0;
}
/* Reconfigure BM to the original MTU */
err = mvpp2_bm_update_mtu(dev, dev->mtu);
if (err)
goto error;
}
mvpp2_stop_dev(port);
err = mvpp2_bm_update_mtu(dev, mtu);
if (!err) {
port->pkt_size = MVPP2_RX_PKT_SIZE(mtu);
goto out_start;
}
/* Reconfigure BM to the original MTU */
err = mvpp2_bm_update_mtu(dev, dev->mtu);
if (err)
goto error;
out_start:
mvpp2_start_dev(port);
mvpp2_egress_enable(port);
mvpp2_ingress_enable(port);
return 0;
error:
netdev_err(dev, "fail to change MTU\n");
return err;
}
static struct rtnl_link_stats64 *
mvpp2_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats)
{
struct mvpp2_port *port = netdev_priv(dev);
unsigned int start;
int cpu;
for_each_possible_cpu(cpu) {
struct mvpp2_pcpu_stats *cpu_stats;
u64 rx_packets;
u64 rx_bytes;
u64 tx_packets;
u64 tx_bytes;
cpu_stats = per_cpu_ptr(port->stats, cpu);
do {
start = u64_stats_fetch_begin_irq(&cpu_stats->syncp);
rx_packets = cpu_stats->rx_packets;
rx_bytes = cpu_stats->rx_bytes;
tx_packets = cpu_stats->tx_packets;
tx_bytes = cpu_stats->tx_bytes;
} while (u64_stats_fetch_retry_irq(&cpu_stats->syncp, start));
stats->rx_packets += rx_packets;
stats->rx_bytes += rx_bytes;
stats->tx_packets += tx_packets;
stats->tx_bytes += tx_bytes;
}
stats->rx_errors = dev->stats.rx_errors;
stats->rx_dropped = dev->stats.rx_dropped;
stats->tx_dropped = dev->stats.tx_dropped;
return stats;
}
static int mvpp2_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct mvpp2_port *port = netdev_priv(dev);
int ret;
if (!port->phy_dev)
return -ENOTSUPP;
ret = phy_mii_ioctl(port->phy_dev, ifr, cmd);
if (!ret)
mvpp2_link_event(dev);
return ret;
}
/* Ethtool methods */
/* Get settings (phy address, speed) for ethtools */
static int mvpp2_ethtool_get_settings(struct net_device *dev,
struct ethtool_cmd *cmd)
{
struct mvpp2_port *port = netdev_priv(dev);
if (!port->phy_dev)
return -ENODEV;
return phy_ethtool_gset(port->phy_dev, cmd);
}
/* Set settings (phy address, speed) for ethtools */
static int mvpp2_ethtool_set_settings(struct net_device *dev,
struct ethtool_cmd *cmd)
{
struct mvpp2_port *port = netdev_priv(dev);
if (!port->phy_dev)
return -ENODEV;
return phy_ethtool_sset(port->phy_dev, cmd);
}
/* Set interrupt coalescing for ethtools */
static int mvpp2_ethtool_set_coalesce(struct net_device *dev,
struct ethtool_coalesce *c)
{
struct mvpp2_port *port = netdev_priv(dev);
int queue;
for (queue = 0; queue < rxq_number; queue++) {
struct mvpp2_rx_queue *rxq = port->rxqs[queue];
rxq->time_coal = c->rx_coalesce_usecs;
rxq->pkts_coal = c->rx_max_coalesced_frames;
mvpp2_rx_pkts_coal_set(port, rxq, rxq->pkts_coal);
mvpp2_rx_time_coal_set(port, rxq, rxq->time_coal);
}
for (queue = 0; queue < txq_number; queue++) {
struct mvpp2_tx_queue *txq = port->txqs[queue];
txq->done_pkts_coal = c->tx_max_coalesced_frames;
}
on_each_cpu(mvpp2_tx_done_pkts_coal_set, port, 1);
return 0;
}
/* get coalescing for ethtools */
static int mvpp2_ethtool_get_coalesce(struct net_device *dev,
struct ethtool_coalesce *c)
{
struct mvpp2_port *port = netdev_priv(dev);
c->rx_coalesce_usecs = port->rxqs[0]->time_coal;
c->rx_max_coalesced_frames = port->rxqs[0]->pkts_coal;
c->tx_max_coalesced_frames = port->txqs[0]->done_pkts_coal;
return 0;
}
static void mvpp2_ethtool_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *drvinfo)
{
strlcpy(drvinfo->driver, MVPP2_DRIVER_NAME,
sizeof(drvinfo->driver));
strlcpy(drvinfo->version, MVPP2_DRIVER_VERSION,
sizeof(drvinfo->version));
strlcpy(drvinfo->bus_info, dev_name(&dev->dev),
sizeof(drvinfo->bus_info));
}
static void mvpp2_ethtool_get_ringparam(struct net_device *dev,
struct ethtool_ringparam *ring)
{
struct mvpp2_port *port = netdev_priv(dev);
ring->rx_max_pending = MVPP2_MAX_RXD;
ring->tx_max_pending = MVPP2_MAX_TXD;
ring->rx_pending = port->rx_ring_size;
ring->tx_pending = port->tx_ring_size;
}
static int mvpp2_ethtool_set_ringparam(struct net_device *dev,
struct ethtool_ringparam *ring)
{
struct mvpp2_port *port = netdev_priv(dev);
u16 prev_rx_ring_size = port->rx_ring_size;
u16 prev_tx_ring_size = port->tx_ring_size;
int err;
err = mvpp2_check_ringparam_valid(dev, ring);
if (err)
return err;
if (!netif_running(dev)) {
port->rx_ring_size = ring->rx_pending;
port->tx_ring_size = ring->tx_pending;
return 0;
}
/* The interface is running, so we have to force a
* reallocation of the queues
*/
mvpp2_stop_dev(port);
mvpp2_cleanup_rxqs(port);
mvpp2_cleanup_txqs(port);
port->rx_ring_size = ring->rx_pending;
port->tx_ring_size = ring->tx_pending;
err = mvpp2_setup_rxqs(port);
if (err) {
/* Reallocate Rx queues with the original ring size */
port->rx_ring_size = prev_rx_ring_size;
ring->rx_pending = prev_rx_ring_size;
err = mvpp2_setup_rxqs(port);
if (err)
goto err_out;
}
err = mvpp2_setup_txqs(port);
if (err) {
/* Reallocate Tx queues with the original ring size */
port->tx_ring_size = prev_tx_ring_size;
ring->tx_pending = prev_tx_ring_size;
err = mvpp2_setup_txqs(port);
if (err)
goto err_clean_rxqs;
}
mvpp2_start_dev(port);
mvpp2_egress_enable(port);
mvpp2_ingress_enable(port);
return 0;
err_clean_rxqs:
mvpp2_cleanup_rxqs(port);
err_out:
netdev_err(dev, "fail to change ring parameters");
return err;
}
/* Device ops */
static const struct net_device_ops mvpp2_netdev_ops = {
.ndo_open = mvpp2_open,
.ndo_stop = mvpp2_stop,
.ndo_start_xmit = mvpp2_tx,
.ndo_set_rx_mode = mvpp2_set_rx_mode,
.ndo_set_mac_address = mvpp2_set_mac_address,
.ndo_change_mtu = mvpp2_change_mtu,
.ndo_get_stats64 = mvpp2_get_stats64,
.ndo_do_ioctl = mvpp2_ioctl,
};
static const struct ethtool_ops mvpp2_eth_tool_ops = {
.get_link = ethtool_op_get_link,
.get_settings = mvpp2_ethtool_get_settings,
.set_settings = mvpp2_ethtool_set_settings,
.set_coalesce = mvpp2_ethtool_set_coalesce,
.get_coalesce = mvpp2_ethtool_get_coalesce,
.get_drvinfo = mvpp2_ethtool_get_drvinfo,
.get_ringparam = mvpp2_ethtool_get_ringparam,
.set_ringparam = mvpp2_ethtool_set_ringparam,
};
/* Driver initialization */
static void mvpp2_port_power_up(struct mvpp2_port *port)
{
mvpp2_port_mii_set(port);
mvpp2_port_periodic_xon_disable(port);
mvpp2_port_fc_adv_enable(port);
mvpp2_port_reset(port);
}
/* Initialize port HW */
static int mvpp2_port_init(struct mvpp2_port *port)
{
struct device *dev = port->dev->dev.parent;
struct mvpp2 *priv = port->priv;
struct mvpp2_txq_pcpu *txq_pcpu;
int queue, cpu, err;
if (port->first_rxq + rxq_number > MVPP2_RXQ_TOTAL_NUM)
return -EINVAL;
/* Disable port */
mvpp2_egress_disable(port);
mvpp2_port_disable(port);
port->txqs = devm_kcalloc(dev, txq_number, sizeof(*port->txqs),
GFP_KERNEL);
if (!port->txqs)
return -ENOMEM;
/* Associate physical Tx queues to this port and initialize.
* The mapping is predefined.
*/
for (queue = 0; queue < txq_number; queue++) {
int queue_phy_id = mvpp2_txq_phys(port->id, queue);
struct mvpp2_tx_queue *txq;
txq = devm_kzalloc(dev, sizeof(*txq), GFP_KERNEL);
if (!txq)
return -ENOMEM;
txq->pcpu = alloc_percpu(struct mvpp2_txq_pcpu);
if (!txq->pcpu) {
err = -ENOMEM;
goto err_free_percpu;
}
txq->id = queue_phy_id;
txq->log_id = queue;
txq->done_pkts_coal = MVPP2_TXDONE_COAL_PKTS_THRESH;
for_each_present_cpu(cpu) {
txq_pcpu = per_cpu_ptr(txq->pcpu, cpu);
txq_pcpu->cpu = cpu;
}
port->txqs[queue] = txq;
}
port->rxqs = devm_kcalloc(dev, rxq_number, sizeof(*port->rxqs),
GFP_KERNEL);
if (!port->rxqs) {
err = -ENOMEM;
goto err_free_percpu;
}
/* Allocate and initialize Rx queue for this port */
for (queue = 0; queue < rxq_number; queue++) {
struct mvpp2_rx_queue *rxq;
/* Map physical Rx queue to port's logical Rx queue */
rxq = devm_kzalloc(dev, sizeof(*rxq), GFP_KERNEL);
if (!rxq)
goto err_free_percpu;
/* Map this Rx queue to a physical queue */
rxq->id = port->first_rxq + queue;
rxq->port = port->id;
rxq->logic_rxq = queue;
port->rxqs[queue] = rxq;
}
/* Configure Rx queue group interrupt for this port */
mvpp2_write(priv, MVPP2_ISR_RXQ_GROUP_REG(port->id), rxq_number);
/* Create Rx descriptor rings */
for (queue = 0; queue < rxq_number; queue++) {
struct mvpp2_rx_queue *rxq = port->rxqs[queue];
rxq->size = port->rx_ring_size;
rxq->pkts_coal = MVPP2_RX_COAL_PKTS;
rxq->time_coal = MVPP2_RX_COAL_USEC;
}
mvpp2_ingress_disable(port);
/* Port default configuration */
mvpp2_defaults_set(port);
/* Port's classifier configuration */
mvpp2_cls_oversize_rxq_set(port);
mvpp2_cls_port_config(port);
/* Provide an initial Rx packet size */
port->pkt_size = MVPP2_RX_PKT_SIZE(port->dev->mtu);
/* Initialize pools for swf */
err = mvpp2_swf_bm_pool_init(port);
if (err)
goto err_free_percpu;
return 0;
err_free_percpu:
for (queue = 0; queue < txq_number; queue++) {
if (!port->txqs[queue])
continue;
free_percpu(port->txqs[queue]->pcpu);
}
return err;
}
/* Ports initialization */
static int mvpp2_port_probe(struct platform_device *pdev,
struct device_node *port_node,
struct mvpp2 *priv,
int *next_first_rxq)
{
struct device_node *phy_node;
struct mvpp2_port *port;
struct net_device *dev;
struct resource *res;
const char *dt_mac_addr;
const char *mac_from;
char hw_mac_addr[ETH_ALEN];
u32 id;
int features;
int phy_mode;
int priv_common_regs_num = 2;
int err, i;
dev = alloc_etherdev_mqs(sizeof(struct mvpp2_port), txq_number,
rxq_number);
if (!dev)
return -ENOMEM;
phy_node = of_parse_phandle(port_node, "phy", 0);
if (!phy_node) {
dev_err(&pdev->dev, "missing phy\n");
err = -ENODEV;
goto err_free_netdev;
}
phy_mode = of_get_phy_mode(port_node);
if (phy_mode < 0) {
dev_err(&pdev->dev, "incorrect phy mode\n");
err = phy_mode;
goto err_free_netdev;
}
if (of_property_read_u32(port_node, "port-id", &id)) {
err = -EINVAL;
dev_err(&pdev->dev, "missing port-id value\n");
goto err_free_netdev;
}
dev->tx_queue_len = MVPP2_MAX_TXD;
dev->watchdog_timeo = 5 * HZ;
dev->netdev_ops = &mvpp2_netdev_ops;
dev->ethtool_ops = &mvpp2_eth_tool_ops;
port = netdev_priv(dev);
port->irq = irq_of_parse_and_map(port_node, 0);
if (port->irq <= 0) {
err = -EINVAL;
goto err_free_netdev;
}
if (of_property_read_bool(port_node, "marvell,loopback"))
port->flags |= MVPP2_F_LOOPBACK;
port->priv = priv;
port->id = id;
port->first_rxq = *next_first_rxq;
port->phy_node = phy_node;
port->phy_interface = phy_mode;
res = platform_get_resource(pdev, IORESOURCE_MEM,
priv_common_regs_num + id);
port->base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(port->base)) {
err = PTR_ERR(port->base);
goto err_free_irq;
}
/* Alloc per-cpu stats */
port->stats = netdev_alloc_pcpu_stats(struct mvpp2_pcpu_stats);
if (!port->stats) {
err = -ENOMEM;
goto err_free_irq;
}
dt_mac_addr = of_get_mac_address(port_node);
if (dt_mac_addr && is_valid_ether_addr(dt_mac_addr)) {
mac_from = "device tree";
ether_addr_copy(dev->dev_addr, dt_mac_addr);
} else {
mvpp2_get_mac_address(port, hw_mac_addr);
if (is_valid_ether_addr(hw_mac_addr)) {
mac_from = "hardware";
ether_addr_copy(dev->dev_addr, hw_mac_addr);
} else {
mac_from = "random";
eth_hw_addr_random(dev);
}
}
port->tx_ring_size = MVPP2_MAX_TXD;
port->rx_ring_size = MVPP2_MAX_RXD;
port->dev = dev;
SET_NETDEV_DEV(dev, &pdev->dev);
err = mvpp2_port_init(port);
if (err < 0) {
dev_err(&pdev->dev, "failed to init port %d\n", id);
goto err_free_stats;
}
mvpp2_port_power_up(port);
netif_napi_add(dev, &port->napi, mvpp2_poll, NAPI_POLL_WEIGHT);
features = NETIF_F_SG | NETIF_F_IP_CSUM;
dev->features = features | NETIF_F_RXCSUM;
dev->hw_features |= features | NETIF_F_RXCSUM | NETIF_F_GRO;
dev->vlan_features |= features;
err = register_netdev(dev);
if (err < 0) {
dev_err(&pdev->dev, "failed to register netdev\n");
goto err_free_txq_pcpu;
}
netdev_info(dev, "Using %s mac address %pM\n", mac_from, dev->dev_addr);
/* Increment the first Rx queue number to be used by the next port */
*next_first_rxq += rxq_number;
priv->port_list[id] = port;
return 0;
err_free_txq_pcpu:
for (i = 0; i < txq_number; i++)
free_percpu(port->txqs[i]->pcpu);
err_free_stats:
free_percpu(port->stats);
err_free_irq:
irq_dispose_mapping(port->irq);
err_free_netdev:
free_netdev(dev);
return err;
}
/* Ports removal routine */
static void mvpp2_port_remove(struct mvpp2_port *port)
{
int i;
unregister_netdev(port->dev);
free_percpu(port->stats);
for (i = 0; i < txq_number; i++)
free_percpu(port->txqs[i]->pcpu);
irq_dispose_mapping(port->irq);
free_netdev(port->dev);
}
/* Initialize decoding windows */
static void mvpp2_conf_mbus_windows(const struct mbus_dram_target_info *dram,
struct mvpp2 *priv)
{
u32 win_enable;
int i;
for (i = 0; i < 6; i++) {
mvpp2_write(priv, MVPP2_WIN_BASE(i), 0);
mvpp2_write(priv, MVPP2_WIN_SIZE(i), 0);
if (i < 4)
mvpp2_write(priv, MVPP2_WIN_REMAP(i), 0);
}
win_enable = 0;
for (i = 0; i < dram->num_cs; i++) {
const struct mbus_dram_window *cs = dram->cs + i;
mvpp2_write(priv, MVPP2_WIN_BASE(i),
(cs->base & 0xffff0000) | (cs->mbus_attr << 8) |
dram->mbus_dram_target_id);
mvpp2_write(priv, MVPP2_WIN_SIZE(i),
(cs->size - 1) & 0xffff0000);
win_enable |= (1 << i);
}
mvpp2_write(priv, MVPP2_BASE_ADDR_ENABLE, win_enable);
}
/* Initialize Rx FIFO's */
static void mvpp2_rx_fifo_init(struct mvpp2 *priv)
{
int port;
for (port = 0; port < MVPP2_MAX_PORTS; port++) {
mvpp2_write(priv, MVPP2_RX_DATA_FIFO_SIZE_REG(port),
MVPP2_RX_FIFO_PORT_DATA_SIZE);
mvpp2_write(priv, MVPP2_RX_ATTR_FIFO_SIZE_REG(port),
MVPP2_RX_FIFO_PORT_ATTR_SIZE);
}
mvpp2_write(priv, MVPP2_RX_MIN_PKT_SIZE_REG,
MVPP2_RX_FIFO_PORT_MIN_PKT);
mvpp2_write(priv, MVPP2_RX_FIFO_INIT_REG, 0x1);
}
/* Initialize network controller common part HW */
static int mvpp2_init(struct platform_device *pdev, struct mvpp2 *priv)
{
const struct mbus_dram_target_info *dram_target_info;
int err, i;
u32 val;
/* Checks for hardware constraints */
if (rxq_number % 4 || (rxq_number > MVPP2_MAX_RXQ) ||
(txq_number > MVPP2_MAX_TXQ)) {
dev_err(&pdev->dev, "invalid queue size parameter\n");
return -EINVAL;
}
/* MBUS windows configuration */
dram_target_info = mv_mbus_dram_info();
if (dram_target_info)
mvpp2_conf_mbus_windows(dram_target_info, priv);
/* Disable HW PHY polling */
val = readl(priv->lms_base + MVPP2_PHY_AN_CFG0_REG);
val |= MVPP2_PHY_AN_STOP_SMI0_MASK;
writel(val, priv->lms_base + MVPP2_PHY_AN_CFG0_REG);
/* Allocate and initialize aggregated TXQs */
priv->aggr_txqs = devm_kcalloc(&pdev->dev, num_present_cpus(),
sizeof(struct mvpp2_tx_queue),
GFP_KERNEL);
if (!priv->aggr_txqs)
return -ENOMEM;
for_each_present_cpu(i) {
priv->aggr_txqs[i].id = i;
priv->aggr_txqs[i].size = MVPP2_AGGR_TXQ_SIZE;
err = mvpp2_aggr_txq_init(pdev, &priv->aggr_txqs[i],
MVPP2_AGGR_TXQ_SIZE, i, priv);
if (err < 0)
return err;
}
/* Rx Fifo Init */
mvpp2_rx_fifo_init(priv);
/* Reset Rx queue group interrupt configuration */
for (i = 0; i < MVPP2_MAX_PORTS; i++)
mvpp2_write(priv, MVPP2_ISR_RXQ_GROUP_REG(i), rxq_number);
writel(MVPP2_EXT_GLOBAL_CTRL_DEFAULT,
priv->lms_base + MVPP2_MNG_EXTENDED_GLOBAL_CTRL_REG);
/* Allow cache snoop when transmiting packets */
mvpp2_write(priv, MVPP2_TX_SNOOP_REG, 0x1);
/* Buffer Manager initialization */
err = mvpp2_bm_init(pdev, priv);
if (err < 0)
return err;
/* Parser default initialization */
err = mvpp2_prs_default_init(pdev, priv);
if (err < 0)
return err;
/* Classifier default initialization */
mvpp2_cls_init(priv);
return 0;
}
static int mvpp2_probe(struct platform_device *pdev)
{
struct device_node *dn = pdev->dev.of_node;
struct device_node *port_node;
struct mvpp2 *priv;
struct resource *res;
int port_count, first_rxq;
int err;
priv = devm_kzalloc(&pdev->dev, sizeof(struct mvpp2), GFP_KERNEL);
if (!priv)
return -ENOMEM;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
priv->base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(priv->base))
return PTR_ERR(priv->base);
res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
priv->lms_base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(priv->lms_base))
return PTR_ERR(priv->lms_base);
priv->pp_clk = devm_clk_get(&pdev->dev, "pp_clk");
if (IS_ERR(priv->pp_clk))
return PTR_ERR(priv->pp_clk);
err = clk_prepare_enable(priv->pp_clk);
if (err < 0)
return err;
priv->gop_clk = devm_clk_get(&pdev->dev, "gop_clk");
if (IS_ERR(priv->gop_clk)) {
err = PTR_ERR(priv->gop_clk);
goto err_pp_clk;
}
err = clk_prepare_enable(priv->gop_clk);
if (err < 0)
goto err_pp_clk;
/* Get system's tclk rate */
priv->tclk = clk_get_rate(priv->pp_clk);
/* Initialize network controller */
err = mvpp2_init(pdev, priv);
if (err < 0) {
dev_err(&pdev->dev, "failed to initialize controller\n");
goto err_gop_clk;
}
port_count = of_get_available_child_count(dn);
if (port_count == 0) {
dev_err(&pdev->dev, "no ports enabled\n");
err = -ENODEV;
goto err_gop_clk;
}
priv->port_list = devm_kcalloc(&pdev->dev, port_count,
sizeof(struct mvpp2_port *),
GFP_KERNEL);
if (!priv->port_list) {
err = -ENOMEM;
goto err_gop_clk;
}
/* Initialize ports */
first_rxq = 0;
for_each_available_child_of_node(dn, port_node) {
err = mvpp2_port_probe(pdev, port_node, priv, &first_rxq);
if (err < 0)
goto err_gop_clk;
}
platform_set_drvdata(pdev, priv);
return 0;
err_gop_clk:
clk_disable_unprepare(priv->gop_clk);
err_pp_clk:
clk_disable_unprepare(priv->pp_clk);
return err;
}
static int mvpp2_remove(struct platform_device *pdev)
{
struct mvpp2 *priv = platform_get_drvdata(pdev);
struct device_node *dn = pdev->dev.of_node;
struct device_node *port_node;
int i = 0;
for_each_available_child_of_node(dn, port_node) {
if (priv->port_list[i])
mvpp2_port_remove(priv->port_list[i]);
i++;
}
for (i = 0; i < MVPP2_BM_POOLS_NUM; i++) {
struct mvpp2_bm_pool *bm_pool = &priv->bm_pools[i];
mvpp2_bm_pool_destroy(pdev, priv, bm_pool);
}
for_each_present_cpu(i) {
struct mvpp2_tx_queue *aggr_txq = &priv->aggr_txqs[i];
dma_free_coherent(&pdev->dev,
MVPP2_AGGR_TXQ_SIZE * MVPP2_DESC_ALIGNED_SIZE,
aggr_txq->descs,
aggr_txq->descs_phys);
}
clk_disable_unprepare(priv->pp_clk);
clk_disable_unprepare(priv->gop_clk);
return 0;
}
static const struct of_device_id mvpp2_match[] = {
{ .compatible = "marvell,armada-375-pp2" },
{ }
};
MODULE_DEVICE_TABLE(of, mvpp2_match);
static struct platform_driver mvpp2_driver = {
.probe = mvpp2_probe,
.remove = mvpp2_remove,
.driver = {
.name = MVPP2_DRIVER_NAME,
.of_match_table = mvpp2_match,
},
};
module_platform_driver(mvpp2_driver);
MODULE_DESCRIPTION("Marvell PPv2 Ethernet Driver - www.marvell.com");
MODULE_AUTHOR("Marcin Wojtas <mw@semihalf.com>");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
ISTweak/android_kernel_samsung_msm8660 | arch/arm/mach-omap2/board-2430sdp.c | 2287 | 6297 | /*
* linux/arch/arm/mach-omap2/board-2430sdp.c
*
* Copyright (C) 2006 Texas Instruments
*
* Modified from mach-omap2/board-generic.c
*
* Initial Code : Based on a patch from Komal Shah and Richard Woodruff
* Updated the Code for 2430 SDP : Syed Mohammed Khasim
*
* 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/init.h>
#include <linux/platform_device.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <linux/mmc/host.h>
#include <linux/delay.h>
#include <linux/i2c/twl.h>
#include <linux/regulator/machine.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <mach/hardware.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <plat/board.h>
#include <plat/common.h>
#include <plat/gpmc.h>
#include <plat/usb.h>
#include <plat/gpmc-smc91x.h>
#include "mux.h"
#include "hsmmc.h"
#include "common-board-devices.h"
#define SDP2430_CS0_BASE 0x04000000
#define SECONDARY_LCD_GPIO 147
static struct mtd_partition sdp2430_partitions[] = {
/* bootloader (U-Boot, etc) in first sector */
{
.name = "bootloader",
.offset = 0,
.size = SZ_256K,
.mask_flags = MTD_WRITEABLE, /* force read-only */
},
/* bootloader params in the next sector */
{
.name = "params",
.offset = MTDPART_OFS_APPEND,
.size = SZ_128K,
.mask_flags = 0,
},
/* kernel */
{
.name = "kernel",
.offset = MTDPART_OFS_APPEND,
.size = SZ_2M,
.mask_flags = 0
},
/* file system */
{
.name = "filesystem",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
.mask_flags = 0
}
};
static struct physmap_flash_data sdp2430_flash_data = {
.width = 2,
.parts = sdp2430_partitions,
.nr_parts = ARRAY_SIZE(sdp2430_partitions),
};
static struct resource sdp2430_flash_resource = {
.start = SDP2430_CS0_BASE,
.end = SDP2430_CS0_BASE + SZ_64M - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device sdp2430_flash_device = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &sdp2430_flash_data,
},
.num_resources = 1,
.resource = &sdp2430_flash_resource,
};
static struct platform_device sdp2430_lcd_device = {
.name = "sdp2430_lcd",
.id = -1,
};
static struct platform_device *sdp2430_devices[] __initdata = {
&sdp2430_flash_device,
&sdp2430_lcd_device,
};
static struct omap_lcd_config sdp2430_lcd_config __initdata = {
.ctrl_name = "internal",
};
#if defined(CONFIG_SMC91X) || defined(CONFIG_SMC91x_MODULE)
static struct omap_smc91x_platform_data board_smc91x_data = {
.cs = 5,
.gpio_irq = 149,
.flags = GPMC_MUX_ADD_DATA | GPMC_TIMINGS_SMC91C96 |
IORESOURCE_IRQ_LOWLEVEL,
};
static void __init board_smc91x_init(void)
{
omap_mux_init_gpio(149, OMAP_PIN_INPUT);
gpmc_smc91x_init(&board_smc91x_data);
}
#else
static inline void board_smc91x_init(void)
{
}
#endif
static struct omap_board_config_kernel sdp2430_config[] __initdata = {
{OMAP_TAG_LCD, &sdp2430_lcd_config},
};
static void __init omap_2430sdp_init_early(void)
{
omap2_init_common_infrastructure();
omap2_init_common_devices(NULL, NULL);
}
static struct regulator_consumer_supply sdp2430_vmmc1_supplies[] = {
REGULATOR_SUPPLY("vmmc", "omap_hsmmc.0"),
};
/* VMMC1 for OMAP VDD_MMC1 (i/o) and MMC1 card */
static struct regulator_init_data sdp2430_vmmc1 = {
.constraints = {
.min_uV = 1850000,
.max_uV = 3150000,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE
| REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = ARRAY_SIZE(sdp2430_vmmc1_supplies),
.consumer_supplies = &sdp2430_vmmc1_supplies[0],
};
static struct twl4030_gpio_platform_data sdp2430_gpio_data = {
.gpio_base = OMAP_MAX_GPIO_LINES,
.irq_base = TWL4030_GPIO_IRQ_BASE,
.irq_end = TWL4030_GPIO_IRQ_END,
};
static struct twl4030_platform_data sdp2430_twldata = {
.irq_base = TWL4030_IRQ_BASE,
.irq_end = TWL4030_IRQ_END,
/* platform_data for children goes here */
.gpio = &sdp2430_gpio_data,
.vmmc1 = &sdp2430_vmmc1,
};
static struct i2c_board_info __initdata sdp2430_i2c1_boardinfo[] = {
{
I2C_BOARD_INFO("isp1301_omap", 0x2D),
.flags = I2C_CLIENT_WAKE,
.irq = OMAP_GPIO_IRQ(78),
},
};
static int __init omap2430_i2c_init(void)
{
omap_register_i2c_bus(1, 100, sdp2430_i2c1_boardinfo,
ARRAY_SIZE(sdp2430_i2c1_boardinfo));
omap2_pmic_init("twl4030", &sdp2430_twldata);
return 0;
}
static struct omap2_hsmmc_info mmc[] __initdata = {
{
.mmc = 1,
.caps = MMC_CAP_4_BIT_DATA,
.gpio_cd = -EINVAL,
.gpio_wp = -EINVAL,
.ext_clock = 1,
},
{} /* Terminator */
};
static struct omap_usb_config sdp2430_usb_config __initdata = {
.otg = 1,
#ifdef CONFIG_USB_GADGET_OMAP
.hmc_mode = 0x0,
#elif defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE)
.hmc_mode = 0x1,
#endif
.pins[0] = 3,
};
#ifdef CONFIG_OMAP_MUX
static struct omap_board_mux board_mux[] __initdata = {
{ .reg_offset = OMAP_MUX_TERMINATOR },
};
#endif
static void __init omap_2430sdp_init(void)
{
omap2430_mux_init(board_mux, OMAP_PACKAGE_ZAC);
omap_board_config = sdp2430_config;
omap_board_config_size = ARRAY_SIZE(sdp2430_config);
omap2430_i2c_init();
platform_add_devices(sdp2430_devices, ARRAY_SIZE(sdp2430_devices));
omap_serial_init();
omap2_hsmmc_init(mmc);
omap2_usbfs_init(&sdp2430_usb_config);
omap_mux_init_signal("usb0hs_stp", OMAP_PULL_ENA | OMAP_PULL_UP);
usb_musb_init(NULL);
board_smc91x_init();
/* Turn off secondary LCD backlight */
gpio_request_one(SECONDARY_LCD_GPIO, GPIOF_OUT_INIT_LOW,
"Secondary LCD backlight");
}
static void __init omap_2430sdp_map_io(void)
{
omap2_set_globals_243x();
omap243x_map_common_io();
}
MACHINE_START(OMAP_2430SDP, "OMAP2430 sdp2430 board")
/* Maintainer: Syed Khasim - Texas Instruments Inc */
.boot_params = 0x80000100,
.reserve = omap_reserve,
.map_io = omap_2430sdp_map_io,
.init_early = omap_2430sdp_init_early,
.init_irq = omap_init_irq,
.init_machine = omap_2430sdp_init,
.timer = &omap_timer,
MACHINE_END
| gpl-2.0 |
aosp/kernel-omap | drivers/net/wireless/ath/ath9k/ar9003_paprd.c | 2287 | 28506 | /*
* Copyright (c) 2010-2011 Atheros Communications Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <linux/export.h>
#include "hw.h"
#include "ar9003_phy.h"
void ar9003_paprd_enable(struct ath_hw *ah, bool val)
{
struct ath9k_channel *chan = ah->curchan;
struct ar9300_eeprom *eep = &ah->eeprom.ar9300_eep;
/*
* 3 bits for modalHeader5G.papdRateMaskHt20
* is used for sub-band disabling of PAPRD.
* 5G band is divided into 3 sub-bands -- upper,
* middle, lower.
* if bit 30 of modalHeader5G.papdRateMaskHt20 is set
* -- disable PAPRD for upper band 5GHz
* if bit 29 of modalHeader5G.papdRateMaskHt20 is set
* -- disable PAPRD for middle band 5GHz
* if bit 28 of modalHeader5G.papdRateMaskHt20 is set
* -- disable PAPRD for lower band 5GHz
*/
if (IS_CHAN_5GHZ(chan)) {
if (chan->channel >= UPPER_5G_SUB_BAND_START) {
if (le32_to_cpu(eep->modalHeader5G.papdRateMaskHt20)
& BIT(30))
val = false;
} else if (chan->channel >= MID_5G_SUB_BAND_START) {
if (le32_to_cpu(eep->modalHeader5G.papdRateMaskHt20)
& BIT(29))
val = false;
} else {
if (le32_to_cpu(eep->modalHeader5G.papdRateMaskHt20)
& BIT(28))
val = false;
}
}
if (val) {
ah->paprd_table_write_done = true;
ath9k_hw_apply_txpower(ah, chan, false);
}
REG_RMW_FIELD(ah, AR_PHY_PAPRD_CTRL0_B0,
AR_PHY_PAPRD_CTRL0_PAPRD_ENABLE, !!val);
if (ah->caps.tx_chainmask & BIT(1))
REG_RMW_FIELD(ah, AR_PHY_PAPRD_CTRL0_B1,
AR_PHY_PAPRD_CTRL0_PAPRD_ENABLE, !!val);
if (ah->caps.tx_chainmask & BIT(2))
REG_RMW_FIELD(ah, AR_PHY_PAPRD_CTRL0_B2,
AR_PHY_PAPRD_CTRL0_PAPRD_ENABLE, !!val);
}
EXPORT_SYMBOL(ar9003_paprd_enable);
static int ar9003_get_training_power_2g(struct ath_hw *ah)
{
struct ath9k_channel *chan = ah->curchan;
unsigned int power, scale, delta;
scale = ar9003_get_paprd_scale_factor(ah, chan);
if (AR_SREV_9330(ah) || AR_SREV_9340(ah) ||
AR_SREV_9462(ah) || AR_SREV_9565(ah)) {
power = ah->paprd_target_power + 2;
} else if (AR_SREV_9485(ah)) {
power = 25;
} else {
power = REG_READ_FIELD(ah, AR_PHY_POWERTX_RATE5,
AR_PHY_POWERTX_RATE5_POWERTXHT20_0);
delta = abs((int) ah->paprd_target_power - (int) power);
if (delta > scale)
return -1;
if (delta < 4)
power -= 4 - delta;
}
return power;
}
static int ar9003_get_training_power_5g(struct ath_hw *ah)
{
struct ath_common *common = ath9k_hw_common(ah);
struct ath9k_channel *chan = ah->curchan;
unsigned int power, scale, delta;
scale = ar9003_get_paprd_scale_factor(ah, chan);
if (IS_CHAN_HT40(chan))
power = REG_READ_FIELD(ah, AR_PHY_POWERTX_RATE8,
AR_PHY_POWERTX_RATE8_POWERTXHT40_5);
else
power = REG_READ_FIELD(ah, AR_PHY_POWERTX_RATE6,
AR_PHY_POWERTX_RATE6_POWERTXHT20_5);
power += scale;
delta = abs((int) ah->paprd_target_power - (int) power);
if (delta > scale)
return -1;
switch (get_streams(ah->txchainmask)) {
case 1:
delta = 6;
break;
case 2:
delta = 4;
break;
case 3:
delta = 2;
break;
default:
delta = 0;
ath_dbg(common, CALIBRATE, "Invalid tx-chainmask: %u\n",
ah->txchainmask);
}
power += delta;
return power;
}
static int ar9003_paprd_setup_single_table(struct ath_hw *ah)
{
struct ath_common *common = ath9k_hw_common(ah);
static const u32 ctrl0[3] = {
AR_PHY_PAPRD_CTRL0_B0,
AR_PHY_PAPRD_CTRL0_B1,
AR_PHY_PAPRD_CTRL0_B2
};
static const u32 ctrl1[3] = {
AR_PHY_PAPRD_CTRL1_B0,
AR_PHY_PAPRD_CTRL1_B1,
AR_PHY_PAPRD_CTRL1_B2
};
int training_power;
int i, val;
u32 am2pm_mask = ah->paprd_ratemask;
if (IS_CHAN_2GHZ(ah->curchan))
training_power = ar9003_get_training_power_2g(ah);
else
training_power = ar9003_get_training_power_5g(ah);
ath_dbg(common, CALIBRATE, "Training power: %d, Target power: %d\n",
training_power, ah->paprd_target_power);
if (training_power < 0) {
ath_dbg(common, CALIBRATE,
"PAPRD target power delta out of range\n");
return -ERANGE;
}
ah->paprd_training_power = training_power;
if (AR_SREV_9330(ah))
am2pm_mask = 0;
REG_RMW_FIELD(ah, AR_PHY_PAPRD_AM2AM, AR_PHY_PAPRD_AM2AM_MASK,
ah->paprd_ratemask);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_AM2PM, AR_PHY_PAPRD_AM2PM_MASK,
am2pm_mask);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_HT40, AR_PHY_PAPRD_HT40_MASK,
ah->paprd_ratemask_ht40);
ath_dbg(common, CALIBRATE, "PAPRD HT20 mask: 0x%x, HT40 mask: 0x%x\n",
ah->paprd_ratemask, ah->paprd_ratemask_ht40);
for (i = 0; i < ah->caps.max_txchains; i++) {
REG_RMW_FIELD(ah, ctrl0[i],
AR_PHY_PAPRD_CTRL0_USE_SINGLE_TABLE_MASK, 1);
REG_RMW_FIELD(ah, ctrl1[i],
AR_PHY_PAPRD_CTRL1_ADAPTIVE_AM2PM_ENABLE, 1);
REG_RMW_FIELD(ah, ctrl1[i],
AR_PHY_PAPRD_CTRL1_ADAPTIVE_AM2AM_ENABLE, 1);
REG_RMW_FIELD(ah, ctrl1[i],
AR_PHY_PAPRD_CTRL1_ADAPTIVE_SCALING_ENA, 0);
REG_RMW_FIELD(ah, ctrl1[i],
AR_PHY_PAPRD_CTRL1_PA_GAIN_SCALE_FACT_MASK, 181);
REG_RMW_FIELD(ah, ctrl1[i],
AR_PHY_PAPRD_CTRL1_PAPRD_MAG_SCALE_FACT, 361);
REG_RMW_FIELD(ah, ctrl1[i],
AR_PHY_PAPRD_CTRL1_ADAPTIVE_SCALING_ENA, 0);
REG_RMW_FIELD(ah, ctrl0[i],
AR_PHY_PAPRD_CTRL0_PAPRD_MAG_THRSH, 3);
}
ar9003_paprd_enable(ah, false);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL1,
AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_LB_SKIP, 0x30);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL1,
AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_LB_ENABLE, 1);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL1,
AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_TX_GAIN_FORCE, 1);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL1,
AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_RX_BB_GAIN_FORCE, 0);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL1,
AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_IQCORR_ENABLE, 0);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL1,
AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_AGC2_SETTLING, 28);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL1,
AR_PHY_PAPRD_TRAINER_CNTL1_CF_CF_PAPRD_TRAIN_ENABLE, 1);
if (AR_SREV_9485(ah)) {
val = 148;
} else {
if (IS_CHAN_2GHZ(ah->curchan)) {
if (AR_SREV_9462(ah) || AR_SREV_9565(ah))
val = 145;
else
val = 147;
} else {
val = 137;
}
}
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL2,
AR_PHY_PAPRD_TRAINER_CNTL2_CF_PAPRD_INIT_RX_BB_GAIN, val);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL3,
AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_FINE_CORR_LEN, 4);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL3,
AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_COARSE_CORR_LEN, 4);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL3,
AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_NUM_CORR_STAGES, 7);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL3,
AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_MIN_LOOPBACK_DEL, 1);
if (AR_SREV_9485(ah) ||
AR_SREV_9462(ah) ||
AR_SREV_9565(ah) ||
AR_SREV_9550(ah) ||
AR_SREV_9330(ah) ||
AR_SREV_9340(ah))
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL3,
AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_QUICK_DROP, -3);
else
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL3,
AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_QUICK_DROP, -6);
val = -10;
if (IS_CHAN_2GHZ(ah->curchan) && !AR_SREV_9462(ah) && !AR_SREV_9565(ah))
val = -15;
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL3,
AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_ADC_DESIRED_SIZE,
val);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL3,
AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_BBTXMIX_DISABLE, 1);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL4,
AR_PHY_PAPRD_TRAINER_CNTL4_CF_PAPRD_SAFETY_DELTA, 0);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL4,
AR_PHY_PAPRD_TRAINER_CNTL4_CF_PAPRD_MIN_CORR, 400);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL4,
AR_PHY_PAPRD_TRAINER_CNTL4_CF_PAPRD_NUM_TRAIN_SAMPLES,
100);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_PRE_POST_SCALE_0_B0,
AR_PHY_PAPRD_PRE_POST_SCALING, 261376);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_PRE_POST_SCALE_1_B0,
AR_PHY_PAPRD_PRE_POST_SCALING, 248079);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_PRE_POST_SCALE_2_B0,
AR_PHY_PAPRD_PRE_POST_SCALING, 233759);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_PRE_POST_SCALE_3_B0,
AR_PHY_PAPRD_PRE_POST_SCALING, 220464);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_PRE_POST_SCALE_4_B0,
AR_PHY_PAPRD_PRE_POST_SCALING, 208194);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_PRE_POST_SCALE_5_B0,
AR_PHY_PAPRD_PRE_POST_SCALING, 196949);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_PRE_POST_SCALE_6_B0,
AR_PHY_PAPRD_PRE_POST_SCALING, 185706);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_PRE_POST_SCALE_7_B0,
AR_PHY_PAPRD_PRE_POST_SCALING, 175487);
return 0;
}
static void ar9003_paprd_get_gain_table(struct ath_hw *ah)
{
u32 *entry = ah->paprd_gain_table_entries;
u8 *index = ah->paprd_gain_table_index;
u32 reg = AR_PHY_TXGAIN_TABLE;
int i;
for (i = 0; i < PAPRD_GAIN_TABLE_ENTRIES; i++) {
entry[i] = REG_READ(ah, reg);
index[i] = (entry[i] >> 24) & 0xff;
reg += 4;
}
}
static unsigned int ar9003_get_desired_gain(struct ath_hw *ah, int chain,
int target_power)
{
int olpc_gain_delta = 0, cl_gain_mod;
int alpha_therm, alpha_volt;
int therm_cal_value, volt_cal_value;
int therm_value, volt_value;
int thermal_gain_corr, voltage_gain_corr;
int desired_scale, desired_gain = 0;
u32 reg_olpc = 0, reg_cl_gain = 0;
REG_CLR_BIT(ah, AR_PHY_PAPRD_TRAINER_STAT1,
AR_PHY_PAPRD_TRAINER_STAT1_PAPRD_TRAIN_DONE);
desired_scale = REG_READ_FIELD(ah, AR_PHY_TPC_12,
AR_PHY_TPC_12_DESIRED_SCALE_HT40_5);
alpha_therm = REG_READ_FIELD(ah, AR_PHY_TPC_19,
AR_PHY_TPC_19_ALPHA_THERM);
alpha_volt = REG_READ_FIELD(ah, AR_PHY_TPC_19,
AR_PHY_TPC_19_ALPHA_VOLT);
therm_cal_value = REG_READ_FIELD(ah, AR_PHY_TPC_18,
AR_PHY_TPC_18_THERM_CAL_VALUE);
volt_cal_value = REG_READ_FIELD(ah, AR_PHY_TPC_18,
AR_PHY_TPC_18_VOLT_CAL_VALUE);
therm_value = REG_READ_FIELD(ah, AR_PHY_BB_THERM_ADC_4,
AR_PHY_BB_THERM_ADC_4_LATEST_THERM_VALUE);
volt_value = REG_READ_FIELD(ah, AR_PHY_BB_THERM_ADC_4,
AR_PHY_BB_THERM_ADC_4_LATEST_VOLT_VALUE);
switch (chain) {
case 0:
reg_olpc = AR_PHY_TPC_11_B0;
reg_cl_gain = AR_PHY_CL_TAB_0;
break;
case 1:
reg_olpc = AR_PHY_TPC_11_B1;
reg_cl_gain = AR_PHY_CL_TAB_1;
break;
case 2:
reg_olpc = AR_PHY_TPC_11_B2;
reg_cl_gain = AR_PHY_CL_TAB_2;
break;
default:
ath_dbg(ath9k_hw_common(ah), CALIBRATE,
"Invalid chainmask: %d\n", chain);
break;
}
olpc_gain_delta = REG_READ_FIELD(ah, reg_olpc,
AR_PHY_TPC_11_OLPC_GAIN_DELTA);
cl_gain_mod = REG_READ_FIELD(ah, reg_cl_gain,
AR_PHY_CL_TAB_CL_GAIN_MOD);
if (olpc_gain_delta >= 128)
olpc_gain_delta = olpc_gain_delta - 256;
thermal_gain_corr = (alpha_therm * (therm_value - therm_cal_value) +
(256 / 2)) / 256;
voltage_gain_corr = (alpha_volt * (volt_value - volt_cal_value) +
(128 / 2)) / 128;
desired_gain = target_power - olpc_gain_delta - thermal_gain_corr -
voltage_gain_corr + desired_scale + cl_gain_mod;
return desired_gain;
}
static void ar9003_tx_force_gain(struct ath_hw *ah, unsigned int gain_index)
{
int selected_gain_entry, txbb1dbgain, txbb6dbgain, txmxrgain;
int padrvgnA, padrvgnB, padrvgnC, padrvgnD;
u32 *gain_table_entries = ah->paprd_gain_table_entries;
selected_gain_entry = gain_table_entries[gain_index];
txbb1dbgain = selected_gain_entry & 0x7;
txbb6dbgain = (selected_gain_entry >> 3) & 0x3;
txmxrgain = (selected_gain_entry >> 5) & 0xf;
padrvgnA = (selected_gain_entry >> 9) & 0xf;
padrvgnB = (selected_gain_entry >> 13) & 0xf;
padrvgnC = (selected_gain_entry >> 17) & 0xf;
padrvgnD = (selected_gain_entry >> 21) & 0x3;
REG_RMW_FIELD(ah, AR_PHY_TX_FORCED_GAIN,
AR_PHY_TX_FORCED_GAIN_FORCED_TXBB1DBGAIN, txbb1dbgain);
REG_RMW_FIELD(ah, AR_PHY_TX_FORCED_GAIN,
AR_PHY_TX_FORCED_GAIN_FORCED_TXBB6DBGAIN, txbb6dbgain);
REG_RMW_FIELD(ah, AR_PHY_TX_FORCED_GAIN,
AR_PHY_TX_FORCED_GAIN_FORCED_TXMXRGAIN, txmxrgain);
REG_RMW_FIELD(ah, AR_PHY_TX_FORCED_GAIN,
AR_PHY_TX_FORCED_GAIN_FORCED_PADRVGNA, padrvgnA);
REG_RMW_FIELD(ah, AR_PHY_TX_FORCED_GAIN,
AR_PHY_TX_FORCED_GAIN_FORCED_PADRVGNB, padrvgnB);
REG_RMW_FIELD(ah, AR_PHY_TX_FORCED_GAIN,
AR_PHY_TX_FORCED_GAIN_FORCED_PADRVGNC, padrvgnC);
REG_RMW_FIELD(ah, AR_PHY_TX_FORCED_GAIN,
AR_PHY_TX_FORCED_GAIN_FORCED_PADRVGND, padrvgnD);
REG_RMW_FIELD(ah, AR_PHY_TX_FORCED_GAIN,
AR_PHY_TX_FORCED_GAIN_FORCED_ENABLE_PAL, 0);
REG_RMW_FIELD(ah, AR_PHY_TX_FORCED_GAIN,
AR_PHY_TX_FORCED_GAIN_FORCE_TX_GAIN, 0);
REG_RMW_FIELD(ah, AR_PHY_TPC_1, AR_PHY_TPC_1_FORCED_DAC_GAIN, 0);
REG_RMW_FIELD(ah, AR_PHY_TPC_1, AR_PHY_TPC_1_FORCE_DAC_GAIN, 0);
}
static inline int find_expn(int num)
{
return fls(num) - 1;
}
static inline int find_proper_scale(int expn, int N)
{
return (expn > N) ? expn - 10 : 0;
}
#define NUM_BIN 23
static bool create_pa_curve(u32 *data_L, u32 *data_U, u32 *pa_table, u16 *gain)
{
unsigned int thresh_accum_cnt;
int x_est[NUM_BIN + 1], Y[NUM_BIN + 1], theta[NUM_BIN + 1];
int PA_in[NUM_BIN + 1];
int B1_tmp[NUM_BIN + 1], B2_tmp[NUM_BIN + 1];
unsigned int B1_abs_max, B2_abs_max;
int max_index, scale_factor;
int y_est[NUM_BIN + 1];
int x_est_fxp1_nonlin, x_tilde[NUM_BIN + 1];
unsigned int x_tilde_abs;
int G_fxp, Y_intercept, order_x_by_y, M, I, L, sum_y_sqr, sum_y_quad;
int Q_x, Q_B1, Q_B2, beta_raw, alpha_raw, scale_B;
int Q_scale_B, Q_beta, Q_alpha, alpha, beta, order_1, order_2;
int order1_5x, order2_3x, order1_5x_rem, order2_3x_rem;
int y5, y3, tmp;
int theta_low_bin = 0;
int i;
/* disregard any bin that contains <= 16 samples */
thresh_accum_cnt = 16;
scale_factor = 5;
max_index = 0;
memset(theta, 0, sizeof(theta));
memset(x_est, 0, sizeof(x_est));
memset(Y, 0, sizeof(Y));
memset(y_est, 0, sizeof(y_est));
memset(x_tilde, 0, sizeof(x_tilde));
for (i = 0; i < NUM_BIN; i++) {
s32 accum_cnt, accum_tx, accum_rx, accum_ang;
/* number of samples */
accum_cnt = data_L[i] & 0xffff;
if (accum_cnt <= thresh_accum_cnt)
continue;
/* sum(tx amplitude) */
accum_tx = ((data_L[i] >> 16) & 0xffff) |
((data_U[i] & 0x7ff) << 16);
/* sum(rx amplitude distance to lower bin edge) */
accum_rx = ((data_U[i] >> 11) & 0x1f) |
((data_L[i + 23] & 0xffff) << 5);
/* sum(angles) */
accum_ang = ((data_L[i + 23] >> 16) & 0xffff) |
((data_U[i + 23] & 0x7ff) << 16);
accum_tx <<= scale_factor;
accum_rx <<= scale_factor;
x_est[i + 1] = (((accum_tx + accum_cnt) / accum_cnt) + 32) >>
scale_factor;
Y[i + 1] = ((((accum_rx + accum_cnt) / accum_cnt) + 32) >>
scale_factor) +
(1 << scale_factor) * max_index + 16;
if (accum_ang >= (1 << 26))
accum_ang -= 1 << 27;
theta[i + 1] = ((accum_ang * (1 << scale_factor)) + accum_cnt) /
accum_cnt;
max_index++;
}
/*
* Find average theta of first 5 bin and all of those to same value.
* Curve is linear at that range.
*/
for (i = 1; i < 6; i++)
theta_low_bin += theta[i];
theta_low_bin = theta_low_bin / 5;
for (i = 1; i < 6; i++)
theta[i] = theta_low_bin;
/* Set values at origin */
theta[0] = theta_low_bin;
for (i = 0; i <= max_index; i++)
theta[i] -= theta_low_bin;
x_est[0] = 0;
Y[0] = 0;
scale_factor = 8;
/* low signal gain */
if (x_est[6] == x_est[3])
return false;
G_fxp =
(((Y[6] - Y[3]) * 1 << scale_factor) +
(x_est[6] - x_est[3])) / (x_est[6] - x_est[3]);
/* prevent division by zero */
if (G_fxp == 0)
return false;
Y_intercept =
(G_fxp * (x_est[0] - x_est[3]) +
(1 << scale_factor)) / (1 << scale_factor) + Y[3];
for (i = 0; i <= max_index; i++)
y_est[i] = Y[i] - Y_intercept;
for (i = 0; i <= 3; i++) {
y_est[i] = i * 32;
x_est[i] = ((y_est[i] * 1 << scale_factor) + G_fxp) / G_fxp;
}
if (y_est[max_index] == 0)
return false;
x_est_fxp1_nonlin =
x_est[max_index] - ((1 << scale_factor) * y_est[max_index] +
G_fxp) / G_fxp;
order_x_by_y =
(x_est_fxp1_nonlin + y_est[max_index]) / y_est[max_index];
if (order_x_by_y == 0)
M = 10;
else if (order_x_by_y == 1)
M = 9;
else
M = 8;
I = (max_index > 15) ? 7 : max_index >> 1;
L = max_index - I;
scale_factor = 8;
sum_y_sqr = 0;
sum_y_quad = 0;
x_tilde_abs = 0;
for (i = 0; i <= L; i++) {
unsigned int y_sqr;
unsigned int y_quad;
unsigned int tmp_abs;
/* prevent division by zero */
if (y_est[i + I] == 0)
return false;
x_est_fxp1_nonlin =
x_est[i + I] - ((1 << scale_factor) * y_est[i + I] +
G_fxp) / G_fxp;
x_tilde[i] =
(x_est_fxp1_nonlin * (1 << M) + y_est[i + I]) / y_est[i +
I];
x_tilde[i] =
(x_tilde[i] * (1 << M) + y_est[i + I]) / y_est[i + I];
x_tilde[i] =
(x_tilde[i] * (1 << M) + y_est[i + I]) / y_est[i + I];
y_sqr =
(y_est[i + I] * y_est[i + I] +
(scale_factor * scale_factor)) / (scale_factor *
scale_factor);
tmp_abs = abs(x_tilde[i]);
if (tmp_abs > x_tilde_abs)
x_tilde_abs = tmp_abs;
y_quad = y_sqr * y_sqr;
sum_y_sqr = sum_y_sqr + y_sqr;
sum_y_quad = sum_y_quad + y_quad;
B1_tmp[i] = y_sqr * (L + 1);
B2_tmp[i] = y_sqr;
}
B1_abs_max = 0;
B2_abs_max = 0;
for (i = 0; i <= L; i++) {
int abs_val;
B1_tmp[i] -= sum_y_sqr;
B2_tmp[i] = sum_y_quad - sum_y_sqr * B2_tmp[i];
abs_val = abs(B1_tmp[i]);
if (abs_val > B1_abs_max)
B1_abs_max = abs_val;
abs_val = abs(B2_tmp[i]);
if (abs_val > B2_abs_max)
B2_abs_max = abs_val;
}
Q_x = find_proper_scale(find_expn(x_tilde_abs), 10);
Q_B1 = find_proper_scale(find_expn(B1_abs_max), 10);
Q_B2 = find_proper_scale(find_expn(B2_abs_max), 10);
beta_raw = 0;
alpha_raw = 0;
for (i = 0; i <= L; i++) {
x_tilde[i] = x_tilde[i] / (1 << Q_x);
B1_tmp[i] = B1_tmp[i] / (1 << Q_B1);
B2_tmp[i] = B2_tmp[i] / (1 << Q_B2);
beta_raw = beta_raw + B1_tmp[i] * x_tilde[i];
alpha_raw = alpha_raw + B2_tmp[i] * x_tilde[i];
}
scale_B =
((sum_y_quad / scale_factor) * (L + 1) -
(sum_y_sqr / scale_factor) * sum_y_sqr) * scale_factor;
Q_scale_B = find_proper_scale(find_expn(abs(scale_B)), 10);
scale_B = scale_B / (1 << Q_scale_B);
if (scale_B == 0)
return false;
Q_beta = find_proper_scale(find_expn(abs(beta_raw)), 10);
Q_alpha = find_proper_scale(find_expn(abs(alpha_raw)), 10);
beta_raw = beta_raw / (1 << Q_beta);
alpha_raw = alpha_raw / (1 << Q_alpha);
alpha = (alpha_raw << 10) / scale_B;
beta = (beta_raw << 10) / scale_B;
order_1 = 3 * M - Q_x - Q_B1 - Q_beta + 10 + Q_scale_B;
order_2 = 3 * M - Q_x - Q_B2 - Q_alpha + 10 + Q_scale_B;
order1_5x = order_1 / 5;
order2_3x = order_2 / 3;
order1_5x_rem = order_1 - 5 * order1_5x;
order2_3x_rem = order_2 - 3 * order2_3x;
for (i = 0; i < PAPRD_TABLE_SZ; i++) {
tmp = i * 32;
y5 = ((beta * tmp) >> 6) >> order1_5x;
y5 = (y5 * tmp) >> order1_5x;
y5 = (y5 * tmp) >> order1_5x;
y5 = (y5 * tmp) >> order1_5x;
y5 = (y5 * tmp) >> order1_5x;
y5 = y5 >> order1_5x_rem;
y3 = (alpha * tmp) >> order2_3x;
y3 = (y3 * tmp) >> order2_3x;
y3 = (y3 * tmp) >> order2_3x;
y3 = y3 >> order2_3x_rem;
PA_in[i] = y5 + y3 + (256 * tmp) / G_fxp;
if (i >= 2) {
tmp = PA_in[i] - PA_in[i - 1];
if (tmp < 0)
PA_in[i] =
PA_in[i - 1] + (PA_in[i - 1] -
PA_in[i - 2]);
}
PA_in[i] = (PA_in[i] < 1400) ? PA_in[i] : 1400;
}
beta_raw = 0;
alpha_raw = 0;
for (i = 0; i <= L; i++) {
int theta_tilde =
((theta[i + I] << M) + y_est[i + I]) / y_est[i + I];
theta_tilde =
((theta_tilde << M) + y_est[i + I]) / y_est[i + I];
theta_tilde =
((theta_tilde << M) + y_est[i + I]) / y_est[i + I];
beta_raw = beta_raw + B1_tmp[i] * theta_tilde;
alpha_raw = alpha_raw + B2_tmp[i] * theta_tilde;
}
Q_beta = find_proper_scale(find_expn(abs(beta_raw)), 10);
Q_alpha = find_proper_scale(find_expn(abs(alpha_raw)), 10);
beta_raw = beta_raw / (1 << Q_beta);
alpha_raw = alpha_raw / (1 << Q_alpha);
alpha = (alpha_raw << 10) / scale_B;
beta = (beta_raw << 10) / scale_B;
order_1 = 3 * M - Q_x - Q_B1 - Q_beta + 10 + Q_scale_B + 5;
order_2 = 3 * M - Q_x - Q_B2 - Q_alpha + 10 + Q_scale_B + 5;
order1_5x = order_1 / 5;
order2_3x = order_2 / 3;
order1_5x_rem = order_1 - 5 * order1_5x;
order2_3x_rem = order_2 - 3 * order2_3x;
for (i = 0; i < PAPRD_TABLE_SZ; i++) {
int PA_angle;
/* pa_table[4] is calculated from PA_angle for i=5 */
if (i == 4)
continue;
tmp = i * 32;
if (beta > 0)
y5 = (((beta * tmp - 64) >> 6) -
(1 << order1_5x)) / (1 << order1_5x);
else
y5 = ((((beta * tmp - 64) >> 6) +
(1 << order1_5x)) / (1 << order1_5x));
y5 = (y5 * tmp) / (1 << order1_5x);
y5 = (y5 * tmp) / (1 << order1_5x);
y5 = (y5 * tmp) / (1 << order1_5x);
y5 = (y5 * tmp) / (1 << order1_5x);
y5 = y5 / (1 << order1_5x_rem);
if (beta > 0)
y3 = (alpha * tmp -
(1 << order2_3x)) / (1 << order2_3x);
else
y3 = (alpha * tmp +
(1 << order2_3x)) / (1 << order2_3x);
y3 = (y3 * tmp) / (1 << order2_3x);
y3 = (y3 * tmp) / (1 << order2_3x);
y3 = y3 / (1 << order2_3x_rem);
if (i < 4) {
PA_angle = 0;
} else {
PA_angle = y5 + y3;
if (PA_angle < -150)
PA_angle = -150;
else if (PA_angle > 150)
PA_angle = 150;
}
pa_table[i] = ((PA_in[i] & 0x7ff) << 11) + (PA_angle & 0x7ff);
if (i == 5) {
PA_angle = (PA_angle + 2) >> 1;
pa_table[i - 1] = ((PA_in[i - 1] & 0x7ff) << 11) +
(PA_angle & 0x7ff);
}
}
*gain = G_fxp;
return true;
}
void ar9003_paprd_populate_single_table(struct ath_hw *ah,
struct ath9k_hw_cal_data *caldata,
int chain)
{
u32 *paprd_table_val = caldata->pa_table[chain];
u32 small_signal_gain = caldata->small_signal_gain[chain];
u32 training_power = ah->paprd_training_power;
u32 reg = 0;
int i;
if (chain == 0)
reg = AR_PHY_PAPRD_MEM_TAB_B0;
else if (chain == 1)
reg = AR_PHY_PAPRD_MEM_TAB_B1;
else if (chain == 2)
reg = AR_PHY_PAPRD_MEM_TAB_B2;
for (i = 0; i < PAPRD_TABLE_SZ; i++) {
REG_WRITE(ah, reg, paprd_table_val[i]);
reg = reg + 4;
}
if (chain == 0)
reg = AR_PHY_PA_GAIN123_B0;
else if (chain == 1)
reg = AR_PHY_PA_GAIN123_B1;
else
reg = AR_PHY_PA_GAIN123_B2;
REG_RMW_FIELD(ah, reg, AR_PHY_PA_GAIN123_PA_GAIN1, small_signal_gain);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_CTRL1_B0,
AR_PHY_PAPRD_CTRL1_PAPRD_POWER_AT_AM2AM_CAL,
training_power);
if (ah->caps.tx_chainmask & BIT(1))
REG_RMW_FIELD(ah, AR_PHY_PAPRD_CTRL1_B1,
AR_PHY_PAPRD_CTRL1_PAPRD_POWER_AT_AM2AM_CAL,
training_power);
if (ah->caps.tx_chainmask & BIT(2))
/* val AR_PHY_PAPRD_CTRL1_PAPRD_POWER_AT_AM2AM_CAL correct? */
REG_RMW_FIELD(ah, AR_PHY_PAPRD_CTRL1_B2,
AR_PHY_PAPRD_CTRL1_PAPRD_POWER_AT_AM2AM_CAL,
training_power);
}
EXPORT_SYMBOL(ar9003_paprd_populate_single_table);
void ar9003_paprd_setup_gain_table(struct ath_hw *ah, int chain)
{
unsigned int i, desired_gain, gain_index;
unsigned int train_power = ah->paprd_training_power;
desired_gain = ar9003_get_desired_gain(ah, chain, train_power);
gain_index = 0;
for (i = 0; i < PAPRD_GAIN_TABLE_ENTRIES; i++) {
if (ah->paprd_gain_table_index[i] >= desired_gain)
break;
gain_index++;
}
ar9003_tx_force_gain(ah, gain_index);
REG_CLR_BIT(ah, AR_PHY_PAPRD_TRAINER_STAT1,
AR_PHY_PAPRD_TRAINER_STAT1_PAPRD_TRAIN_DONE);
}
EXPORT_SYMBOL(ar9003_paprd_setup_gain_table);
static bool ar9003_paprd_retrain_pa_in(struct ath_hw *ah,
struct ath9k_hw_cal_data *caldata,
int chain)
{
u32 *pa_in = caldata->pa_table[chain];
int capdiv_offset, quick_drop_offset;
int capdiv2g, quick_drop;
int count = 0;
int i;
if (!AR_SREV_9485(ah) && !AR_SREV_9330(ah))
return false;
capdiv2g = REG_READ_FIELD(ah, AR_PHY_65NM_CH0_TXRF3,
AR_PHY_65NM_CH0_TXRF3_CAPDIV2G);
quick_drop = REG_READ_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL3,
AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_QUICK_DROP);
if (quick_drop)
quick_drop -= 0x40;
for (i = 0; i < NUM_BIN + 1; i++) {
if (pa_in[i] == 1400)
count++;
}
if (AR_SREV_9485(ah)) {
if (pa_in[23] < 800) {
capdiv_offset = (int)((1000 - pa_in[23] + 75) / 150);
capdiv2g += capdiv_offset;
if (capdiv2g > 7) {
capdiv2g = 7;
if (pa_in[23] < 600) {
quick_drop++;
if (quick_drop > 0)
quick_drop = 0;
}
}
} else if (pa_in[23] == 1400) {
quick_drop_offset = min_t(int, count / 3, 2);
quick_drop += quick_drop_offset;
capdiv2g += quick_drop_offset / 2;
if (capdiv2g > 7)
capdiv2g = 7;
if (quick_drop > 0) {
quick_drop = 0;
capdiv2g -= quick_drop_offset;
if (capdiv2g < 0)
capdiv2g = 0;
}
} else {
return false;
}
} else if (AR_SREV_9330(ah)) {
if (pa_in[23] < 1000) {
capdiv_offset = (1000 - pa_in[23]) / 100;
capdiv2g += capdiv_offset;
if (capdiv_offset > 3) {
capdiv_offset = 1;
quick_drop--;
}
capdiv2g += capdiv_offset;
if (capdiv2g > 6)
capdiv2g = 6;
if (quick_drop < -4)
quick_drop = -4;
} else if (pa_in[23] == 1400) {
if (count > 3) {
quick_drop++;
capdiv2g -= count / 4;
if (quick_drop > -2)
quick_drop = -2;
} else {
capdiv2g--;
}
if (capdiv2g < 0)
capdiv2g = 0;
} else {
return false;
}
}
REG_RMW_FIELD(ah, AR_PHY_65NM_CH0_TXRF3,
AR_PHY_65NM_CH0_TXRF3_CAPDIV2G, capdiv2g);
REG_RMW_FIELD(ah, AR_PHY_PAPRD_TRAINER_CNTL3,
AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_QUICK_DROP,
quick_drop);
return true;
}
int ar9003_paprd_create_curve(struct ath_hw *ah,
struct ath9k_hw_cal_data *caldata, int chain)
{
u16 *small_signal_gain = &caldata->small_signal_gain[chain];
u32 *pa_table = caldata->pa_table[chain];
u32 *data_L, *data_U;
int i, status = 0;
u32 *buf;
u32 reg;
memset(caldata->pa_table[chain], 0, sizeof(caldata->pa_table[chain]));
buf = kmalloc(2 * 48 * sizeof(u32), GFP_KERNEL);
if (!buf)
return -ENOMEM;
data_L = &buf[0];
data_U = &buf[48];
REG_CLR_BIT(ah, AR_PHY_CHAN_INFO_MEMORY,
AR_PHY_CHAN_INFO_MEMORY_CHANINFOMEM_S2_READ);
reg = AR_PHY_CHAN_INFO_TAB_0;
for (i = 0; i < 48; i++)
data_L[i] = REG_READ(ah, reg + (i << 2));
REG_SET_BIT(ah, AR_PHY_CHAN_INFO_MEMORY,
AR_PHY_CHAN_INFO_MEMORY_CHANINFOMEM_S2_READ);
for (i = 0; i < 48; i++)
data_U[i] = REG_READ(ah, reg + (i << 2));
if (!create_pa_curve(data_L, data_U, pa_table, small_signal_gain))
status = -2;
if (ar9003_paprd_retrain_pa_in(ah, caldata, chain))
status = -EINPROGRESS;
REG_CLR_BIT(ah, AR_PHY_PAPRD_TRAINER_STAT1,
AR_PHY_PAPRD_TRAINER_STAT1_PAPRD_TRAIN_DONE);
kfree(buf);
return status;
}
EXPORT_SYMBOL(ar9003_paprd_create_curve);
int ar9003_paprd_init_table(struct ath_hw *ah)
{
int ret;
ret = ar9003_paprd_setup_single_table(ah);
if (ret < 0)
return ret;
ar9003_paprd_get_gain_table(ah);
return 0;
}
EXPORT_SYMBOL(ar9003_paprd_init_table);
bool ar9003_paprd_is_done(struct ath_hw *ah)
{
int paprd_done, agc2_pwr;
paprd_done = REG_READ_FIELD(ah, AR_PHY_PAPRD_TRAINER_STAT1,
AR_PHY_PAPRD_TRAINER_STAT1_PAPRD_TRAIN_DONE);
if (AR_SREV_9485(ah))
goto exit;
if (paprd_done == 0x1) {
agc2_pwr = REG_READ_FIELD(ah, AR_PHY_PAPRD_TRAINER_STAT1,
AR_PHY_PAPRD_TRAINER_STAT1_PAPRD_AGC2_PWR);
ath_dbg(ath9k_hw_common(ah), CALIBRATE,
"AGC2_PWR = 0x%x training done = 0x%x\n",
agc2_pwr, paprd_done);
/*
* agc2_pwr range should not be less than 'IDEAL_AGC2_PWR_CHANGE'
* when the training is completely done, otherwise retraining is
* done to make sure the value is in ideal range
*/
if (agc2_pwr <= PAPRD_IDEAL_AGC2_PWR_RANGE)
paprd_done = 0;
}
exit:
return !!paprd_done;
}
EXPORT_SYMBOL(ar9003_paprd_is_done);
bool ar9003_is_paprd_enabled(struct ath_hw *ah)
{
if ((ah->caps.hw_caps & ATH9K_HW_CAP_PAPRD) && ah->config.enable_paprd)
return true;
return false;
}
EXPORT_SYMBOL(ar9003_is_paprd_enabled);
| gpl-2.0 |
superr/android_kernel_lge_w5c | arch/x86/kernel/paravirt.c | 3311 | 12239 | /* Paravirtualization interfaces
Copyright (C) 2006 Rusty Russell IBM Corporation
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
2007 - x86_64 support added by Glauber de Oliveira Costa, Red Hat Inc
*/
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/efi.h>
#include <linux/bcd.h>
#include <linux/highmem.h>
#include <asm/bug.h>
#include <asm/paravirt.h>
#include <asm/debugreg.h>
#include <asm/desc.h>
#include <asm/setup.h>
#include <asm/pgtable.h>
#include <asm/time.h>
#include <asm/pgalloc.h>
#include <asm/irq.h>
#include <asm/delay.h>
#include <asm/fixmap.h>
#include <asm/apic.h>
#include <asm/tlbflush.h>
#include <asm/timer.h>
#include <asm/special_insns.h>
/* nop stub */
void _paravirt_nop(void)
{
}
/* identity function, which can be inlined */
u32 _paravirt_ident_32(u32 x)
{
return x;
}
u64 _paravirt_ident_64(u64 x)
{
return x;
}
void __init default_banner(void)
{
printk(KERN_INFO "Booting paravirtualized kernel on %s\n",
pv_info.name);
}
/* Simple instruction patching code. */
#define DEF_NATIVE(ops, name, code) \
extern const char start_##ops##_##name[], end_##ops##_##name[]; \
asm("start_" #ops "_" #name ": " code "; end_" #ops "_" #name ":")
/* Undefined instruction for dealing with missing ops pointers. */
static const unsigned char ud2a[] = { 0x0f, 0x0b };
unsigned paravirt_patch_nop(void)
{
return 0;
}
unsigned paravirt_patch_ignore(unsigned len)
{
return len;
}
struct branch {
unsigned char opcode;
u32 delta;
} __attribute__((packed));
unsigned paravirt_patch_call(void *insnbuf,
const void *target, u16 tgt_clobbers,
unsigned long addr, u16 site_clobbers,
unsigned len)
{
struct branch *b = insnbuf;
unsigned long delta = (unsigned long)target - (addr+5);
if (tgt_clobbers & ~site_clobbers)
return len; /* target would clobber too much for this site */
if (len < 5)
return len; /* call too long for patch site */
b->opcode = 0xe8; /* call */
b->delta = delta;
BUILD_BUG_ON(sizeof(*b) != 5);
return 5;
}
unsigned paravirt_patch_jmp(void *insnbuf, const void *target,
unsigned long addr, unsigned len)
{
struct branch *b = insnbuf;
unsigned long delta = (unsigned long)target - (addr+5);
if (len < 5)
return len; /* call too long for patch site */
b->opcode = 0xe9; /* jmp */
b->delta = delta;
return 5;
}
/* Neat trick to map patch type back to the call within the
* corresponding structure. */
static void *get_call_destination(u8 type)
{
struct paravirt_patch_template tmpl = {
.pv_init_ops = pv_init_ops,
.pv_time_ops = pv_time_ops,
.pv_cpu_ops = pv_cpu_ops,
.pv_irq_ops = pv_irq_ops,
.pv_apic_ops = pv_apic_ops,
.pv_mmu_ops = pv_mmu_ops,
#ifdef CONFIG_PARAVIRT_SPINLOCKS
.pv_lock_ops = pv_lock_ops,
#endif
};
return *((void **)&tmpl + type);
}
unsigned paravirt_patch_default(u8 type, u16 clobbers, void *insnbuf,
unsigned long addr, unsigned len)
{
void *opfunc = get_call_destination(type);
unsigned ret;
if (opfunc == NULL)
/* If there's no function, patch it with a ud2a (BUG) */
ret = paravirt_patch_insns(insnbuf, len, ud2a, ud2a+sizeof(ud2a));
else if (opfunc == _paravirt_nop)
/* If the operation is a nop, then nop the callsite */
ret = paravirt_patch_nop();
/* identity functions just return their single argument */
else if (opfunc == _paravirt_ident_32)
ret = paravirt_patch_ident_32(insnbuf, len);
else if (opfunc == _paravirt_ident_64)
ret = paravirt_patch_ident_64(insnbuf, len);
else if (type == PARAVIRT_PATCH(pv_cpu_ops.iret) ||
type == PARAVIRT_PATCH(pv_cpu_ops.irq_enable_sysexit) ||
type == PARAVIRT_PATCH(pv_cpu_ops.usergs_sysret32) ||
type == PARAVIRT_PATCH(pv_cpu_ops.usergs_sysret64))
/* If operation requires a jmp, then jmp */
ret = paravirt_patch_jmp(insnbuf, opfunc, addr, len);
else
/* Otherwise call the function; assume target could
clobber any caller-save reg */
ret = paravirt_patch_call(insnbuf, opfunc, CLBR_ANY,
addr, clobbers, len);
return ret;
}
unsigned paravirt_patch_insns(void *insnbuf, unsigned len,
const char *start, const char *end)
{
unsigned insn_len = end - start;
if (insn_len > len || start == NULL)
insn_len = len;
else
memcpy(insnbuf, start, insn_len);
return insn_len;
}
static void native_flush_tlb(void)
{
__native_flush_tlb();
}
/*
* Global pages have to be flushed a bit differently. Not a real
* performance problem because this does not happen often.
*/
static void native_flush_tlb_global(void)
{
__native_flush_tlb_global();
}
static void native_flush_tlb_single(unsigned long addr)
{
__native_flush_tlb_single(addr);
}
struct static_key paravirt_steal_enabled;
struct static_key paravirt_steal_rq_enabled;
static u64 native_steal_clock(int cpu)
{
return 0;
}
/* These are in entry.S */
extern void native_iret(void);
extern void native_irq_enable_sysexit(void);
extern void native_usergs_sysret32(void);
extern void native_usergs_sysret64(void);
static struct resource reserve_ioports = {
.start = 0,
.end = IO_SPACE_LIMIT,
.name = "paravirt-ioport",
.flags = IORESOURCE_IO | IORESOURCE_BUSY,
};
/*
* Reserve the whole legacy IO space to prevent any legacy drivers
* from wasting time probing for their hardware. This is a fairly
* brute-force approach to disabling all non-virtual drivers.
*
* Note that this must be called very early to have any effect.
*/
int paravirt_disable_iospace(void)
{
return request_resource(&ioport_resource, &reserve_ioports);
}
static DEFINE_PER_CPU(enum paravirt_lazy_mode, paravirt_lazy_mode) = PARAVIRT_LAZY_NONE;
static inline void enter_lazy(enum paravirt_lazy_mode mode)
{
BUG_ON(percpu_read(paravirt_lazy_mode) != PARAVIRT_LAZY_NONE);
percpu_write(paravirt_lazy_mode, mode);
}
static void leave_lazy(enum paravirt_lazy_mode mode)
{
BUG_ON(percpu_read(paravirt_lazy_mode) != mode);
percpu_write(paravirt_lazy_mode, PARAVIRT_LAZY_NONE);
}
void paravirt_enter_lazy_mmu(void)
{
enter_lazy(PARAVIRT_LAZY_MMU);
}
void paravirt_leave_lazy_mmu(void)
{
leave_lazy(PARAVIRT_LAZY_MMU);
}
void paravirt_start_context_switch(struct task_struct *prev)
{
BUG_ON(preemptible());
if (percpu_read(paravirt_lazy_mode) == PARAVIRT_LAZY_MMU) {
arch_leave_lazy_mmu_mode();
set_ti_thread_flag(task_thread_info(prev), TIF_LAZY_MMU_UPDATES);
}
enter_lazy(PARAVIRT_LAZY_CPU);
}
void paravirt_end_context_switch(struct task_struct *next)
{
BUG_ON(preemptible());
leave_lazy(PARAVIRT_LAZY_CPU);
if (test_and_clear_ti_thread_flag(task_thread_info(next), TIF_LAZY_MMU_UPDATES))
arch_enter_lazy_mmu_mode();
}
enum paravirt_lazy_mode paravirt_get_lazy_mode(void)
{
if (in_interrupt())
return PARAVIRT_LAZY_NONE;
return percpu_read(paravirt_lazy_mode);
}
void arch_flush_lazy_mmu_mode(void)
{
preempt_disable();
if (paravirt_get_lazy_mode() == PARAVIRT_LAZY_MMU) {
arch_leave_lazy_mmu_mode();
arch_enter_lazy_mmu_mode();
}
preempt_enable();
}
struct pv_info pv_info = {
.name = "bare hardware",
.paravirt_enabled = 0,
.kernel_rpl = 0,
.shared_kernel_pmd = 1, /* Only used when CONFIG_X86_PAE is set */
#ifdef CONFIG_X86_64
.extra_user_64bit_cs = __USER_CS,
#endif
};
struct pv_init_ops pv_init_ops = {
.patch = native_patch,
};
struct pv_time_ops pv_time_ops = {
.sched_clock = native_sched_clock,
.steal_clock = native_steal_clock,
};
struct pv_irq_ops pv_irq_ops = {
.save_fl = __PV_IS_CALLEE_SAVE(native_save_fl),
.restore_fl = __PV_IS_CALLEE_SAVE(native_restore_fl),
.irq_disable = __PV_IS_CALLEE_SAVE(native_irq_disable),
.irq_enable = __PV_IS_CALLEE_SAVE(native_irq_enable),
.safe_halt = native_safe_halt,
.halt = native_halt,
#ifdef CONFIG_X86_64
.adjust_exception_frame = paravirt_nop,
#endif
};
struct pv_cpu_ops pv_cpu_ops = {
.cpuid = native_cpuid,
.get_debugreg = native_get_debugreg,
.set_debugreg = native_set_debugreg,
.clts = native_clts,
.read_cr0 = native_read_cr0,
.write_cr0 = native_write_cr0,
.read_cr4 = native_read_cr4,
.read_cr4_safe = native_read_cr4_safe,
.write_cr4 = native_write_cr4,
#ifdef CONFIG_X86_64
.read_cr8 = native_read_cr8,
.write_cr8 = native_write_cr8,
#endif
.wbinvd = native_wbinvd,
.read_msr = native_read_msr_safe,
.rdmsr_regs = native_rdmsr_safe_regs,
.write_msr = native_write_msr_safe,
.wrmsr_regs = native_wrmsr_safe_regs,
.read_tsc = native_read_tsc,
.read_pmc = native_read_pmc,
.read_tscp = native_read_tscp,
.load_tr_desc = native_load_tr_desc,
.set_ldt = native_set_ldt,
.load_gdt = native_load_gdt,
.load_idt = native_load_idt,
.store_gdt = native_store_gdt,
.store_idt = native_store_idt,
.store_tr = native_store_tr,
.load_tls = native_load_tls,
#ifdef CONFIG_X86_64
.load_gs_index = native_load_gs_index,
#endif
.write_ldt_entry = native_write_ldt_entry,
.write_gdt_entry = native_write_gdt_entry,
.write_idt_entry = native_write_idt_entry,
.alloc_ldt = paravirt_nop,
.free_ldt = paravirt_nop,
.load_sp0 = native_load_sp0,
#if defined(CONFIG_X86_32) || defined(CONFIG_IA32_EMULATION)
.irq_enable_sysexit = native_irq_enable_sysexit,
#endif
#ifdef CONFIG_X86_64
#ifdef CONFIG_IA32_EMULATION
.usergs_sysret32 = native_usergs_sysret32,
#endif
.usergs_sysret64 = native_usergs_sysret64,
#endif
.iret = native_iret,
.swapgs = native_swapgs,
.set_iopl_mask = native_set_iopl_mask,
.io_delay = native_io_delay,
.start_context_switch = paravirt_nop,
.end_context_switch = paravirt_nop,
};
struct pv_apic_ops pv_apic_ops = {
#ifdef CONFIG_X86_LOCAL_APIC
.startup_ipi_hook = paravirt_nop,
#endif
};
#if defined(CONFIG_X86_32) && !defined(CONFIG_X86_PAE)
/* 32-bit pagetable entries */
#define PTE_IDENT __PV_IS_CALLEE_SAVE(_paravirt_ident_32)
#else
/* 64-bit pagetable entries */
#define PTE_IDENT __PV_IS_CALLEE_SAVE(_paravirt_ident_64)
#endif
struct pv_mmu_ops pv_mmu_ops = {
.read_cr2 = native_read_cr2,
.write_cr2 = native_write_cr2,
.read_cr3 = native_read_cr3,
.write_cr3 = native_write_cr3,
.flush_tlb_user = native_flush_tlb,
.flush_tlb_kernel = native_flush_tlb_global,
.flush_tlb_single = native_flush_tlb_single,
.flush_tlb_others = native_flush_tlb_others,
.pgd_alloc = __paravirt_pgd_alloc,
.pgd_free = paravirt_nop,
.alloc_pte = paravirt_nop,
.alloc_pmd = paravirt_nop,
.alloc_pud = paravirt_nop,
.release_pte = paravirt_nop,
.release_pmd = paravirt_nop,
.release_pud = paravirt_nop,
.set_pte = native_set_pte,
.set_pte_at = native_set_pte_at,
.set_pmd = native_set_pmd,
.set_pmd_at = native_set_pmd_at,
.pte_update = paravirt_nop,
.pte_update_defer = paravirt_nop,
.pmd_update = paravirt_nop,
.pmd_update_defer = paravirt_nop,
.ptep_modify_prot_start = __ptep_modify_prot_start,
.ptep_modify_prot_commit = __ptep_modify_prot_commit,
#if PAGETABLE_LEVELS >= 3
#ifdef CONFIG_X86_PAE
.set_pte_atomic = native_set_pte_atomic,
.pte_clear = native_pte_clear,
.pmd_clear = native_pmd_clear,
#endif
.set_pud = native_set_pud,
.pmd_val = PTE_IDENT,
.make_pmd = PTE_IDENT,
#if PAGETABLE_LEVELS == 4
.pud_val = PTE_IDENT,
.make_pud = PTE_IDENT,
.set_pgd = native_set_pgd,
#endif
#endif /* PAGETABLE_LEVELS >= 3 */
.pte_val = PTE_IDENT,
.pgd_val = PTE_IDENT,
.make_pte = PTE_IDENT,
.make_pgd = PTE_IDENT,
.dup_mmap = paravirt_nop,
.exit_mmap = paravirt_nop,
.activate_mm = paravirt_nop,
.lazy_mode = {
.enter = paravirt_nop,
.leave = paravirt_nop,
},
.set_fixmap = native_set_fixmap,
};
EXPORT_SYMBOL_GPL(pv_time_ops);
EXPORT_SYMBOL (pv_cpu_ops);
EXPORT_SYMBOL (pv_mmu_ops);
EXPORT_SYMBOL_GPL(pv_apic_ops);
EXPORT_SYMBOL_GPL(pv_info);
EXPORT_SYMBOL (pv_irq_ops);
| gpl-2.0 |
mukulsoni/android_kernel_cyanogen_msm8916 | arch/powerpc/platforms/83xx/mpc836x_rdk.c | 4079 | 1598 | /*
* MPC8360E-RDK board file.
*
* Copyright (c) 2006 Freescale Semiconductor, Inc.
* Copyright (c) 2007-2008 MontaVista Software, Inc.
*
* Author: Anton Vorontsov <avorontsov@ru.mvista.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/of_platform.h>
#include <linux/io.h>
#include <asm/prom.h>
#include <asm/time.h>
#include <asm/ipic.h>
#include <asm/udbg.h>
#include <asm/qe.h>
#include <asm/qe_ic.h>
#include <sysdev/fsl_soc.h>
#include <sysdev/fsl_pci.h>
#include "mpc83xx.h"
machine_device_initcall(mpc836x_rdk, mpc83xx_declare_of_platform_devices);
static void __init mpc836x_rdk_setup_arch(void)
{
if (ppc_md.progress)
ppc_md.progress("mpc836x_rdk_setup_arch()", 0);
mpc83xx_setup_pci();
#ifdef CONFIG_QUICC_ENGINE
qe_reset();
#endif
}
/*
* Called very early, MMU is off, device-tree isn't unflattened.
*/
static int __init mpc836x_rdk_probe(void)
{
unsigned long root = of_get_flat_dt_root();
return of_flat_dt_is_compatible(root, "fsl,mpc8360rdk");
}
define_machine(mpc836x_rdk) {
.name = "MPC836x RDK",
.probe = mpc836x_rdk_probe,
.setup_arch = mpc836x_rdk_setup_arch,
.init_IRQ = mpc83xx_ipic_and_qe_init_IRQ,
.get_irq = ipic_get_irq,
.restart = mpc83xx_restart,
.time_init = mpc83xx_time_init,
.calibrate_decr = generic_calibrate_decr,
.progress = udbg_progress,
};
| gpl-2.0 |
sudosurootdev/kernel_lge_g3-wip | drivers/acpi/acpica/hwregs.c | 4847 | 19936 |
/*******************************************************************************
*
* Module Name: hwregs - Read/write access functions for the various ACPI
* control and status registers.
*
******************************************************************************/
/*
* 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.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acnamesp.h"
#include "acevents.h"
#define _COMPONENT ACPI_HARDWARE
ACPI_MODULE_NAME("hwregs")
#if (!ACPI_REDUCED_HARDWARE)
/* Local Prototypes */
static acpi_status
acpi_hw_read_multiple(u32 *value,
struct acpi_generic_address *register_a,
struct acpi_generic_address *register_b);
static acpi_status
acpi_hw_write_multiple(u32 value,
struct acpi_generic_address *register_a,
struct acpi_generic_address *register_b);
#endif /* !ACPI_REDUCED_HARDWARE */
/******************************************************************************
*
* FUNCTION: acpi_hw_validate_register
*
* PARAMETERS: Reg - GAS register structure
* max_bit_width - Max bit_width supported (32 or 64)
* Address - Pointer to where the gas->address
* is returned
*
* RETURN: Status
*
* DESCRIPTION: Validate the contents of a GAS register. Checks the GAS
* pointer, Address, space_id, bit_width, and bit_offset.
*
******************************************************************************/
acpi_status
acpi_hw_validate_register(struct acpi_generic_address *reg,
u8 max_bit_width, u64 *address)
{
/* Must have a valid pointer to a GAS structure */
if (!reg) {
return (AE_BAD_PARAMETER);
}
/*
* Copy the target address. This handles possible alignment issues.
* Address must not be null. A null address also indicates an optional
* ACPI register that is not supported, so no error message.
*/
ACPI_MOVE_64_TO_64(address, ®->address);
if (!(*address)) {
return (AE_BAD_ADDRESS);
}
/* Validate the space_iD */
if ((reg->space_id != ACPI_ADR_SPACE_SYSTEM_MEMORY) &&
(reg->space_id != ACPI_ADR_SPACE_SYSTEM_IO)) {
ACPI_ERROR((AE_INFO,
"Unsupported address space: 0x%X", reg->space_id));
return (AE_SUPPORT);
}
/* Validate the bit_width */
if ((reg->bit_width != 8) &&
(reg->bit_width != 16) &&
(reg->bit_width != 32) && (reg->bit_width != max_bit_width)) {
ACPI_ERROR((AE_INFO,
"Unsupported register bit width: 0x%X",
reg->bit_width));
return (AE_SUPPORT);
}
/* Validate the bit_offset. Just a warning for now. */
if (reg->bit_offset != 0) {
ACPI_WARNING((AE_INFO,
"Unsupported register bit offset: 0x%X",
reg->bit_offset));
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: acpi_hw_read
*
* PARAMETERS: Value - Where the value is returned
* Reg - GAS register structure
*
* RETURN: Status
*
* DESCRIPTION: Read from either memory or IO space. This is a 32-bit max
* version of acpi_read, used internally since the overhead of
* 64-bit values is not needed.
*
* LIMITATIONS: <These limitations also apply to acpi_hw_write>
* bit_width must be exactly 8, 16, or 32.
* space_iD must be system_memory or system_iO.
* bit_offset and access_width are currently ignored, as there has
* not been a need to implement these.
*
******************************************************************************/
acpi_status acpi_hw_read(u32 *value, struct acpi_generic_address *reg)
{
u64 address;
u64 value64;
acpi_status status;
ACPI_FUNCTION_NAME(hw_read);
/* Validate contents of the GAS register */
status = acpi_hw_validate_register(reg, 32, &address);
if (ACPI_FAILURE(status)) {
return (status);
}
/* Initialize entire 32-bit return value to zero */
*value = 0;
/*
* Two address spaces supported: Memory or IO. PCI_Config is
* not supported here because the GAS structure is insufficient
*/
if (reg->space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY) {
status = acpi_os_read_memory((acpi_physical_address)
address, &value64, reg->bit_width);
*value = (u32)value64;
} else { /* ACPI_ADR_SPACE_SYSTEM_IO, validated earlier */
status = acpi_hw_read_port((acpi_io_address)
address, value, reg->bit_width);
}
ACPI_DEBUG_PRINT((ACPI_DB_IO,
"Read: %8.8X width %2d from %8.8X%8.8X (%s)\n",
*value, reg->bit_width, ACPI_FORMAT_UINT64(address),
acpi_ut_get_region_name(reg->space_id)));
return (status);
}
/******************************************************************************
*
* FUNCTION: acpi_hw_write
*
* PARAMETERS: Value - Value to be written
* Reg - GAS register structure
*
* RETURN: Status
*
* DESCRIPTION: Write to either memory or IO space. This is a 32-bit max
* version of acpi_write, used internally since the overhead of
* 64-bit values is not needed.
*
******************************************************************************/
acpi_status acpi_hw_write(u32 value, struct acpi_generic_address *reg)
{
u64 address;
acpi_status status;
ACPI_FUNCTION_NAME(hw_write);
/* Validate contents of the GAS register */
status = acpi_hw_validate_register(reg, 32, &address);
if (ACPI_FAILURE(status)) {
return (status);
}
/*
* Two address spaces supported: Memory or IO. PCI_Config is
* not supported here because the GAS structure is insufficient
*/
if (reg->space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY) {
status = acpi_os_write_memory((acpi_physical_address)
address, (u64)value,
reg->bit_width);
} else { /* ACPI_ADR_SPACE_SYSTEM_IO, validated earlier */
status = acpi_hw_write_port((acpi_io_address)
address, value, reg->bit_width);
}
ACPI_DEBUG_PRINT((ACPI_DB_IO,
"Wrote: %8.8X width %2d to %8.8X%8.8X (%s)\n",
value, reg->bit_width, ACPI_FORMAT_UINT64(address),
acpi_ut_get_region_name(reg->space_id)));
return (status);
}
#if (!ACPI_REDUCED_HARDWARE)
/*******************************************************************************
*
* FUNCTION: acpi_hw_clear_acpi_status
*
* PARAMETERS: None
*
* RETURN: Status
*
* DESCRIPTION: Clears all fixed and general purpose status bits
*
******************************************************************************/
acpi_status acpi_hw_clear_acpi_status(void)
{
acpi_status status;
acpi_cpu_flags lock_flags = 0;
ACPI_FUNCTION_TRACE(hw_clear_acpi_status);
ACPI_DEBUG_PRINT((ACPI_DB_IO, "About to write %04X to %8.8X%8.8X\n",
ACPI_BITMASK_ALL_FIXED_STATUS,
ACPI_FORMAT_UINT64(acpi_gbl_xpm1a_status.address)));
lock_flags = acpi_os_acquire_lock(acpi_gbl_hardware_lock);
/* Clear the fixed events in PM1 A/B */
status = acpi_hw_register_write(ACPI_REGISTER_PM1_STATUS,
ACPI_BITMASK_ALL_FIXED_STATUS);
acpi_os_release_lock(acpi_gbl_hardware_lock, lock_flags);
if (ACPI_FAILURE(status))
goto exit;
/* Clear the GPE Bits in all GPE registers in all GPE blocks */
status = acpi_ev_walk_gpe_list(acpi_hw_clear_gpe_block, NULL);
exit:
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_hw_get_bit_register_info
*
* PARAMETERS: register_id - Index of ACPI Register to access
*
* RETURN: The bitmask to be used when accessing the register
*
* DESCRIPTION: Map register_id into a register bitmask.
*
******************************************************************************/
struct acpi_bit_register_info *acpi_hw_get_bit_register_info(u32 register_id)
{
ACPI_FUNCTION_ENTRY();
if (register_id > ACPI_BITREG_MAX) {
ACPI_ERROR((AE_INFO, "Invalid BitRegister ID: 0x%X",
register_id));
return (NULL);
}
return (&acpi_gbl_bit_register_info[register_id]);
}
/******************************************************************************
*
* FUNCTION: acpi_hw_write_pm1_control
*
* PARAMETERS: pm1a_control - Value to be written to PM1A control
* pm1b_control - Value to be written to PM1B control
*
* RETURN: Status
*
* DESCRIPTION: Write the PM1 A/B control registers. These registers are
* different than than the PM1 A/B status and enable registers
* in that different values can be written to the A/B registers.
* Most notably, the SLP_TYP bits can be different, as per the
* values returned from the _Sx predefined methods.
*
******************************************************************************/
acpi_status acpi_hw_write_pm1_control(u32 pm1a_control, u32 pm1b_control)
{
acpi_status status;
ACPI_FUNCTION_TRACE(hw_write_pm1_control);
status =
acpi_hw_write(pm1a_control, &acpi_gbl_FADT.xpm1a_control_block);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
if (acpi_gbl_FADT.xpm1b_control_block.address) {
status =
acpi_hw_write(pm1b_control,
&acpi_gbl_FADT.xpm1b_control_block);
}
return_ACPI_STATUS(status);
}
/******************************************************************************
*
* FUNCTION: acpi_hw_register_read
*
* PARAMETERS: register_id - ACPI Register ID
* return_value - Where the register value is returned
*
* RETURN: Status and the value read.
*
* DESCRIPTION: Read from the specified ACPI register
*
******************************************************************************/
acpi_status
acpi_hw_register_read(u32 register_id, u32 * return_value)
{
u32 value = 0;
acpi_status status;
ACPI_FUNCTION_TRACE(hw_register_read);
switch (register_id) {
case ACPI_REGISTER_PM1_STATUS: /* PM1 A/B: 16-bit access each */
status = acpi_hw_read_multiple(&value,
&acpi_gbl_xpm1a_status,
&acpi_gbl_xpm1b_status);
break;
case ACPI_REGISTER_PM1_ENABLE: /* PM1 A/B: 16-bit access each */
status = acpi_hw_read_multiple(&value,
&acpi_gbl_xpm1a_enable,
&acpi_gbl_xpm1b_enable);
break;
case ACPI_REGISTER_PM1_CONTROL: /* PM1 A/B: 16-bit access each */
status = acpi_hw_read_multiple(&value,
&acpi_gbl_FADT.
xpm1a_control_block,
&acpi_gbl_FADT.
xpm1b_control_block);
/*
* Zero the write-only bits. From the ACPI specification, "Hardware
* Write-Only Bits": "Upon reads to registers with write-only bits,
* software masks out all write-only bits."
*/
value &= ~ACPI_PM1_CONTROL_WRITEONLY_BITS;
break;
case ACPI_REGISTER_PM2_CONTROL: /* 8-bit access */
status =
acpi_hw_read(&value, &acpi_gbl_FADT.xpm2_control_block);
break;
case ACPI_REGISTER_PM_TIMER: /* 32-bit access */
status = acpi_hw_read(&value, &acpi_gbl_FADT.xpm_timer_block);
break;
case ACPI_REGISTER_SMI_COMMAND_BLOCK: /* 8-bit access */
status =
acpi_hw_read_port(acpi_gbl_FADT.smi_command, &value, 8);
break;
default:
ACPI_ERROR((AE_INFO, "Unknown Register ID: 0x%X", register_id));
status = AE_BAD_PARAMETER;
break;
}
if (ACPI_SUCCESS(status)) {
*return_value = value;
}
return_ACPI_STATUS(status);
}
/******************************************************************************
*
* FUNCTION: acpi_hw_register_write
*
* PARAMETERS: register_id - ACPI Register ID
* Value - The value to write
*
* RETURN: Status
*
* DESCRIPTION: Write to the specified ACPI register
*
* NOTE: In accordance with the ACPI specification, this function automatically
* preserves the value of the following bits, meaning that these bits cannot be
* changed via this interface:
*
* PM1_CONTROL[0] = SCI_EN
* PM1_CONTROL[9]
* PM1_STATUS[11]
*
* ACPI References:
* 1) Hardware Ignored Bits: When software writes to a register with ignored
* bit fields, it preserves the ignored bit fields
* 2) SCI_EN: OSPM always preserves this bit position
*
******************************************************************************/
acpi_status acpi_hw_register_write(u32 register_id, u32 value)
{
acpi_status status;
u32 read_value;
ACPI_FUNCTION_TRACE(hw_register_write);
switch (register_id) {
case ACPI_REGISTER_PM1_STATUS: /* PM1 A/B: 16-bit access each */
/*
* Handle the "ignored" bit in PM1 Status. According to the ACPI
* specification, ignored bits are to be preserved when writing.
* Normally, this would mean a read/modify/write sequence. However,
* preserving a bit in the status register is different. Writing a
* one clears the status, and writing a zero preserves the status.
* Therefore, we must always write zero to the ignored bit.
*
* This behavior is clarified in the ACPI 4.0 specification.
*/
value &= ~ACPI_PM1_STATUS_PRESERVED_BITS;
status = acpi_hw_write_multiple(value,
&acpi_gbl_xpm1a_status,
&acpi_gbl_xpm1b_status);
break;
case ACPI_REGISTER_PM1_ENABLE: /* PM1 A/B: 16-bit access */
status = acpi_hw_write_multiple(value,
&acpi_gbl_xpm1a_enable,
&acpi_gbl_xpm1b_enable);
break;
case ACPI_REGISTER_PM1_CONTROL: /* PM1 A/B: 16-bit access each */
/*
* Perform a read first to preserve certain bits (per ACPI spec)
* Note: This includes SCI_EN, we never want to change this bit
*/
status = acpi_hw_read_multiple(&read_value,
&acpi_gbl_FADT.
xpm1a_control_block,
&acpi_gbl_FADT.
xpm1b_control_block);
if (ACPI_FAILURE(status)) {
goto exit;
}
/* Insert the bits to be preserved */
ACPI_INSERT_BITS(value, ACPI_PM1_CONTROL_PRESERVED_BITS,
read_value);
/* Now we can write the data */
status = acpi_hw_write_multiple(value,
&acpi_gbl_FADT.
xpm1a_control_block,
&acpi_gbl_FADT.
xpm1b_control_block);
break;
case ACPI_REGISTER_PM2_CONTROL: /* 8-bit access */
/*
* For control registers, all reserved bits must be preserved,
* as per the ACPI spec.
*/
status =
acpi_hw_read(&read_value,
&acpi_gbl_FADT.xpm2_control_block);
if (ACPI_FAILURE(status)) {
goto exit;
}
/* Insert the bits to be preserved */
ACPI_INSERT_BITS(value, ACPI_PM2_CONTROL_PRESERVED_BITS,
read_value);
status =
acpi_hw_write(value, &acpi_gbl_FADT.xpm2_control_block);
break;
case ACPI_REGISTER_PM_TIMER: /* 32-bit access */
status = acpi_hw_write(value, &acpi_gbl_FADT.xpm_timer_block);
break;
case ACPI_REGISTER_SMI_COMMAND_BLOCK: /* 8-bit access */
/* SMI_CMD is currently always in IO space */
status =
acpi_hw_write_port(acpi_gbl_FADT.smi_command, value, 8);
break;
default:
ACPI_ERROR((AE_INFO, "Unknown Register ID: 0x%X", register_id));
status = AE_BAD_PARAMETER;
break;
}
exit:
return_ACPI_STATUS(status);
}
/******************************************************************************
*
* FUNCTION: acpi_hw_read_multiple
*
* PARAMETERS: Value - Where the register value is returned
* register_a - First ACPI register (required)
* register_b - Second ACPI register (optional)
*
* RETURN: Status
*
* DESCRIPTION: Read from the specified two-part ACPI register (such as PM1 A/B)
*
******************************************************************************/
static acpi_status
acpi_hw_read_multiple(u32 *value,
struct acpi_generic_address *register_a,
struct acpi_generic_address *register_b)
{
u32 value_a = 0;
u32 value_b = 0;
acpi_status status;
/* The first register is always required */
status = acpi_hw_read(&value_a, register_a);
if (ACPI_FAILURE(status)) {
return (status);
}
/* Second register is optional */
if (register_b->address) {
status = acpi_hw_read(&value_b, register_b);
if (ACPI_FAILURE(status)) {
return (status);
}
}
/*
* OR the two return values together. No shifting or masking is necessary,
* because of how the PM1 registers are defined in the ACPI specification:
*
* "Although the bits can be split between the two register blocks (each
* register block has a unique pointer within the FADT), the bit positions
* are maintained. The register block with unimplemented bits (that is,
* those implemented in the other register block) always returns zeros,
* and writes have no side effects"
*/
*value = (value_a | value_b);
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: acpi_hw_write_multiple
*
* PARAMETERS: Value - The value to write
* register_a - First ACPI register (required)
* register_b - Second ACPI register (optional)
*
* RETURN: Status
*
* DESCRIPTION: Write to the specified two-part ACPI register (such as PM1 A/B)
*
******************************************************************************/
static acpi_status
acpi_hw_write_multiple(u32 value,
struct acpi_generic_address *register_a,
struct acpi_generic_address *register_b)
{
acpi_status status;
/* The first register is always required */
status = acpi_hw_write(value, register_a);
if (ACPI_FAILURE(status)) {
return (status);
}
/*
* Second register is optional
*
* No bit shifting or clearing is necessary, because of how the PM1
* registers are defined in the ACPI specification:
*
* "Although the bits can be split between the two register blocks (each
* register block has a unique pointer within the FADT), the bit positions
* are maintained. The register block with unimplemented bits (that is,
* those implemented in the other register block) always returns zeros,
* and writes have no side effects"
*/
if (register_b->address) {
status = acpi_hw_write(value, register_b);
}
return (status);
}
#endif /* !ACPI_REDUCED_HARDWARE */
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.