repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
ivanmmj/CommunityEris | drivers/s390/ebcdic.c | 356 | 11067 | /*
* arch/s390/kernel/ebcdic.c
* ECBDIC -> ASCII, ASCII -> ECBDIC conversion tables.
*
* S390 version
* Copyright (C) 1998 IBM Corporation
* Author(s): Martin Schwidefsky <schwidefsky@de.ibm.com>
*/
#include <asm/types.h>
/*
* ASCII -> EBCDIC
*/
__u8 _ascebc[256] =
{
/*00 NL SH SX EX ET NQ AK BL */
0x00, 0x01, 0x02, 0x03, 0x37, 0x2D, 0x2E, 0x2F,
/*08 BS HT LF VT FF CR SO SI */
0x16, 0x05, 0x15, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
/*10 DL D1 D2 D3 D4 NK SN EB */
0x10, 0x11, 0x12, 0x13, 0x3C, 0x15, 0x32, 0x26,
/*18 CN EM SB EC FS GS RS US */
0x18, 0x19, 0x3F, 0x27, 0x1C, 0x1D, 0x1E, 0x1F,
/*20 SP ! " # $ % & ' */
0x40, 0x5A, 0x7F, 0x7B, 0x5B, 0x6C, 0x50, 0x7D,
/*28 ( ) * + , - . / */
0x4D, 0x5D, 0x5C, 0x4E, 0x6B, 0x60, 0x4B, 0x61,
/*30 0 1 2 3 4 5 6 7 */
0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7,
/*38 8 9 : ; < = > ? */
0xF8, 0xF9, 0x7A, 0x5E, 0x4C, 0x7E, 0x6E, 0x6F,
/*40 @ A B C D E F G */
0x7C, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7,
/*48 H I J K L M N O */
0xC8, 0xC9, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6,
/*50 P Q R S T U V W */
0xD7, 0xD8, 0xD9, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6,
/*58 X Y Z [ \ ] ^ _ */
0xE7, 0xE8, 0xE9, 0xAD, 0xE0, 0xBD, 0x5F, 0x6D,
/*60 ` a b c d e f g */
0x79, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
/*68 h i j k l m n o */
0x88, 0x89, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96,
/*70 p q r s t u v w */
0x97, 0x98, 0x99, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6,
/*78 x y z { | } ~ DL */
0xA7, 0xA8, 0xA9, 0xC0, 0x4F, 0xD0, 0xA1, 0x07,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0xFF
};
/*
* EBCDIC -> ASCII
*/
__u8 _ebcasc[256] =
{
/* 0x00 NUL SOH STX ETX *SEL HT *RNL DEL */
0x00, 0x01, 0x02, 0x03, 0x07, 0x09, 0x07, 0x7F,
/* 0x08 -GE -SPS -RPT VT FF CR SO SI */
0x07, 0x07, 0x07, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
/* 0x10 DLE DC1 DC2 DC3 -RES -NL BS -POC
-ENP ->LF */
0x10, 0x11, 0x12, 0x13, 0x07, 0x0A, 0x08, 0x07,
/* 0x18 CAN EM -UBS -CU1 -IFS -IGS -IRS -ITB
-IUS */
0x18, 0x19, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
/* 0x20 -DS -SOS FS -WUS -BYP LF ETB ESC
-INP */
0x07, 0x07, 0x1C, 0x07, 0x07, 0x0A, 0x17, 0x1B,
/* 0x28 -SA -SFE -SM -CSP -MFA ENQ ACK BEL
-SW */
0x07, 0x07, 0x07, 0x07, 0x07, 0x05, 0x06, 0x07,
/* 0x30 ---- ---- SYN -IR -PP -TRN -NBS EOT */
0x07, 0x07, 0x16, 0x07, 0x07, 0x07, 0x07, 0x04,
/* 0x38 -SBS -IT -RFF -CU3 DC4 NAK ---- SUB */
0x07, 0x07, 0x07, 0x07, 0x14, 0x15, 0x07, 0x1A,
/* 0x40 SP RSP ä ---- */
0x20, 0xFF, 0x83, 0x84, 0x85, 0xA0, 0x07, 0x86,
/* 0x48 . < ( + | */
0x87, 0xA4, 0x9B, 0x2E, 0x3C, 0x28, 0x2B, 0x7C,
/* 0x50 & ---- */
0x26, 0x82, 0x88, 0x89, 0x8A, 0xA1, 0x8C, 0x07,
/* 0x58 ß ! $ * ) ; */
0x8D, 0xE1, 0x21, 0x24, 0x2A, 0x29, 0x3B, 0xAA,
/* 0x60 - / ---- Ä ---- ---- ---- */
0x2D, 0x2F, 0x07, 0x8E, 0x07, 0x07, 0x07, 0x8F,
/* 0x68 ---- , % _ > ? */
0x80, 0xA5, 0x07, 0x2C, 0x25, 0x5F, 0x3E, 0x3F,
/* 0x70 ---- ---- ---- ---- ---- ---- ---- */
0x07, 0x90, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
/* 0x78 * ` : # @ ' = " */
0x70, 0x60, 0x3A, 0x23, 0x40, 0x27, 0x3D, 0x22,
/* 0x80 * a b c d e f g */
0x07, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
/* 0x88 h i ---- ---- ---- */
0x68, 0x69, 0xAE, 0xAF, 0x07, 0x07, 0x07, 0xF1,
/* 0x90 ° j k l m n o p */
0xF8, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70,
/* 0x98 q r ---- ---- */
0x71, 0x72, 0xA6, 0xA7, 0x91, 0x07, 0x92, 0x07,
/* 0xA0 ~ s t u v w x */
0xE6, 0x7E, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
/* 0xA8 y z ---- ---- ---- ---- */
0x79, 0x7A, 0xAD, 0xAB, 0x07, 0x07, 0x07, 0x07,
/* 0xB0 ^ ---- § ---- */
0x5E, 0x9C, 0x9D, 0xFA, 0x07, 0x07, 0x07, 0xAC,
/* 0xB8 ---- [ ] ---- ---- ---- ---- */
0xAB, 0x07, 0x5B, 0x5D, 0x07, 0x07, 0x07, 0x07,
/* 0xC0 { A B C D E F G */
0x7B, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
/* 0xC8 H I ---- ö ---- */
0x48, 0x49, 0x07, 0x93, 0x94, 0x95, 0xA2, 0x07,
/* 0xD0 } J K L M N O P */
0x7D, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50,
/* 0xD8 Q R ---- ü */
0x51, 0x52, 0x07, 0x96, 0x81, 0x97, 0xA3, 0x98,
/* 0xE0 \ S T U V W X */
0x5C, 0xF6, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
/* 0xE8 Y Z ---- Ö ---- ---- ---- */
0x59, 0x5A, 0xFD, 0x07, 0x99, 0x07, 0x07, 0x07,
/* 0xF0 0 1 2 3 4 5 6 7 */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
/* 0xF8 8 9 ---- ---- Ü ---- ---- ---- */
0x38, 0x39, 0x07, 0x07, 0x9A, 0x07, 0x07, 0x07
};
/*
* EBCDIC (capitals) -> ASCII (small case)
*/
__u8 _ebcasc_reduce_case[256] =
{
/* 0x00 NUL SOH STX ETX *SEL HT *RNL DEL */
0x00, 0x01, 0x02, 0x03, 0x07, 0x09, 0x07, 0x7F,
/* 0x08 -GE -SPS -RPT VT FF CR SO SI */
0x07, 0x07, 0x07, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
/* 0x10 DLE DC1 DC2 DC3 -RES -NL BS -POC
-ENP ->LF */
0x10, 0x11, 0x12, 0x13, 0x07, 0x0A, 0x08, 0x07,
/* 0x18 CAN EM -UBS -CU1 -IFS -IGS -IRS -ITB
-IUS */
0x18, 0x19, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
/* 0x20 -DS -SOS FS -WUS -BYP LF ETB ESC
-INP */
0x07, 0x07, 0x1C, 0x07, 0x07, 0x0A, 0x17, 0x1B,
/* 0x28 -SA -SFE -SM -CSP -MFA ENQ ACK BEL
-SW */
0x07, 0x07, 0x07, 0x07, 0x07, 0x05, 0x06, 0x07,
/* 0x30 ---- ---- SYN -IR -PP -TRN -NBS EOT */
0x07, 0x07, 0x16, 0x07, 0x07, 0x07, 0x07, 0x04,
/* 0x38 -SBS -IT -RFF -CU3 DC4 NAK ---- SUB */
0x07, 0x07, 0x07, 0x07, 0x14, 0x15, 0x07, 0x1A,
/* 0x40 SP RSP ä ---- */
0x20, 0xFF, 0x83, 0x84, 0x85, 0xA0, 0x07, 0x86,
/* 0x48 . < ( + | */
0x87, 0xA4, 0x9B, 0x2E, 0x3C, 0x28, 0x2B, 0x7C,
/* 0x50 & ---- */
0x26, 0x82, 0x88, 0x89, 0x8A, 0xA1, 0x8C, 0x07,
/* 0x58 ß ! $ * ) ; */
0x8D, 0xE1, 0x21, 0x24, 0x2A, 0x29, 0x3B, 0xAA,
/* 0x60 - / ---- Ä ---- ---- ---- */
0x2D, 0x2F, 0x07, 0x84, 0x07, 0x07, 0x07, 0x8F,
/* 0x68 ---- , % _ > ? */
0x80, 0xA5, 0x07, 0x2C, 0x25, 0x5F, 0x3E, 0x3F,
/* 0x70 ---- ---- ---- ---- ---- ---- ---- */
0x07, 0x90, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
/* 0x78 * ` : # @ ' = " */
0x70, 0x60, 0x3A, 0x23, 0x40, 0x27, 0x3D, 0x22,
/* 0x80 * a b c d e f g */
0x07, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
/* 0x88 h i ---- ---- ---- */
0x68, 0x69, 0xAE, 0xAF, 0x07, 0x07, 0x07, 0xF1,
/* 0x90 ° j k l m n o p */
0xF8, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70,
/* 0x98 q r ---- ---- */
0x71, 0x72, 0xA6, 0xA7, 0x91, 0x07, 0x92, 0x07,
/* 0xA0 ~ s t u v w x */
0xE6, 0x7E, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
/* 0xA8 y z ---- ---- ---- ---- */
0x79, 0x7A, 0xAD, 0xAB, 0x07, 0x07, 0x07, 0x07,
/* 0xB0 ^ ---- § ---- */
0x5E, 0x9C, 0x9D, 0xFA, 0x07, 0x07, 0x07, 0xAC,
/* 0xB8 ---- [ ] ---- ---- ---- ---- */
0xAB, 0x07, 0x5B, 0x5D, 0x07, 0x07, 0x07, 0x07,
/* 0xC0 { A B C D E F G */
0x7B, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
/* 0xC8 H I ---- ö ---- */
0x68, 0x69, 0x07, 0x93, 0x94, 0x95, 0xA2, 0x07,
/* 0xD0 } J K L M N O P */
0x7D, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70,
/* 0xD8 Q R ---- ü */
0x71, 0x72, 0x07, 0x96, 0x81, 0x97, 0xA3, 0x98,
/* 0xE0 \ S T U V W X */
0x5C, 0xF6, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
/* 0xE8 Y Z ---- Ö ---- ---- ---- */
0x79, 0x7A, 0xFD, 0x07, 0x94, 0x07, 0x07, 0x07,
/* 0xF0 0 1 2 3 4 5 6 7 */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
/* 0xF8 8 9 ---- ---- Ü ---- ---- ---- */
0x38, 0x39, 0x07, 0x07, 0x81, 0x07, 0x07, 0x07
};
| gpl-2.0 |
tinixx/linux | net/ipv4/netfilter/nf_tables_ipv4.c | 612 | 3184 | /*
* Copyright (c) 2008 Patrick McHardy <kaber@trash.net>
* Copyright (c) 2012-2013 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.
*
* Development of this code funded by Astaro AG (http://www.astaro.com/)
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/ip.h>
#include <linux/netfilter_ipv4.h>
#include <net/netfilter/nf_tables.h>
#include <net/net_namespace.h>
#include <net/ip.h>
#include <net/netfilter/nf_tables_ipv4.h>
static unsigned int nft_do_chain_ipv4(const struct nf_hook_ops *ops,
struct sk_buff *skb,
const struct nf_hook_state *state)
{
struct nft_pktinfo pkt;
nft_set_pktinfo_ipv4(&pkt, ops, skb, state);
return nft_do_chain(&pkt, ops);
}
static unsigned int nft_ipv4_output(const struct nf_hook_ops *ops,
struct sk_buff *skb,
const struct nf_hook_state *state)
{
if (unlikely(skb->len < sizeof(struct iphdr) ||
ip_hdr(skb)->ihl < sizeof(struct iphdr) / 4)) {
if (net_ratelimit())
pr_info("nf_tables_ipv4: ignoring short SOCK_RAW "
"packet\n");
return NF_ACCEPT;
}
return nft_do_chain_ipv4(ops, skb, state);
}
struct nft_af_info nft_af_ipv4 __read_mostly = {
.family = NFPROTO_IPV4,
.nhooks = NF_INET_NUMHOOKS,
.owner = THIS_MODULE,
.nops = 1,
.hooks = {
[NF_INET_LOCAL_IN] = nft_do_chain_ipv4,
[NF_INET_LOCAL_OUT] = nft_ipv4_output,
[NF_INET_FORWARD] = nft_do_chain_ipv4,
[NF_INET_PRE_ROUTING] = nft_do_chain_ipv4,
[NF_INET_POST_ROUTING] = nft_do_chain_ipv4,
},
};
EXPORT_SYMBOL_GPL(nft_af_ipv4);
static int nf_tables_ipv4_init_net(struct net *net)
{
net->nft.ipv4 = kmalloc(sizeof(struct nft_af_info), GFP_KERNEL);
if (net->nft.ipv4 == NULL)
return -ENOMEM;
memcpy(net->nft.ipv4, &nft_af_ipv4, sizeof(nft_af_ipv4));
if (nft_register_afinfo(net, net->nft.ipv4) < 0)
goto err;
return 0;
err:
kfree(net->nft.ipv4);
return -ENOMEM;
}
static void nf_tables_ipv4_exit_net(struct net *net)
{
nft_unregister_afinfo(net->nft.ipv4);
kfree(net->nft.ipv4);
}
static struct pernet_operations nf_tables_ipv4_net_ops = {
.init = nf_tables_ipv4_init_net,
.exit = nf_tables_ipv4_exit_net,
};
static const struct nf_chain_type filter_ipv4 = {
.name = "filter",
.type = NFT_CHAIN_T_DEFAULT,
.family = NFPROTO_IPV4,
.owner = THIS_MODULE,
.hook_mask = (1 << NF_INET_LOCAL_IN) |
(1 << NF_INET_LOCAL_OUT) |
(1 << NF_INET_FORWARD) |
(1 << NF_INET_PRE_ROUTING) |
(1 << NF_INET_POST_ROUTING),
};
static int __init nf_tables_ipv4_init(void)
{
int ret;
nft_register_chain_type(&filter_ipv4);
ret = register_pernet_subsys(&nf_tables_ipv4_net_ops);
if (ret < 0)
nft_unregister_chain_type(&filter_ipv4);
return ret;
}
static void __exit nf_tables_ipv4_exit(void)
{
unregister_pernet_subsys(&nf_tables_ipv4_net_ops);
nft_unregister_chain_type(&filter_ipv4);
}
module_init(nf_tables_ipv4_init);
module_exit(nf_tables_ipv4_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
MODULE_ALIAS_NFT_FAMILY(AF_INET);
| gpl-2.0 |
HelllGuest/sprout_kernel | drivers/usb/gadget/uvc_queue.c | 1892 | 10318 | /*
* uvc_queue.c -- USB Video Class driver - Buffers management
*
* Copyright (C) 2005-2010
* Laurent Pinchart (laurent.pinchart@ideasonboard.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/atomic.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/videodev2.h>
#include <linux/vmalloc.h>
#include <linux/wait.h>
#include <media/videobuf2-vmalloc.h>
#include "uvc.h"
/* ------------------------------------------------------------------------
* Video buffers queue management.
*
* Video queues is initialized by uvc_queue_init(). The function performs
* basic initialization of the uvc_video_queue struct and never fails.
*
* Video buffers are managed by videobuf2. The driver uses a mutex to protect
* the videobuf2 queue operations by serializing calls to videobuf2 and a
* spinlock to protect the IRQ queue that holds the buffers to be processed by
* the driver.
*/
/* -----------------------------------------------------------------------------
* videobuf2 queue operations
*/
static int uvc_queue_setup(struct vb2_queue *vq, const struct v4l2_format *fmt,
unsigned int *nbuffers, unsigned int *nplanes,
unsigned int sizes[], void *alloc_ctxs[])
{
struct uvc_video_queue *queue = vb2_get_drv_priv(vq);
struct uvc_video *video = container_of(queue, struct uvc_video, queue);
if (*nbuffers > UVC_MAX_VIDEO_BUFFERS)
*nbuffers = UVC_MAX_VIDEO_BUFFERS;
*nplanes = 1;
sizes[0] = video->imagesize;
return 0;
}
static int uvc_buffer_prepare(struct vb2_buffer *vb)
{
struct uvc_video_queue *queue = vb2_get_drv_priv(vb->vb2_queue);
struct uvc_buffer *buf = container_of(vb, struct uvc_buffer, buf);
if (vb->v4l2_buf.type == V4L2_BUF_TYPE_VIDEO_OUTPUT &&
vb2_get_plane_payload(vb, 0) > vb2_plane_size(vb, 0)) {
uvc_trace(UVC_TRACE_CAPTURE, "[E] Bytes used out of bounds.\n");
return -EINVAL;
}
if (unlikely(queue->flags & UVC_QUEUE_DISCONNECTED))
return -ENODEV;
buf->state = UVC_BUF_STATE_QUEUED;
buf->mem = vb2_plane_vaddr(vb, 0);
buf->length = vb2_plane_size(vb, 0);
if (vb->v4l2_buf.type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
buf->bytesused = 0;
else
buf->bytesused = vb2_get_plane_payload(vb, 0);
return 0;
}
static void uvc_buffer_queue(struct vb2_buffer *vb)
{
struct uvc_video_queue *queue = vb2_get_drv_priv(vb->vb2_queue);
struct uvc_buffer *buf = container_of(vb, struct uvc_buffer, buf);
unsigned long flags;
spin_lock_irqsave(&queue->irqlock, flags);
if (likely(!(queue->flags & UVC_QUEUE_DISCONNECTED))) {
list_add_tail(&buf->queue, &queue->irqqueue);
} else {
/* If the device is disconnected return the buffer to userspace
* directly. The next QBUF call will fail with -ENODEV.
*/
buf->state = UVC_BUF_STATE_ERROR;
vb2_buffer_done(&buf->buf, VB2_BUF_STATE_ERROR);
}
spin_unlock_irqrestore(&queue->irqlock, flags);
}
static struct vb2_ops uvc_queue_qops = {
.queue_setup = uvc_queue_setup,
.buf_prepare = uvc_buffer_prepare,
.buf_queue = uvc_buffer_queue,
};
static int uvc_queue_init(struct uvc_video_queue *queue,
enum v4l2_buf_type type)
{
int ret;
queue->queue.type = type;
queue->queue.io_modes = VB2_MMAP | VB2_USERPTR;
queue->queue.drv_priv = queue;
queue->queue.buf_struct_size = sizeof(struct uvc_buffer);
queue->queue.ops = &uvc_queue_qops;
queue->queue.mem_ops = &vb2_vmalloc_memops;
ret = vb2_queue_init(&queue->queue);
if (ret)
return ret;
mutex_init(&queue->mutex);
spin_lock_init(&queue->irqlock);
INIT_LIST_HEAD(&queue->irqqueue);
queue->flags = 0;
return 0;
}
/*
* Free the video buffers.
*/
static void uvc_free_buffers(struct uvc_video_queue *queue)
{
mutex_lock(&queue->mutex);
vb2_queue_release(&queue->queue);
mutex_unlock(&queue->mutex);
}
/*
* Allocate the video buffers.
*/
static int uvc_alloc_buffers(struct uvc_video_queue *queue,
struct v4l2_requestbuffers *rb)
{
int ret;
mutex_lock(&queue->mutex);
ret = vb2_reqbufs(&queue->queue, rb);
mutex_unlock(&queue->mutex);
return ret ? ret : rb->count;
}
static int uvc_query_buffer(struct uvc_video_queue *queue,
struct v4l2_buffer *buf)
{
int ret;
mutex_lock(&queue->mutex);
ret = vb2_querybuf(&queue->queue, buf);
mutex_unlock(&queue->mutex);
return ret;
}
static int uvc_queue_buffer(struct uvc_video_queue *queue,
struct v4l2_buffer *buf)
{
unsigned long flags;
int ret;
mutex_lock(&queue->mutex);
ret = vb2_qbuf(&queue->queue, buf);
if (ret < 0)
goto done;
spin_lock_irqsave(&queue->irqlock, flags);
ret = (queue->flags & UVC_QUEUE_PAUSED) != 0;
queue->flags &= ~UVC_QUEUE_PAUSED;
spin_unlock_irqrestore(&queue->irqlock, flags);
done:
mutex_unlock(&queue->mutex);
return ret;
}
/*
* Dequeue a video buffer. If nonblocking is false, block until a buffer is
* available.
*/
static int uvc_dequeue_buffer(struct uvc_video_queue *queue,
struct v4l2_buffer *buf, int nonblocking)
{
int ret;
mutex_lock(&queue->mutex);
ret = vb2_dqbuf(&queue->queue, buf, nonblocking);
mutex_unlock(&queue->mutex);
return ret;
}
/*
* Poll the video queue.
*
* This function implements video queue polling and is intended to be used by
* the device poll handler.
*/
static unsigned int uvc_queue_poll(struct uvc_video_queue *queue,
struct file *file, poll_table *wait)
{
unsigned int ret;
mutex_lock(&queue->mutex);
ret = vb2_poll(&queue->queue, file, wait);
mutex_unlock(&queue->mutex);
return ret;
}
static int uvc_queue_mmap(struct uvc_video_queue *queue,
struct vm_area_struct *vma)
{
int ret;
mutex_lock(&queue->mutex);
ret = vb2_mmap(&queue->queue, vma);
mutex_unlock(&queue->mutex);
return ret;
}
#ifndef CONFIG_MMU
/*
* Get unmapped area.
*
* NO-MMU arch need this function to make mmap() work correctly.
*/
static unsigned long uvc_queue_get_unmapped_area(struct uvc_video_queue *queue,
unsigned long pgoff)
{
unsigned long ret;
mutex_lock(&queue->mutex);
ret = vb2_get_unmapped_area(&queue->queue, 0, 0, pgoff, 0);
mutex_unlock(&queue->mutex);
return ret;
}
#endif
/*
* Cancel the video buffers queue.
*
* Cancelling the queue marks all buffers on the irq queue as erroneous,
* wakes them up and removes them from the queue.
*
* If the disconnect parameter is set, further calls to uvc_queue_buffer will
* fail with -ENODEV.
*
* This function acquires the irq spinlock and can be called from interrupt
* context.
*/
static void uvc_queue_cancel(struct uvc_video_queue *queue, int disconnect)
{
struct uvc_buffer *buf;
unsigned long flags;
spin_lock_irqsave(&queue->irqlock, flags);
while (!list_empty(&queue->irqqueue)) {
buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
queue);
list_del(&buf->queue);
buf->state = UVC_BUF_STATE_ERROR;
vb2_buffer_done(&buf->buf, VB2_BUF_STATE_ERROR);
}
/* This must be protected by the irqlock spinlock to avoid race
* conditions between uvc_queue_buffer and the disconnection event that
* could result in an interruptible wait in uvc_dequeue_buffer. Do not
* blindly replace this logic by checking for the UVC_DEV_DISCONNECTED
* state outside the queue code.
*/
if (disconnect)
queue->flags |= UVC_QUEUE_DISCONNECTED;
spin_unlock_irqrestore(&queue->irqlock, flags);
}
/*
* Enable or disable the video buffers queue.
*
* The queue must be enabled before starting video acquisition and must be
* disabled after stopping it. This ensures that the video buffers queue
* state can be properly initialized before buffers are accessed from the
* interrupt handler.
*
* Enabling the video queue initializes parameters (such as sequence number,
* sync pattern, ...). If the queue is already enabled, return -EBUSY.
*
* Disabling the video queue cancels the queue and removes all buffers from
* the main queue.
*
* This function can't be called from interrupt context. Use
* uvc_queue_cancel() instead.
*/
static int uvc_queue_enable(struct uvc_video_queue *queue, int enable)
{
unsigned long flags;
int ret = 0;
mutex_lock(&queue->mutex);
if (enable) {
ret = vb2_streamon(&queue->queue, queue->queue.type);
if (ret < 0)
goto done;
queue->sequence = 0;
queue->buf_used = 0;
} else {
ret = vb2_streamoff(&queue->queue, queue->queue.type);
if (ret < 0)
goto done;
spin_lock_irqsave(&queue->irqlock, flags);
INIT_LIST_HEAD(&queue->irqqueue);
/*
* FIXME: We need to clear the DISCONNECTED flag to ensure that
* applications will be able to queue buffers for the next
* streaming run. However, clearing it here doesn't guarantee
* that the device will be reconnected in the meantime.
*/
queue->flags &= ~UVC_QUEUE_DISCONNECTED;
spin_unlock_irqrestore(&queue->irqlock, flags);
}
done:
mutex_unlock(&queue->mutex);
return ret;
}
/* called with &queue_irqlock held.. */
static struct uvc_buffer *uvc_queue_next_buffer(struct uvc_video_queue *queue,
struct uvc_buffer *buf)
{
struct uvc_buffer *nextbuf;
if ((queue->flags & UVC_QUEUE_DROP_INCOMPLETE) &&
buf->length != buf->bytesused) {
buf->state = UVC_BUF_STATE_QUEUED;
vb2_set_plane_payload(&buf->buf, 0, 0);
return buf;
}
list_del(&buf->queue);
if (!list_empty(&queue->irqqueue))
nextbuf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
queue);
else
nextbuf = NULL;
/*
* FIXME: with videobuf2, the sequence number or timestamp fields
* are valid only for video capture devices and the UVC gadget usually
* is a video output device. Keeping these until the specs are clear on
* this aspect.
*/
buf->buf.v4l2_buf.sequence = queue->sequence++;
do_gettimeofday(&buf->buf.v4l2_buf.timestamp);
vb2_set_plane_payload(&buf->buf, 0, buf->bytesused);
vb2_buffer_done(&buf->buf, VB2_BUF_STATE_DONE);
return nextbuf;
}
static struct uvc_buffer *uvc_queue_head(struct uvc_video_queue *queue)
{
struct uvc_buffer *buf = NULL;
if (!list_empty(&queue->irqqueue))
buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
queue);
else
queue->flags |= UVC_QUEUE_PAUSED;
return buf;
}
| gpl-2.0 |
RadonX-MM/kernel | drivers/media/platform/msm/camera_v2/sensor/io/msm_camera_i2c_mux.c | 2148 | 5319 | /* Copyright (c) 2011-2013, The Linux Foundatation. 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/delay.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/module.h>
#include <mach/board.h>
#include <mach/camera.h>
#include "msm_camera_i2c_mux.h"
/* TODO move this somewhere else */
#define MSM_I2C_MUX_DRV_NAME "msm_cam_i2c_mux"
static int msm_i2c_mux_config(struct i2c_mux_device *mux_device, uint8_t *mode)
{
uint32_t val;
val = msm_camera_io_r(mux_device->ctl_base);
if (*mode == MODE_DUAL) {
msm_camera_io_w(val | 0x3, mux_device->ctl_base);
} else if (*mode == MODE_L) {
msm_camera_io_w(((val | 0x2) & ~(0x1)), mux_device->ctl_base);
val = msm_camera_io_r(mux_device->ctl_base);
CDBG("the camio mode config left value is %d\n", val);
} else {
msm_camera_io_w(((val | 0x1) & ~(0x2)), mux_device->ctl_base);
val = msm_camera_io_r(mux_device->ctl_base);
CDBG("the camio mode config right value is %d\n", val);
}
return 0;
}
static int msm_i2c_mux_init(struct i2c_mux_device *mux_device)
{
int rc = 0, val = 0;
if (mux_device->use_count == 0) {
mux_device->ctl_base = ioremap(mux_device->ctl_mem->start,
resource_size(mux_device->ctl_mem));
if (!mux_device->ctl_base) {
rc = -ENOMEM;
return rc;
}
mux_device->rw_base = ioremap(mux_device->rw_mem->start,
resource_size(mux_device->rw_mem));
if (!mux_device->rw_base) {
rc = -ENOMEM;
iounmap(mux_device->ctl_base);
return rc;
}
val = msm_camera_io_r(mux_device->rw_base);
msm_camera_io_w((val | 0x200), mux_device->rw_base);
}
mux_device->use_count++;
return 0;
};
static int msm_i2c_mux_release(struct i2c_mux_device *mux_device)
{
int val = 0;
mux_device->use_count--;
if (mux_device->use_count == 0) {
val = msm_camera_io_r(mux_device->rw_base);
msm_camera_io_w((val & ~0x200), mux_device->rw_base);
iounmap(mux_device->rw_base);
iounmap(mux_device->ctl_base);
}
return 0;
}
static long msm_i2c_mux_subdev_ioctl(struct v4l2_subdev *sd,
unsigned int cmd, void *arg)
{
struct i2c_mux_device *mux_device;
int rc = 0;
mux_device = v4l2_get_subdevdata(sd);
if (mux_device == NULL) {
rc = -ENOMEM;
return rc;
}
mutex_lock(&mux_device->mutex);
switch (cmd) {
case VIDIOC_MSM_I2C_MUX_CFG:
rc = msm_i2c_mux_config(mux_device, (uint8_t *) arg);
break;
case VIDIOC_MSM_I2C_MUX_INIT:
rc = msm_i2c_mux_init(mux_device);
break;
case VIDIOC_MSM_I2C_MUX_RELEASE:
rc = msm_i2c_mux_release(mux_device);
break;
default:
rc = -ENOIOCTLCMD;
}
mutex_unlock(&mux_device->mutex);
return rc;
}
static struct v4l2_subdev_core_ops msm_i2c_mux_subdev_core_ops = {
.ioctl = &msm_i2c_mux_subdev_ioctl,
};
static const struct v4l2_subdev_ops msm_i2c_mux_subdev_ops = {
.core = &msm_i2c_mux_subdev_core_ops,
};
static int __devinit i2c_mux_probe(struct platform_device *pdev)
{
struct i2c_mux_device *mux_device;
int rc = 0;
CDBG("%s: device id = %d\n", __func__, pdev->id);
mux_device = kzalloc(sizeof(struct i2c_mux_device), GFP_KERNEL);
if (!mux_device) {
pr_err("%s: no enough memory\n", __func__);
return -ENOMEM;
}
v4l2_subdev_init(&mux_device->subdev, &msm_i2c_mux_subdev_ops);
v4l2_set_subdevdata(&mux_device->subdev, mux_device);
platform_set_drvdata(pdev, &mux_device->subdev);
mutex_init(&mux_device->mutex);
mux_device->ctl_mem = platform_get_resource_byname(pdev,
IORESOURCE_MEM, "i2c_mux_ctl");
if (!mux_device->ctl_mem) {
pr_err("%s: no mem resource?\n", __func__);
rc = -ENODEV;
goto i2c_mux_no_resource;
}
mux_device->ctl_io = request_mem_region(mux_device->ctl_mem->start,
resource_size(mux_device->ctl_mem), pdev->name);
if (!mux_device->ctl_io) {
pr_err("%s: no valid mem region\n", __func__);
rc = -EBUSY;
goto i2c_mux_no_resource;
}
mux_device->rw_mem = platform_get_resource_byname(pdev,
IORESOURCE_MEM, "i2c_mux_rw");
if (!mux_device->rw_mem) {
pr_err("%s: no mem resource?\n", __func__);
rc = -ENODEV;
goto i2c_mux_no_resource;
}
mux_device->rw_io = request_mem_region(mux_device->rw_mem->start,
resource_size(mux_device->rw_mem), pdev->name);
if (!mux_device->rw_io) {
pr_err("%s: no valid mem region\n", __func__);
rc = -EBUSY;
goto i2c_mux_no_resource;
}
mux_device->pdev = pdev;
return 0;
i2c_mux_no_resource:
mutex_destroy(&mux_device->mutex);
kfree(mux_device);
return 0;
}
static struct platform_driver i2c_mux_driver = {
.probe = i2c_mux_probe,
.driver = {
.name = MSM_I2C_MUX_DRV_NAME,
.owner = THIS_MODULE,
},
};
static int __init msm_camera_i2c_mux_init_module(void)
{
return platform_driver_register(&i2c_mux_driver);
}
static void __exit msm_camera_i2c_mux_exit_module(void)
{
platform_driver_unregister(&i2c_mux_driver);
}
module_init(msm_camera_i2c_mux_init_module);
module_exit(msm_camera_i2c_mux_exit_module);
MODULE_DESCRIPTION("MSM Camera I2C mux driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
AnguisCaptor/PwnKernel_Shamu_M | arch/arm/mach-shark/leds.c | 2404 | 2403 | /*
* DIGITAL Shark LED control routines.
*
* Driver for the 3 user LEDs found on the Shark
* Based on Versatile and RealView machine LED code
*
* License terms: GNU General Public License (GPL) version 2
* Author: Bryan Wu <bryan.wu@canonical.com>
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/slab.h>
#include <linux/leds.h>
#include <asm/mach-types.h>
#if defined(CONFIG_NEW_LEDS) && defined(CONFIG_LEDS_CLASS)
struct shark_led {
struct led_classdev cdev;
u8 mask;
};
/*
* The triggers lines up below will only be used if the
* LED triggers are compiled in.
*/
static const struct {
const char *name;
const char *trigger;
} shark_leds[] = {
{ "shark:amber0", "default-on", }, /* Bit 5 */
{ "shark:green", "heartbeat", }, /* Bit 6 */
{ "shark:amber1", "cpu0" }, /* Bit 7 */
};
static u16 led_reg_read(void)
{
outw(0x09, 0x24);
return inw(0x26);
}
static void led_reg_write(u16 value)
{
outw(0x09, 0x24);
outw(value, 0x26);
}
static void shark_led_set(struct led_classdev *cdev,
enum led_brightness b)
{
struct shark_led *led = container_of(cdev,
struct shark_led, cdev);
u16 reg = led_reg_read();
if (b != LED_OFF)
reg |= led->mask;
else
reg &= ~led->mask;
led_reg_write(reg);
}
static enum led_brightness shark_led_get(struct led_classdev *cdev)
{
struct shark_led *led = container_of(cdev,
struct shark_led, cdev);
u16 reg = led_reg_read();
return (reg & led->mask) ? LED_FULL : LED_OFF;
}
static int __init shark_leds_init(void)
{
int i;
u16 reg;
if (!machine_is_shark())
return -ENODEV;
for (i = 0; i < ARRAY_SIZE(shark_leds); i++) {
struct shark_led *led;
led = kzalloc(sizeof(*led), GFP_KERNEL);
if (!led)
break;
led->cdev.name = shark_leds[i].name;
led->cdev.brightness_set = shark_led_set;
led->cdev.brightness_get = shark_led_get;
led->cdev.default_trigger = shark_leds[i].trigger;
/* Count in 5 bits offset */
led->mask = BIT(i + 5);
if (led_classdev_register(NULL, &led->cdev) < 0) {
kfree(led);
break;
}
}
/* Make LEDs independent of power-state */
request_region(0x24, 4, "led_reg");
reg = led_reg_read();
reg |= 1 << 10;
led_reg_write(reg);
return 0;
}
/*
* Since we may have triggers on any subsystem, defer registration
* until after subsystem_init.
*/
fs_initcall(shark_leds_init);
#endif
| gpl-2.0 |
paloda/android_kernel_bq_vegetalte | drivers/watchdog/sch311x_wdt.c | 2404 | 13891 | /*
* sch311x_wdt.c - Driver for the SCH311x Super-I/O chips
* integrated watchdog.
*
* (c) Copyright 2008 Wim Van Sebroeck <wim@iguana.be>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Neither Wim Van Sebroeck nor Iguana vzw. admit liability nor
* provide warranty for any of this software. This material is
* provided "AS-IS" and at no charge.
*/
/*
* Includes, defines, variables, module parameters, ...
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
/* Includes */
#include <linux/module.h> /* For module specific items */
#include <linux/moduleparam.h> /* For new moduleparam's */
#include <linux/types.h> /* For standard types (like size_t) */
#include <linux/errno.h> /* For the -ENODEV/... values */
#include <linux/kernel.h> /* For printk/... */
#include <linux/miscdevice.h> /* For MODULE_ALIAS_MISCDEV
(WATCHDOG_MINOR) */
#include <linux/watchdog.h> /* For the watchdog specific items */
#include <linux/init.h> /* For __init/__exit/... */
#include <linux/fs.h> /* For file operations */
#include <linux/platform_device.h> /* For platform_driver framework */
#include <linux/ioport.h> /* For io-port access */
#include <linux/spinlock.h> /* For spin_lock/spin_unlock/... */
#include <linux/uaccess.h> /* For copy_to_user/put_user/... */
#include <linux/io.h> /* For inb/outb/... */
/* Module and version information */
#define DRV_NAME "sch311x_wdt"
/* Runtime registers */
#define GP60 0x47
#define WDT_TIME_OUT 0x65
#define WDT_VAL 0x66
#define WDT_CFG 0x67
#define WDT_CTRL 0x68
/* internal variables */
static unsigned long sch311x_wdt_is_open;
static char sch311x_wdt_expect_close;
static struct platform_device *sch311x_wdt_pdev;
static int sch311x_ioports[] = { 0x2e, 0x4e, 0x162e, 0x164e, 0x00 };
static struct { /* The devices private data */
/* the Runtime Register base address */
unsigned short runtime_reg;
/* The card's boot status */
int boot_status;
/* the lock for io operations */
spinlock_t io_lock;
} sch311x_wdt_data;
/* Module load parameters */
static unsigned short force_id;
module_param(force_id, ushort, 0);
MODULE_PARM_DESC(force_id, "Override the detected device ID");
#define WATCHDOG_TIMEOUT 60 /* 60 sec default timeout */
static int timeout = WATCHDOG_TIMEOUT; /* in seconds */
module_param(timeout, int, 0);
MODULE_PARM_DESC(timeout,
"Watchdog timeout in seconds. 1<= timeout <=15300, default="
__MODULE_STRING(WATCHDOG_TIMEOUT) ".");
static bool nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout,
"Watchdog cannot be stopped once started (default="
__MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
/*
* Super-IO functions
*/
static inline void sch311x_sio_enter(int sio_config_port)
{
outb(0x55, sio_config_port);
}
static inline void sch311x_sio_exit(int sio_config_port)
{
outb(0xaa, sio_config_port);
}
static inline int sch311x_sio_inb(int sio_config_port, int reg)
{
outb(reg, sio_config_port);
return inb(sio_config_port + 1);
}
static inline void sch311x_sio_outb(int sio_config_port, int reg, int val)
{
outb(reg, sio_config_port);
outb(val, sio_config_port + 1);
}
/*
* Watchdog Operations
*/
static void sch311x_wdt_set_timeout(int t)
{
unsigned char timeout_unit = 0x80;
/* When new timeout is bigger then 255 seconds, we will use minutes */
if (t > 255) {
timeout_unit = 0;
t /= 60;
}
/* -- Watchdog Timeout --
* Bit 0-6 (Reserved)
* Bit 7 WDT Time-out Value Units Select
* (0 = Minutes, 1 = Seconds)
*/
outb(timeout_unit, sch311x_wdt_data.runtime_reg + WDT_TIME_OUT);
/* -- Watchdog Timer Time-out Value --
* Bit 0-7 Binary coded units (0=Disabled, 1..255)
*/
outb(t, sch311x_wdt_data.runtime_reg + WDT_VAL);
}
static void sch311x_wdt_start(void)
{
unsigned char t;
spin_lock(&sch311x_wdt_data.io_lock);
/* set watchdog's timeout */
sch311x_wdt_set_timeout(timeout);
/* enable the watchdog */
/* -- General Purpose I/O Bit 6.0 --
* Bit 0, In/Out: 0 = Output, 1 = Input
* Bit 1, Polarity: 0 = No Invert, 1 = Invert
* Bit 2-3, Function select: 00 = GPI/O, 01 = LED1, 11 = WDT,
* 10 = Either Edge Triggered Intr.4
* Bit 4-6 (Reserved)
* Bit 7, Output Type: 0 = Push Pull Bit, 1 = Open Drain
*/
t = inb(sch311x_wdt_data.runtime_reg + GP60);
outb((t & ~0x0d) | 0x0c, sch311x_wdt_data.runtime_reg + GP60);
spin_unlock(&sch311x_wdt_data.io_lock);
}
static void sch311x_wdt_stop(void)
{
unsigned char t;
spin_lock(&sch311x_wdt_data.io_lock);
/* stop the watchdog */
t = inb(sch311x_wdt_data.runtime_reg + GP60);
outb((t & ~0x0d) | 0x01, sch311x_wdt_data.runtime_reg + GP60);
/* disable timeout by setting it to 0 */
sch311x_wdt_set_timeout(0);
spin_unlock(&sch311x_wdt_data.io_lock);
}
static void sch311x_wdt_keepalive(void)
{
spin_lock(&sch311x_wdt_data.io_lock);
sch311x_wdt_set_timeout(timeout);
spin_unlock(&sch311x_wdt_data.io_lock);
}
static int sch311x_wdt_set_heartbeat(int t)
{
if (t < 1 || t > (255*60))
return -EINVAL;
/* When new timeout is bigger then 255 seconds,
* we will round up to minutes (with a max of 255) */
if (t > 255)
t = (((t - 1) / 60) + 1) * 60;
timeout = t;
return 0;
}
static void sch311x_wdt_get_status(int *status)
{
unsigned char new_status;
*status = 0;
spin_lock(&sch311x_wdt_data.io_lock);
/* -- Watchdog timer control --
* Bit 0 Status Bit: 0 = Timer counting, 1 = Timeout occurred
* Bit 1 Reserved
* Bit 2 Force Timeout: 1 = Forces WD timeout event (self-cleaning)
* Bit 3 P20 Force Timeout enabled:
* 0 = P20 activity does not generate the WD timeout event
* 1 = P20 Allows rising edge of P20, from the keyboard
* controller, to force the WD timeout event.
* Bit 4-7 Reserved
*/
new_status = inb(sch311x_wdt_data.runtime_reg + WDT_CTRL);
if (new_status & 0x01)
*status |= WDIOF_CARDRESET;
spin_unlock(&sch311x_wdt_data.io_lock);
}
/*
* /dev/watchdog handling
*/
static ssize_t sch311x_wdt_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
if (count) {
if (!nowayout) {
size_t i;
sch311x_wdt_expect_close = 0;
for (i = 0; i != count; i++) {
char c;
if (get_user(c, buf + i))
return -EFAULT;
if (c == 'V')
sch311x_wdt_expect_close = 42;
}
}
sch311x_wdt_keepalive();
}
return count;
}
static long sch311x_wdt_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
int status;
int new_timeout;
void __user *argp = (void __user *)arg;
int __user *p = argp;
static const struct watchdog_info ident = {
.options = WDIOF_KEEPALIVEPING |
WDIOF_SETTIMEOUT |
WDIOF_MAGICCLOSE,
.firmware_version = 1,
.identity = DRV_NAME,
};
switch (cmd) {
case WDIOC_GETSUPPORT:
if (copy_to_user(argp, &ident, sizeof(ident)))
return -EFAULT;
break;
case WDIOC_GETSTATUS:
{
sch311x_wdt_get_status(&status);
return put_user(status, p);
}
case WDIOC_GETBOOTSTATUS:
return put_user(sch311x_wdt_data.boot_status, p);
case WDIOC_SETOPTIONS:
{
int options, retval = -EINVAL;
if (get_user(options, p))
return -EFAULT;
if (options & WDIOS_DISABLECARD) {
sch311x_wdt_stop();
retval = 0;
}
if (options & WDIOS_ENABLECARD) {
sch311x_wdt_start();
retval = 0;
}
return retval;
}
case WDIOC_KEEPALIVE:
sch311x_wdt_keepalive();
break;
case WDIOC_SETTIMEOUT:
if (get_user(new_timeout, p))
return -EFAULT;
if (sch311x_wdt_set_heartbeat(new_timeout))
return -EINVAL;
sch311x_wdt_keepalive();
/* Fall */
case WDIOC_GETTIMEOUT:
return put_user(timeout, p);
default:
return -ENOTTY;
}
return 0;
}
static int sch311x_wdt_open(struct inode *inode, struct file *file)
{
if (test_and_set_bit(0, &sch311x_wdt_is_open))
return -EBUSY;
/*
* Activate
*/
sch311x_wdt_start();
return nonseekable_open(inode, file);
}
static int sch311x_wdt_close(struct inode *inode, struct file *file)
{
if (sch311x_wdt_expect_close == 42) {
sch311x_wdt_stop();
} else {
pr_crit("Unexpected close, not stopping watchdog!\n");
sch311x_wdt_keepalive();
}
clear_bit(0, &sch311x_wdt_is_open);
sch311x_wdt_expect_close = 0;
return 0;
}
/*
* Kernel Interfaces
*/
static const struct file_operations sch311x_wdt_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.write = sch311x_wdt_write,
.unlocked_ioctl = sch311x_wdt_ioctl,
.open = sch311x_wdt_open,
.release = sch311x_wdt_close,
};
static struct miscdevice sch311x_wdt_miscdev = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &sch311x_wdt_fops,
};
/*
* Init & exit routines
*/
static int sch311x_wdt_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
int err;
spin_lock_init(&sch311x_wdt_data.io_lock);
if (!request_region(sch311x_wdt_data.runtime_reg + GP60, 1, DRV_NAME)) {
dev_err(dev, "Failed to request region 0x%04x-0x%04x.\n",
sch311x_wdt_data.runtime_reg + GP60,
sch311x_wdt_data.runtime_reg + GP60);
err = -EBUSY;
goto exit;
}
if (!request_region(sch311x_wdt_data.runtime_reg + WDT_TIME_OUT, 4,
DRV_NAME)) {
dev_err(dev, "Failed to request region 0x%04x-0x%04x.\n",
sch311x_wdt_data.runtime_reg + WDT_TIME_OUT,
sch311x_wdt_data.runtime_reg + WDT_CTRL);
err = -EBUSY;
goto exit_release_region;
}
/* Make sure that the watchdog is not running */
sch311x_wdt_stop();
/* Disable keyboard and mouse interaction and interrupt */
/* -- Watchdog timer configuration --
* Bit 0 Reserved
* Bit 1 Keyboard enable: 0* = No Reset, 1 = Reset WDT upon KBD Intr.
* Bit 2 Mouse enable: 0* = No Reset, 1 = Reset WDT upon Mouse Intr
* Bit 3 Reserved
* Bit 4-7 WDT Interrupt Mapping: (0000* = Disabled,
* 0001=IRQ1, 0010=(Invalid), 0011=IRQ3 to 1111=IRQ15)
*/
outb(0, sch311x_wdt_data.runtime_reg + WDT_CFG);
/* Check that the heartbeat value is within it's range ;
* if not reset to the default */
if (sch311x_wdt_set_heartbeat(timeout)) {
sch311x_wdt_set_heartbeat(WATCHDOG_TIMEOUT);
dev_info(dev, "timeout value must be 1<=x<=15300, using %d\n",
timeout);
}
/* Get status at boot */
sch311x_wdt_get_status(&sch311x_wdt_data.boot_status);
sch311x_wdt_miscdev.parent = dev;
err = misc_register(&sch311x_wdt_miscdev);
if (err != 0) {
dev_err(dev, "cannot register miscdev on minor=%d (err=%d)\n",
WATCHDOG_MINOR, err);
goto exit_release_region2;
}
dev_info(dev,
"SMSC SCH311x WDT initialized. timeout=%d sec (nowayout=%d)\n",
timeout, nowayout);
return 0;
exit_release_region2:
release_region(sch311x_wdt_data.runtime_reg + WDT_TIME_OUT, 4);
exit_release_region:
release_region(sch311x_wdt_data.runtime_reg + GP60, 1);
sch311x_wdt_data.runtime_reg = 0;
exit:
return err;
}
static int sch311x_wdt_remove(struct platform_device *pdev)
{
/* Stop the timer before we leave */
if (!nowayout)
sch311x_wdt_stop();
/* Deregister */
misc_deregister(&sch311x_wdt_miscdev);
release_region(sch311x_wdt_data.runtime_reg + WDT_TIME_OUT, 4);
release_region(sch311x_wdt_data.runtime_reg + GP60, 1);
sch311x_wdt_data.runtime_reg = 0;
return 0;
}
static void sch311x_wdt_shutdown(struct platform_device *dev)
{
/* Turn the WDT off if we have a soft shutdown */
sch311x_wdt_stop();
}
static struct platform_driver sch311x_wdt_driver = {
.probe = sch311x_wdt_probe,
.remove = sch311x_wdt_remove,
.shutdown = sch311x_wdt_shutdown,
.driver = {
.owner = THIS_MODULE,
.name = DRV_NAME,
},
};
static int __init sch311x_detect(int sio_config_port, unsigned short *addr)
{
int err = 0, reg;
unsigned short base_addr;
unsigned char dev_id;
sch311x_sio_enter(sio_config_port);
/* Check device ID. We currently know about:
* SCH3112 (0x7c), SCH3114 (0x7d), and SCH3116 (0x7f). */
reg = force_id ? force_id : sch311x_sio_inb(sio_config_port, 0x20);
if (!(reg == 0x7c || reg == 0x7d || reg == 0x7f)) {
err = -ENODEV;
goto exit;
}
dev_id = reg == 0x7c ? 2 : reg == 0x7d ? 4 : 6;
/* Select logical device A (runtime registers) */
sch311x_sio_outb(sio_config_port, 0x07, 0x0a);
/* Check if Logical Device Register is currently active */
if ((sch311x_sio_inb(sio_config_port, 0x30) & 0x01) == 0)
pr_info("Seems that LDN 0x0a is not active...\n");
/* Get the base address of the runtime registers */
base_addr = (sch311x_sio_inb(sio_config_port, 0x60) << 8) |
sch311x_sio_inb(sio_config_port, 0x61);
if (!base_addr) {
pr_err("Base address not set\n");
err = -ENODEV;
goto exit;
}
*addr = base_addr;
pr_info("Found an SMSC SCH311%d chip at 0x%04x\n", dev_id, base_addr);
exit:
sch311x_sio_exit(sio_config_port);
return err;
}
static int __init sch311x_wdt_init(void)
{
int err, i, found = 0;
unsigned short addr = 0;
for (i = 0; !found && sch311x_ioports[i]; i++)
if (sch311x_detect(sch311x_ioports[i], &addr) == 0)
found++;
if (!found)
return -ENODEV;
sch311x_wdt_data.runtime_reg = addr;
err = platform_driver_register(&sch311x_wdt_driver);
if (err)
return err;
sch311x_wdt_pdev = platform_device_register_simple(DRV_NAME, addr,
NULL, 0);
if (IS_ERR(sch311x_wdt_pdev)) {
err = PTR_ERR(sch311x_wdt_pdev);
goto unreg_platform_driver;
}
return 0;
unreg_platform_driver:
platform_driver_unregister(&sch311x_wdt_driver);
return err;
}
static void __exit sch311x_wdt_exit(void)
{
platform_device_unregister(sch311x_wdt_pdev);
platform_driver_unregister(&sch311x_wdt_driver);
}
module_init(sch311x_wdt_init);
module_exit(sch311x_wdt_exit);
MODULE_AUTHOR("Wim Van Sebroeck <wim@iguana.be>");
MODULE_DESCRIPTION("SMSC SCH311x WatchDog Timer Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
| gpl-2.0 |
lnfamous/Kernel_Stock_Pico | net/rose/rose_dev.c | 2660 | 3694 | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Copyright (C) Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk)
*/
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/sysctl.h>
#include <linux/string.h>
#include <linux/socket.h>
#include <linux/errno.h>
#include <linux/fcntl.h>
#include <linux/in.h>
#include <linux/if_ether.h>
#include <linux/slab.h>
#include <asm/system.h>
#include <asm/io.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/if_arp.h>
#include <linux/skbuff.h>
#include <net/ip.h>
#include <net/arp.h>
#include <net/ax25.h>
#include <net/rose.h>
static int rose_header(struct sk_buff *skb, struct net_device *dev,
unsigned short type,
const void *daddr, const void *saddr, unsigned len)
{
unsigned char *buff = skb_push(skb, ROSE_MIN_LEN + 2);
*buff++ = ROSE_GFI | ROSE_Q_BIT;
*buff++ = 0x00;
*buff++ = ROSE_DATA;
*buff++ = 0x7F;
*buff++ = AX25_P_IP;
if (daddr != NULL)
return 37;
return -37;
}
static int rose_rebuild_header(struct sk_buff *skb)
{
#ifdef CONFIG_INET
struct net_device *dev = skb->dev;
struct net_device_stats *stats = &dev->stats;
unsigned char *bp = (unsigned char *)skb->data;
struct sk_buff *skbn;
unsigned int len;
if (arp_find(bp + 7, skb)) {
return 1;
}
if ((skbn = skb_clone(skb, GFP_ATOMIC)) == NULL) {
kfree_skb(skb);
return 1;
}
if (skb->sk != NULL)
skb_set_owner_w(skbn, skb->sk);
kfree_skb(skb);
len = skbn->len;
if (!rose_route_frame(skbn, NULL)) {
kfree_skb(skbn);
stats->tx_errors++;
return 1;
}
stats->tx_packets++;
stats->tx_bytes += len;
#endif
return 1;
}
static int rose_set_mac_address(struct net_device *dev, void *addr)
{
struct sockaddr *sa = addr;
int err;
if (!memcpy(dev->dev_addr, sa->sa_data, dev->addr_len))
return 0;
if (dev->flags & IFF_UP) {
err = rose_add_loopback_node((rose_address *)dev->dev_addr);
if (err)
return err;
rose_del_loopback_node((rose_address *)dev->dev_addr);
}
memcpy(dev->dev_addr, sa->sa_data, dev->addr_len);
return 0;
}
static int rose_open(struct net_device *dev)
{
int err;
err = rose_add_loopback_node((rose_address *)dev->dev_addr);
if (err)
return err;
netif_start_queue(dev);
return 0;
}
static int rose_close(struct net_device *dev)
{
netif_stop_queue(dev);
rose_del_loopback_node((rose_address *)dev->dev_addr);
return 0;
}
static netdev_tx_t rose_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct net_device_stats *stats = &dev->stats;
if (!netif_running(dev)) {
printk(KERN_ERR "ROSE: rose_xmit - called when iface is down\n");
return NETDEV_TX_BUSY;
}
dev_kfree_skb(skb);
stats->tx_errors++;
return NETDEV_TX_OK;
}
static const struct header_ops rose_header_ops = {
.create = rose_header,
.rebuild= rose_rebuild_header,
};
static const struct net_device_ops rose_netdev_ops = {
.ndo_open = rose_open,
.ndo_stop = rose_close,
.ndo_start_xmit = rose_xmit,
.ndo_set_mac_address = rose_set_mac_address,
};
void rose_setup(struct net_device *dev)
{
dev->mtu = ROSE_MAX_PACKET_SIZE - 2;
dev->netdev_ops = &rose_netdev_ops;
dev->header_ops = &rose_header_ops;
dev->hard_header_len = AX25_BPQ_HEADER_LEN + AX25_MAX_HEADER_LEN + ROSE_MIN_LEN;
dev->addr_len = ROSE_ADDR_LEN;
dev->type = ARPHRD_ROSE;
/* New-style flags. */
dev->flags = IFF_NOARP;
}
| gpl-2.0 |
faux123/msm8660-aosp-ics | drivers/usb/host/imx21-hcd.c | 2916 | 48862 | /*
* USB Host Controller Driver for IMX21
*
* Copyright (C) 2006 Loping Dog Embedded Systems
* Copyright (C) 2009 Martin Fuzzey
* Originally written by Jay Monkman <jtm@lopingdog.com>
* Ported to 2.6.30, debugged and enhanced by Martin Fuzzey
*
* 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.
*/
/*
* The i.MX21 USB hardware contains
* * 32 transfer descriptors (called ETDs)
* * 4Kb of Data memory
*
* The data memory is shared between the host and function controllers
* (but this driver only supports the host controller)
*
* So setting up a transfer involves:
* * Allocating a ETD
* * Fill in ETD with appropriate information
* * Allocating data memory (and putting the offset in the ETD)
* * Activate the ETD
* * Get interrupt when done.
*
* An ETD is assigned to each active endpoint.
*
* Low resource (ETD and Data memory) situations are handled differently for
* isochronous and non insosynchronous transactions :
*
* Non ISOC transfers are queued if either ETDs or Data memory are unavailable
*
* ISOC transfers use 2 ETDs per endpoint to achieve double buffering.
* They allocate both ETDs and Data memory during URB submission
* (and fail if unavailable).
*/
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/usb/hcd.h>
#include <linux/dma-mapping.h>
#include "imx21-hcd.h"
#ifdef DEBUG
#define DEBUG_LOG_FRAME(imx21, etd, event) \
(etd)->event##_frame = readl((imx21)->regs + USBH_FRMNUB)
#else
#define DEBUG_LOG_FRAME(imx21, etd, event) do { } while (0)
#endif
static const char hcd_name[] = "imx21-hcd";
static inline struct imx21 *hcd_to_imx21(struct usb_hcd *hcd)
{
return (struct imx21 *)hcd->hcd_priv;
}
/* =========================================== */
/* Hardware access helpers */
/* =========================================== */
static inline void set_register_bits(struct imx21 *imx21, u32 offset, u32 mask)
{
void __iomem *reg = imx21->regs + offset;
writel(readl(reg) | mask, reg);
}
static inline void clear_register_bits(struct imx21 *imx21,
u32 offset, u32 mask)
{
void __iomem *reg = imx21->regs + offset;
writel(readl(reg) & ~mask, reg);
}
static inline void clear_toggle_bit(struct imx21 *imx21, u32 offset, u32 mask)
{
void __iomem *reg = imx21->regs + offset;
if (readl(reg) & mask)
writel(mask, reg);
}
static inline void set_toggle_bit(struct imx21 *imx21, u32 offset, u32 mask)
{
void __iomem *reg = imx21->regs + offset;
if (!(readl(reg) & mask))
writel(mask, reg);
}
static void etd_writel(struct imx21 *imx21, int etd_num, int dword, u32 value)
{
writel(value, imx21->regs + USB_ETD_DWORD(etd_num, dword));
}
static u32 etd_readl(struct imx21 *imx21, int etd_num, int dword)
{
return readl(imx21->regs + USB_ETD_DWORD(etd_num, dword));
}
static inline int wrap_frame(int counter)
{
return counter & 0xFFFF;
}
static inline int frame_after(int frame, int after)
{
/* handle wrapping like jiffies time_afer */
return (s16)((s16)after - (s16)frame) < 0;
}
static int imx21_hc_get_frame(struct usb_hcd *hcd)
{
struct imx21 *imx21 = hcd_to_imx21(hcd);
return wrap_frame(readl(imx21->regs + USBH_FRMNUB));
}
static inline bool unsuitable_for_dma(dma_addr_t addr)
{
return (addr & 3) != 0;
}
#include "imx21-dbg.c"
static void nonisoc_urb_completed_for_etd(
struct imx21 *imx21, struct etd_priv *etd, int status);
static void schedule_nonisoc_etd(struct imx21 *imx21, struct urb *urb);
static void free_dmem(struct imx21 *imx21, struct etd_priv *etd);
/* =========================================== */
/* ETD management */
/* =========================================== */
static int alloc_etd(struct imx21 *imx21)
{
int i;
struct etd_priv *etd = imx21->etd;
for (i = 0; i < USB_NUM_ETD; i++, etd++) {
if (etd->alloc == 0) {
memset(etd, 0, sizeof(imx21->etd[0]));
etd->alloc = 1;
debug_etd_allocated(imx21);
return i;
}
}
return -1;
}
static void disactivate_etd(struct imx21 *imx21, int num)
{
int etd_mask = (1 << num);
struct etd_priv *etd = &imx21->etd[num];
writel(etd_mask, imx21->regs + USBH_ETDENCLR);
clear_register_bits(imx21, USBH_ETDDONEEN, etd_mask);
writel(etd_mask, imx21->regs + USB_ETDDMACHANLCLR);
clear_toggle_bit(imx21, USBH_ETDDONESTAT, etd_mask);
etd->active_count = 0;
DEBUG_LOG_FRAME(imx21, etd, disactivated);
}
static void reset_etd(struct imx21 *imx21, int num)
{
struct etd_priv *etd = imx21->etd + num;
int i;
disactivate_etd(imx21, num);
for (i = 0; i < 4; i++)
etd_writel(imx21, num, i, 0);
etd->urb = NULL;
etd->ep = NULL;
etd->td = NULL;
etd->bounce_buffer = NULL;
}
static void free_etd(struct imx21 *imx21, int num)
{
if (num < 0)
return;
if (num >= USB_NUM_ETD) {
dev_err(imx21->dev, "BAD etd=%d!\n", num);
return;
}
if (imx21->etd[num].alloc == 0) {
dev_err(imx21->dev, "ETD %d already free!\n", num);
return;
}
debug_etd_freed(imx21);
reset_etd(imx21, num);
memset(&imx21->etd[num], 0, sizeof(imx21->etd[0]));
}
static void setup_etd_dword0(struct imx21 *imx21,
int etd_num, struct urb *urb, u8 dir, u16 maxpacket)
{
etd_writel(imx21, etd_num, 0,
((u32) usb_pipedevice(urb->pipe)) << DW0_ADDRESS |
((u32) usb_pipeendpoint(urb->pipe) << DW0_ENDPNT) |
((u32) dir << DW0_DIRECT) |
((u32) ((urb->dev->speed == USB_SPEED_LOW) ?
1 : 0) << DW0_SPEED) |
((u32) fmt_urb_to_etd[usb_pipetype(urb->pipe)] << DW0_FORMAT) |
((u32) maxpacket << DW0_MAXPKTSIZ));
}
/**
* Copy buffer to data controller data memory.
* We cannot use memcpy_toio() because the hardware requires 32bit writes
*/
static void copy_to_dmem(
struct imx21 *imx21, int dmem_offset, void *src, int count)
{
void __iomem *dmem = imx21->regs + USBOTG_DMEM + dmem_offset;
u32 word = 0;
u8 *p = src;
int byte = 0;
int i;
for (i = 0; i < count; i++) {
byte = i % 4;
word += (*p++ << (byte * 8));
if (byte == 3) {
writel(word, dmem);
dmem += 4;
word = 0;
}
}
if (count && byte != 3)
writel(word, dmem);
}
static void activate_etd(struct imx21 *imx21, int etd_num, u8 dir)
{
u32 etd_mask = 1 << etd_num;
struct etd_priv *etd = &imx21->etd[etd_num];
if (etd->dma_handle && unsuitable_for_dma(etd->dma_handle)) {
/* For non aligned isoc the condition below is always true */
if (etd->len <= etd->dmem_size) {
/* Fits into data memory, use PIO */
if (dir != TD_DIR_IN) {
copy_to_dmem(imx21,
etd->dmem_offset,
etd->cpu_buffer, etd->len);
}
etd->dma_handle = 0;
} else {
/* Too big for data memory, use bounce buffer */
enum dma_data_direction dmadir;
if (dir == TD_DIR_IN) {
dmadir = DMA_FROM_DEVICE;
etd->bounce_buffer = kmalloc(etd->len,
GFP_ATOMIC);
} else {
dmadir = DMA_TO_DEVICE;
etd->bounce_buffer = kmemdup(etd->cpu_buffer,
etd->len,
GFP_ATOMIC);
}
if (!etd->bounce_buffer) {
dev_err(imx21->dev, "failed bounce alloc\n");
goto err_bounce_alloc;
}
etd->dma_handle =
dma_map_single(imx21->dev,
etd->bounce_buffer,
etd->len,
dmadir);
if (dma_mapping_error(imx21->dev, etd->dma_handle)) {
dev_err(imx21->dev, "failed bounce map\n");
goto err_bounce_map;
}
}
}
clear_toggle_bit(imx21, USBH_ETDDONESTAT, etd_mask);
set_register_bits(imx21, USBH_ETDDONEEN, etd_mask);
clear_toggle_bit(imx21, USBH_XFILLSTAT, etd_mask);
clear_toggle_bit(imx21, USBH_YFILLSTAT, etd_mask);
if (etd->dma_handle) {
set_register_bits(imx21, USB_ETDDMACHANLCLR, etd_mask);
clear_toggle_bit(imx21, USBH_XBUFSTAT, etd_mask);
clear_toggle_bit(imx21, USBH_YBUFSTAT, etd_mask);
writel(etd->dma_handle, imx21->regs + USB_ETDSMSA(etd_num));
set_register_bits(imx21, USB_ETDDMAEN, etd_mask);
} else {
if (dir != TD_DIR_IN) {
/* need to set for ZLP and PIO */
set_toggle_bit(imx21, USBH_XFILLSTAT, etd_mask);
set_toggle_bit(imx21, USBH_YFILLSTAT, etd_mask);
}
}
DEBUG_LOG_FRAME(imx21, etd, activated);
#ifdef DEBUG
if (!etd->active_count) {
int i;
etd->activated_frame = readl(imx21->regs + USBH_FRMNUB);
etd->disactivated_frame = -1;
etd->last_int_frame = -1;
etd->last_req_frame = -1;
for (i = 0; i < 4; i++)
etd->submitted_dwords[i] = etd_readl(imx21, etd_num, i);
}
#endif
etd->active_count = 1;
writel(etd_mask, imx21->regs + USBH_ETDENSET);
return;
err_bounce_map:
kfree(etd->bounce_buffer);
err_bounce_alloc:
free_dmem(imx21, etd);
nonisoc_urb_completed_for_etd(imx21, etd, -ENOMEM);
}
/* =========================================== */
/* Data memory management */
/* =========================================== */
static int alloc_dmem(struct imx21 *imx21, unsigned int size,
struct usb_host_endpoint *ep)
{
unsigned int offset = 0;
struct imx21_dmem_area *area;
struct imx21_dmem_area *tmp;
size += (~size + 1) & 0x3; /* Round to 4 byte multiple */
if (size > DMEM_SIZE) {
dev_err(imx21->dev, "size=%d > DMEM_SIZE(%d)\n",
size, DMEM_SIZE);
return -EINVAL;
}
list_for_each_entry(tmp, &imx21->dmem_list, list) {
if ((size + offset) < offset)
goto fail;
if ((size + offset) <= tmp->offset)
break;
offset = tmp->size + tmp->offset;
if ((offset + size) > DMEM_SIZE)
goto fail;
}
area = kmalloc(sizeof(struct imx21_dmem_area), GFP_ATOMIC);
if (area == NULL)
return -ENOMEM;
area->ep = ep;
area->offset = offset;
area->size = size;
list_add_tail(&area->list, &tmp->list);
debug_dmem_allocated(imx21, size);
return offset;
fail:
return -ENOMEM;
}
/* Memory now available for a queued ETD - activate it */
static void activate_queued_etd(struct imx21 *imx21,
struct etd_priv *etd, u32 dmem_offset)
{
struct urb_priv *urb_priv = etd->urb->hcpriv;
int etd_num = etd - &imx21->etd[0];
u32 maxpacket = etd_readl(imx21, etd_num, 1) >> DW1_YBUFSRTAD;
u8 dir = (etd_readl(imx21, etd_num, 2) >> DW2_DIRPID) & 0x03;
dev_dbg(imx21->dev, "activating queued ETD %d now DMEM available\n",
etd_num);
etd_writel(imx21, etd_num, 1,
((dmem_offset + maxpacket) << DW1_YBUFSRTAD) | dmem_offset);
etd->dmem_offset = dmem_offset;
urb_priv->active = 1;
activate_etd(imx21, etd_num, dir);
}
static void free_dmem(struct imx21 *imx21, struct etd_priv *etd)
{
struct imx21_dmem_area *area;
struct etd_priv *tmp;
int found = 0;
int offset;
if (!etd->dmem_size)
return;
etd->dmem_size = 0;
offset = etd->dmem_offset;
list_for_each_entry(area, &imx21->dmem_list, list) {
if (area->offset == offset) {
debug_dmem_freed(imx21, area->size);
list_del(&area->list);
kfree(area);
found = 1;
break;
}
}
if (!found) {
dev_err(imx21->dev,
"Trying to free unallocated DMEM %d\n", offset);
return;
}
/* Try again to allocate memory for anything we've queued */
list_for_each_entry_safe(etd, tmp, &imx21->queue_for_dmem, queue) {
offset = alloc_dmem(imx21, etd->dmem_size, etd->ep);
if (offset >= 0) {
list_del(&etd->queue);
activate_queued_etd(imx21, etd, (u32)offset);
}
}
}
static void free_epdmem(struct imx21 *imx21, struct usb_host_endpoint *ep)
{
struct imx21_dmem_area *area, *tmp;
list_for_each_entry_safe(area, tmp, &imx21->dmem_list, list) {
if (area->ep == ep) {
dev_err(imx21->dev,
"Active DMEM %d for disabled ep=%p\n",
area->offset, ep);
list_del(&area->list);
kfree(area);
}
}
}
/* =========================================== */
/* End handling */
/* =========================================== */
/* Endpoint now idle - release it's ETD(s) or asssign to queued request */
static void ep_idle(struct imx21 *imx21, struct ep_priv *ep_priv)
{
int i;
for (i = 0; i < NUM_ISO_ETDS; i++) {
int etd_num = ep_priv->etd[i];
struct etd_priv *etd;
if (etd_num < 0)
continue;
etd = &imx21->etd[etd_num];
ep_priv->etd[i] = -1;
free_dmem(imx21, etd); /* for isoc */
if (list_empty(&imx21->queue_for_etd)) {
free_etd(imx21, etd_num);
continue;
}
dev_dbg(imx21->dev,
"assigning idle etd %d for queued request\n", etd_num);
ep_priv = list_first_entry(&imx21->queue_for_etd,
struct ep_priv, queue);
list_del(&ep_priv->queue);
reset_etd(imx21, etd_num);
ep_priv->waiting_etd = 0;
ep_priv->etd[i] = etd_num;
if (list_empty(&ep_priv->ep->urb_list)) {
dev_err(imx21->dev, "No urb for queued ep!\n");
continue;
}
schedule_nonisoc_etd(imx21, list_first_entry(
&ep_priv->ep->urb_list, struct urb, urb_list));
}
}
static void urb_done(struct usb_hcd *hcd, struct urb *urb, int status)
__releases(imx21->lock)
__acquires(imx21->lock)
{
struct imx21 *imx21 = hcd_to_imx21(hcd);
struct ep_priv *ep_priv = urb->ep->hcpriv;
struct urb_priv *urb_priv = urb->hcpriv;
debug_urb_completed(imx21, urb, status);
dev_vdbg(imx21->dev, "urb %p done %d\n", urb, status);
kfree(urb_priv->isoc_td);
kfree(urb->hcpriv);
urb->hcpriv = NULL;
usb_hcd_unlink_urb_from_ep(hcd, urb);
spin_unlock(&imx21->lock);
usb_hcd_giveback_urb(hcd, urb, status);
spin_lock(&imx21->lock);
if (list_empty(&ep_priv->ep->urb_list))
ep_idle(imx21, ep_priv);
}
static void nonisoc_urb_completed_for_etd(
struct imx21 *imx21, struct etd_priv *etd, int status)
{
struct usb_host_endpoint *ep = etd->ep;
urb_done(imx21->hcd, etd->urb, status);
etd->urb = NULL;
if (!list_empty(&ep->urb_list)) {
struct urb *urb = list_first_entry(
&ep->urb_list, struct urb, urb_list);
dev_vdbg(imx21->dev, "next URB %p\n", urb);
schedule_nonisoc_etd(imx21, urb);
}
}
/* =========================================== */
/* ISOC Handling ... */
/* =========================================== */
static void schedule_isoc_etds(struct usb_hcd *hcd,
struct usb_host_endpoint *ep)
{
struct imx21 *imx21 = hcd_to_imx21(hcd);
struct ep_priv *ep_priv = ep->hcpriv;
struct etd_priv *etd;
struct urb_priv *urb_priv;
struct td *td;
int etd_num;
int i;
int cur_frame;
u8 dir;
for (i = 0; i < NUM_ISO_ETDS; i++) {
too_late:
if (list_empty(&ep_priv->td_list))
break;
etd_num = ep_priv->etd[i];
if (etd_num < 0)
break;
etd = &imx21->etd[etd_num];
if (etd->urb)
continue;
td = list_entry(ep_priv->td_list.next, struct td, list);
list_del(&td->list);
urb_priv = td->urb->hcpriv;
cur_frame = imx21_hc_get_frame(hcd);
if (frame_after(cur_frame, td->frame)) {
dev_dbg(imx21->dev, "isoc too late frame %d > %d\n",
cur_frame, td->frame);
urb_priv->isoc_status = -EXDEV;
td->urb->iso_frame_desc[
td->isoc_index].actual_length = 0;
td->urb->iso_frame_desc[td->isoc_index].status = -EXDEV;
if (--urb_priv->isoc_remaining == 0)
urb_done(hcd, td->urb, urb_priv->isoc_status);
goto too_late;
}
urb_priv->active = 1;
etd->td = td;
etd->ep = td->ep;
etd->urb = td->urb;
etd->len = td->len;
etd->dma_handle = td->dma_handle;
etd->cpu_buffer = td->cpu_buffer;
debug_isoc_submitted(imx21, cur_frame, td);
dir = usb_pipeout(td->urb->pipe) ? TD_DIR_OUT : TD_DIR_IN;
setup_etd_dword0(imx21, etd_num, td->urb, dir, etd->dmem_size);
etd_writel(imx21, etd_num, 1, etd->dmem_offset);
etd_writel(imx21, etd_num, 2,
(TD_NOTACCESSED << DW2_COMPCODE) |
((td->frame & 0xFFFF) << DW2_STARTFRM));
etd_writel(imx21, etd_num, 3,
(TD_NOTACCESSED << DW3_COMPCODE0) |
(td->len << DW3_PKTLEN0));
activate_etd(imx21, etd_num, dir);
}
}
static void isoc_etd_done(struct usb_hcd *hcd, int etd_num)
{
struct imx21 *imx21 = hcd_to_imx21(hcd);
int etd_mask = 1 << etd_num;
struct etd_priv *etd = imx21->etd + etd_num;
struct urb *urb = etd->urb;
struct urb_priv *urb_priv = urb->hcpriv;
struct td *td = etd->td;
struct usb_host_endpoint *ep = etd->ep;
int isoc_index = td->isoc_index;
unsigned int pipe = urb->pipe;
int dir_in = usb_pipein(pipe);
int cc;
int bytes_xfrd;
disactivate_etd(imx21, etd_num);
cc = (etd_readl(imx21, etd_num, 3) >> DW3_COMPCODE0) & 0xf;
bytes_xfrd = etd_readl(imx21, etd_num, 3) & 0x3ff;
/* Input doesn't always fill the buffer, don't generate an error
* when this happens.
*/
if (dir_in && (cc == TD_DATAUNDERRUN))
cc = TD_CC_NOERROR;
if (cc == TD_NOTACCESSED)
bytes_xfrd = 0;
debug_isoc_completed(imx21,
imx21_hc_get_frame(hcd), td, cc, bytes_xfrd);
if (cc) {
urb_priv->isoc_status = -EXDEV;
dev_dbg(imx21->dev,
"bad iso cc=0x%X frame=%d sched frame=%d "
"cnt=%d len=%d urb=%p etd=%d index=%d\n",
cc, imx21_hc_get_frame(hcd), td->frame,
bytes_xfrd, td->len, urb, etd_num, isoc_index);
}
if (dir_in) {
clear_toggle_bit(imx21, USBH_XFILLSTAT, etd_mask);
if (!etd->dma_handle)
memcpy_fromio(etd->cpu_buffer,
imx21->regs + USBOTG_DMEM + etd->dmem_offset,
bytes_xfrd);
}
urb->actual_length += bytes_xfrd;
urb->iso_frame_desc[isoc_index].actual_length = bytes_xfrd;
urb->iso_frame_desc[isoc_index].status = cc_to_error[cc];
etd->td = NULL;
etd->urb = NULL;
etd->ep = NULL;
if (--urb_priv->isoc_remaining == 0)
urb_done(hcd, urb, urb_priv->isoc_status);
schedule_isoc_etds(hcd, ep);
}
static struct ep_priv *alloc_isoc_ep(
struct imx21 *imx21, struct usb_host_endpoint *ep)
{
struct ep_priv *ep_priv;
int i;
ep_priv = kzalloc(sizeof(struct ep_priv), GFP_ATOMIC);
if (!ep_priv)
return NULL;
for (i = 0; i < NUM_ISO_ETDS; i++)
ep_priv->etd[i] = -1;
INIT_LIST_HEAD(&ep_priv->td_list);
ep_priv->ep = ep;
ep->hcpriv = ep_priv;
return ep_priv;
}
static int alloc_isoc_etds(struct imx21 *imx21, struct ep_priv *ep_priv)
{
int i, j;
int etd_num;
/* Allocate the ETDs if required */
for (i = 0; i < NUM_ISO_ETDS; i++) {
if (ep_priv->etd[i] < 0) {
etd_num = alloc_etd(imx21);
if (etd_num < 0)
goto alloc_etd_failed;
ep_priv->etd[i] = etd_num;
imx21->etd[etd_num].ep = ep_priv->ep;
}
}
return 0;
alloc_etd_failed:
dev_err(imx21->dev, "isoc: Couldn't allocate etd\n");
for (j = 0; j < i; j++) {
free_etd(imx21, ep_priv->etd[j]);
ep_priv->etd[j] = -1;
}
return -ENOMEM;
}
static int imx21_hc_urb_enqueue_isoc(struct usb_hcd *hcd,
struct usb_host_endpoint *ep,
struct urb *urb, gfp_t mem_flags)
{
struct imx21 *imx21 = hcd_to_imx21(hcd);
struct urb_priv *urb_priv;
unsigned long flags;
struct ep_priv *ep_priv;
struct td *td = NULL;
int i;
int ret;
int cur_frame;
u16 maxpacket;
urb_priv = kzalloc(sizeof(struct urb_priv), mem_flags);
if (urb_priv == NULL)
return -ENOMEM;
urb_priv->isoc_td = kzalloc(
sizeof(struct td) * urb->number_of_packets, mem_flags);
if (urb_priv->isoc_td == NULL) {
ret = -ENOMEM;
goto alloc_td_failed;
}
spin_lock_irqsave(&imx21->lock, flags);
if (ep->hcpriv == NULL) {
ep_priv = alloc_isoc_ep(imx21, ep);
if (ep_priv == NULL) {
ret = -ENOMEM;
goto alloc_ep_failed;
}
} else {
ep_priv = ep->hcpriv;
}
ret = alloc_isoc_etds(imx21, ep_priv);
if (ret)
goto alloc_etd_failed;
ret = usb_hcd_link_urb_to_ep(hcd, urb);
if (ret)
goto link_failed;
urb->status = -EINPROGRESS;
urb->actual_length = 0;
urb->error_count = 0;
urb->hcpriv = urb_priv;
urb_priv->ep = ep;
/* allocate data memory for largest packets if not already done */
maxpacket = usb_maxpacket(urb->dev, urb->pipe, usb_pipeout(urb->pipe));
for (i = 0; i < NUM_ISO_ETDS; i++) {
struct etd_priv *etd = &imx21->etd[ep_priv->etd[i]];
if (etd->dmem_size > 0 && etd->dmem_size < maxpacket) {
/* not sure if this can really occur.... */
dev_err(imx21->dev, "increasing isoc buffer %d->%d\n",
etd->dmem_size, maxpacket);
ret = -EMSGSIZE;
goto alloc_dmem_failed;
}
if (etd->dmem_size == 0) {
etd->dmem_offset = alloc_dmem(imx21, maxpacket, ep);
if (etd->dmem_offset < 0) {
dev_dbg(imx21->dev, "failed alloc isoc dmem\n");
ret = -EAGAIN;
goto alloc_dmem_failed;
}
etd->dmem_size = maxpacket;
}
}
/* calculate frame */
cur_frame = imx21_hc_get_frame(hcd);
if (urb->transfer_flags & URB_ISO_ASAP) {
if (list_empty(&ep_priv->td_list))
urb->start_frame = cur_frame + 5;
else
urb->start_frame = list_entry(
ep_priv->td_list.prev,
struct td, list)->frame + urb->interval;
}
urb->start_frame = wrap_frame(urb->start_frame);
if (frame_after(cur_frame, urb->start_frame)) {
dev_dbg(imx21->dev,
"enqueue: adjusting iso start %d (cur=%d) asap=%d\n",
urb->start_frame, cur_frame,
(urb->transfer_flags & URB_ISO_ASAP) != 0);
urb->start_frame = wrap_frame(cur_frame + 1);
}
/* set up transfers */
td = urb_priv->isoc_td;
for (i = 0; i < urb->number_of_packets; i++, td++) {
unsigned int offset = urb->iso_frame_desc[i].offset;
td->ep = ep;
td->urb = urb;
td->len = urb->iso_frame_desc[i].length;
td->isoc_index = i;
td->frame = wrap_frame(urb->start_frame + urb->interval * i);
td->dma_handle = urb->transfer_dma + offset;
td->cpu_buffer = urb->transfer_buffer + offset;
list_add_tail(&td->list, &ep_priv->td_list);
}
urb_priv->isoc_remaining = urb->number_of_packets;
dev_vdbg(imx21->dev, "setup %d packets for iso frame %d->%d\n",
urb->number_of_packets, urb->start_frame, td->frame);
debug_urb_submitted(imx21, urb);
schedule_isoc_etds(hcd, ep);
spin_unlock_irqrestore(&imx21->lock, flags);
return 0;
alloc_dmem_failed:
usb_hcd_unlink_urb_from_ep(hcd, urb);
link_failed:
alloc_etd_failed:
alloc_ep_failed:
spin_unlock_irqrestore(&imx21->lock, flags);
kfree(urb_priv->isoc_td);
alloc_td_failed:
kfree(urb_priv);
return ret;
}
static void dequeue_isoc_urb(struct imx21 *imx21,
struct urb *urb, struct ep_priv *ep_priv)
{
struct urb_priv *urb_priv = urb->hcpriv;
struct td *td, *tmp;
int i;
if (urb_priv->active) {
for (i = 0; i < NUM_ISO_ETDS; i++) {
int etd_num = ep_priv->etd[i];
if (etd_num != -1 && imx21->etd[etd_num].urb == urb) {
struct etd_priv *etd = imx21->etd + etd_num;
reset_etd(imx21, etd_num);
free_dmem(imx21, etd);
}
}
}
list_for_each_entry_safe(td, tmp, &ep_priv->td_list, list) {
if (td->urb == urb) {
dev_vdbg(imx21->dev, "removing td %p\n", td);
list_del(&td->list);
}
}
}
/* =========================================== */
/* NON ISOC Handling ... */
/* =========================================== */
static void schedule_nonisoc_etd(struct imx21 *imx21, struct urb *urb)
{
unsigned int pipe = urb->pipe;
struct urb_priv *urb_priv = urb->hcpriv;
struct ep_priv *ep_priv = urb_priv->ep->hcpriv;
int state = urb_priv->state;
int etd_num = ep_priv->etd[0];
struct etd_priv *etd;
u32 count;
u16 etd_buf_size;
u16 maxpacket;
u8 dir;
u8 bufround;
u8 datatoggle;
u8 interval = 0;
u8 relpolpos = 0;
if (etd_num < 0) {
dev_err(imx21->dev, "No valid ETD\n");
return;
}
if (readl(imx21->regs + USBH_ETDENSET) & (1 << etd_num))
dev_err(imx21->dev, "submitting to active ETD %d\n", etd_num);
etd = &imx21->etd[etd_num];
maxpacket = usb_maxpacket(urb->dev, pipe, usb_pipeout(pipe));
if (!maxpacket)
maxpacket = 8;
if (usb_pipecontrol(pipe) && (state != US_CTRL_DATA)) {
if (state == US_CTRL_SETUP) {
dir = TD_DIR_SETUP;
if (unsuitable_for_dma(urb->setup_dma))
usb_hcd_unmap_urb_setup_for_dma(imx21->hcd,
urb);
etd->dma_handle = urb->setup_dma;
etd->cpu_buffer = urb->setup_packet;
bufround = 0;
count = 8;
datatoggle = TD_TOGGLE_DATA0;
} else { /* US_CTRL_ACK */
dir = usb_pipeout(pipe) ? TD_DIR_IN : TD_DIR_OUT;
bufround = 0;
count = 0;
datatoggle = TD_TOGGLE_DATA1;
}
} else {
dir = usb_pipeout(pipe) ? TD_DIR_OUT : TD_DIR_IN;
bufround = (dir == TD_DIR_IN) ? 1 : 0;
if (unsuitable_for_dma(urb->transfer_dma))
usb_hcd_unmap_urb_for_dma(imx21->hcd, urb);
etd->dma_handle = urb->transfer_dma;
etd->cpu_buffer = urb->transfer_buffer;
if (usb_pipebulk(pipe) && (state == US_BULK0))
count = 0;
else
count = urb->transfer_buffer_length;
if (usb_pipecontrol(pipe)) {
datatoggle = TD_TOGGLE_DATA1;
} else {
if (usb_gettoggle(
urb->dev,
usb_pipeendpoint(urb->pipe),
usb_pipeout(urb->pipe)))
datatoggle = TD_TOGGLE_DATA1;
else
datatoggle = TD_TOGGLE_DATA0;
}
}
etd->urb = urb;
etd->ep = urb_priv->ep;
etd->len = count;
if (usb_pipeint(pipe)) {
interval = urb->interval;
relpolpos = (readl(imx21->regs + USBH_FRMNUB) + 1) & 0xff;
}
/* Write ETD to device memory */
setup_etd_dword0(imx21, etd_num, urb, dir, maxpacket);
etd_writel(imx21, etd_num, 2,
(u32) interval << DW2_POLINTERV |
((u32) relpolpos << DW2_RELPOLPOS) |
((u32) dir << DW2_DIRPID) |
((u32) bufround << DW2_BUFROUND) |
((u32) datatoggle << DW2_DATATOG) |
((u32) TD_NOTACCESSED << DW2_COMPCODE));
/* DMA will always transfer buffer size even if TOBYCNT in DWORD3
is smaller. Make sure we don't overrun the buffer!
*/
if (count && count < maxpacket)
etd_buf_size = count;
else
etd_buf_size = maxpacket;
etd_writel(imx21, etd_num, 3,
((u32) (etd_buf_size - 1) << DW3_BUFSIZE) | (u32) count);
if (!count)
etd->dma_handle = 0;
/* allocate x and y buffer space at once */
etd->dmem_size = (count > maxpacket) ? maxpacket * 2 : maxpacket;
etd->dmem_offset = alloc_dmem(imx21, etd->dmem_size, urb_priv->ep);
if (etd->dmem_offset < 0) {
/* Setup everything we can in HW and update when we get DMEM */
etd_writel(imx21, etd_num, 1, (u32)maxpacket << 16);
dev_dbg(imx21->dev, "Queuing etd %d for DMEM\n", etd_num);
debug_urb_queued_for_dmem(imx21, urb);
list_add_tail(&etd->queue, &imx21->queue_for_dmem);
return;
}
etd_writel(imx21, etd_num, 1,
(((u32) etd->dmem_offset + (u32) maxpacket) << DW1_YBUFSRTAD) |
(u32) etd->dmem_offset);
urb_priv->active = 1;
/* enable the ETD to kick off transfer */
dev_vdbg(imx21->dev, "Activating etd %d for %d bytes %s\n",
etd_num, count, dir != TD_DIR_IN ? "out" : "in");
activate_etd(imx21, etd_num, dir);
}
static void nonisoc_etd_done(struct usb_hcd *hcd, int etd_num)
{
struct imx21 *imx21 = hcd_to_imx21(hcd);
struct etd_priv *etd = &imx21->etd[etd_num];
struct urb *urb = etd->urb;
u32 etd_mask = 1 << etd_num;
struct urb_priv *urb_priv = urb->hcpriv;
int dir;
int cc;
u32 bytes_xfrd;
int etd_done;
disactivate_etd(imx21, etd_num);
dir = (etd_readl(imx21, etd_num, 0) >> DW0_DIRECT) & 0x3;
cc = (etd_readl(imx21, etd_num, 2) >> DW2_COMPCODE) & 0xf;
bytes_xfrd = etd->len - (etd_readl(imx21, etd_num, 3) & 0x1fffff);
/* save toggle carry */
usb_settoggle(urb->dev, usb_pipeendpoint(urb->pipe),
usb_pipeout(urb->pipe),
(etd_readl(imx21, etd_num, 0) >> DW0_TOGCRY) & 0x1);
if (dir == TD_DIR_IN) {
clear_toggle_bit(imx21, USBH_XFILLSTAT, etd_mask);
clear_toggle_bit(imx21, USBH_YFILLSTAT, etd_mask);
if (etd->bounce_buffer) {
memcpy(etd->cpu_buffer, etd->bounce_buffer, bytes_xfrd);
dma_unmap_single(imx21->dev,
etd->dma_handle, etd->len, DMA_FROM_DEVICE);
} else if (!etd->dma_handle && bytes_xfrd) {/* PIO */
memcpy_fromio(etd->cpu_buffer,
imx21->regs + USBOTG_DMEM + etd->dmem_offset,
bytes_xfrd);
}
}
kfree(etd->bounce_buffer);
etd->bounce_buffer = NULL;
free_dmem(imx21, etd);
urb->error_count = 0;
if (!(urb->transfer_flags & URB_SHORT_NOT_OK)
&& (cc == TD_DATAUNDERRUN))
cc = TD_CC_NOERROR;
if (cc != 0)
dev_vdbg(imx21->dev, "cc is 0x%x\n", cc);
etd_done = (cc_to_error[cc] != 0); /* stop if error */
switch (usb_pipetype(urb->pipe)) {
case PIPE_CONTROL:
switch (urb_priv->state) {
case US_CTRL_SETUP:
if (urb->transfer_buffer_length > 0)
urb_priv->state = US_CTRL_DATA;
else
urb_priv->state = US_CTRL_ACK;
break;
case US_CTRL_DATA:
urb->actual_length += bytes_xfrd;
urb_priv->state = US_CTRL_ACK;
break;
case US_CTRL_ACK:
etd_done = 1;
break;
default:
dev_err(imx21->dev,
"Invalid pipe state %d\n", urb_priv->state);
etd_done = 1;
break;
}
break;
case PIPE_BULK:
urb->actual_length += bytes_xfrd;
if ((urb_priv->state == US_BULK)
&& (urb->transfer_flags & URB_ZERO_PACKET)
&& urb->transfer_buffer_length > 0
&& ((urb->transfer_buffer_length %
usb_maxpacket(urb->dev, urb->pipe,
usb_pipeout(urb->pipe))) == 0)) {
/* need a 0-packet */
urb_priv->state = US_BULK0;
} else {
etd_done = 1;
}
break;
case PIPE_INTERRUPT:
urb->actual_length += bytes_xfrd;
etd_done = 1;
break;
}
if (etd_done)
nonisoc_urb_completed_for_etd(imx21, etd, cc_to_error[cc]);
else {
dev_vdbg(imx21->dev, "next state=%d\n", urb_priv->state);
schedule_nonisoc_etd(imx21, urb);
}
}
static struct ep_priv *alloc_ep(void)
{
int i;
struct ep_priv *ep_priv;
ep_priv = kzalloc(sizeof(struct ep_priv), GFP_ATOMIC);
if (!ep_priv)
return NULL;
for (i = 0; i < NUM_ISO_ETDS; ++i)
ep_priv->etd[i] = -1;
return ep_priv;
}
static int imx21_hc_urb_enqueue(struct usb_hcd *hcd,
struct urb *urb, gfp_t mem_flags)
{
struct imx21 *imx21 = hcd_to_imx21(hcd);
struct usb_host_endpoint *ep = urb->ep;
struct urb_priv *urb_priv;
struct ep_priv *ep_priv;
struct etd_priv *etd;
int ret;
unsigned long flags;
dev_vdbg(imx21->dev,
"enqueue urb=%p ep=%p len=%d "
"buffer=%p dma=%08X setupBuf=%p setupDma=%08X\n",
urb, ep,
urb->transfer_buffer_length,
urb->transfer_buffer, urb->transfer_dma,
urb->setup_packet, urb->setup_dma);
if (usb_pipeisoc(urb->pipe))
return imx21_hc_urb_enqueue_isoc(hcd, ep, urb, mem_flags);
urb_priv = kzalloc(sizeof(struct urb_priv), mem_flags);
if (!urb_priv)
return -ENOMEM;
spin_lock_irqsave(&imx21->lock, flags);
ep_priv = ep->hcpriv;
if (ep_priv == NULL) {
ep_priv = alloc_ep();
if (!ep_priv) {
ret = -ENOMEM;
goto failed_alloc_ep;
}
ep->hcpriv = ep_priv;
ep_priv->ep = ep;
}
ret = usb_hcd_link_urb_to_ep(hcd, urb);
if (ret)
goto failed_link;
urb->status = -EINPROGRESS;
urb->actual_length = 0;
urb->error_count = 0;
urb->hcpriv = urb_priv;
urb_priv->ep = ep;
switch (usb_pipetype(urb->pipe)) {
case PIPE_CONTROL:
urb_priv->state = US_CTRL_SETUP;
break;
case PIPE_BULK:
urb_priv->state = US_BULK;
break;
}
debug_urb_submitted(imx21, urb);
if (ep_priv->etd[0] < 0) {
if (ep_priv->waiting_etd) {
dev_dbg(imx21->dev,
"no ETD available already queued %p\n",
ep_priv);
debug_urb_queued_for_etd(imx21, urb);
goto out;
}
ep_priv->etd[0] = alloc_etd(imx21);
if (ep_priv->etd[0] < 0) {
dev_dbg(imx21->dev,
"no ETD available queueing %p\n", ep_priv);
debug_urb_queued_for_etd(imx21, urb);
list_add_tail(&ep_priv->queue, &imx21->queue_for_etd);
ep_priv->waiting_etd = 1;
goto out;
}
}
/* Schedule if no URB already active for this endpoint */
etd = &imx21->etd[ep_priv->etd[0]];
if (etd->urb == NULL) {
DEBUG_LOG_FRAME(imx21, etd, last_req);
schedule_nonisoc_etd(imx21, urb);
}
out:
spin_unlock_irqrestore(&imx21->lock, flags);
return 0;
failed_link:
failed_alloc_ep:
spin_unlock_irqrestore(&imx21->lock, flags);
kfree(urb_priv);
return ret;
}
static int imx21_hc_urb_dequeue(struct usb_hcd *hcd, struct urb *urb,
int status)
{
struct imx21 *imx21 = hcd_to_imx21(hcd);
unsigned long flags;
struct usb_host_endpoint *ep;
struct ep_priv *ep_priv;
struct urb_priv *urb_priv = urb->hcpriv;
int ret = -EINVAL;
dev_vdbg(imx21->dev, "dequeue urb=%p iso=%d status=%d\n",
urb, usb_pipeisoc(urb->pipe), status);
spin_lock_irqsave(&imx21->lock, flags);
ret = usb_hcd_check_unlink_urb(hcd, urb, status);
if (ret)
goto fail;
ep = urb_priv->ep;
ep_priv = ep->hcpriv;
debug_urb_unlinked(imx21, urb);
if (usb_pipeisoc(urb->pipe)) {
dequeue_isoc_urb(imx21, urb, ep_priv);
schedule_isoc_etds(hcd, ep);
} else if (urb_priv->active) {
int etd_num = ep_priv->etd[0];
if (etd_num != -1) {
struct etd_priv *etd = &imx21->etd[etd_num];
disactivate_etd(imx21, etd_num);
free_dmem(imx21, etd);
etd->urb = NULL;
kfree(etd->bounce_buffer);
etd->bounce_buffer = NULL;
}
}
urb_done(hcd, urb, status);
spin_unlock_irqrestore(&imx21->lock, flags);
return 0;
fail:
spin_unlock_irqrestore(&imx21->lock, flags);
return ret;
}
/* =========================================== */
/* Interrupt dispatch */
/* =========================================== */
static void process_etds(struct usb_hcd *hcd, struct imx21 *imx21, int sof)
{
int etd_num;
int enable_sof_int = 0;
unsigned long flags;
spin_lock_irqsave(&imx21->lock, flags);
for (etd_num = 0; etd_num < USB_NUM_ETD; etd_num++) {
u32 etd_mask = 1 << etd_num;
u32 enabled = readl(imx21->regs + USBH_ETDENSET) & etd_mask;
u32 done = readl(imx21->regs + USBH_ETDDONESTAT) & etd_mask;
struct etd_priv *etd = &imx21->etd[etd_num];
if (done) {
DEBUG_LOG_FRAME(imx21, etd, last_int);
} else {
/*
* Kludge warning!
*
* When multiple transfers are using the bus we sometimes get into a state
* where the transfer has completed (the CC field of the ETD is != 0x0F),
* the ETD has self disabled but the ETDDONESTAT flag is not set
* (and hence no interrupt occurs).
* This causes the transfer in question to hang.
* The kludge below checks for this condition at each SOF and processes any
* blocked ETDs (after an arbitrary 10 frame wait)
*
* With a single active transfer the usbtest test suite will run for days
* without the kludge.
* With other bus activity (eg mass storage) even just test1 will hang without
* the kludge.
*/
u32 dword0;
int cc;
if (etd->active_count && !enabled) /* suspicious... */
enable_sof_int = 1;
if (!sof || enabled || !etd->active_count)
continue;
cc = etd_readl(imx21, etd_num, 2) >> DW2_COMPCODE;
if (cc == TD_NOTACCESSED)
continue;
if (++etd->active_count < 10)
continue;
dword0 = etd_readl(imx21, etd_num, 0);
dev_dbg(imx21->dev,
"unblock ETD %d dev=0x%X ep=0x%X cc=0x%02X!\n",
etd_num, dword0 & 0x7F,
(dword0 >> DW0_ENDPNT) & 0x0F,
cc);
#ifdef DEBUG
dev_dbg(imx21->dev,
"frame: act=%d disact=%d"
" int=%d req=%d cur=%d\n",
etd->activated_frame,
etd->disactivated_frame,
etd->last_int_frame,
etd->last_req_frame,
readl(imx21->regs + USBH_FRMNUB));
imx21->debug_unblocks++;
#endif
etd->active_count = 0;
/* End of kludge */
}
if (etd->ep == NULL || etd->urb == NULL) {
dev_dbg(imx21->dev,
"Interrupt for unexpected etd %d"
" ep=%p urb=%p\n",
etd_num, etd->ep, etd->urb);
disactivate_etd(imx21, etd_num);
continue;
}
if (usb_pipeisoc(etd->urb->pipe))
isoc_etd_done(hcd, etd_num);
else
nonisoc_etd_done(hcd, etd_num);
}
/* only enable SOF interrupt if it may be needed for the kludge */
if (enable_sof_int)
set_register_bits(imx21, USBH_SYSIEN, USBH_SYSIEN_SOFINT);
else
clear_register_bits(imx21, USBH_SYSIEN, USBH_SYSIEN_SOFINT);
spin_unlock_irqrestore(&imx21->lock, flags);
}
static irqreturn_t imx21_irq(struct usb_hcd *hcd)
{
struct imx21 *imx21 = hcd_to_imx21(hcd);
u32 ints = readl(imx21->regs + USBH_SYSISR);
if (ints & USBH_SYSIEN_HERRINT)
dev_dbg(imx21->dev, "Scheduling error\n");
if (ints & USBH_SYSIEN_SORINT)
dev_dbg(imx21->dev, "Scheduling overrun\n");
if (ints & (USBH_SYSISR_DONEINT | USBH_SYSISR_SOFINT))
process_etds(hcd, imx21, ints & USBH_SYSISR_SOFINT);
writel(ints, imx21->regs + USBH_SYSISR);
return IRQ_HANDLED;
}
static void imx21_hc_endpoint_disable(struct usb_hcd *hcd,
struct usb_host_endpoint *ep)
{
struct imx21 *imx21 = hcd_to_imx21(hcd);
unsigned long flags;
struct ep_priv *ep_priv;
int i;
if (ep == NULL)
return;
spin_lock_irqsave(&imx21->lock, flags);
ep_priv = ep->hcpriv;
dev_vdbg(imx21->dev, "disable ep=%p, ep->hcpriv=%p\n", ep, ep_priv);
if (!list_empty(&ep->urb_list))
dev_dbg(imx21->dev, "ep's URB list is not empty\n");
if (ep_priv != NULL) {
for (i = 0; i < NUM_ISO_ETDS; i++) {
if (ep_priv->etd[i] > -1)
dev_dbg(imx21->dev, "free etd %d for disable\n",
ep_priv->etd[i]);
free_etd(imx21, ep_priv->etd[i]);
}
kfree(ep_priv);
ep->hcpriv = NULL;
}
for (i = 0; i < USB_NUM_ETD; i++) {
if (imx21->etd[i].alloc && imx21->etd[i].ep == ep) {
dev_err(imx21->dev,
"Active etd %d for disabled ep=%p!\n", i, ep);
free_etd(imx21, i);
}
}
free_epdmem(imx21, ep);
spin_unlock_irqrestore(&imx21->lock, flags);
}
/* =========================================== */
/* Hub handling */
/* =========================================== */
static int get_hub_descriptor(struct usb_hcd *hcd,
struct usb_hub_descriptor *desc)
{
struct imx21 *imx21 = hcd_to_imx21(hcd);
desc->bDescriptorType = 0x29; /* HUB descriptor */
desc->bHubContrCurrent = 0;
desc->bNbrPorts = readl(imx21->regs + USBH_ROOTHUBA)
& USBH_ROOTHUBA_NDNSTMPRT_MASK;
desc->bDescLength = 9;
desc->bPwrOn2PwrGood = 0;
desc->wHubCharacteristics = (__force __u16) cpu_to_le16(
0x0002 | /* No power switching */
0x0010 | /* No over current protection */
0);
desc->u.hs.DeviceRemovable[0] = 1 << 1;
desc->u.hs.DeviceRemovable[1] = ~0;
return 0;
}
static int imx21_hc_hub_status_data(struct usb_hcd *hcd, char *buf)
{
struct imx21 *imx21 = hcd_to_imx21(hcd);
int ports;
int changed = 0;
int i;
unsigned long flags;
spin_lock_irqsave(&imx21->lock, flags);
ports = readl(imx21->regs + USBH_ROOTHUBA)
& USBH_ROOTHUBA_NDNSTMPRT_MASK;
if (ports > 7) {
ports = 7;
dev_err(imx21->dev, "ports %d > 7\n", ports);
}
for (i = 0; i < ports; i++) {
if (readl(imx21->regs + USBH_PORTSTAT(i)) &
(USBH_PORTSTAT_CONNECTSC |
USBH_PORTSTAT_PRTENBLSC |
USBH_PORTSTAT_PRTSTATSC |
USBH_PORTSTAT_OVRCURIC |
USBH_PORTSTAT_PRTRSTSC)) {
changed = 1;
buf[0] |= 1 << (i + 1);
}
}
spin_unlock_irqrestore(&imx21->lock, flags);
if (changed)
dev_info(imx21->dev, "Hub status changed\n");
return changed;
}
static int imx21_hc_hub_control(struct usb_hcd *hcd,
u16 typeReq,
u16 wValue, u16 wIndex, char *buf, u16 wLength)
{
struct imx21 *imx21 = hcd_to_imx21(hcd);
int rc = 0;
u32 status_write = 0;
switch (typeReq) {
case ClearHubFeature:
dev_dbg(imx21->dev, "ClearHubFeature\n");
switch (wValue) {
case C_HUB_OVER_CURRENT:
dev_dbg(imx21->dev, " OVER_CURRENT\n");
break;
case C_HUB_LOCAL_POWER:
dev_dbg(imx21->dev, " LOCAL_POWER\n");
break;
default:
dev_dbg(imx21->dev, " unknown\n");
rc = -EINVAL;
break;
}
break;
case ClearPortFeature:
dev_dbg(imx21->dev, "ClearPortFeature\n");
switch (wValue) {
case USB_PORT_FEAT_ENABLE:
dev_dbg(imx21->dev, " ENABLE\n");
status_write = USBH_PORTSTAT_CURCONST;
break;
case USB_PORT_FEAT_SUSPEND:
dev_dbg(imx21->dev, " SUSPEND\n");
status_write = USBH_PORTSTAT_PRTOVRCURI;
break;
case USB_PORT_FEAT_POWER:
dev_dbg(imx21->dev, " POWER\n");
status_write = USBH_PORTSTAT_LSDEVCON;
break;
case USB_PORT_FEAT_C_ENABLE:
dev_dbg(imx21->dev, " C_ENABLE\n");
status_write = USBH_PORTSTAT_PRTENBLSC;
break;
case USB_PORT_FEAT_C_SUSPEND:
dev_dbg(imx21->dev, " C_SUSPEND\n");
status_write = USBH_PORTSTAT_PRTSTATSC;
break;
case USB_PORT_FEAT_C_CONNECTION:
dev_dbg(imx21->dev, " C_CONNECTION\n");
status_write = USBH_PORTSTAT_CONNECTSC;
break;
case USB_PORT_FEAT_C_OVER_CURRENT:
dev_dbg(imx21->dev, " C_OVER_CURRENT\n");
status_write = USBH_PORTSTAT_OVRCURIC;
break;
case USB_PORT_FEAT_C_RESET:
dev_dbg(imx21->dev, " C_RESET\n");
status_write = USBH_PORTSTAT_PRTRSTSC;
break;
default:
dev_dbg(imx21->dev, " unknown\n");
rc = -EINVAL;
break;
}
break;
case GetHubDescriptor:
dev_dbg(imx21->dev, "GetHubDescriptor\n");
rc = get_hub_descriptor(hcd, (void *)buf);
break;
case GetHubStatus:
dev_dbg(imx21->dev, " GetHubStatus\n");
*(__le32 *) buf = 0;
break;
case GetPortStatus:
dev_dbg(imx21->dev, "GetPortStatus: port: %d, 0x%x\n",
wIndex, USBH_PORTSTAT(wIndex - 1));
*(__le32 *) buf = readl(imx21->regs +
USBH_PORTSTAT(wIndex - 1));
break;
case SetHubFeature:
dev_dbg(imx21->dev, "SetHubFeature\n");
switch (wValue) {
case C_HUB_OVER_CURRENT:
dev_dbg(imx21->dev, " OVER_CURRENT\n");
break;
case C_HUB_LOCAL_POWER:
dev_dbg(imx21->dev, " LOCAL_POWER\n");
break;
default:
dev_dbg(imx21->dev, " unknown\n");
rc = -EINVAL;
break;
}
break;
case SetPortFeature:
dev_dbg(imx21->dev, "SetPortFeature\n");
switch (wValue) {
case USB_PORT_FEAT_SUSPEND:
dev_dbg(imx21->dev, " SUSPEND\n");
status_write = USBH_PORTSTAT_PRTSUSPST;
break;
case USB_PORT_FEAT_POWER:
dev_dbg(imx21->dev, " POWER\n");
status_write = USBH_PORTSTAT_PRTPWRST;
break;
case USB_PORT_FEAT_RESET:
dev_dbg(imx21->dev, " RESET\n");
status_write = USBH_PORTSTAT_PRTRSTST;
break;
default:
dev_dbg(imx21->dev, " unknown\n");
rc = -EINVAL;
break;
}
break;
default:
dev_dbg(imx21->dev, " unknown\n");
rc = -EINVAL;
break;
}
if (status_write)
writel(status_write, imx21->regs + USBH_PORTSTAT(wIndex - 1));
return rc;
}
/* =========================================== */
/* Host controller management */
/* =========================================== */
static int imx21_hc_reset(struct usb_hcd *hcd)
{
struct imx21 *imx21 = hcd_to_imx21(hcd);
unsigned long timeout;
unsigned long flags;
spin_lock_irqsave(&imx21->lock, flags);
/* Reset the Host controller modules */
writel(USBOTG_RST_RSTCTRL | USBOTG_RST_RSTRH |
USBOTG_RST_RSTHSIE | USBOTG_RST_RSTHC,
imx21->regs + USBOTG_RST_CTRL);
/* Wait for reset to finish */
timeout = jiffies + HZ;
while (readl(imx21->regs + USBOTG_RST_CTRL) != 0) {
if (time_after(jiffies, timeout)) {
spin_unlock_irqrestore(&imx21->lock, flags);
dev_err(imx21->dev, "timeout waiting for reset\n");
return -ETIMEDOUT;
}
spin_unlock_irq(&imx21->lock);
schedule_timeout_uninterruptible(1);
spin_lock_irq(&imx21->lock);
}
spin_unlock_irqrestore(&imx21->lock, flags);
return 0;
}
static int __devinit imx21_hc_start(struct usb_hcd *hcd)
{
struct imx21 *imx21 = hcd_to_imx21(hcd);
unsigned long flags;
int i, j;
u32 hw_mode = USBOTG_HWMODE_CRECFG_HOST;
u32 usb_control = 0;
hw_mode |= ((imx21->pdata->host_xcvr << USBOTG_HWMODE_HOSTXCVR_SHIFT) &
USBOTG_HWMODE_HOSTXCVR_MASK);
hw_mode |= ((imx21->pdata->otg_xcvr << USBOTG_HWMODE_OTGXCVR_SHIFT) &
USBOTG_HWMODE_OTGXCVR_MASK);
if (imx21->pdata->host1_txenoe)
usb_control |= USBCTRL_HOST1_TXEN_OE;
if (!imx21->pdata->host1_xcverless)
usb_control |= USBCTRL_HOST1_BYP_TLL;
if (imx21->pdata->otg_ext_xcvr)
usb_control |= USBCTRL_OTC_RCV_RXDP;
spin_lock_irqsave(&imx21->lock, flags);
writel((USBOTG_CLK_CTRL_HST | USBOTG_CLK_CTRL_MAIN),
imx21->regs + USBOTG_CLK_CTRL);
writel(hw_mode, imx21->regs + USBOTG_HWMODE);
writel(usb_control, imx21->regs + USBCTRL);
writel(USB_MISCCONTROL_SKPRTRY | USB_MISCCONTROL_ARBMODE,
imx21->regs + USB_MISCCONTROL);
/* Clear the ETDs */
for (i = 0; i < USB_NUM_ETD; i++)
for (j = 0; j < 4; j++)
etd_writel(imx21, i, j, 0);
/* Take the HC out of reset */
writel(USBH_HOST_CTRL_HCUSBSTE_OPERATIONAL | USBH_HOST_CTRL_CTLBLKSR_1,
imx21->regs + USBH_HOST_CTRL);
/* Enable ports */
if (imx21->pdata->enable_otg_host)
writel(USBH_PORTSTAT_PRTPWRST | USBH_PORTSTAT_PRTENABST,
imx21->regs + USBH_PORTSTAT(0));
if (imx21->pdata->enable_host1)
writel(USBH_PORTSTAT_PRTPWRST | USBH_PORTSTAT_PRTENABST,
imx21->regs + USBH_PORTSTAT(1));
if (imx21->pdata->enable_host2)
writel(USBH_PORTSTAT_PRTPWRST | USBH_PORTSTAT_PRTENABST,
imx21->regs + USBH_PORTSTAT(2));
hcd->state = HC_STATE_RUNNING;
/* Enable host controller interrupts */
set_register_bits(imx21, USBH_SYSIEN,
USBH_SYSIEN_HERRINT |
USBH_SYSIEN_DONEINT | USBH_SYSIEN_SORINT);
set_register_bits(imx21, USBOTG_CINT_STEN, USBOTG_HCINT);
spin_unlock_irqrestore(&imx21->lock, flags);
return 0;
}
static void imx21_hc_stop(struct usb_hcd *hcd)
{
struct imx21 *imx21 = hcd_to_imx21(hcd);
unsigned long flags;
spin_lock_irqsave(&imx21->lock, flags);
writel(0, imx21->regs + USBH_SYSIEN);
clear_register_bits(imx21, USBOTG_CINT_STEN, USBOTG_HCINT);
clear_register_bits(imx21, USBOTG_CLK_CTRL_HST | USBOTG_CLK_CTRL_MAIN,
USBOTG_CLK_CTRL);
spin_unlock_irqrestore(&imx21->lock, flags);
}
/* =========================================== */
/* Driver glue */
/* =========================================== */
static struct hc_driver imx21_hc_driver = {
.description = hcd_name,
.product_desc = "IMX21 USB Host Controller",
.hcd_priv_size = sizeof(struct imx21),
.flags = HCD_USB11,
.irq = imx21_irq,
.reset = imx21_hc_reset,
.start = imx21_hc_start,
.stop = imx21_hc_stop,
/* I/O requests */
.urb_enqueue = imx21_hc_urb_enqueue,
.urb_dequeue = imx21_hc_urb_dequeue,
.endpoint_disable = imx21_hc_endpoint_disable,
/* scheduling support */
.get_frame_number = imx21_hc_get_frame,
/* Root hub support */
.hub_status_data = imx21_hc_hub_status_data,
.hub_control = imx21_hc_hub_control,
};
static struct mx21_usbh_platform_data default_pdata = {
.host_xcvr = MX21_USBXCVR_TXDIF_RXDIF,
.otg_xcvr = MX21_USBXCVR_TXDIF_RXDIF,
.enable_host1 = 1,
.enable_host2 = 1,
.enable_otg_host = 1,
};
static int imx21_remove(struct platform_device *pdev)
{
struct usb_hcd *hcd = platform_get_drvdata(pdev);
struct imx21 *imx21 = hcd_to_imx21(hcd);
struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
remove_debug_files(imx21);
usb_remove_hcd(hcd);
if (res != NULL) {
clk_disable(imx21->clk);
clk_put(imx21->clk);
iounmap(imx21->regs);
release_mem_region(res->start, resource_size(res));
}
kfree(hcd);
return 0;
}
static int imx21_probe(struct platform_device *pdev)
{
struct usb_hcd *hcd;
struct imx21 *imx21;
struct resource *res;
int ret;
int irq;
printk(KERN_INFO "%s\n", imx21_hc_driver.product_desc);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENODEV;
irq = platform_get_irq(pdev, 0);
if (irq < 0)
return -ENXIO;
hcd = usb_create_hcd(&imx21_hc_driver,
&pdev->dev, dev_name(&pdev->dev));
if (hcd == NULL) {
dev_err(&pdev->dev, "Cannot create hcd (%s)\n",
dev_name(&pdev->dev));
return -ENOMEM;
}
imx21 = hcd_to_imx21(hcd);
imx21->hcd = hcd;
imx21->dev = &pdev->dev;
imx21->pdata = pdev->dev.platform_data;
if (!imx21->pdata)
imx21->pdata = &default_pdata;
spin_lock_init(&imx21->lock);
INIT_LIST_HEAD(&imx21->dmem_list);
INIT_LIST_HEAD(&imx21->queue_for_etd);
INIT_LIST_HEAD(&imx21->queue_for_dmem);
create_debug_files(imx21);
res = request_mem_region(res->start, resource_size(res), hcd_name);
if (!res) {
ret = -EBUSY;
goto failed_request_mem;
}
imx21->regs = ioremap(res->start, resource_size(res));
if (imx21->regs == NULL) {
dev_err(imx21->dev, "Cannot map registers\n");
ret = -ENOMEM;
goto failed_ioremap;
}
/* Enable clocks source */
imx21->clk = clk_get(imx21->dev, NULL);
if (IS_ERR(imx21->clk)) {
dev_err(imx21->dev, "no clock found\n");
ret = PTR_ERR(imx21->clk);
goto failed_clock_get;
}
ret = clk_set_rate(imx21->clk, clk_round_rate(imx21->clk, 48000000));
if (ret)
goto failed_clock_set;
ret = clk_enable(imx21->clk);
if (ret)
goto failed_clock_enable;
dev_info(imx21->dev, "Hardware HC revision: 0x%02X\n",
(readl(imx21->regs + USBOTG_HWMODE) >> 16) & 0xFF);
ret = usb_add_hcd(hcd, irq, IRQF_DISABLED);
if (ret != 0) {
dev_err(imx21->dev, "usb_add_hcd() returned %d\n", ret);
goto failed_add_hcd;
}
return 0;
failed_add_hcd:
clk_disable(imx21->clk);
failed_clock_enable:
failed_clock_set:
clk_put(imx21->clk);
failed_clock_get:
iounmap(imx21->regs);
failed_ioremap:
release_mem_region(res->start, resource_size(res));
failed_request_mem:
remove_debug_files(imx21);
usb_put_hcd(hcd);
return ret;
}
static struct platform_driver imx21_hcd_driver = {
.driver = {
.name = (char *)hcd_name,
},
.probe = imx21_probe,
.remove = imx21_remove,
.suspend = NULL,
.resume = NULL,
};
static int __init imx21_hcd_init(void)
{
return platform_driver_register(&imx21_hcd_driver);
}
static void __exit imx21_hcd_cleanup(void)
{
platform_driver_unregister(&imx21_hcd_driver);
}
module_init(imx21_hcd_init);
module_exit(imx21_hcd_cleanup);
MODULE_DESCRIPTION("i.MX21 USB Host controller");
MODULE_AUTHOR("Martin Fuzzey");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:imx21-hcd");
| gpl-2.0 |
xcstacy/mako-deprecated | drivers/net/wan/ixp4xx_hss.c | 3940 | 37785 | /*
* Intel IXP4xx HSS (synchronous serial port) driver for Linux
*
* Copyright (C) 2007-2008 Krzysztof Hałasa <khc@pm.waw.pl>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License
* as published by the Free Software Foundation.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/bitops.h>
#include <linux/cdev.h>
#include <linux/dma-mapping.h>
#include <linux/dmapool.h>
#include <linux/fs.h>
#include <linux/hdlc.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/poll.h>
#include <linux/slab.h>
#include <mach/npe.h>
#include <mach/qmgr.h>
#define DEBUG_DESC 0
#define DEBUG_RX 0
#define DEBUG_TX 0
#define DEBUG_PKT_BYTES 0
#define DEBUG_CLOSE 0
#define DRV_NAME "ixp4xx_hss"
#define PKT_EXTRA_FLAGS 0 /* orig 1 */
#define PKT_NUM_PIPES 1 /* 1, 2 or 4 */
#define PKT_PIPE_FIFO_SIZEW 4 /* total 4 dwords per HSS */
#define RX_DESCS 16 /* also length of all RX queues */
#define TX_DESCS 16 /* also length of all TX queues */
#define POOL_ALLOC_SIZE (sizeof(struct desc) * (RX_DESCS + TX_DESCS))
#define RX_SIZE (HDLC_MAX_MRU + 4) /* NPE needs more space */
#define MAX_CLOSE_WAIT 1000 /* microseconds */
#define HSS_COUNT 2
#define FRAME_SIZE 256 /* doesn't matter at this point */
#define FRAME_OFFSET 0
#define MAX_CHANNELS (FRAME_SIZE / 8)
#define NAPI_WEIGHT 16
/* Queue IDs */
#define HSS0_CHL_RXTRIG_QUEUE 12 /* orig size = 32 dwords */
#define HSS0_PKT_RX_QUEUE 13 /* orig size = 32 dwords */
#define HSS0_PKT_TX0_QUEUE 14 /* orig size = 16 dwords */
#define HSS0_PKT_TX1_QUEUE 15
#define HSS0_PKT_TX2_QUEUE 16
#define HSS0_PKT_TX3_QUEUE 17
#define HSS0_PKT_RXFREE0_QUEUE 18 /* orig size = 16 dwords */
#define HSS0_PKT_RXFREE1_QUEUE 19
#define HSS0_PKT_RXFREE2_QUEUE 20
#define HSS0_PKT_RXFREE3_QUEUE 21
#define HSS0_PKT_TXDONE_QUEUE 22 /* orig size = 64 dwords */
#define HSS1_CHL_RXTRIG_QUEUE 10
#define HSS1_PKT_RX_QUEUE 0
#define HSS1_PKT_TX0_QUEUE 5
#define HSS1_PKT_TX1_QUEUE 6
#define HSS1_PKT_TX2_QUEUE 7
#define HSS1_PKT_TX3_QUEUE 8
#define HSS1_PKT_RXFREE0_QUEUE 1
#define HSS1_PKT_RXFREE1_QUEUE 2
#define HSS1_PKT_RXFREE2_QUEUE 3
#define HSS1_PKT_RXFREE3_QUEUE 4
#define HSS1_PKT_TXDONE_QUEUE 9
#define NPE_PKT_MODE_HDLC 0
#define NPE_PKT_MODE_RAW 1
#define NPE_PKT_MODE_56KMODE 2
#define NPE_PKT_MODE_56KENDIAN_MSB 4
/* PKT_PIPE_HDLC_CFG_WRITE flags */
#define PKT_HDLC_IDLE_ONES 0x1 /* default = flags */
#define PKT_HDLC_CRC_32 0x2 /* default = CRC-16 */
#define PKT_HDLC_MSB_ENDIAN 0x4 /* default = LE */
/* hss_config, PCRs */
/* Frame sync sampling, default = active low */
#define PCR_FRM_SYNC_ACTIVE_HIGH 0x40000000
#define PCR_FRM_SYNC_FALLINGEDGE 0x80000000
#define PCR_FRM_SYNC_RISINGEDGE 0xC0000000
/* Frame sync pin: input (default) or output generated off a given clk edge */
#define PCR_FRM_SYNC_OUTPUT_FALLING 0x20000000
#define PCR_FRM_SYNC_OUTPUT_RISING 0x30000000
/* Frame and data clock sampling on edge, default = falling */
#define PCR_FCLK_EDGE_RISING 0x08000000
#define PCR_DCLK_EDGE_RISING 0x04000000
/* Clock direction, default = input */
#define PCR_SYNC_CLK_DIR_OUTPUT 0x02000000
/* Generate/Receive frame pulses, default = enabled */
#define PCR_FRM_PULSE_DISABLED 0x01000000
/* Data rate is full (default) or half the configured clk speed */
#define PCR_HALF_CLK_RATE 0x00200000
/* Invert data between NPE and HSS FIFOs? (default = no) */
#define PCR_DATA_POLARITY_INVERT 0x00100000
/* TX/RX endianness, default = LSB */
#define PCR_MSB_ENDIAN 0x00080000
/* Normal (default) / open drain mode (TX only) */
#define PCR_TX_PINS_OPEN_DRAIN 0x00040000
/* No framing bit transmitted and expected on RX? (default = framing bit) */
#define PCR_SOF_NO_FBIT 0x00020000
/* Drive data pins? */
#define PCR_TX_DATA_ENABLE 0x00010000
/* Voice 56k type: drive the data pins low (default), high, high Z */
#define PCR_TX_V56K_HIGH 0x00002000
#define PCR_TX_V56K_HIGH_IMP 0x00004000
/* Unassigned type: drive the data pins low (default), high, high Z */
#define PCR_TX_UNASS_HIGH 0x00000800
#define PCR_TX_UNASS_HIGH_IMP 0x00001000
/* T1 @ 1.544MHz only: Fbit dictated in FIFO (default) or high Z */
#define PCR_TX_FB_HIGH_IMP 0x00000400
/* 56k data endiannes - which bit unused: high (default) or low */
#define PCR_TX_56KE_BIT_0_UNUSED 0x00000200
/* 56k data transmission type: 32/8 bit data (default) or 56K data */
#define PCR_TX_56KS_56K_DATA 0x00000100
/* hss_config, cCR */
/* Number of packetized clients, default = 1 */
#define CCR_NPE_HFIFO_2_HDLC 0x04000000
#define CCR_NPE_HFIFO_3_OR_4HDLC 0x08000000
/* default = no loopback */
#define CCR_LOOPBACK 0x02000000
/* HSS number, default = 0 (first) */
#define CCR_SECOND_HSS 0x01000000
/* hss_config, clkCR: main:10, num:10, denom:12 */
#define CLK42X_SPEED_EXP ((0x3FF << 22) | ( 2 << 12) | 15) /*65 KHz*/
#define CLK42X_SPEED_512KHZ (( 130 << 22) | ( 2 << 12) | 15)
#define CLK42X_SPEED_1536KHZ (( 43 << 22) | ( 18 << 12) | 47)
#define CLK42X_SPEED_1544KHZ (( 43 << 22) | ( 33 << 12) | 192)
#define CLK42X_SPEED_2048KHZ (( 32 << 22) | ( 34 << 12) | 63)
#define CLK42X_SPEED_4096KHZ (( 16 << 22) | ( 34 << 12) | 127)
#define CLK42X_SPEED_8192KHZ (( 8 << 22) | ( 34 << 12) | 255)
#define CLK46X_SPEED_512KHZ (( 130 << 22) | ( 24 << 12) | 127)
#define CLK46X_SPEED_1536KHZ (( 43 << 22) | (152 << 12) | 383)
#define CLK46X_SPEED_1544KHZ (( 43 << 22) | ( 66 << 12) | 385)
#define CLK46X_SPEED_2048KHZ (( 32 << 22) | (280 << 12) | 511)
#define CLK46X_SPEED_4096KHZ (( 16 << 22) | (280 << 12) | 1023)
#define CLK46X_SPEED_8192KHZ (( 8 << 22) | (280 << 12) | 2047)
/*
* HSS_CONFIG_CLOCK_CR register consists of 3 parts:
* A (10 bits), B (10 bits) and C (12 bits).
* IXP42x HSS clock generator operation (verified with an oscilloscope):
* Each clock bit takes 7.5 ns (1 / 133.xx MHz).
* The clock sequence consists of (C - B) states of 0s and 1s, each state is
* A bits wide. It's followed by (B + 1) states of 0s and 1s, each state is
* (A + 1) bits wide.
*
* The resulting average clock frequency (assuming 33.333 MHz oscillator) is:
* freq = 66.666 MHz / (A + (B + 1) / (C + 1))
* minimum freq = 66.666 MHz / (A + 1)
* maximum freq = 66.666 MHz / A
*
* Example: A = 2, B = 2, C = 7, CLOCK_CR register = 2 << 22 | 2 << 12 | 7
* freq = 66.666 MHz / (2 + (2 + 1) / (7 + 1)) = 28.07 MHz (Mb/s).
* The clock sequence is: 1100110011 (5 doubles) 000111000 (3 triples).
* The sequence takes (C - B) * A + (B + 1) * (A + 1) = 5 * 2 + 3 * 3 bits
* = 19 bits (each 7.5 ns long) = 142.5 ns (then the sequence repeats).
* The sequence consists of 4 complete clock periods, thus the average
* frequency (= clock rate) is 4 / 142.5 ns = 28.07 MHz (Mb/s).
* (max specified clock rate for IXP42x HSS is 8.192 Mb/s).
*/
/* hss_config, LUT entries */
#define TDMMAP_UNASSIGNED 0
#define TDMMAP_HDLC 1 /* HDLC - packetized */
#define TDMMAP_VOICE56K 2 /* Voice56K - 7-bit channelized */
#define TDMMAP_VOICE64K 3 /* Voice64K - 8-bit channelized */
/* offsets into HSS config */
#define HSS_CONFIG_TX_PCR 0x00 /* port configuration registers */
#define HSS_CONFIG_RX_PCR 0x04
#define HSS_CONFIG_CORE_CR 0x08 /* loopback control, HSS# */
#define HSS_CONFIG_CLOCK_CR 0x0C /* clock generator control */
#define HSS_CONFIG_TX_FCR 0x10 /* frame configuration registers */
#define HSS_CONFIG_RX_FCR 0x14
#define HSS_CONFIG_TX_LUT 0x18 /* channel look-up tables */
#define HSS_CONFIG_RX_LUT 0x38
/* NPE command codes */
/* writes the ConfigWord value to the location specified by offset */
#define PORT_CONFIG_WRITE 0x40
/* triggers the NPE to load the contents of the configuration table */
#define PORT_CONFIG_LOAD 0x41
/* triggers the NPE to return an HssErrorReadResponse message */
#define PORT_ERROR_READ 0x42
/* triggers the NPE to reset internal status and enable the HssPacketized
operation for the flow specified by pPipe */
#define PKT_PIPE_FLOW_ENABLE 0x50
#define PKT_PIPE_FLOW_DISABLE 0x51
#define PKT_NUM_PIPES_WRITE 0x52
#define PKT_PIPE_FIFO_SIZEW_WRITE 0x53
#define PKT_PIPE_HDLC_CFG_WRITE 0x54
#define PKT_PIPE_IDLE_PATTERN_WRITE 0x55
#define PKT_PIPE_RX_SIZE_WRITE 0x56
#define PKT_PIPE_MODE_WRITE 0x57
/* HDLC packet status values - desc->status */
#define ERR_SHUTDOWN 1 /* stop or shutdown occurrence */
#define ERR_HDLC_ALIGN 2 /* HDLC alignment error */
#define ERR_HDLC_FCS 3 /* HDLC Frame Check Sum error */
#define ERR_RXFREE_Q_EMPTY 4 /* RX-free queue became empty while receiving
this packet (if buf_len < pkt_len) */
#define ERR_HDLC_TOO_LONG 5 /* HDLC frame size too long */
#define ERR_HDLC_ABORT 6 /* abort sequence received */
#define ERR_DISCONNECTING 7 /* disconnect is in progress */
#ifdef __ARMEB__
typedef struct sk_buff buffer_t;
#define free_buffer dev_kfree_skb
#define free_buffer_irq dev_kfree_skb_irq
#else
typedef void buffer_t;
#define free_buffer kfree
#define free_buffer_irq kfree
#endif
struct port {
struct device *dev;
struct npe *npe;
struct net_device *netdev;
struct napi_struct napi;
struct hss_plat_info *plat;
buffer_t *rx_buff_tab[RX_DESCS], *tx_buff_tab[TX_DESCS];
struct desc *desc_tab; /* coherent */
u32 desc_tab_phys;
unsigned int id;
unsigned int clock_type, clock_rate, loopback;
unsigned int initialized, carrier;
u8 hdlc_cfg;
u32 clock_reg;
};
/* NPE message structure */
struct msg {
#ifdef __ARMEB__
u8 cmd, unused, hss_port, index;
union {
struct { u8 data8a, data8b, data8c, data8d; };
struct { u16 data16a, data16b; };
struct { u32 data32; };
};
#else
u8 index, hss_port, unused, cmd;
union {
struct { u8 data8d, data8c, data8b, data8a; };
struct { u16 data16b, data16a; };
struct { u32 data32; };
};
#endif
};
/* HDLC packet descriptor */
struct desc {
u32 next; /* pointer to next buffer, unused */
#ifdef __ARMEB__
u16 buf_len; /* buffer length */
u16 pkt_len; /* packet length */
u32 data; /* pointer to data buffer in RAM */
u8 status;
u8 error_count;
u16 __reserved;
#else
u16 pkt_len; /* packet length */
u16 buf_len; /* buffer length */
u32 data; /* pointer to data buffer in RAM */
u16 __reserved;
u8 error_count;
u8 status;
#endif
u32 __reserved1[4];
};
#define rx_desc_phys(port, n) ((port)->desc_tab_phys + \
(n) * sizeof(struct desc))
#define rx_desc_ptr(port, n) (&(port)->desc_tab[n])
#define tx_desc_phys(port, n) ((port)->desc_tab_phys + \
((n) + RX_DESCS) * sizeof(struct desc))
#define tx_desc_ptr(port, n) (&(port)->desc_tab[(n) + RX_DESCS])
/*****************************************************************************
* global variables
****************************************************************************/
static int ports_open;
static struct dma_pool *dma_pool;
static spinlock_t npe_lock;
static const struct {
int tx, txdone, rx, rxfree;
}queue_ids[2] = {{HSS0_PKT_TX0_QUEUE, HSS0_PKT_TXDONE_QUEUE, HSS0_PKT_RX_QUEUE,
HSS0_PKT_RXFREE0_QUEUE},
{HSS1_PKT_TX0_QUEUE, HSS1_PKT_TXDONE_QUEUE, HSS1_PKT_RX_QUEUE,
HSS1_PKT_RXFREE0_QUEUE},
};
/*****************************************************************************
* utility functions
****************************************************************************/
static inline struct port* dev_to_port(struct net_device *dev)
{
return dev_to_hdlc(dev)->priv;
}
#ifndef __ARMEB__
static inline void memcpy_swab32(u32 *dest, u32 *src, int cnt)
{
int i;
for (i = 0; i < cnt; i++)
dest[i] = swab32(src[i]);
}
#endif
/*****************************************************************************
* HSS access
****************************************************************************/
static void hss_npe_send(struct port *port, struct msg *msg, const char* what)
{
u32 *val = (u32*)msg;
if (npe_send_message(port->npe, msg, what)) {
pr_crit("HSS-%i: unable to send command [%08X:%08X] to %s\n",
port->id, val[0], val[1], npe_name(port->npe));
BUG();
}
}
static void hss_config_set_lut(struct port *port)
{
struct msg msg;
int ch;
memset(&msg, 0, sizeof(msg));
msg.cmd = PORT_CONFIG_WRITE;
msg.hss_port = port->id;
for (ch = 0; ch < MAX_CHANNELS; ch++) {
msg.data32 >>= 2;
msg.data32 |= TDMMAP_HDLC << 30;
if (ch % 16 == 15) {
msg.index = HSS_CONFIG_TX_LUT + ((ch / 4) & ~3);
hss_npe_send(port, &msg, "HSS_SET_TX_LUT");
msg.index += HSS_CONFIG_RX_LUT - HSS_CONFIG_TX_LUT;
hss_npe_send(port, &msg, "HSS_SET_RX_LUT");
}
}
}
static void hss_config(struct port *port)
{
struct msg msg;
memset(&msg, 0, sizeof(msg));
msg.cmd = PORT_CONFIG_WRITE;
msg.hss_port = port->id;
msg.index = HSS_CONFIG_TX_PCR;
msg.data32 = PCR_FRM_PULSE_DISABLED | PCR_MSB_ENDIAN |
PCR_TX_DATA_ENABLE | PCR_SOF_NO_FBIT;
if (port->clock_type == CLOCK_INT)
msg.data32 |= PCR_SYNC_CLK_DIR_OUTPUT;
hss_npe_send(port, &msg, "HSS_SET_TX_PCR");
msg.index = HSS_CONFIG_RX_PCR;
msg.data32 ^= PCR_TX_DATA_ENABLE | PCR_DCLK_EDGE_RISING;
hss_npe_send(port, &msg, "HSS_SET_RX_PCR");
memset(&msg, 0, sizeof(msg));
msg.cmd = PORT_CONFIG_WRITE;
msg.hss_port = port->id;
msg.index = HSS_CONFIG_CORE_CR;
msg.data32 = (port->loopback ? CCR_LOOPBACK : 0) |
(port->id ? CCR_SECOND_HSS : 0);
hss_npe_send(port, &msg, "HSS_SET_CORE_CR");
memset(&msg, 0, sizeof(msg));
msg.cmd = PORT_CONFIG_WRITE;
msg.hss_port = port->id;
msg.index = HSS_CONFIG_CLOCK_CR;
msg.data32 = port->clock_reg;
hss_npe_send(port, &msg, "HSS_SET_CLOCK_CR");
memset(&msg, 0, sizeof(msg));
msg.cmd = PORT_CONFIG_WRITE;
msg.hss_port = port->id;
msg.index = HSS_CONFIG_TX_FCR;
msg.data16a = FRAME_OFFSET;
msg.data16b = FRAME_SIZE - 1;
hss_npe_send(port, &msg, "HSS_SET_TX_FCR");
memset(&msg, 0, sizeof(msg));
msg.cmd = PORT_CONFIG_WRITE;
msg.hss_port = port->id;
msg.index = HSS_CONFIG_RX_FCR;
msg.data16a = FRAME_OFFSET;
msg.data16b = FRAME_SIZE - 1;
hss_npe_send(port, &msg, "HSS_SET_RX_FCR");
hss_config_set_lut(port);
memset(&msg, 0, sizeof(msg));
msg.cmd = PORT_CONFIG_LOAD;
msg.hss_port = port->id;
hss_npe_send(port, &msg, "HSS_LOAD_CONFIG");
if (npe_recv_message(port->npe, &msg, "HSS_LOAD_CONFIG") ||
/* HSS_LOAD_CONFIG for port #1 returns port_id = #4 */
msg.cmd != PORT_CONFIG_LOAD || msg.data32) {
pr_crit("HSS-%i: HSS_LOAD_CONFIG failed\n", port->id);
BUG();
}
/* HDLC may stop working without this - check FIXME */
npe_recv_message(port->npe, &msg, "FLUSH_IT");
}
static void hss_set_hdlc_cfg(struct port *port)
{
struct msg msg;
memset(&msg, 0, sizeof(msg));
msg.cmd = PKT_PIPE_HDLC_CFG_WRITE;
msg.hss_port = port->id;
msg.data8a = port->hdlc_cfg; /* rx_cfg */
msg.data8b = port->hdlc_cfg | (PKT_EXTRA_FLAGS << 3); /* tx_cfg */
hss_npe_send(port, &msg, "HSS_SET_HDLC_CFG");
}
static u32 hss_get_status(struct port *port)
{
struct msg msg;
memset(&msg, 0, sizeof(msg));
msg.cmd = PORT_ERROR_READ;
msg.hss_port = port->id;
hss_npe_send(port, &msg, "PORT_ERROR_READ");
if (npe_recv_message(port->npe, &msg, "PORT_ERROR_READ")) {
pr_crit("HSS-%i: unable to read HSS status\n", port->id);
BUG();
}
return msg.data32;
}
static void hss_start_hdlc(struct port *port)
{
struct msg msg;
memset(&msg, 0, sizeof(msg));
msg.cmd = PKT_PIPE_FLOW_ENABLE;
msg.hss_port = port->id;
msg.data32 = 0;
hss_npe_send(port, &msg, "HSS_ENABLE_PKT_PIPE");
}
static void hss_stop_hdlc(struct port *port)
{
struct msg msg;
memset(&msg, 0, sizeof(msg));
msg.cmd = PKT_PIPE_FLOW_DISABLE;
msg.hss_port = port->id;
hss_npe_send(port, &msg, "HSS_DISABLE_PKT_PIPE");
hss_get_status(port); /* make sure it's halted */
}
static int hss_load_firmware(struct port *port)
{
struct msg msg;
int err;
if (port->initialized)
return 0;
if (!npe_running(port->npe) &&
(err = npe_load_firmware(port->npe, npe_name(port->npe),
port->dev)))
return err;
/* HDLC mode configuration */
memset(&msg, 0, sizeof(msg));
msg.cmd = PKT_NUM_PIPES_WRITE;
msg.hss_port = port->id;
msg.data8a = PKT_NUM_PIPES;
hss_npe_send(port, &msg, "HSS_SET_PKT_PIPES");
msg.cmd = PKT_PIPE_FIFO_SIZEW_WRITE;
msg.data8a = PKT_PIPE_FIFO_SIZEW;
hss_npe_send(port, &msg, "HSS_SET_PKT_FIFO");
msg.cmd = PKT_PIPE_MODE_WRITE;
msg.data8a = NPE_PKT_MODE_HDLC;
/* msg.data8b = inv_mask */
/* msg.data8c = or_mask */
hss_npe_send(port, &msg, "HSS_SET_PKT_MODE");
msg.cmd = PKT_PIPE_RX_SIZE_WRITE;
msg.data16a = HDLC_MAX_MRU; /* including CRC */
hss_npe_send(port, &msg, "HSS_SET_PKT_RX_SIZE");
msg.cmd = PKT_PIPE_IDLE_PATTERN_WRITE;
msg.data32 = 0x7F7F7F7F; /* ??? FIXME */
hss_npe_send(port, &msg, "HSS_SET_PKT_IDLE");
port->initialized = 1;
return 0;
}
/*****************************************************************************
* packetized (HDLC) operation
****************************************************************************/
static inline void debug_pkt(struct net_device *dev, const char *func,
u8 *data, int len)
{
#if DEBUG_PKT_BYTES
int i;
printk(KERN_DEBUG "%s: %s(%i)", dev->name, func, len);
for (i = 0; i < len; i++) {
if (i >= DEBUG_PKT_BYTES)
break;
printk("%s%02X", !(i % 4) ? " " : "", data[i]);
}
printk("\n");
#endif
}
static inline void debug_desc(u32 phys, struct desc *desc)
{
#if DEBUG_DESC
printk(KERN_DEBUG "%X: %X %3X %3X %08X %X %X\n",
phys, desc->next, desc->buf_len, desc->pkt_len,
desc->data, desc->status, desc->error_count);
#endif
}
static inline int queue_get_desc(unsigned int queue, struct port *port,
int is_tx)
{
u32 phys, tab_phys, n_desc;
struct desc *tab;
if (!(phys = qmgr_get_entry(queue)))
return -1;
BUG_ON(phys & 0x1F);
tab_phys = is_tx ? tx_desc_phys(port, 0) : rx_desc_phys(port, 0);
tab = is_tx ? tx_desc_ptr(port, 0) : rx_desc_ptr(port, 0);
n_desc = (phys - tab_phys) / sizeof(struct desc);
BUG_ON(n_desc >= (is_tx ? TX_DESCS : RX_DESCS));
debug_desc(phys, &tab[n_desc]);
BUG_ON(tab[n_desc].next);
return n_desc;
}
static inline void queue_put_desc(unsigned int queue, u32 phys,
struct desc *desc)
{
debug_desc(phys, desc);
BUG_ON(phys & 0x1F);
qmgr_put_entry(queue, phys);
/* Don't check for queue overflow here, we've allocated sufficient
length and queues >= 32 don't support this check anyway. */
}
static inline void dma_unmap_tx(struct port *port, struct desc *desc)
{
#ifdef __ARMEB__
dma_unmap_single(&port->netdev->dev, desc->data,
desc->buf_len, DMA_TO_DEVICE);
#else
dma_unmap_single(&port->netdev->dev, desc->data & ~3,
ALIGN((desc->data & 3) + desc->buf_len, 4),
DMA_TO_DEVICE);
#endif
}
static void hss_hdlc_set_carrier(void *pdev, int carrier)
{
struct net_device *netdev = pdev;
struct port *port = dev_to_port(netdev);
unsigned long flags;
spin_lock_irqsave(&npe_lock, flags);
port->carrier = carrier;
if (!port->loopback) {
if (carrier)
netif_carrier_on(netdev);
else
netif_carrier_off(netdev);
}
spin_unlock_irqrestore(&npe_lock, flags);
}
static void hss_hdlc_rx_irq(void *pdev)
{
struct net_device *dev = pdev;
struct port *port = dev_to_port(dev);
#if DEBUG_RX
printk(KERN_DEBUG "%s: hss_hdlc_rx_irq\n", dev->name);
#endif
qmgr_disable_irq(queue_ids[port->id].rx);
napi_schedule(&port->napi);
}
static int hss_hdlc_poll(struct napi_struct *napi, int budget)
{
struct port *port = container_of(napi, struct port, napi);
struct net_device *dev = port->netdev;
unsigned int rxq = queue_ids[port->id].rx;
unsigned int rxfreeq = queue_ids[port->id].rxfree;
int received = 0;
#if DEBUG_RX
printk(KERN_DEBUG "%s: hss_hdlc_poll\n", dev->name);
#endif
while (received < budget) {
struct sk_buff *skb;
struct desc *desc;
int n;
#ifdef __ARMEB__
struct sk_buff *temp;
u32 phys;
#endif
if ((n = queue_get_desc(rxq, port, 0)) < 0) {
#if DEBUG_RX
printk(KERN_DEBUG "%s: hss_hdlc_poll"
" napi_complete\n", dev->name);
#endif
napi_complete(napi);
qmgr_enable_irq(rxq);
if (!qmgr_stat_empty(rxq) &&
napi_reschedule(napi)) {
#if DEBUG_RX
printk(KERN_DEBUG "%s: hss_hdlc_poll"
" napi_reschedule succeeded\n",
dev->name);
#endif
qmgr_disable_irq(rxq);
continue;
}
#if DEBUG_RX
printk(KERN_DEBUG "%s: hss_hdlc_poll all done\n",
dev->name);
#endif
return received; /* all work done */
}
desc = rx_desc_ptr(port, n);
#if 0 /* FIXME - error_count counts modulo 256, perhaps we should use it */
if (desc->error_count)
printk(KERN_DEBUG "%s: hss_hdlc_poll status 0x%02X"
" errors %u\n", dev->name, desc->status,
desc->error_count);
#endif
skb = NULL;
switch (desc->status) {
case 0:
#ifdef __ARMEB__
if ((skb = netdev_alloc_skb(dev, RX_SIZE)) != NULL) {
phys = dma_map_single(&dev->dev, skb->data,
RX_SIZE,
DMA_FROM_DEVICE);
if (dma_mapping_error(&dev->dev, phys)) {
dev_kfree_skb(skb);
skb = NULL;
}
}
#else
skb = netdev_alloc_skb(dev, desc->pkt_len);
#endif
if (!skb)
dev->stats.rx_dropped++;
break;
case ERR_HDLC_ALIGN:
case ERR_HDLC_ABORT:
dev->stats.rx_frame_errors++;
dev->stats.rx_errors++;
break;
case ERR_HDLC_FCS:
dev->stats.rx_crc_errors++;
dev->stats.rx_errors++;
break;
case ERR_HDLC_TOO_LONG:
dev->stats.rx_length_errors++;
dev->stats.rx_errors++;
break;
default: /* FIXME - remove printk */
netdev_err(dev, "hss_hdlc_poll: status 0x%02X errors %u\n",
desc->status, desc->error_count);
dev->stats.rx_errors++;
}
if (!skb) {
/* put the desc back on RX-ready queue */
desc->buf_len = RX_SIZE;
desc->pkt_len = desc->status = 0;
queue_put_desc(rxfreeq, rx_desc_phys(port, n), desc);
continue;
}
/* process received frame */
#ifdef __ARMEB__
temp = skb;
skb = port->rx_buff_tab[n];
dma_unmap_single(&dev->dev, desc->data,
RX_SIZE, DMA_FROM_DEVICE);
#else
dma_sync_single_for_cpu(&dev->dev, desc->data,
RX_SIZE, DMA_FROM_DEVICE);
memcpy_swab32((u32 *)skb->data, (u32 *)port->rx_buff_tab[n],
ALIGN(desc->pkt_len, 4) / 4);
#endif
skb_put(skb, desc->pkt_len);
debug_pkt(dev, "hss_hdlc_poll", skb->data, skb->len);
skb->protocol = hdlc_type_trans(skb, dev);
dev->stats.rx_packets++;
dev->stats.rx_bytes += skb->len;
netif_receive_skb(skb);
/* put the new buffer on RX-free queue */
#ifdef __ARMEB__
port->rx_buff_tab[n] = temp;
desc->data = phys;
#endif
desc->buf_len = RX_SIZE;
desc->pkt_len = 0;
queue_put_desc(rxfreeq, rx_desc_phys(port, n), desc);
received++;
}
#if DEBUG_RX
printk(KERN_DEBUG "hss_hdlc_poll: end, not all work done\n");
#endif
return received; /* not all work done */
}
static void hss_hdlc_txdone_irq(void *pdev)
{
struct net_device *dev = pdev;
struct port *port = dev_to_port(dev);
int n_desc;
#if DEBUG_TX
printk(KERN_DEBUG DRV_NAME ": hss_hdlc_txdone_irq\n");
#endif
while ((n_desc = queue_get_desc(queue_ids[port->id].txdone,
port, 1)) >= 0) {
struct desc *desc;
int start;
desc = tx_desc_ptr(port, n_desc);
dev->stats.tx_packets++;
dev->stats.tx_bytes += desc->pkt_len;
dma_unmap_tx(port, desc);
#if DEBUG_TX
printk(KERN_DEBUG "%s: hss_hdlc_txdone_irq free %p\n",
dev->name, port->tx_buff_tab[n_desc]);
#endif
free_buffer_irq(port->tx_buff_tab[n_desc]);
port->tx_buff_tab[n_desc] = NULL;
start = qmgr_stat_below_low_watermark(port->plat->txreadyq);
queue_put_desc(port->plat->txreadyq,
tx_desc_phys(port, n_desc), desc);
if (start) { /* TX-ready queue was empty */
#if DEBUG_TX
printk(KERN_DEBUG "%s: hss_hdlc_txdone_irq xmit"
" ready\n", dev->name);
#endif
netif_wake_queue(dev);
}
}
}
static int hss_hdlc_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct port *port = dev_to_port(dev);
unsigned int txreadyq = port->plat->txreadyq;
int len, offset, bytes, n;
void *mem;
u32 phys;
struct desc *desc;
#if DEBUG_TX
printk(KERN_DEBUG "%s: hss_hdlc_xmit\n", dev->name);
#endif
if (unlikely(skb->len > HDLC_MAX_MRU)) {
dev_kfree_skb(skb);
dev->stats.tx_errors++;
return NETDEV_TX_OK;
}
debug_pkt(dev, "hss_hdlc_xmit", skb->data, skb->len);
len = skb->len;
#ifdef __ARMEB__
offset = 0; /* no need to keep alignment */
bytes = len;
mem = skb->data;
#else
offset = (int)skb->data & 3; /* keep 32-bit alignment */
bytes = ALIGN(offset + len, 4);
if (!(mem = kmalloc(bytes, GFP_ATOMIC))) {
dev_kfree_skb(skb);
dev->stats.tx_dropped++;
return NETDEV_TX_OK;
}
memcpy_swab32(mem, (u32 *)((int)skb->data & ~3), bytes / 4);
dev_kfree_skb(skb);
#endif
phys = dma_map_single(&dev->dev, mem, bytes, DMA_TO_DEVICE);
if (dma_mapping_error(&dev->dev, phys)) {
#ifdef __ARMEB__
dev_kfree_skb(skb);
#else
kfree(mem);
#endif
dev->stats.tx_dropped++;
return NETDEV_TX_OK;
}
n = queue_get_desc(txreadyq, port, 1);
BUG_ON(n < 0);
desc = tx_desc_ptr(port, n);
#ifdef __ARMEB__
port->tx_buff_tab[n] = skb;
#else
port->tx_buff_tab[n] = mem;
#endif
desc->data = phys + offset;
desc->buf_len = desc->pkt_len = len;
wmb();
queue_put_desc(queue_ids[port->id].tx, tx_desc_phys(port, n), desc);
if (qmgr_stat_below_low_watermark(txreadyq)) { /* empty */
#if DEBUG_TX
printk(KERN_DEBUG "%s: hss_hdlc_xmit queue full\n", dev->name);
#endif
netif_stop_queue(dev);
/* we could miss TX ready interrupt */
if (!qmgr_stat_below_low_watermark(txreadyq)) {
#if DEBUG_TX
printk(KERN_DEBUG "%s: hss_hdlc_xmit ready again\n",
dev->name);
#endif
netif_wake_queue(dev);
}
}
#if DEBUG_TX
printk(KERN_DEBUG "%s: hss_hdlc_xmit end\n", dev->name);
#endif
return NETDEV_TX_OK;
}
static int request_hdlc_queues(struct port *port)
{
int err;
err = qmgr_request_queue(queue_ids[port->id].rxfree, RX_DESCS, 0, 0,
"%s:RX-free", port->netdev->name);
if (err)
return err;
err = qmgr_request_queue(queue_ids[port->id].rx, RX_DESCS, 0, 0,
"%s:RX", port->netdev->name);
if (err)
goto rel_rxfree;
err = qmgr_request_queue(queue_ids[port->id].tx, TX_DESCS, 0, 0,
"%s:TX", port->netdev->name);
if (err)
goto rel_rx;
err = qmgr_request_queue(port->plat->txreadyq, TX_DESCS, 0, 0,
"%s:TX-ready", port->netdev->name);
if (err)
goto rel_tx;
err = qmgr_request_queue(queue_ids[port->id].txdone, TX_DESCS, 0, 0,
"%s:TX-done", port->netdev->name);
if (err)
goto rel_txready;
return 0;
rel_txready:
qmgr_release_queue(port->plat->txreadyq);
rel_tx:
qmgr_release_queue(queue_ids[port->id].tx);
rel_rx:
qmgr_release_queue(queue_ids[port->id].rx);
rel_rxfree:
qmgr_release_queue(queue_ids[port->id].rxfree);
printk(KERN_DEBUG "%s: unable to request hardware queues\n",
port->netdev->name);
return err;
}
static void release_hdlc_queues(struct port *port)
{
qmgr_release_queue(queue_ids[port->id].rxfree);
qmgr_release_queue(queue_ids[port->id].rx);
qmgr_release_queue(queue_ids[port->id].txdone);
qmgr_release_queue(queue_ids[port->id].tx);
qmgr_release_queue(port->plat->txreadyq);
}
static int init_hdlc_queues(struct port *port)
{
int i;
if (!ports_open)
if (!(dma_pool = dma_pool_create(DRV_NAME, NULL,
POOL_ALLOC_SIZE, 32, 0)))
return -ENOMEM;
if (!(port->desc_tab = dma_pool_alloc(dma_pool, GFP_KERNEL,
&port->desc_tab_phys)))
return -ENOMEM;
memset(port->desc_tab, 0, POOL_ALLOC_SIZE);
memset(port->rx_buff_tab, 0, sizeof(port->rx_buff_tab)); /* tables */
memset(port->tx_buff_tab, 0, sizeof(port->tx_buff_tab));
/* Setup RX buffers */
for (i = 0; i < RX_DESCS; i++) {
struct desc *desc = rx_desc_ptr(port, i);
buffer_t *buff;
void *data;
#ifdef __ARMEB__
if (!(buff = netdev_alloc_skb(port->netdev, RX_SIZE)))
return -ENOMEM;
data = buff->data;
#else
if (!(buff = kmalloc(RX_SIZE, GFP_KERNEL)))
return -ENOMEM;
data = buff;
#endif
desc->buf_len = RX_SIZE;
desc->data = dma_map_single(&port->netdev->dev, data,
RX_SIZE, DMA_FROM_DEVICE);
if (dma_mapping_error(&port->netdev->dev, desc->data)) {
free_buffer(buff);
return -EIO;
}
port->rx_buff_tab[i] = buff;
}
return 0;
}
static void destroy_hdlc_queues(struct port *port)
{
int i;
if (port->desc_tab) {
for (i = 0; i < RX_DESCS; i++) {
struct desc *desc = rx_desc_ptr(port, i);
buffer_t *buff = port->rx_buff_tab[i];
if (buff) {
dma_unmap_single(&port->netdev->dev,
desc->data, RX_SIZE,
DMA_FROM_DEVICE);
free_buffer(buff);
}
}
for (i = 0; i < TX_DESCS; i++) {
struct desc *desc = tx_desc_ptr(port, i);
buffer_t *buff = port->tx_buff_tab[i];
if (buff) {
dma_unmap_tx(port, desc);
free_buffer(buff);
}
}
dma_pool_free(dma_pool, port->desc_tab, port->desc_tab_phys);
port->desc_tab = NULL;
}
if (!ports_open && dma_pool) {
dma_pool_destroy(dma_pool);
dma_pool = NULL;
}
}
static int hss_hdlc_open(struct net_device *dev)
{
struct port *port = dev_to_port(dev);
unsigned long flags;
int i, err = 0;
if ((err = hdlc_open(dev)))
return err;
if ((err = hss_load_firmware(port)))
goto err_hdlc_close;
if ((err = request_hdlc_queues(port)))
goto err_hdlc_close;
if ((err = init_hdlc_queues(port)))
goto err_destroy_queues;
spin_lock_irqsave(&npe_lock, flags);
if (port->plat->open)
if ((err = port->plat->open(port->id, dev,
hss_hdlc_set_carrier)))
goto err_unlock;
spin_unlock_irqrestore(&npe_lock, flags);
/* Populate queues with buffers, no failure after this point */
for (i = 0; i < TX_DESCS; i++)
queue_put_desc(port->plat->txreadyq,
tx_desc_phys(port, i), tx_desc_ptr(port, i));
for (i = 0; i < RX_DESCS; i++)
queue_put_desc(queue_ids[port->id].rxfree,
rx_desc_phys(port, i), rx_desc_ptr(port, i));
napi_enable(&port->napi);
netif_start_queue(dev);
qmgr_set_irq(queue_ids[port->id].rx, QUEUE_IRQ_SRC_NOT_EMPTY,
hss_hdlc_rx_irq, dev);
qmgr_set_irq(queue_ids[port->id].txdone, QUEUE_IRQ_SRC_NOT_EMPTY,
hss_hdlc_txdone_irq, dev);
qmgr_enable_irq(queue_ids[port->id].txdone);
ports_open++;
hss_set_hdlc_cfg(port);
hss_config(port);
hss_start_hdlc(port);
/* we may already have RX data, enables IRQ */
napi_schedule(&port->napi);
return 0;
err_unlock:
spin_unlock_irqrestore(&npe_lock, flags);
err_destroy_queues:
destroy_hdlc_queues(port);
release_hdlc_queues(port);
err_hdlc_close:
hdlc_close(dev);
return err;
}
static int hss_hdlc_close(struct net_device *dev)
{
struct port *port = dev_to_port(dev);
unsigned long flags;
int i, buffs = RX_DESCS; /* allocated RX buffers */
spin_lock_irqsave(&npe_lock, flags);
ports_open--;
qmgr_disable_irq(queue_ids[port->id].rx);
netif_stop_queue(dev);
napi_disable(&port->napi);
hss_stop_hdlc(port);
while (queue_get_desc(queue_ids[port->id].rxfree, port, 0) >= 0)
buffs--;
while (queue_get_desc(queue_ids[port->id].rx, port, 0) >= 0)
buffs--;
if (buffs)
netdev_crit(dev, "unable to drain RX queue, %i buffer(s) left in NPE\n",
buffs);
buffs = TX_DESCS;
while (queue_get_desc(queue_ids[port->id].tx, port, 1) >= 0)
buffs--; /* cancel TX */
i = 0;
do {
while (queue_get_desc(port->plat->txreadyq, port, 1) >= 0)
buffs--;
if (!buffs)
break;
} while (++i < MAX_CLOSE_WAIT);
if (buffs)
netdev_crit(dev, "unable to drain TX queue, %i buffer(s) left in NPE\n",
buffs);
#if DEBUG_CLOSE
if (!buffs)
printk(KERN_DEBUG "Draining TX queues took %i cycles\n", i);
#endif
qmgr_disable_irq(queue_ids[port->id].txdone);
if (port->plat->close)
port->plat->close(port->id, dev);
spin_unlock_irqrestore(&npe_lock, flags);
destroy_hdlc_queues(port);
release_hdlc_queues(port);
hdlc_close(dev);
return 0;
}
static int hss_hdlc_attach(struct net_device *dev, unsigned short encoding,
unsigned short parity)
{
struct port *port = dev_to_port(dev);
if (encoding != ENCODING_NRZ)
return -EINVAL;
switch(parity) {
case PARITY_CRC16_PR1_CCITT:
port->hdlc_cfg = 0;
return 0;
case PARITY_CRC32_PR1_CCITT:
port->hdlc_cfg = PKT_HDLC_CRC_32;
return 0;
default:
return -EINVAL;
}
}
static u32 check_clock(u32 rate, u32 a, u32 b, u32 c,
u32 *best, u32 *best_diff, u32 *reg)
{
/* a is 10-bit, b is 10-bit, c is 12-bit */
u64 new_rate;
u32 new_diff;
new_rate = ixp4xx_timer_freq * (u64)(c + 1);
do_div(new_rate, a * (c + 1) + b + 1);
new_diff = abs((u32)new_rate - rate);
if (new_diff < *best_diff) {
*best = new_rate;
*best_diff = new_diff;
*reg = (a << 22) | (b << 12) | c;
}
return new_diff;
}
static void find_best_clock(u32 rate, u32 *best, u32 *reg)
{
u32 a, b, diff = 0xFFFFFFFF;
a = ixp4xx_timer_freq / rate;
if (a > 0x3FF) { /* 10-bit value - we can go as slow as ca. 65 kb/s */
check_clock(rate, 0x3FF, 1, 1, best, &diff, reg);
return;
}
if (a == 0) { /* > 66.666 MHz */
a = 1; /* minimum divider is 1 (a = 0, b = 1, c = 1) */
rate = ixp4xx_timer_freq;
}
if (rate * a == ixp4xx_timer_freq) { /* don't divide by 0 later */
check_clock(rate, a - 1, 1, 1, best, &diff, reg);
return;
}
for (b = 0; b < 0x400; b++) {
u64 c = (b + 1) * (u64)rate;
do_div(c, ixp4xx_timer_freq - rate * a);
c--;
if (c >= 0xFFF) { /* 12-bit - no need to check more 'b's */
if (b == 0 && /* also try a bit higher rate */
!check_clock(rate, a - 1, 1, 1, best, &diff, reg))
return;
check_clock(rate, a, b, 0xFFF, best, &diff, reg);
return;
}
if (!check_clock(rate, a, b, c, best, &diff, reg))
return;
if (!check_clock(rate, a, b, c + 1, best, &diff, reg))
return;
}
}
static int hss_hdlc_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
const size_t size = sizeof(sync_serial_settings);
sync_serial_settings new_line;
sync_serial_settings __user *line = ifr->ifr_settings.ifs_ifsu.sync;
struct port *port = dev_to_port(dev);
unsigned long flags;
int clk;
if (cmd != SIOCWANDEV)
return hdlc_ioctl(dev, ifr, cmd);
switch(ifr->ifr_settings.type) {
case IF_GET_IFACE:
ifr->ifr_settings.type = IF_IFACE_V35;
if (ifr->ifr_settings.size < size) {
ifr->ifr_settings.size = size; /* data size wanted */
return -ENOBUFS;
}
memset(&new_line, 0, sizeof(new_line));
new_line.clock_type = port->clock_type;
new_line.clock_rate = port->clock_rate;
new_line.loopback = port->loopback;
if (copy_to_user(line, &new_line, size))
return -EFAULT;
return 0;
case IF_IFACE_SYNC_SERIAL:
case IF_IFACE_V35:
if(!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&new_line, line, size))
return -EFAULT;
clk = new_line.clock_type;
if (port->plat->set_clock)
clk = port->plat->set_clock(port->id, clk);
if (clk != CLOCK_EXT && clk != CLOCK_INT)
return -EINVAL; /* No such clock setting */
if (new_line.loopback != 0 && new_line.loopback != 1)
return -EINVAL;
port->clock_type = clk; /* Update settings */
if (clk == CLOCK_INT)
find_best_clock(new_line.clock_rate, &port->clock_rate,
&port->clock_reg);
else {
port->clock_rate = 0;
port->clock_reg = CLK42X_SPEED_2048KHZ;
}
port->loopback = new_line.loopback;
spin_lock_irqsave(&npe_lock, flags);
if (dev->flags & IFF_UP)
hss_config(port);
if (port->loopback || port->carrier)
netif_carrier_on(port->netdev);
else
netif_carrier_off(port->netdev);
spin_unlock_irqrestore(&npe_lock, flags);
return 0;
default:
return hdlc_ioctl(dev, ifr, cmd);
}
}
/*****************************************************************************
* initialization
****************************************************************************/
static const struct net_device_ops hss_hdlc_ops = {
.ndo_open = hss_hdlc_open,
.ndo_stop = hss_hdlc_close,
.ndo_change_mtu = hdlc_change_mtu,
.ndo_start_xmit = hdlc_start_xmit,
.ndo_do_ioctl = hss_hdlc_ioctl,
};
static int __devinit hss_init_one(struct platform_device *pdev)
{
struct port *port;
struct net_device *dev;
hdlc_device *hdlc;
int err;
if ((port = kzalloc(sizeof(*port), GFP_KERNEL)) == NULL)
return -ENOMEM;
if ((port->npe = npe_request(0)) == NULL) {
err = -ENODEV;
goto err_free;
}
if ((port->netdev = dev = alloc_hdlcdev(port)) == NULL) {
err = -ENOMEM;
goto err_plat;
}
SET_NETDEV_DEV(dev, &pdev->dev);
hdlc = dev_to_hdlc(dev);
hdlc->attach = hss_hdlc_attach;
hdlc->xmit = hss_hdlc_xmit;
dev->netdev_ops = &hss_hdlc_ops;
dev->tx_queue_len = 100;
port->clock_type = CLOCK_EXT;
port->clock_rate = 0;
port->clock_reg = CLK42X_SPEED_2048KHZ;
port->id = pdev->id;
port->dev = &pdev->dev;
port->plat = pdev->dev.platform_data;
netif_napi_add(dev, &port->napi, hss_hdlc_poll, NAPI_WEIGHT);
if ((err = register_hdlc_device(dev)))
goto err_free_netdev;
platform_set_drvdata(pdev, port);
netdev_info(dev, "HSS-%i\n", port->id);
return 0;
err_free_netdev:
free_netdev(dev);
err_plat:
npe_release(port->npe);
err_free:
kfree(port);
return err;
}
static int __devexit hss_remove_one(struct platform_device *pdev)
{
struct port *port = platform_get_drvdata(pdev);
unregister_hdlc_device(port->netdev);
free_netdev(port->netdev);
npe_release(port->npe);
platform_set_drvdata(pdev, NULL);
kfree(port);
return 0;
}
static struct platform_driver ixp4xx_hss_driver = {
.driver.name = DRV_NAME,
.probe = hss_init_one,
.remove = hss_remove_one,
};
static int __init hss_init_module(void)
{
if ((ixp4xx_read_feature_bits() &
(IXP4XX_FEATURE_HDLC | IXP4XX_FEATURE_HSS)) !=
(IXP4XX_FEATURE_HDLC | IXP4XX_FEATURE_HSS))
return -ENODEV;
spin_lock_init(&npe_lock);
return platform_driver_register(&ixp4xx_hss_driver);
}
static void __exit hss_cleanup_module(void)
{
platform_driver_unregister(&ixp4xx_hss_driver);
}
MODULE_AUTHOR("Krzysztof Halasa");
MODULE_DESCRIPTION("Intel IXP4xx HSS driver");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:ixp4xx_hss");
module_init(hss_init_module);
module_exit(hss_cleanup_module);
| gpl-2.0 |
jjhmod/mk908-jjh-kernel | drivers/macintosh/windfarm_lm75_sensor.c | 4196 | 6035 | /*
* Windfarm PowerMac thermal control. LM75 sensor
*
* (c) Copyright 2005 Benjamin Herrenschmidt, IBM Corp.
* <benh@kernel.crashing.org>
*
* Released under the term of the GNU GPL v2.
*/
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/wait.h>
#include <linux/i2c.h>
#include <asm/prom.h>
#include <asm/machdep.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/sections.h>
#include <asm/pmac_low_i2c.h>
#include "windfarm.h"
#define VERSION "0.2"
#undef DEBUG
#ifdef DEBUG
#define DBG(args...) printk(args)
#else
#define DBG(args...) do { } while(0)
#endif
struct wf_lm75_sensor {
int ds1775 : 1;
int inited : 1;
struct i2c_client *i2c;
struct wf_sensor sens;
};
#define wf_to_lm75(c) container_of(c, struct wf_lm75_sensor, sens)
static int wf_lm75_get(struct wf_sensor *sr, s32 *value)
{
struct wf_lm75_sensor *lm = wf_to_lm75(sr);
s32 data;
if (lm->i2c == NULL)
return -ENODEV;
/* Init chip if necessary */
if (!lm->inited) {
u8 cfg_new, cfg = (u8)i2c_smbus_read_byte_data(lm->i2c, 1);
DBG("wf_lm75: Initializing %s, cfg was: %02x\n",
sr->name, cfg);
/* clear shutdown bit, keep other settings as left by
* the firmware for now
*/
cfg_new = cfg & ~0x01;
i2c_smbus_write_byte_data(lm->i2c, 1, cfg_new);
lm->inited = 1;
/* If we just powered it up, let's wait 200 ms */
msleep(200);
}
/* Read temperature register */
data = (s32)le16_to_cpu(i2c_smbus_read_word_data(lm->i2c, 0));
data <<= 8;
*value = data;
return 0;
}
static void wf_lm75_release(struct wf_sensor *sr)
{
struct wf_lm75_sensor *lm = wf_to_lm75(sr);
kfree(lm);
}
static struct wf_sensor_ops wf_lm75_ops = {
.get_value = wf_lm75_get,
.release = wf_lm75_release,
.owner = THIS_MODULE,
};
static int wf_lm75_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct wf_lm75_sensor *lm;
int rc;
lm = kzalloc(sizeof(struct wf_lm75_sensor), GFP_KERNEL);
if (lm == NULL)
return -ENODEV;
lm->inited = 0;
lm->ds1775 = id->driver_data;
lm->i2c = client;
lm->sens.name = client->dev.platform_data;
lm->sens.ops = &wf_lm75_ops;
i2c_set_clientdata(client, lm);
rc = wf_register_sensor(&lm->sens);
if (rc)
kfree(lm);
return rc;
}
static struct i2c_driver wf_lm75_driver;
static struct i2c_client *wf_lm75_create(struct i2c_adapter *adapter,
u8 addr, int ds1775,
const char *loc)
{
struct i2c_board_info info;
struct i2c_client *client;
char *name;
DBG("wf_lm75: creating %s device at address 0x%02x\n",
ds1775 ? "ds1775" : "lm75", addr);
/* Usual rant about sensor names not beeing very consistent in
* the device-tree, oh well ...
* Add more entries below as you deal with more setups
*/
if (!strcmp(loc, "Hard drive") || !strcmp(loc, "DRIVE BAY"))
name = "hd-temp";
else if (!strcmp(loc, "Incoming Air Temp"))
name = "incoming-air-temp";
else if (!strcmp(loc, "ODD Temp"))
name = "optical-drive-temp";
else if (!strcmp(loc, "HD Temp"))
name = "hard-drive-temp";
else
goto fail;
memset(&info, 0, sizeof(struct i2c_board_info));
info.addr = (addr >> 1) & 0x7f;
info.platform_data = name;
strlcpy(info.type, ds1775 ? "wf_ds1775" : "wf_lm75", I2C_NAME_SIZE);
client = i2c_new_device(adapter, &info);
if (client == NULL) {
printk(KERN_ERR "windfarm: failed to attach %s %s to i2c\n",
ds1775 ? "ds1775" : "lm75", name);
goto fail;
}
/*
* Let i2c-core delete that device on driver removal.
* This is safe because i2c-core holds the core_lock mutex for us.
*/
list_add_tail(&client->detected, &wf_lm75_driver.clients);
return client;
fail:
return NULL;
}
static int wf_lm75_attach(struct i2c_adapter *adapter)
{
struct device_node *busnode, *dev;
struct pmac_i2c_bus *bus;
DBG("wf_lm75: adapter %s detected\n", adapter->name);
bus = pmac_i2c_adapter_to_bus(adapter);
if (bus == NULL)
return -ENODEV;
busnode = pmac_i2c_get_bus_node(bus);
DBG("wf_lm75: bus found, looking for device...\n");
/* Now look for lm75(s) in there */
for (dev = NULL;
(dev = of_get_next_child(busnode, dev)) != NULL;) {
const char *loc =
of_get_property(dev, "hwsensor-location", NULL);
u8 addr;
/* We must re-match the adapter in order to properly check
* the channel on multibus setups
*/
if (!pmac_i2c_match_adapter(dev, adapter))
continue;
addr = pmac_i2c_get_dev_addr(dev);
if (loc == NULL || addr == 0)
continue;
/* real lm75 */
if (of_device_is_compatible(dev, "lm75"))
wf_lm75_create(adapter, addr, 0, loc);
/* ds1775 (compatible, better resolution */
else if (of_device_is_compatible(dev, "ds1775"))
wf_lm75_create(adapter, addr, 1, loc);
}
return 0;
}
static int wf_lm75_remove(struct i2c_client *client)
{
struct wf_lm75_sensor *lm = i2c_get_clientdata(client);
DBG("wf_lm75: i2c detatch called for %s\n", lm->sens.name);
/* Mark client detached */
lm->i2c = NULL;
/* release sensor */
wf_unregister_sensor(&lm->sens);
return 0;
}
static const struct i2c_device_id wf_lm75_id[] = {
{ "wf_lm75", 0 },
{ "wf_ds1775", 1 },
{ }
};
static struct i2c_driver wf_lm75_driver = {
.driver = {
.name = "wf_lm75",
},
.attach_adapter = wf_lm75_attach,
.probe = wf_lm75_probe,
.remove = wf_lm75_remove,
.id_table = wf_lm75_id,
};
static int __init wf_lm75_sensor_init(void)
{
/* Don't register on old machines that use therm_pm72 for now */
if (of_machine_is_compatible("PowerMac7,2") ||
of_machine_is_compatible("PowerMac7,3") ||
of_machine_is_compatible("RackMac3,1"))
return -ENODEV;
return i2c_add_driver(&wf_lm75_driver);
}
static void __exit wf_lm75_sensor_exit(void)
{
i2c_del_driver(&wf_lm75_driver);
}
module_init(wf_lm75_sensor_init);
module_exit(wf_lm75_sensor_exit);
MODULE_AUTHOR("Benjamin Herrenschmidt <benh@kernel.crashing.org>");
MODULE_DESCRIPTION("LM75 sensor objects for PowerMacs thermal control");
MODULE_LICENSE("GPL");
| gpl-2.0 |
intervigilium/android_kernel_google_msm | drivers/staging/iio/accel/adis16203_core.c | 4964 | 12419 | /*
* ADIS16203 Programmable Digital Vibration Sensor driver
*
* Copyright 2010 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#include <linux/delay.h>
#include <linux/mutex.h>
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/spi/spi.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include <linux/module.h>
#include "../iio.h"
#include "../sysfs.h"
#include "../buffer.h"
#include "adis16203.h"
#define DRIVER_NAME "adis16203"
/**
* adis16203_spi_write_reg_8() - write single byte to a register
* @indio_dev: iio device associated with child of actual device
* @reg_address: the address of the register to be written
* @val: the value to write
**/
static int adis16203_spi_write_reg_8(struct iio_dev *indio_dev,
u8 reg_address,
u8 val)
{
int ret;
struct adis16203_state *st = iio_priv(indio_dev);
mutex_lock(&st->buf_lock);
st->tx[0] = ADIS16203_WRITE_REG(reg_address);
st->tx[1] = val;
ret = spi_write(st->us, st->tx, 2);
mutex_unlock(&st->buf_lock);
return ret;
}
/**
* adis16203_spi_write_reg_16() - write 2 bytes to a pair of registers
* @indio_dev: iio device associated with child of actual device
* @reg_address: the address of the lower of the two registers. Second register
* is assumed to have address one greater.
* @val: value to be written
**/
static int adis16203_spi_write_reg_16(struct iio_dev *indio_dev,
u8 lower_reg_address,
u16 value)
{
int ret;
struct spi_message msg;
struct adis16203_state *st = iio_priv(indio_dev);
struct spi_transfer xfers[] = {
{
.tx_buf = st->tx,
.bits_per_word = 8,
.len = 2,
.cs_change = 1,
}, {
.tx_buf = st->tx + 2,
.bits_per_word = 8,
.len = 2,
},
};
mutex_lock(&st->buf_lock);
st->tx[0] = ADIS16203_WRITE_REG(lower_reg_address);
st->tx[1] = value & 0xFF;
st->tx[2] = ADIS16203_WRITE_REG(lower_reg_address + 1);
st->tx[3] = (value >> 8) & 0xFF;
spi_message_init(&msg);
spi_message_add_tail(&xfers[0], &msg);
spi_message_add_tail(&xfers[1], &msg);
ret = spi_sync(st->us, &msg);
mutex_unlock(&st->buf_lock);
return ret;
}
/**
* adis16203_spi_read_reg_16() - read 2 bytes from a 16-bit register
* @indio_dev: iio device associated with child of actual device
* @reg_address: the address of the lower of the two registers. Second register
* is assumed to have address one greater.
* @val: somewhere to pass back the value read
**/
static int adis16203_spi_read_reg_16(struct iio_dev *indio_dev,
u8 lower_reg_address,
u16 *val)
{
struct spi_message msg;
struct adis16203_state *st = iio_priv(indio_dev);
int ret;
struct spi_transfer xfers[] = {
{
.tx_buf = st->tx,
.bits_per_word = 8,
.len = 2,
.cs_change = 1,
.delay_usecs = 20,
}, {
.rx_buf = st->rx,
.bits_per_word = 8,
.len = 2,
.delay_usecs = 20,
},
};
mutex_lock(&st->buf_lock);
st->tx[0] = ADIS16203_READ_REG(lower_reg_address);
st->tx[1] = 0;
spi_message_init(&msg);
spi_message_add_tail(&xfers[0], &msg);
spi_message_add_tail(&xfers[1], &msg);
ret = spi_sync(st->us, &msg);
if (ret) {
dev_err(&st->us->dev, "problem when reading 16 bit register 0x%02X",
lower_reg_address);
goto error_ret;
}
*val = (st->rx[0] << 8) | st->rx[1];
error_ret:
mutex_unlock(&st->buf_lock);
return ret;
}
static int adis16203_check_status(struct iio_dev *indio_dev)
{
u16 status;
int ret;
ret = adis16203_spi_read_reg_16(indio_dev,
ADIS16203_DIAG_STAT,
&status);
if (ret < 0) {
dev_err(&indio_dev->dev, "Reading status failed\n");
goto error_ret;
}
ret = status & 0x1F;
if (status & ADIS16203_DIAG_STAT_SELFTEST_FAIL)
dev_err(&indio_dev->dev, "Self test failure\n");
if (status & ADIS16203_DIAG_STAT_SPI_FAIL)
dev_err(&indio_dev->dev, "SPI failure\n");
if (status & ADIS16203_DIAG_STAT_FLASH_UPT)
dev_err(&indio_dev->dev, "Flash update failed\n");
if (status & ADIS16203_DIAG_STAT_POWER_HIGH)
dev_err(&indio_dev->dev, "Power supply above 3.625V\n");
if (status & ADIS16203_DIAG_STAT_POWER_LOW)
dev_err(&indio_dev->dev, "Power supply below 3.15V\n");
error_ret:
return ret;
}
static int adis16203_reset(struct iio_dev *indio_dev)
{
int ret;
ret = adis16203_spi_write_reg_8(indio_dev,
ADIS16203_GLOB_CMD,
ADIS16203_GLOB_CMD_SW_RESET);
if (ret)
dev_err(&indio_dev->dev, "problem resetting device");
return ret;
}
static ssize_t adis16203_write_reset(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct iio_dev *indio_dev = dev_get_drvdata(dev);
if (len < 1)
return -EINVAL;
switch (buf[0]) {
case '1':
case 'y':
case 'Y':
return adis16203_reset(indio_dev);
}
return -EINVAL;
}
int adis16203_set_irq(struct iio_dev *indio_dev, bool enable)
{
int ret = 0;
u16 msc;
ret = adis16203_spi_read_reg_16(indio_dev, ADIS16203_MSC_CTRL, &msc);
if (ret)
goto error_ret;
msc |= ADIS16203_MSC_CTRL_ACTIVE_HIGH;
msc &= ~ADIS16203_MSC_CTRL_DATA_RDY_DIO1;
if (enable)
msc |= ADIS16203_MSC_CTRL_DATA_RDY_EN;
else
msc &= ~ADIS16203_MSC_CTRL_DATA_RDY_EN;
ret = adis16203_spi_write_reg_16(indio_dev, ADIS16203_MSC_CTRL, msc);
error_ret:
return ret;
}
static int adis16203_self_test(struct iio_dev *indio_dev)
{
int ret;
ret = adis16203_spi_write_reg_16(indio_dev,
ADIS16203_MSC_CTRL,
ADIS16203_MSC_CTRL_SELF_TEST_EN);
if (ret) {
dev_err(&indio_dev->dev, "problem starting self test");
goto err_ret;
}
adis16203_check_status(indio_dev);
err_ret:
return ret;
}
static int adis16203_initial_setup(struct iio_dev *indio_dev)
{
int ret;
/* Disable IRQ */
ret = adis16203_set_irq(indio_dev, false);
if (ret) {
dev_err(&indio_dev->dev, "disable irq failed");
goto err_ret;
}
/* Do self test */
ret = adis16203_self_test(indio_dev);
if (ret) {
dev_err(&indio_dev->dev, "self test failure");
goto err_ret;
}
/* Read status register to check the result */
ret = adis16203_check_status(indio_dev);
if (ret) {
adis16203_reset(indio_dev);
dev_err(&indio_dev->dev, "device not playing ball -> reset");
msleep(ADIS16203_STARTUP_DELAY);
ret = adis16203_check_status(indio_dev);
if (ret) {
dev_err(&indio_dev->dev, "giving up");
goto err_ret;
}
}
err_ret:
return ret;
}
enum adis16203_chan {
in_supply,
in_aux,
incli_x,
incli_y,
temp,
};
static u8 adis16203_addresses[5][2] = {
[in_supply] = { ADIS16203_SUPPLY_OUT },
[in_aux] = { ADIS16203_AUX_ADC },
[incli_x] = { ADIS16203_XINCL_OUT, ADIS16203_INCL_NULL},
[incli_y] = { ADIS16203_YINCL_OUT },
[temp] = { ADIS16203_TEMP_OUT }
};
static int adis16203_write_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int val,
int val2,
long mask)
{
/* currently only one writable parameter which keeps this simple */
u8 addr = adis16203_addresses[chan->address][1];
return adis16203_spi_write_reg_16(indio_dev, addr, val & 0x3FFF);
}
static int adis16203_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int *val, int *val2,
long mask)
{
int ret;
int bits;
u8 addr;
s16 val16;
switch (mask) {
case 0:
mutex_lock(&indio_dev->mlock);
addr = adis16203_addresses[chan->address][0];
ret = adis16203_spi_read_reg_16(indio_dev, addr, &val16);
if (ret) {
mutex_unlock(&indio_dev->mlock);
return ret;
}
if (val16 & ADIS16203_ERROR_ACTIVE) {
ret = adis16203_check_status(indio_dev);
if (ret) {
mutex_unlock(&indio_dev->mlock);
return ret;
}
}
val16 = val16 & ((1 << chan->scan_type.realbits) - 1);
if (chan->scan_type.sign == 's')
val16 = (s16)(val16 <<
(16 - chan->scan_type.realbits)) >>
(16 - chan->scan_type.realbits);
*val = val16;
mutex_unlock(&indio_dev->mlock);
return IIO_VAL_INT;
case IIO_CHAN_INFO_SCALE:
switch (chan->type) {
case IIO_VOLTAGE:
*val = 0;
if (chan->channel == 0)
*val2 = 1220;
else
*val2 = 610;
return IIO_VAL_INT_PLUS_MICRO;
case IIO_TEMP:
*val = 0;
*val2 = -470000;
return IIO_VAL_INT_PLUS_MICRO;
case IIO_INCLI:
*val = 0;
*val2 = 25000;
return IIO_VAL_INT_PLUS_MICRO;
default:
return -EINVAL;
}
case IIO_CHAN_INFO_OFFSET:
*val = 25;
return IIO_VAL_INT;
case IIO_CHAN_INFO_CALIBBIAS:
bits = 14;
mutex_lock(&indio_dev->mlock);
addr = adis16203_addresses[chan->address][1];
ret = adis16203_spi_read_reg_16(indio_dev, addr, &val16);
if (ret) {
mutex_unlock(&indio_dev->mlock);
return ret;
}
val16 &= (1 << bits) - 1;
val16 = (s16)(val16 << (16 - bits)) >> (16 - bits);
*val = val16;
mutex_unlock(&indio_dev->mlock);
return IIO_VAL_INT;
default:
return -EINVAL;
}
}
static struct iio_chan_spec adis16203_channels[] = {
IIO_CHAN(IIO_VOLTAGE, 0, 1, 0, "supply", 0, 0,
IIO_CHAN_INFO_SCALE_SEPARATE_BIT,
in_supply, ADIS16203_SCAN_SUPPLY,
IIO_ST('u', 12, 16, 0), 0),
IIO_CHAN(IIO_VOLTAGE, 0, 1, 0, NULL, 1, 0,
IIO_CHAN_INFO_SCALE_SEPARATE_BIT,
in_aux, ADIS16203_SCAN_AUX_ADC,
IIO_ST('u', 12, 16, 0), 0),
IIO_CHAN(IIO_INCLI, 1, 0, 0, NULL, 0, IIO_MOD_X,
IIO_CHAN_INFO_SCALE_SHARED_BIT |
IIO_CHAN_INFO_CALIBBIAS_SEPARATE_BIT,
incli_x, ADIS16203_SCAN_INCLI_X,
IIO_ST('s', 14, 16, 0), 0),
/* Fixme: Not what it appears to be - see data sheet */
IIO_CHAN(IIO_INCLI, 1, 0, 0, NULL, 0, IIO_MOD_Y,
IIO_CHAN_INFO_SCALE_SHARED_BIT,
incli_y, ADIS16203_SCAN_INCLI_Y,
IIO_ST('s', 14, 16, 0), 0),
IIO_CHAN(IIO_TEMP, 0, 1, 0, NULL, 0, 0,
IIO_CHAN_INFO_SCALE_SEPARATE_BIT |
IIO_CHAN_INFO_OFFSET_SEPARATE_BIT,
temp, ADIS16203_SCAN_TEMP,
IIO_ST('u', 12, 16, 0), 0),
IIO_CHAN_SOFT_TIMESTAMP(5),
};
static IIO_DEVICE_ATTR(reset, S_IWUSR, NULL, adis16203_write_reset, 0);
static struct attribute *adis16203_attributes[] = {
&iio_dev_attr_reset.dev_attr.attr,
NULL
};
static const struct attribute_group adis16203_attribute_group = {
.attrs = adis16203_attributes,
};
static const struct iio_info adis16203_info = {
.attrs = &adis16203_attribute_group,
.read_raw = &adis16203_read_raw,
.write_raw = &adis16203_write_raw,
.driver_module = THIS_MODULE,
};
static int __devinit adis16203_probe(struct spi_device *spi)
{
int ret;
struct iio_dev *indio_dev;
struct adis16203_state *st;
/* setup the industrialio driver allocated elements */
indio_dev = iio_allocate_device(sizeof(*st));
if (indio_dev == NULL) {
ret = -ENOMEM;
goto error_ret;
}
st = iio_priv(indio_dev);
/* this is only used for removal purposes */
spi_set_drvdata(spi, indio_dev);
st->us = spi;
mutex_init(&st->buf_lock);
indio_dev->name = spi->dev.driver->name;
indio_dev->dev.parent = &spi->dev;
indio_dev->channels = adis16203_channels;
indio_dev->num_channels = ARRAY_SIZE(adis16203_channels);
indio_dev->info = &adis16203_info;
indio_dev->modes = INDIO_DIRECT_MODE;
ret = adis16203_configure_ring(indio_dev);
if (ret)
goto error_free_dev;
ret = iio_buffer_register(indio_dev,
adis16203_channels,
ARRAY_SIZE(adis16203_channels));
if (ret) {
printk(KERN_ERR "failed to initialize the ring\n");
goto error_unreg_ring_funcs;
}
if (spi->irq) {
ret = adis16203_probe_trigger(indio_dev);
if (ret)
goto error_uninitialize_ring;
}
/* Get the device into a sane initial state */
ret = adis16203_initial_setup(indio_dev);
if (ret)
goto error_remove_trigger;
ret = iio_device_register(indio_dev);
if (ret)
goto error_remove_trigger;
return 0;
error_remove_trigger:
adis16203_remove_trigger(indio_dev);
error_uninitialize_ring:
iio_buffer_unregister(indio_dev);
error_unreg_ring_funcs:
adis16203_unconfigure_ring(indio_dev);
error_free_dev:
iio_free_device(indio_dev);
error_ret:
return ret;
}
static int adis16203_remove(struct spi_device *spi)
{
struct iio_dev *indio_dev = spi_get_drvdata(spi);
iio_device_unregister(indio_dev);
adis16203_remove_trigger(indio_dev);
iio_buffer_unregister(indio_dev);
adis16203_unconfigure_ring(indio_dev);
iio_free_device(indio_dev);
return 0;
}
static struct spi_driver adis16203_driver = {
.driver = {
.name = "adis16203",
.owner = THIS_MODULE,
},
.probe = adis16203_probe,
.remove = __devexit_p(adis16203_remove),
};
module_spi_driver(adis16203_driver);
MODULE_AUTHOR("Barry Song <21cnbao@gmail.com>");
MODULE_DESCRIPTION("Analog Devices ADIS16203 Programmable Digital Vibration Sensor driver");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("spi:adis16203");
| gpl-2.0 |
couga6442/kernel_samsung_toroplus | drivers/net/wireless/wl1251/ps.c | 8292 | 4284 | /*
* This file is part of wl1251
*
* Copyright (C) 2008 Nokia Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "reg.h"
#include "ps.h"
#include "cmd.h"
#include "io.h"
/* in ms */
#define WL1251_WAKEUP_TIMEOUT 100
void wl1251_elp_work(struct work_struct *work)
{
struct delayed_work *dwork;
struct wl1251 *wl;
dwork = container_of(work, struct delayed_work, work);
wl = container_of(dwork, struct wl1251, elp_work);
wl1251_debug(DEBUG_PSM, "elp work");
mutex_lock(&wl->mutex);
if (wl->elp || wl->station_mode == STATION_ACTIVE_MODE)
goto out;
wl1251_debug(DEBUG_PSM, "chip to elp");
wl1251_write_elp(wl, HW_ACCESS_ELP_CTRL_REG_ADDR, ELPCTRL_SLEEP);
wl->elp = true;
out:
mutex_unlock(&wl->mutex);
}
#define ELP_ENTRY_DELAY 5
/* Routines to toggle sleep mode while in ELP */
void wl1251_ps_elp_sleep(struct wl1251 *wl)
{
unsigned long delay;
if (wl->station_mode != STATION_ACTIVE_MODE) {
delay = msecs_to_jiffies(ELP_ENTRY_DELAY);
ieee80211_queue_delayed_work(wl->hw, &wl->elp_work, delay);
}
}
int wl1251_ps_elp_wakeup(struct wl1251 *wl)
{
unsigned long timeout, start;
u32 elp_reg;
if (delayed_work_pending(&wl->elp_work))
cancel_delayed_work(&wl->elp_work);
if (!wl->elp)
return 0;
wl1251_debug(DEBUG_PSM, "waking up chip from elp");
start = jiffies;
timeout = jiffies + msecs_to_jiffies(WL1251_WAKEUP_TIMEOUT);
wl1251_write_elp(wl, HW_ACCESS_ELP_CTRL_REG_ADDR, ELPCTRL_WAKE_UP);
elp_reg = wl1251_read_elp(wl, HW_ACCESS_ELP_CTRL_REG_ADDR);
/*
* FIXME: we should wait for irq from chip but, as a temporary
* solution to simplify locking, let's poll instead
*/
while (!(elp_reg & ELPCTRL_WLAN_READY)) {
if (time_after(jiffies, timeout)) {
wl1251_error("elp wakeup timeout");
return -ETIMEDOUT;
}
msleep(1);
elp_reg = wl1251_read_elp(wl, HW_ACCESS_ELP_CTRL_REG_ADDR);
}
wl1251_debug(DEBUG_PSM, "wakeup time: %u ms",
jiffies_to_msecs(jiffies - start));
wl->elp = false;
return 0;
}
int wl1251_ps_set_mode(struct wl1251 *wl, enum wl1251_station_mode mode)
{
int ret;
switch (mode) {
case STATION_POWER_SAVE_MODE:
wl1251_debug(DEBUG_PSM, "entering psm");
/* enable beacon filtering */
ret = wl1251_acx_beacon_filter_opt(wl, true);
if (ret < 0)
return ret;
ret = wl1251_acx_wake_up_conditions(wl,
WAKE_UP_EVENT_DTIM_BITMAP,
wl->listen_int);
if (ret < 0)
return ret;
ret = wl1251_acx_bet_enable(wl, WL1251_ACX_BET_ENABLE,
WL1251_DEFAULT_BET_CONSECUTIVE);
if (ret < 0)
return ret;
ret = wl1251_cmd_ps_mode(wl, CHIP_POWER_SAVE_MODE);
if (ret < 0)
return ret;
ret = wl1251_acx_sleep_auth(wl, WL1251_PSM_ELP);
if (ret < 0)
return ret;
break;
case STATION_IDLE:
wl1251_debug(DEBUG_PSM, "entering idle");
ret = wl1251_acx_sleep_auth(wl, WL1251_PSM_ELP);
if (ret < 0)
return ret;
ret = wl1251_cmd_template_set(wl, CMD_DISCONNECT, NULL, 0);
if (ret < 0)
return ret;
break;
case STATION_ACTIVE_MODE:
default:
wl1251_debug(DEBUG_PSM, "leaving psm");
ret = wl1251_acx_sleep_auth(wl, WL1251_PSM_CAM);
if (ret < 0)
return ret;
/* disable BET */
ret = wl1251_acx_bet_enable(wl, WL1251_ACX_BET_DISABLE,
WL1251_DEFAULT_BET_CONSECUTIVE);
if (ret < 0)
return ret;
/* disable beacon filtering */
ret = wl1251_acx_beacon_filter_opt(wl, false);
if (ret < 0)
return ret;
ret = wl1251_acx_wake_up_conditions(wl,
WAKE_UP_EVENT_DTIM_BITMAP,
wl->listen_int);
if (ret < 0)
return ret;
ret = wl1251_cmd_ps_mode(wl, CHIP_ACTIVE_MODE);
if (ret < 0)
return ret;
break;
}
wl->station_mode = mode;
return ret;
}
| gpl-2.0 |
qriozum/kernel | arch/mips/kernel/cpufreq/loongson2_cpufreq.c | 8292 | 5399 | /*
* Cpufreq driver for the loongson-2 processors
*
* The 2E revision of loongson processor not support this feature.
*
* Copyright (C) 2006 - 2008 Lemote Inc. & Insititute of Computing Technology
* Author: Yanhua, yanh@lemote.com
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/cpufreq.h>
#include <linux/module.h>
#include <linux/err.h>
#include <linux/sched.h> /* set_cpus_allowed() */
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <asm/clock.h>
#include <loongson.h>
static uint nowait;
static struct clk *cpuclk;
static void (*saved_cpu_wait) (void);
static int loongson2_cpu_freq_notifier(struct notifier_block *nb,
unsigned long val, void *data);
static struct notifier_block loongson2_cpufreq_notifier_block = {
.notifier_call = loongson2_cpu_freq_notifier
};
static int loongson2_cpu_freq_notifier(struct notifier_block *nb,
unsigned long val, void *data)
{
if (val == CPUFREQ_POSTCHANGE)
current_cpu_data.udelay_val = loops_per_jiffy;
return 0;
}
static unsigned int loongson2_cpufreq_get(unsigned int cpu)
{
return clk_get_rate(cpuclk);
}
/*
* Here we notify other drivers of the proposed change and the final change.
*/
static int loongson2_cpufreq_target(struct cpufreq_policy *policy,
unsigned int target_freq,
unsigned int relation)
{
unsigned int cpu = policy->cpu;
unsigned int newstate = 0;
cpumask_t cpus_allowed;
struct cpufreq_freqs freqs;
unsigned int freq;
if (!cpu_online(cpu))
return -ENODEV;
cpus_allowed = current->cpus_allowed;
set_cpus_allowed_ptr(current, cpumask_of(cpu));
if (cpufreq_frequency_table_target
(policy, &loongson2_clockmod_table[0], target_freq, relation,
&newstate))
return -EINVAL;
freq =
((cpu_clock_freq / 1000) *
loongson2_clockmod_table[newstate].index) / 8;
if (freq < policy->min || freq > policy->max)
return -EINVAL;
pr_debug("cpufreq: requested frequency %u Hz\n", target_freq * 1000);
freqs.cpu = cpu;
freqs.old = loongson2_cpufreq_get(cpu);
freqs.new = freq;
freqs.flags = 0;
if (freqs.new == freqs.old)
return 0;
/* notifiers */
cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE);
set_cpus_allowed_ptr(current, &cpus_allowed);
/* setting the cpu frequency */
clk_set_rate(cpuclk, freq);
/* notifiers */
cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
pr_debug("cpufreq: set frequency %u kHz\n", freq);
return 0;
}
static int loongson2_cpufreq_cpu_init(struct cpufreq_policy *policy)
{
int i;
if (!cpu_online(policy->cpu))
return -ENODEV;
cpuclk = clk_get(NULL, "cpu_clk");
if (IS_ERR(cpuclk)) {
printk(KERN_ERR "cpufreq: couldn't get CPU clk\n");
return PTR_ERR(cpuclk);
}
cpuclk->rate = cpu_clock_freq / 1000;
if (!cpuclk->rate)
return -EINVAL;
/* clock table init */
for (i = 2;
(loongson2_clockmod_table[i].frequency != CPUFREQ_TABLE_END);
i++)
loongson2_clockmod_table[i].frequency = (cpuclk->rate * i) / 8;
policy->cur = loongson2_cpufreq_get(policy->cpu);
cpufreq_frequency_table_get_attr(&loongson2_clockmod_table[0],
policy->cpu);
return cpufreq_frequency_table_cpuinfo(policy,
&loongson2_clockmod_table[0]);
}
static int loongson2_cpufreq_verify(struct cpufreq_policy *policy)
{
return cpufreq_frequency_table_verify(policy,
&loongson2_clockmod_table[0]);
}
static int loongson2_cpufreq_exit(struct cpufreq_policy *policy)
{
clk_put(cpuclk);
return 0;
}
static struct freq_attr *loongson2_table_attr[] = {
&cpufreq_freq_attr_scaling_available_freqs,
NULL,
};
static struct cpufreq_driver loongson2_cpufreq_driver = {
.owner = THIS_MODULE,
.name = "loongson2",
.init = loongson2_cpufreq_cpu_init,
.verify = loongson2_cpufreq_verify,
.target = loongson2_cpufreq_target,
.get = loongson2_cpufreq_get,
.exit = loongson2_cpufreq_exit,
.attr = loongson2_table_attr,
};
static struct platform_device_id platform_device_ids[] = {
{
.name = "loongson2_cpufreq",
},
{}
};
MODULE_DEVICE_TABLE(platform, platform_device_ids);
static struct platform_driver platform_driver = {
.driver = {
.name = "loongson2_cpufreq",
.owner = THIS_MODULE,
},
.id_table = platform_device_ids,
};
static int __init cpufreq_init(void)
{
int ret;
/* Register platform stuff */
ret = platform_driver_register(&platform_driver);
if (ret)
return ret;
pr_info("cpufreq: Loongson-2F CPU frequency driver.\n");
cpufreq_register_notifier(&loongson2_cpufreq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
ret = cpufreq_register_driver(&loongson2_cpufreq_driver);
if (!ret && !nowait) {
saved_cpu_wait = cpu_wait;
cpu_wait = loongson2_cpu_wait;
}
return ret;
}
static void __exit cpufreq_exit(void)
{
if (!nowait && saved_cpu_wait)
cpu_wait = saved_cpu_wait;
cpufreq_unregister_driver(&loongson2_cpufreq_driver);
cpufreq_unregister_notifier(&loongson2_cpufreq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
platform_driver_unregister(&platform_driver);
}
module_init(cpufreq_init);
module_exit(cpufreq_exit);
module_param(nowait, uint, 0644);
MODULE_PARM_DESC(nowait, "Disable Loongson-2F specific wait");
MODULE_AUTHOR("Yanhua <yanh@lemote.com>");
MODULE_DESCRIPTION("cpufreq driver for Loongson2F");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ravendra275/sony_kernel_msm8960t | arch/mips/kernel/cpufreq/loongson2_cpufreq.c | 8292 | 5399 | /*
* Cpufreq driver for the loongson-2 processors
*
* The 2E revision of loongson processor not support this feature.
*
* Copyright (C) 2006 - 2008 Lemote Inc. & Insititute of Computing Technology
* Author: Yanhua, yanh@lemote.com
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/cpufreq.h>
#include <linux/module.h>
#include <linux/err.h>
#include <linux/sched.h> /* set_cpus_allowed() */
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <asm/clock.h>
#include <loongson.h>
static uint nowait;
static struct clk *cpuclk;
static void (*saved_cpu_wait) (void);
static int loongson2_cpu_freq_notifier(struct notifier_block *nb,
unsigned long val, void *data);
static struct notifier_block loongson2_cpufreq_notifier_block = {
.notifier_call = loongson2_cpu_freq_notifier
};
static int loongson2_cpu_freq_notifier(struct notifier_block *nb,
unsigned long val, void *data)
{
if (val == CPUFREQ_POSTCHANGE)
current_cpu_data.udelay_val = loops_per_jiffy;
return 0;
}
static unsigned int loongson2_cpufreq_get(unsigned int cpu)
{
return clk_get_rate(cpuclk);
}
/*
* Here we notify other drivers of the proposed change and the final change.
*/
static int loongson2_cpufreq_target(struct cpufreq_policy *policy,
unsigned int target_freq,
unsigned int relation)
{
unsigned int cpu = policy->cpu;
unsigned int newstate = 0;
cpumask_t cpus_allowed;
struct cpufreq_freqs freqs;
unsigned int freq;
if (!cpu_online(cpu))
return -ENODEV;
cpus_allowed = current->cpus_allowed;
set_cpus_allowed_ptr(current, cpumask_of(cpu));
if (cpufreq_frequency_table_target
(policy, &loongson2_clockmod_table[0], target_freq, relation,
&newstate))
return -EINVAL;
freq =
((cpu_clock_freq / 1000) *
loongson2_clockmod_table[newstate].index) / 8;
if (freq < policy->min || freq > policy->max)
return -EINVAL;
pr_debug("cpufreq: requested frequency %u Hz\n", target_freq * 1000);
freqs.cpu = cpu;
freqs.old = loongson2_cpufreq_get(cpu);
freqs.new = freq;
freqs.flags = 0;
if (freqs.new == freqs.old)
return 0;
/* notifiers */
cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE);
set_cpus_allowed_ptr(current, &cpus_allowed);
/* setting the cpu frequency */
clk_set_rate(cpuclk, freq);
/* notifiers */
cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
pr_debug("cpufreq: set frequency %u kHz\n", freq);
return 0;
}
static int loongson2_cpufreq_cpu_init(struct cpufreq_policy *policy)
{
int i;
if (!cpu_online(policy->cpu))
return -ENODEV;
cpuclk = clk_get(NULL, "cpu_clk");
if (IS_ERR(cpuclk)) {
printk(KERN_ERR "cpufreq: couldn't get CPU clk\n");
return PTR_ERR(cpuclk);
}
cpuclk->rate = cpu_clock_freq / 1000;
if (!cpuclk->rate)
return -EINVAL;
/* clock table init */
for (i = 2;
(loongson2_clockmod_table[i].frequency != CPUFREQ_TABLE_END);
i++)
loongson2_clockmod_table[i].frequency = (cpuclk->rate * i) / 8;
policy->cur = loongson2_cpufreq_get(policy->cpu);
cpufreq_frequency_table_get_attr(&loongson2_clockmod_table[0],
policy->cpu);
return cpufreq_frequency_table_cpuinfo(policy,
&loongson2_clockmod_table[0]);
}
static int loongson2_cpufreq_verify(struct cpufreq_policy *policy)
{
return cpufreq_frequency_table_verify(policy,
&loongson2_clockmod_table[0]);
}
static int loongson2_cpufreq_exit(struct cpufreq_policy *policy)
{
clk_put(cpuclk);
return 0;
}
static struct freq_attr *loongson2_table_attr[] = {
&cpufreq_freq_attr_scaling_available_freqs,
NULL,
};
static struct cpufreq_driver loongson2_cpufreq_driver = {
.owner = THIS_MODULE,
.name = "loongson2",
.init = loongson2_cpufreq_cpu_init,
.verify = loongson2_cpufreq_verify,
.target = loongson2_cpufreq_target,
.get = loongson2_cpufreq_get,
.exit = loongson2_cpufreq_exit,
.attr = loongson2_table_attr,
};
static struct platform_device_id platform_device_ids[] = {
{
.name = "loongson2_cpufreq",
},
{}
};
MODULE_DEVICE_TABLE(platform, platform_device_ids);
static struct platform_driver platform_driver = {
.driver = {
.name = "loongson2_cpufreq",
.owner = THIS_MODULE,
},
.id_table = platform_device_ids,
};
static int __init cpufreq_init(void)
{
int ret;
/* Register platform stuff */
ret = platform_driver_register(&platform_driver);
if (ret)
return ret;
pr_info("cpufreq: Loongson-2F CPU frequency driver.\n");
cpufreq_register_notifier(&loongson2_cpufreq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
ret = cpufreq_register_driver(&loongson2_cpufreq_driver);
if (!ret && !nowait) {
saved_cpu_wait = cpu_wait;
cpu_wait = loongson2_cpu_wait;
}
return ret;
}
static void __exit cpufreq_exit(void)
{
if (!nowait && saved_cpu_wait)
cpu_wait = saved_cpu_wait;
cpufreq_unregister_driver(&loongson2_cpufreq_driver);
cpufreq_unregister_notifier(&loongson2_cpufreq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
platform_driver_unregister(&platform_driver);
}
module_init(cpufreq_init);
module_exit(cpufreq_exit);
module_param(nowait, uint, 0644);
MODULE_PARM_DESC(nowait, "Disable Loongson-2F specific wait");
MODULE_AUTHOR("Yanhua <yanh@lemote.com>");
MODULE_DESCRIPTION("cpufreq driver for Loongson2F");
MODULE_LICENSE("GPL");
| gpl-2.0 |
xobs/novena-linux | drivers/net/wireless/ath/ath10k/pci.c | 101 | 80997 | /*
* Copyright (c) 2005-2011 Atheros Communications Inc.
* Copyright (c) 2011-2013 Qualcomm Atheros, 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/pci.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/bitops.h>
#include "core.h"
#include "debug.h"
#include "targaddrs.h"
#include "bmi.h"
#include "hif.h"
#include "htc.h"
#include "ce.h"
#include "pci.h"
enum ath10k_pci_irq_mode {
ATH10K_PCI_IRQ_AUTO = 0,
ATH10K_PCI_IRQ_LEGACY = 1,
ATH10K_PCI_IRQ_MSI = 2,
};
enum ath10k_pci_reset_mode {
ATH10K_PCI_RESET_AUTO = 0,
ATH10K_PCI_RESET_WARM_ONLY = 1,
};
static unsigned int ath10k_pci_irq_mode = ATH10K_PCI_IRQ_AUTO;
static unsigned int ath10k_pci_reset_mode = ATH10K_PCI_RESET_AUTO;
module_param_named(irq_mode, ath10k_pci_irq_mode, uint, 0644);
MODULE_PARM_DESC(irq_mode, "0: auto, 1: legacy, 2: msi (default: 0)");
module_param_named(reset_mode, ath10k_pci_reset_mode, uint, 0644);
MODULE_PARM_DESC(reset_mode, "0: auto, 1: warm only (default: 0)");
/* how long wait to wait for target to initialise, in ms */
#define ATH10K_PCI_TARGET_WAIT 3000
#define ATH10K_PCI_NUM_WARM_RESET_ATTEMPTS 3
static const struct pci_device_id ath10k_pci_id_table[] = {
{ PCI_VDEVICE(ATHEROS, QCA988X_2_0_DEVICE_ID) }, /* PCI-E QCA988X V2 */
{ PCI_VDEVICE(ATHEROS, QCA6164_2_1_DEVICE_ID) }, /* PCI-E QCA6164 V2.1 */
{ PCI_VDEVICE(ATHEROS, QCA6174_2_1_DEVICE_ID) }, /* PCI-E QCA6174 V2.1 */
{ PCI_VDEVICE(ATHEROS, QCA99X0_2_0_DEVICE_ID) }, /* PCI-E QCA99X0 V2 */
{ PCI_VDEVICE(ATHEROS, QCA9377_1_0_DEVICE_ID) }, /* PCI-E QCA9377 V1 */
{0}
};
static const struct ath10k_pci_supp_chip ath10k_pci_supp_chips[] = {
/* QCA988X pre 2.0 chips are not supported because they need some nasty
* hacks. ath10k doesn't have them and these devices crash horribly
* because of that.
*/
{ QCA988X_2_0_DEVICE_ID, QCA988X_HW_2_0_CHIP_ID_REV },
{ QCA6164_2_1_DEVICE_ID, QCA6174_HW_2_1_CHIP_ID_REV },
{ QCA6164_2_1_DEVICE_ID, QCA6174_HW_2_2_CHIP_ID_REV },
{ QCA6164_2_1_DEVICE_ID, QCA6174_HW_3_0_CHIP_ID_REV },
{ QCA6164_2_1_DEVICE_ID, QCA6174_HW_3_1_CHIP_ID_REV },
{ QCA6164_2_1_DEVICE_ID, QCA6174_HW_3_2_CHIP_ID_REV },
{ QCA6174_2_1_DEVICE_ID, QCA6174_HW_2_1_CHIP_ID_REV },
{ QCA6174_2_1_DEVICE_ID, QCA6174_HW_2_2_CHIP_ID_REV },
{ QCA6174_2_1_DEVICE_ID, QCA6174_HW_3_0_CHIP_ID_REV },
{ QCA6174_2_1_DEVICE_ID, QCA6174_HW_3_1_CHIP_ID_REV },
{ QCA6174_2_1_DEVICE_ID, QCA6174_HW_3_2_CHIP_ID_REV },
{ QCA99X0_2_0_DEVICE_ID, QCA99X0_HW_2_0_CHIP_ID_REV },
{ QCA9377_1_0_DEVICE_ID, QCA9377_HW_1_0_CHIP_ID_REV },
{ QCA9377_1_0_DEVICE_ID, QCA9377_HW_1_1_CHIP_ID_REV },
};
static void ath10k_pci_buffer_cleanup(struct ath10k *ar);
static int ath10k_pci_cold_reset(struct ath10k *ar);
static int ath10k_pci_safe_chip_reset(struct ath10k *ar);
static int ath10k_pci_wait_for_target_init(struct ath10k *ar);
static int ath10k_pci_init_irq(struct ath10k *ar);
static int ath10k_pci_deinit_irq(struct ath10k *ar);
static int ath10k_pci_request_irq(struct ath10k *ar);
static void ath10k_pci_free_irq(struct ath10k *ar);
static int ath10k_pci_bmi_wait(struct ath10k_ce_pipe *tx_pipe,
struct ath10k_ce_pipe *rx_pipe,
struct bmi_xfer *xfer);
static int ath10k_pci_qca99x0_chip_reset(struct ath10k *ar);
static void ath10k_pci_htc_tx_cb(struct ath10k_ce_pipe *ce_state);
static void ath10k_pci_htc_rx_cb(struct ath10k_ce_pipe *ce_state);
static void ath10k_pci_htt_tx_cb(struct ath10k_ce_pipe *ce_state);
static void ath10k_pci_htt_rx_cb(struct ath10k_ce_pipe *ce_state);
static void ath10k_pci_htt_htc_rx_cb(struct ath10k_ce_pipe *ce_state);
static struct ce_attr host_ce_config_wlan[] = {
/* CE0: host->target HTC control and raw streams */
{
.flags = CE_ATTR_FLAGS,
.src_nentries = 16,
.src_sz_max = 256,
.dest_nentries = 0,
.send_cb = ath10k_pci_htc_tx_cb,
},
/* CE1: target->host HTT + HTC control */
{
.flags = CE_ATTR_FLAGS,
.src_nentries = 0,
.src_sz_max = 2048,
.dest_nentries = 512,
.recv_cb = ath10k_pci_htt_htc_rx_cb,
},
/* CE2: target->host WMI */
{
.flags = CE_ATTR_FLAGS,
.src_nentries = 0,
.src_sz_max = 2048,
.dest_nentries = 128,
.recv_cb = ath10k_pci_htc_rx_cb,
},
/* CE3: host->target WMI */
{
.flags = CE_ATTR_FLAGS,
.src_nentries = 32,
.src_sz_max = 2048,
.dest_nentries = 0,
.send_cb = ath10k_pci_htc_tx_cb,
},
/* CE4: host->target HTT */
{
.flags = CE_ATTR_FLAGS | CE_ATTR_DIS_INTR,
.src_nentries = CE_HTT_H2T_MSG_SRC_NENTRIES,
.src_sz_max = 256,
.dest_nentries = 0,
.send_cb = ath10k_pci_htt_tx_cb,
},
/* CE5: target->host HTT (HIF->HTT) */
{
.flags = CE_ATTR_FLAGS,
.src_nentries = 0,
.src_sz_max = 512,
.dest_nentries = 512,
.recv_cb = ath10k_pci_htt_rx_cb,
},
/* CE6: target autonomous hif_memcpy */
{
.flags = CE_ATTR_FLAGS,
.src_nentries = 0,
.src_sz_max = 0,
.dest_nentries = 0,
},
/* CE7: ce_diag, the Diagnostic Window */
{
.flags = CE_ATTR_FLAGS,
.src_nentries = 2,
.src_sz_max = DIAG_TRANSFER_LIMIT,
.dest_nentries = 2,
},
/* CE8: target->host pktlog */
{
.flags = CE_ATTR_FLAGS,
.src_nentries = 0,
.src_sz_max = 2048,
.dest_nentries = 128,
},
/* CE9 target autonomous qcache memcpy */
{
.flags = CE_ATTR_FLAGS,
.src_nentries = 0,
.src_sz_max = 0,
.dest_nentries = 0,
},
/* CE10: target autonomous hif memcpy */
{
.flags = CE_ATTR_FLAGS,
.src_nentries = 0,
.src_sz_max = 0,
.dest_nentries = 0,
},
/* CE11: target autonomous hif memcpy */
{
.flags = CE_ATTR_FLAGS,
.src_nentries = 0,
.src_sz_max = 0,
.dest_nentries = 0,
},
};
/* Target firmware's Copy Engine configuration. */
static struct ce_pipe_config target_ce_config_wlan[] = {
/* CE0: host->target HTC control and raw streams */
{
.pipenum = __cpu_to_le32(0),
.pipedir = __cpu_to_le32(PIPEDIR_OUT),
.nentries = __cpu_to_le32(32),
.nbytes_max = __cpu_to_le32(256),
.flags = __cpu_to_le32(CE_ATTR_FLAGS),
.reserved = __cpu_to_le32(0),
},
/* CE1: target->host HTT + HTC control */
{
.pipenum = __cpu_to_le32(1),
.pipedir = __cpu_to_le32(PIPEDIR_IN),
.nentries = __cpu_to_le32(32),
.nbytes_max = __cpu_to_le32(2048),
.flags = __cpu_to_le32(CE_ATTR_FLAGS),
.reserved = __cpu_to_le32(0),
},
/* CE2: target->host WMI */
{
.pipenum = __cpu_to_le32(2),
.pipedir = __cpu_to_le32(PIPEDIR_IN),
.nentries = __cpu_to_le32(64),
.nbytes_max = __cpu_to_le32(2048),
.flags = __cpu_to_le32(CE_ATTR_FLAGS),
.reserved = __cpu_to_le32(0),
},
/* CE3: host->target WMI */
{
.pipenum = __cpu_to_le32(3),
.pipedir = __cpu_to_le32(PIPEDIR_OUT),
.nentries = __cpu_to_le32(32),
.nbytes_max = __cpu_to_le32(2048),
.flags = __cpu_to_le32(CE_ATTR_FLAGS),
.reserved = __cpu_to_le32(0),
},
/* CE4: host->target HTT */
{
.pipenum = __cpu_to_le32(4),
.pipedir = __cpu_to_le32(PIPEDIR_OUT),
.nentries = __cpu_to_le32(256),
.nbytes_max = __cpu_to_le32(256),
.flags = __cpu_to_le32(CE_ATTR_FLAGS),
.reserved = __cpu_to_le32(0),
},
/* NB: 50% of src nentries, since tx has 2 frags */
/* CE5: target->host HTT (HIF->HTT) */
{
.pipenum = __cpu_to_le32(5),
.pipedir = __cpu_to_le32(PIPEDIR_IN),
.nentries = __cpu_to_le32(32),
.nbytes_max = __cpu_to_le32(512),
.flags = __cpu_to_le32(CE_ATTR_FLAGS),
.reserved = __cpu_to_le32(0),
},
/* CE6: Reserved for target autonomous hif_memcpy */
{
.pipenum = __cpu_to_le32(6),
.pipedir = __cpu_to_le32(PIPEDIR_INOUT),
.nentries = __cpu_to_le32(32),
.nbytes_max = __cpu_to_le32(4096),
.flags = __cpu_to_le32(CE_ATTR_FLAGS),
.reserved = __cpu_to_le32(0),
},
/* CE7 used only by Host */
{
.pipenum = __cpu_to_le32(7),
.pipedir = __cpu_to_le32(PIPEDIR_INOUT),
.nentries = __cpu_to_le32(0),
.nbytes_max = __cpu_to_le32(0),
.flags = __cpu_to_le32(0),
.reserved = __cpu_to_le32(0),
},
/* CE8 target->host packtlog */
{
.pipenum = __cpu_to_le32(8),
.pipedir = __cpu_to_le32(PIPEDIR_IN),
.nentries = __cpu_to_le32(64),
.nbytes_max = __cpu_to_le32(2048),
.flags = __cpu_to_le32(CE_ATTR_FLAGS | CE_ATTR_DIS_INTR),
.reserved = __cpu_to_le32(0),
},
/* CE9 target autonomous qcache memcpy */
{
.pipenum = __cpu_to_le32(9),
.pipedir = __cpu_to_le32(PIPEDIR_INOUT),
.nentries = __cpu_to_le32(32),
.nbytes_max = __cpu_to_le32(2048),
.flags = __cpu_to_le32(CE_ATTR_FLAGS | CE_ATTR_DIS_INTR),
.reserved = __cpu_to_le32(0),
},
/* It not necessary to send target wlan configuration for CE10 & CE11
* as these CEs are not actively used in target.
*/
};
/*
* Map from service/endpoint to Copy Engine.
* This table is derived from the CE_PCI TABLE, above.
* It is passed to the Target at startup for use by firmware.
*/
static struct service_to_pipe target_service_to_ce_map_wlan[] = {
{
__cpu_to_le32(ATH10K_HTC_SVC_ID_WMI_DATA_VO),
__cpu_to_le32(PIPEDIR_OUT), /* out = UL = host -> target */
__cpu_to_le32(3),
},
{
__cpu_to_le32(ATH10K_HTC_SVC_ID_WMI_DATA_VO),
__cpu_to_le32(PIPEDIR_IN), /* in = DL = target -> host */
__cpu_to_le32(2),
},
{
__cpu_to_le32(ATH10K_HTC_SVC_ID_WMI_DATA_BK),
__cpu_to_le32(PIPEDIR_OUT), /* out = UL = host -> target */
__cpu_to_le32(3),
},
{
__cpu_to_le32(ATH10K_HTC_SVC_ID_WMI_DATA_BK),
__cpu_to_le32(PIPEDIR_IN), /* in = DL = target -> host */
__cpu_to_le32(2),
},
{
__cpu_to_le32(ATH10K_HTC_SVC_ID_WMI_DATA_BE),
__cpu_to_le32(PIPEDIR_OUT), /* out = UL = host -> target */
__cpu_to_le32(3),
},
{
__cpu_to_le32(ATH10K_HTC_SVC_ID_WMI_DATA_BE),
__cpu_to_le32(PIPEDIR_IN), /* in = DL = target -> host */
__cpu_to_le32(2),
},
{
__cpu_to_le32(ATH10K_HTC_SVC_ID_WMI_DATA_VI),
__cpu_to_le32(PIPEDIR_OUT), /* out = UL = host -> target */
__cpu_to_le32(3),
},
{
__cpu_to_le32(ATH10K_HTC_SVC_ID_WMI_DATA_VI),
__cpu_to_le32(PIPEDIR_IN), /* in = DL = target -> host */
__cpu_to_le32(2),
},
{
__cpu_to_le32(ATH10K_HTC_SVC_ID_WMI_CONTROL),
__cpu_to_le32(PIPEDIR_OUT), /* out = UL = host -> target */
__cpu_to_le32(3),
},
{
__cpu_to_le32(ATH10K_HTC_SVC_ID_WMI_CONTROL),
__cpu_to_le32(PIPEDIR_IN), /* in = DL = target -> host */
__cpu_to_le32(2),
},
{
__cpu_to_le32(ATH10K_HTC_SVC_ID_RSVD_CTRL),
__cpu_to_le32(PIPEDIR_OUT), /* out = UL = host -> target */
__cpu_to_le32(0),
},
{
__cpu_to_le32(ATH10K_HTC_SVC_ID_RSVD_CTRL),
__cpu_to_le32(PIPEDIR_IN), /* in = DL = target -> host */
__cpu_to_le32(1),
},
{ /* not used */
__cpu_to_le32(ATH10K_HTC_SVC_ID_TEST_RAW_STREAMS),
__cpu_to_le32(PIPEDIR_OUT), /* out = UL = host -> target */
__cpu_to_le32(0),
},
{ /* not used */
__cpu_to_le32(ATH10K_HTC_SVC_ID_TEST_RAW_STREAMS),
__cpu_to_le32(PIPEDIR_IN), /* in = DL = target -> host */
__cpu_to_le32(1),
},
{
__cpu_to_le32(ATH10K_HTC_SVC_ID_HTT_DATA_MSG),
__cpu_to_le32(PIPEDIR_OUT), /* out = UL = host -> target */
__cpu_to_le32(4),
},
{
__cpu_to_le32(ATH10K_HTC_SVC_ID_HTT_DATA_MSG),
__cpu_to_le32(PIPEDIR_IN), /* in = DL = target -> host */
__cpu_to_le32(5),
},
/* (Additions here) */
{ /* must be last */
__cpu_to_le32(0),
__cpu_to_le32(0),
__cpu_to_le32(0),
},
};
static bool ath10k_pci_is_awake(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
u32 val = ioread32(ar_pci->mem + PCIE_LOCAL_BASE_ADDRESS +
RTC_STATE_ADDRESS);
return RTC_STATE_V_GET(val) == RTC_STATE_V_ON;
}
static void __ath10k_pci_wake(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
lockdep_assert_held(&ar_pci->ps_lock);
ath10k_dbg(ar, ATH10K_DBG_PCI_PS, "pci ps wake reg refcount %lu awake %d\n",
ar_pci->ps_wake_refcount, ar_pci->ps_awake);
iowrite32(PCIE_SOC_WAKE_V_MASK,
ar_pci->mem + PCIE_LOCAL_BASE_ADDRESS +
PCIE_SOC_WAKE_ADDRESS);
}
static void __ath10k_pci_sleep(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
lockdep_assert_held(&ar_pci->ps_lock);
ath10k_dbg(ar, ATH10K_DBG_PCI_PS, "pci ps sleep reg refcount %lu awake %d\n",
ar_pci->ps_wake_refcount, ar_pci->ps_awake);
iowrite32(PCIE_SOC_WAKE_RESET,
ar_pci->mem + PCIE_LOCAL_BASE_ADDRESS +
PCIE_SOC_WAKE_ADDRESS);
ar_pci->ps_awake = false;
}
static int ath10k_pci_wake_wait(struct ath10k *ar)
{
int tot_delay = 0;
int curr_delay = 5;
while (tot_delay < PCIE_WAKE_TIMEOUT) {
if (ath10k_pci_is_awake(ar)) {
if (tot_delay > PCIE_WAKE_LATE_US)
ath10k_warn(ar, "device wakeup took %d ms which is unusally long, otherwise it works normally.\n",
tot_delay / 1000);
return 0;
}
udelay(curr_delay);
tot_delay += curr_delay;
if (curr_delay < 50)
curr_delay += 5;
}
return -ETIMEDOUT;
}
static int ath10k_pci_force_wake(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&ar_pci->ps_lock, flags);
if (!ar_pci->ps_awake) {
iowrite32(PCIE_SOC_WAKE_V_MASK,
ar_pci->mem + PCIE_LOCAL_BASE_ADDRESS +
PCIE_SOC_WAKE_ADDRESS);
ret = ath10k_pci_wake_wait(ar);
if (ret == 0)
ar_pci->ps_awake = true;
}
spin_unlock_irqrestore(&ar_pci->ps_lock, flags);
return ret;
}
static void ath10k_pci_force_sleep(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
unsigned long flags;
spin_lock_irqsave(&ar_pci->ps_lock, flags);
iowrite32(PCIE_SOC_WAKE_RESET,
ar_pci->mem + PCIE_LOCAL_BASE_ADDRESS +
PCIE_SOC_WAKE_ADDRESS);
ar_pci->ps_awake = false;
spin_unlock_irqrestore(&ar_pci->ps_lock, flags);
}
static int ath10k_pci_wake(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
unsigned long flags;
int ret = 0;
if (ar_pci->pci_ps == 0)
return ret;
spin_lock_irqsave(&ar_pci->ps_lock, flags);
ath10k_dbg(ar, ATH10K_DBG_PCI_PS, "pci ps wake refcount %lu awake %d\n",
ar_pci->ps_wake_refcount, ar_pci->ps_awake);
/* This function can be called very frequently. To avoid excessive
* CPU stalls for MMIO reads use a cache var to hold the device state.
*/
if (!ar_pci->ps_awake) {
__ath10k_pci_wake(ar);
ret = ath10k_pci_wake_wait(ar);
if (ret == 0)
ar_pci->ps_awake = true;
}
if (ret == 0) {
ar_pci->ps_wake_refcount++;
WARN_ON(ar_pci->ps_wake_refcount == 0);
}
spin_unlock_irqrestore(&ar_pci->ps_lock, flags);
return ret;
}
static void ath10k_pci_sleep(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
unsigned long flags;
if (ar_pci->pci_ps == 0)
return;
spin_lock_irqsave(&ar_pci->ps_lock, flags);
ath10k_dbg(ar, ATH10K_DBG_PCI_PS, "pci ps sleep refcount %lu awake %d\n",
ar_pci->ps_wake_refcount, ar_pci->ps_awake);
if (WARN_ON(ar_pci->ps_wake_refcount == 0))
goto skip;
ar_pci->ps_wake_refcount--;
mod_timer(&ar_pci->ps_timer, jiffies +
msecs_to_jiffies(ATH10K_PCI_SLEEP_GRACE_PERIOD_MSEC));
skip:
spin_unlock_irqrestore(&ar_pci->ps_lock, flags);
}
static void ath10k_pci_ps_timer(unsigned long ptr)
{
struct ath10k *ar = (void *)ptr;
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
unsigned long flags;
spin_lock_irqsave(&ar_pci->ps_lock, flags);
ath10k_dbg(ar, ATH10K_DBG_PCI_PS, "pci ps timer refcount %lu awake %d\n",
ar_pci->ps_wake_refcount, ar_pci->ps_awake);
if (ar_pci->ps_wake_refcount > 0)
goto skip;
__ath10k_pci_sleep(ar);
skip:
spin_unlock_irqrestore(&ar_pci->ps_lock, flags);
}
static void ath10k_pci_sleep_sync(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
unsigned long flags;
if (ar_pci->pci_ps == 0) {
ath10k_pci_force_sleep(ar);
return;
}
del_timer_sync(&ar_pci->ps_timer);
spin_lock_irqsave(&ar_pci->ps_lock, flags);
WARN_ON(ar_pci->ps_wake_refcount > 0);
__ath10k_pci_sleep(ar);
spin_unlock_irqrestore(&ar_pci->ps_lock, flags);
}
void ath10k_pci_write32(struct ath10k *ar, u32 offset, u32 value)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
int ret;
if (unlikely(offset + sizeof(value) > ar_pci->mem_len)) {
ath10k_warn(ar, "refusing to write mmio out of bounds at 0x%08x - 0x%08zx (max 0x%08zx)\n",
offset, offset + sizeof(value), ar_pci->mem_len);
return;
}
ret = ath10k_pci_wake(ar);
if (ret) {
ath10k_warn(ar, "failed to wake target for write32 of 0x%08x at 0x%08x: %d\n",
value, offset, ret);
return;
}
iowrite32(value, ar_pci->mem + offset);
ath10k_pci_sleep(ar);
}
u32 ath10k_pci_read32(struct ath10k *ar, u32 offset)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
u32 val;
int ret;
if (unlikely(offset + sizeof(val) > ar_pci->mem_len)) {
ath10k_warn(ar, "refusing to read mmio out of bounds at 0x%08x - 0x%08zx (max 0x%08zx)\n",
offset, offset + sizeof(val), ar_pci->mem_len);
return 0;
}
ret = ath10k_pci_wake(ar);
if (ret) {
ath10k_warn(ar, "failed to wake target for read32 at 0x%08x: %d\n",
offset, ret);
return 0xffffffff;
}
val = ioread32(ar_pci->mem + offset);
ath10k_pci_sleep(ar);
return val;
}
u32 ath10k_pci_soc_read32(struct ath10k *ar, u32 addr)
{
return ath10k_pci_read32(ar, RTC_SOC_BASE_ADDRESS + addr);
}
void ath10k_pci_soc_write32(struct ath10k *ar, u32 addr, u32 val)
{
ath10k_pci_write32(ar, RTC_SOC_BASE_ADDRESS + addr, val);
}
u32 ath10k_pci_reg_read32(struct ath10k *ar, u32 addr)
{
return ath10k_pci_read32(ar, PCIE_LOCAL_BASE_ADDRESS + addr);
}
void ath10k_pci_reg_write32(struct ath10k *ar, u32 addr, u32 val)
{
ath10k_pci_write32(ar, PCIE_LOCAL_BASE_ADDRESS + addr, val);
}
static bool ath10k_pci_irq_pending(struct ath10k *ar)
{
u32 cause;
/* Check if the shared legacy irq is for us */
cause = ath10k_pci_read32(ar, SOC_CORE_BASE_ADDRESS +
PCIE_INTR_CAUSE_ADDRESS);
if (cause & (PCIE_INTR_FIRMWARE_MASK | PCIE_INTR_CE_MASK_ALL))
return true;
return false;
}
static void ath10k_pci_disable_and_clear_legacy_irq(struct ath10k *ar)
{
/* IMPORTANT: INTR_CLR register has to be set after
* INTR_ENABLE is set to 0, otherwise interrupt can not be
* really cleared. */
ath10k_pci_write32(ar, SOC_CORE_BASE_ADDRESS + PCIE_INTR_ENABLE_ADDRESS,
0);
ath10k_pci_write32(ar, SOC_CORE_BASE_ADDRESS + PCIE_INTR_CLR_ADDRESS,
PCIE_INTR_FIRMWARE_MASK | PCIE_INTR_CE_MASK_ALL);
/* IMPORTANT: this extra read transaction is required to
* flush the posted write buffer. */
(void)ath10k_pci_read32(ar, SOC_CORE_BASE_ADDRESS +
PCIE_INTR_ENABLE_ADDRESS);
}
static void ath10k_pci_enable_legacy_irq(struct ath10k *ar)
{
ath10k_pci_write32(ar, SOC_CORE_BASE_ADDRESS +
PCIE_INTR_ENABLE_ADDRESS,
PCIE_INTR_FIRMWARE_MASK | PCIE_INTR_CE_MASK_ALL);
/* IMPORTANT: this extra read transaction is required to
* flush the posted write buffer. */
(void)ath10k_pci_read32(ar, SOC_CORE_BASE_ADDRESS +
PCIE_INTR_ENABLE_ADDRESS);
}
static inline const char *ath10k_pci_get_irq_method(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
if (ar_pci->num_msi_intrs > 1)
return "msi-x";
if (ar_pci->num_msi_intrs == 1)
return "msi";
return "legacy";
}
static int __ath10k_pci_rx_post_buf(struct ath10k_pci_pipe *pipe)
{
struct ath10k *ar = pipe->hif_ce_state;
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
struct ath10k_ce_pipe *ce_pipe = pipe->ce_hdl;
struct sk_buff *skb;
dma_addr_t paddr;
int ret;
skb = dev_alloc_skb(pipe->buf_sz);
if (!skb)
return -ENOMEM;
WARN_ONCE((unsigned long)skb->data & 3, "unaligned skb");
paddr = dma_map_single(ar->dev, skb->data,
skb->len + skb_tailroom(skb),
DMA_FROM_DEVICE);
if (unlikely(dma_mapping_error(ar->dev, paddr))) {
ath10k_warn(ar, "failed to dma map pci rx buf\n");
dev_kfree_skb_any(skb);
return -EIO;
}
ATH10K_SKB_RXCB(skb)->paddr = paddr;
spin_lock_bh(&ar_pci->ce_lock);
ret = __ath10k_ce_rx_post_buf(ce_pipe, skb, paddr);
spin_unlock_bh(&ar_pci->ce_lock);
if (ret) {
dma_unmap_single(ar->dev, paddr, skb->len + skb_tailroom(skb),
DMA_FROM_DEVICE);
dev_kfree_skb_any(skb);
return ret;
}
return 0;
}
static void ath10k_pci_rx_post_pipe(struct ath10k_pci_pipe *pipe)
{
struct ath10k *ar = pipe->hif_ce_state;
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
struct ath10k_ce_pipe *ce_pipe = pipe->ce_hdl;
int ret, num;
if (pipe->buf_sz == 0)
return;
if (!ce_pipe->dest_ring)
return;
spin_lock_bh(&ar_pci->ce_lock);
num = __ath10k_ce_rx_num_free_bufs(ce_pipe);
spin_unlock_bh(&ar_pci->ce_lock);
while (num--) {
ret = __ath10k_pci_rx_post_buf(pipe);
if (ret) {
if (ret == -ENOSPC)
break;
ath10k_warn(ar, "failed to post pci rx buf: %d\n", ret);
mod_timer(&ar_pci->rx_post_retry, jiffies +
ATH10K_PCI_RX_POST_RETRY_MS);
break;
}
}
}
static void ath10k_pci_rx_post(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
int i;
for (i = 0; i < CE_COUNT; i++)
ath10k_pci_rx_post_pipe(&ar_pci->pipe_info[i]);
}
static void ath10k_pci_rx_replenish_retry(unsigned long ptr)
{
struct ath10k *ar = (void *)ptr;
ath10k_pci_rx_post(ar);
}
static u32 ath10k_pci_targ_cpu_to_ce_addr(struct ath10k *ar, u32 addr)
{
u32 val = 0;
switch (ar->hw_rev) {
case ATH10K_HW_QCA988X:
case ATH10K_HW_QCA6174:
case ATH10K_HW_QCA9377:
val = (ath10k_pci_read32(ar, SOC_CORE_BASE_ADDRESS +
CORE_CTRL_ADDRESS) &
0x7ff) << 21;
break;
case ATH10K_HW_QCA99X0:
val = ath10k_pci_read32(ar, PCIE_BAR_REG_ADDRESS);
break;
}
val |= 0x100000 | (addr & 0xfffff);
return val;
}
/*
* Diagnostic read/write access is provided for startup/config/debug usage.
* Caller must guarantee proper alignment, when applicable, and single user
* at any moment.
*/
static int ath10k_pci_diag_read_mem(struct ath10k *ar, u32 address, void *data,
int nbytes)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
int ret = 0;
u32 buf;
unsigned int completed_nbytes, orig_nbytes, remaining_bytes;
unsigned int id;
unsigned int flags;
struct ath10k_ce_pipe *ce_diag;
/* Host buffer address in CE space */
u32 ce_data;
dma_addr_t ce_data_base = 0;
void *data_buf = NULL;
int i;
spin_lock_bh(&ar_pci->ce_lock);
ce_diag = ar_pci->ce_diag;
/*
* Allocate a temporary bounce buffer to hold caller's data
* to be DMA'ed from Target. This guarantees
* 1) 4-byte alignment
* 2) Buffer in DMA-able space
*/
orig_nbytes = nbytes;
data_buf = (unsigned char *)dma_alloc_coherent(ar->dev,
orig_nbytes,
&ce_data_base,
GFP_ATOMIC);
if (!data_buf) {
ret = -ENOMEM;
goto done;
}
memset(data_buf, 0, orig_nbytes);
remaining_bytes = orig_nbytes;
ce_data = ce_data_base;
while (remaining_bytes) {
nbytes = min_t(unsigned int, remaining_bytes,
DIAG_TRANSFER_LIMIT);
ret = __ath10k_ce_rx_post_buf(ce_diag, NULL, ce_data);
if (ret != 0)
goto done;
/* Request CE to send from Target(!) address to Host buffer */
/*
* The address supplied by the caller is in the
* Target CPU virtual address space.
*
* In order to use this address with the diagnostic CE,
* convert it from Target CPU virtual address space
* to CE address space
*/
address = ath10k_pci_targ_cpu_to_ce_addr(ar, address);
ret = ath10k_ce_send_nolock(ce_diag, NULL, (u32)address, nbytes, 0,
0);
if (ret)
goto done;
i = 0;
while (ath10k_ce_completed_send_next_nolock(ce_diag,
NULL) != 0) {
mdelay(1);
if (i++ > DIAG_ACCESS_CE_TIMEOUT_MS) {
ret = -EBUSY;
goto done;
}
}
i = 0;
while (ath10k_ce_completed_recv_next_nolock(ce_diag, NULL, &buf,
&completed_nbytes,
&id, &flags) != 0) {
mdelay(1);
if (i++ > DIAG_ACCESS_CE_TIMEOUT_MS) {
ret = -EBUSY;
goto done;
}
}
if (nbytes != completed_nbytes) {
ret = -EIO;
goto done;
}
if (buf != ce_data) {
ret = -EIO;
goto done;
}
remaining_bytes -= nbytes;
address += nbytes;
ce_data += nbytes;
}
done:
if (ret == 0)
memcpy(data, data_buf, orig_nbytes);
else
ath10k_warn(ar, "failed to read diag value at 0x%x: %d\n",
address, ret);
if (data_buf)
dma_free_coherent(ar->dev, orig_nbytes, data_buf,
ce_data_base);
spin_unlock_bh(&ar_pci->ce_lock);
return ret;
}
static int ath10k_pci_diag_read32(struct ath10k *ar, u32 address, u32 *value)
{
__le32 val = 0;
int ret;
ret = ath10k_pci_diag_read_mem(ar, address, &val, sizeof(val));
*value = __le32_to_cpu(val);
return ret;
}
static int __ath10k_pci_diag_read_hi(struct ath10k *ar, void *dest,
u32 src, u32 len)
{
u32 host_addr, addr;
int ret;
host_addr = host_interest_item_address(src);
ret = ath10k_pci_diag_read32(ar, host_addr, &addr);
if (ret != 0) {
ath10k_warn(ar, "failed to get memcpy hi address for firmware address %d: %d\n",
src, ret);
return ret;
}
ret = ath10k_pci_diag_read_mem(ar, addr, dest, len);
if (ret != 0) {
ath10k_warn(ar, "failed to memcpy firmware memory from %d (%d B): %d\n",
addr, len, ret);
return ret;
}
return 0;
}
#define ath10k_pci_diag_read_hi(ar, dest, src, len) \
__ath10k_pci_diag_read_hi(ar, dest, HI_ITEM(src), len)
static int ath10k_pci_diag_write_mem(struct ath10k *ar, u32 address,
const void *data, int nbytes)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
int ret = 0;
u32 buf;
unsigned int completed_nbytes, orig_nbytes, remaining_bytes;
unsigned int id;
unsigned int flags;
struct ath10k_ce_pipe *ce_diag;
void *data_buf = NULL;
u32 ce_data; /* Host buffer address in CE space */
dma_addr_t ce_data_base = 0;
int i;
spin_lock_bh(&ar_pci->ce_lock);
ce_diag = ar_pci->ce_diag;
/*
* Allocate a temporary bounce buffer to hold caller's data
* to be DMA'ed to Target. This guarantees
* 1) 4-byte alignment
* 2) Buffer in DMA-able space
*/
orig_nbytes = nbytes;
data_buf = (unsigned char *)dma_alloc_coherent(ar->dev,
orig_nbytes,
&ce_data_base,
GFP_ATOMIC);
if (!data_buf) {
ret = -ENOMEM;
goto done;
}
/* Copy caller's data to allocated DMA buf */
memcpy(data_buf, data, orig_nbytes);
/*
* The address supplied by the caller is in the
* Target CPU virtual address space.
*
* In order to use this address with the diagnostic CE,
* convert it from
* Target CPU virtual address space
* to
* CE address space
*/
address = ath10k_pci_targ_cpu_to_ce_addr(ar, address);
remaining_bytes = orig_nbytes;
ce_data = ce_data_base;
while (remaining_bytes) {
/* FIXME: check cast */
nbytes = min_t(int, remaining_bytes, DIAG_TRANSFER_LIMIT);
/* Set up to receive directly into Target(!) address */
ret = __ath10k_ce_rx_post_buf(ce_diag, NULL, address);
if (ret != 0)
goto done;
/*
* Request CE to send caller-supplied data that
* was copied to bounce buffer to Target(!) address.
*/
ret = ath10k_ce_send_nolock(ce_diag, NULL, (u32)ce_data,
nbytes, 0, 0);
if (ret != 0)
goto done;
i = 0;
while (ath10k_ce_completed_send_next_nolock(ce_diag,
NULL) != 0) {
mdelay(1);
if (i++ > DIAG_ACCESS_CE_TIMEOUT_MS) {
ret = -EBUSY;
goto done;
}
}
i = 0;
while (ath10k_ce_completed_recv_next_nolock(ce_diag, NULL, &buf,
&completed_nbytes,
&id, &flags) != 0) {
mdelay(1);
if (i++ > DIAG_ACCESS_CE_TIMEOUT_MS) {
ret = -EBUSY;
goto done;
}
}
if (nbytes != completed_nbytes) {
ret = -EIO;
goto done;
}
if (buf != address) {
ret = -EIO;
goto done;
}
remaining_bytes -= nbytes;
address += nbytes;
ce_data += nbytes;
}
done:
if (data_buf) {
dma_free_coherent(ar->dev, orig_nbytes, data_buf,
ce_data_base);
}
if (ret != 0)
ath10k_warn(ar, "failed to write diag value at 0x%x: %d\n",
address, ret);
spin_unlock_bh(&ar_pci->ce_lock);
return ret;
}
static int ath10k_pci_diag_write32(struct ath10k *ar, u32 address, u32 value)
{
__le32 val = __cpu_to_le32(value);
return ath10k_pci_diag_write_mem(ar, address, &val, sizeof(val));
}
/* Called by lower (CE) layer when a send to Target completes. */
static void ath10k_pci_htc_tx_cb(struct ath10k_ce_pipe *ce_state)
{
struct ath10k *ar = ce_state->ar;
struct sk_buff_head list;
struct sk_buff *skb;
__skb_queue_head_init(&list);
while (ath10k_ce_completed_send_next(ce_state, (void **)&skb) == 0) {
/* no need to call tx completion for NULL pointers */
if (skb == NULL)
continue;
__skb_queue_tail(&list, skb);
}
while ((skb = __skb_dequeue(&list)))
ath10k_htc_tx_completion_handler(ar, skb);
}
static void ath10k_pci_process_rx_cb(struct ath10k_ce_pipe *ce_state,
void (*callback)(struct ath10k *ar,
struct sk_buff *skb))
{
struct ath10k *ar = ce_state->ar;
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
struct ath10k_pci_pipe *pipe_info = &ar_pci->pipe_info[ce_state->id];
struct sk_buff *skb;
struct sk_buff_head list;
void *transfer_context;
u32 ce_data;
unsigned int nbytes, max_nbytes;
unsigned int transfer_id;
unsigned int flags;
__skb_queue_head_init(&list);
while (ath10k_ce_completed_recv_next(ce_state, &transfer_context,
&ce_data, &nbytes, &transfer_id,
&flags) == 0) {
skb = transfer_context;
max_nbytes = skb->len + skb_tailroom(skb);
dma_unmap_single(ar->dev, ATH10K_SKB_RXCB(skb)->paddr,
max_nbytes, DMA_FROM_DEVICE);
if (unlikely(max_nbytes < nbytes)) {
ath10k_warn(ar, "rxed more than expected (nbytes %d, max %d)",
nbytes, max_nbytes);
dev_kfree_skb_any(skb);
continue;
}
skb_put(skb, nbytes);
__skb_queue_tail(&list, skb);
}
while ((skb = __skb_dequeue(&list))) {
ath10k_dbg(ar, ATH10K_DBG_PCI, "pci rx ce pipe %d len %d\n",
ce_state->id, skb->len);
ath10k_dbg_dump(ar, ATH10K_DBG_PCI_DUMP, NULL, "pci rx: ",
skb->data, skb->len);
callback(ar, skb);
}
ath10k_pci_rx_post_pipe(pipe_info);
}
/* Called by lower (CE) layer when data is received from the Target. */
static void ath10k_pci_htc_rx_cb(struct ath10k_ce_pipe *ce_state)
{
ath10k_pci_process_rx_cb(ce_state, ath10k_htc_rx_completion_handler);
}
static void ath10k_pci_htt_htc_rx_cb(struct ath10k_ce_pipe *ce_state)
{
/* CE4 polling needs to be done whenever CE pipe which transports
* HTT Rx (target->host) is processed.
*/
ath10k_ce_per_engine_service(ce_state->ar, 4);
ath10k_pci_process_rx_cb(ce_state, ath10k_htc_rx_completion_handler);
}
/* Called by lower (CE) layer when a send to HTT Target completes. */
static void ath10k_pci_htt_tx_cb(struct ath10k_ce_pipe *ce_state)
{
struct ath10k *ar = ce_state->ar;
struct sk_buff *skb;
while (ath10k_ce_completed_send_next(ce_state, (void **)&skb) == 0) {
/* no need to call tx completion for NULL pointers */
if (!skb)
continue;
dma_unmap_single(ar->dev, ATH10K_SKB_CB(skb)->paddr,
skb->len, DMA_TO_DEVICE);
ath10k_htt_hif_tx_complete(ar, skb);
}
}
static void ath10k_pci_htt_rx_deliver(struct ath10k *ar, struct sk_buff *skb)
{
skb_pull(skb, sizeof(struct ath10k_htc_hdr));
ath10k_htt_t2h_msg_handler(ar, skb);
}
/* Called by lower (CE) layer when HTT data is received from the Target. */
static void ath10k_pci_htt_rx_cb(struct ath10k_ce_pipe *ce_state)
{
/* CE4 polling needs to be done whenever CE pipe which transports
* HTT Rx (target->host) is processed.
*/
ath10k_ce_per_engine_service(ce_state->ar, 4);
ath10k_pci_process_rx_cb(ce_state, ath10k_pci_htt_rx_deliver);
}
static int ath10k_pci_hif_tx_sg(struct ath10k *ar, u8 pipe_id,
struct ath10k_hif_sg_item *items, int n_items)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
struct ath10k_pci_pipe *pci_pipe = &ar_pci->pipe_info[pipe_id];
struct ath10k_ce_pipe *ce_pipe = pci_pipe->ce_hdl;
struct ath10k_ce_ring *src_ring = ce_pipe->src_ring;
unsigned int nentries_mask;
unsigned int sw_index;
unsigned int write_index;
int err, i = 0;
spin_lock_bh(&ar_pci->ce_lock);
nentries_mask = src_ring->nentries_mask;
sw_index = src_ring->sw_index;
write_index = src_ring->write_index;
if (unlikely(CE_RING_DELTA(nentries_mask,
write_index, sw_index - 1) < n_items)) {
err = -ENOBUFS;
goto err;
}
for (i = 0; i < n_items - 1; i++) {
ath10k_dbg(ar, ATH10K_DBG_PCI,
"pci tx item %d paddr 0x%08x len %d n_items %d\n",
i, items[i].paddr, items[i].len, n_items);
ath10k_dbg_dump(ar, ATH10K_DBG_PCI_DUMP, NULL, "pci tx data: ",
items[i].vaddr, items[i].len);
err = ath10k_ce_send_nolock(ce_pipe,
items[i].transfer_context,
items[i].paddr,
items[i].len,
items[i].transfer_id,
CE_SEND_FLAG_GATHER);
if (err)
goto err;
}
/* `i` is equal to `n_items -1` after for() */
ath10k_dbg(ar, ATH10K_DBG_PCI,
"pci tx item %d paddr 0x%08x len %d n_items %d\n",
i, items[i].paddr, items[i].len, n_items);
ath10k_dbg_dump(ar, ATH10K_DBG_PCI_DUMP, NULL, "pci tx data: ",
items[i].vaddr, items[i].len);
err = ath10k_ce_send_nolock(ce_pipe,
items[i].transfer_context,
items[i].paddr,
items[i].len,
items[i].transfer_id,
0);
if (err)
goto err;
spin_unlock_bh(&ar_pci->ce_lock);
return 0;
err:
for (; i > 0; i--)
__ath10k_ce_send_revert(ce_pipe);
spin_unlock_bh(&ar_pci->ce_lock);
return err;
}
static int ath10k_pci_hif_diag_read(struct ath10k *ar, u32 address, void *buf,
size_t buf_len)
{
return ath10k_pci_diag_read_mem(ar, address, buf, buf_len);
}
static u16 ath10k_pci_hif_get_free_queue_number(struct ath10k *ar, u8 pipe)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
ath10k_dbg(ar, ATH10K_DBG_PCI, "pci hif get free queue number\n");
return ath10k_ce_num_free_src_entries(ar_pci->pipe_info[pipe].ce_hdl);
}
static void ath10k_pci_dump_registers(struct ath10k *ar,
struct ath10k_fw_crash_data *crash_data)
{
__le32 reg_dump_values[REG_DUMP_COUNT_QCA988X] = {};
int i, ret;
lockdep_assert_held(&ar->data_lock);
ret = ath10k_pci_diag_read_hi(ar, ®_dump_values[0],
hi_failure_state,
REG_DUMP_COUNT_QCA988X * sizeof(__le32));
if (ret) {
ath10k_err(ar, "failed to read firmware dump area: %d\n", ret);
return;
}
BUILD_BUG_ON(REG_DUMP_COUNT_QCA988X % 4);
ath10k_err(ar, "firmware register dump:\n");
for (i = 0; i < REG_DUMP_COUNT_QCA988X; i += 4)
ath10k_err(ar, "[%02d]: 0x%08X 0x%08X 0x%08X 0x%08X\n",
i,
__le32_to_cpu(reg_dump_values[i]),
__le32_to_cpu(reg_dump_values[i + 1]),
__le32_to_cpu(reg_dump_values[i + 2]),
__le32_to_cpu(reg_dump_values[i + 3]));
if (!crash_data)
return;
for (i = 0; i < REG_DUMP_COUNT_QCA988X; i++)
crash_data->registers[i] = reg_dump_values[i];
}
static void ath10k_pci_fw_crashed_dump(struct ath10k *ar)
{
struct ath10k_fw_crash_data *crash_data;
char uuid[50];
spin_lock_bh(&ar->data_lock);
ar->stats.fw_crash_counter++;
crash_data = ath10k_debug_get_new_fw_crash_data(ar);
if (crash_data)
scnprintf(uuid, sizeof(uuid), "%pUl", &crash_data->uuid);
else
scnprintf(uuid, sizeof(uuid), "n/a");
ath10k_err(ar, "firmware crashed! (uuid %s)\n", uuid);
ath10k_print_driver_info(ar);
ath10k_pci_dump_registers(ar, crash_data);
spin_unlock_bh(&ar->data_lock);
queue_work(ar->workqueue, &ar->restart_work);
}
static void ath10k_pci_hif_send_complete_check(struct ath10k *ar, u8 pipe,
int force)
{
ath10k_dbg(ar, ATH10K_DBG_PCI, "pci hif send complete check\n");
if (!force) {
int resources;
/*
* Decide whether to actually poll for completions, or just
* wait for a later chance.
* If there seem to be plenty of resources left, then just wait
* since checking involves reading a CE register, which is a
* relatively expensive operation.
*/
resources = ath10k_pci_hif_get_free_queue_number(ar, pipe);
/*
* If at least 50% of the total resources are still available,
* don't bother checking again yet.
*/
if (resources > (host_ce_config_wlan[pipe].src_nentries >> 1))
return;
}
ath10k_ce_per_engine_service(ar, pipe);
}
static void ath10k_pci_kill_tasklet(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
int i;
tasklet_kill(&ar_pci->intr_tq);
tasklet_kill(&ar_pci->msi_fw_err);
for (i = 0; i < CE_COUNT; i++)
tasklet_kill(&ar_pci->pipe_info[i].intr);
del_timer_sync(&ar_pci->rx_post_retry);
}
static int ath10k_pci_hif_map_service_to_pipe(struct ath10k *ar, u16 service_id,
u8 *ul_pipe, u8 *dl_pipe)
{
const struct service_to_pipe *entry;
bool ul_set = false, dl_set = false;
int i;
ath10k_dbg(ar, ATH10K_DBG_PCI, "pci hif map service\n");
for (i = 0; i < ARRAY_SIZE(target_service_to_ce_map_wlan); i++) {
entry = &target_service_to_ce_map_wlan[i];
if (__le32_to_cpu(entry->service_id) != service_id)
continue;
switch (__le32_to_cpu(entry->pipedir)) {
case PIPEDIR_NONE:
break;
case PIPEDIR_IN:
WARN_ON(dl_set);
*dl_pipe = __le32_to_cpu(entry->pipenum);
dl_set = true;
break;
case PIPEDIR_OUT:
WARN_ON(ul_set);
*ul_pipe = __le32_to_cpu(entry->pipenum);
ul_set = true;
break;
case PIPEDIR_INOUT:
WARN_ON(dl_set);
WARN_ON(ul_set);
*dl_pipe = __le32_to_cpu(entry->pipenum);
*ul_pipe = __le32_to_cpu(entry->pipenum);
dl_set = true;
ul_set = true;
break;
}
}
if (WARN_ON(!ul_set || !dl_set))
return -ENOENT;
return 0;
}
static void ath10k_pci_hif_get_default_pipe(struct ath10k *ar,
u8 *ul_pipe, u8 *dl_pipe)
{
ath10k_dbg(ar, ATH10K_DBG_PCI, "pci hif get default pipe\n");
(void)ath10k_pci_hif_map_service_to_pipe(ar,
ATH10K_HTC_SVC_ID_RSVD_CTRL,
ul_pipe, dl_pipe);
}
static void ath10k_pci_irq_msi_fw_mask(struct ath10k *ar)
{
u32 val;
switch (ar->hw_rev) {
case ATH10K_HW_QCA988X:
case ATH10K_HW_QCA6174:
case ATH10K_HW_QCA9377:
val = ath10k_pci_read32(ar, SOC_CORE_BASE_ADDRESS +
CORE_CTRL_ADDRESS);
val &= ~CORE_CTRL_PCIE_REG_31_MASK;
ath10k_pci_write32(ar, SOC_CORE_BASE_ADDRESS +
CORE_CTRL_ADDRESS, val);
break;
case ATH10K_HW_QCA99X0:
/* TODO: Find appropriate register configuration for QCA99X0
* to mask irq/MSI.
*/
break;
}
}
static void ath10k_pci_irq_msi_fw_unmask(struct ath10k *ar)
{
u32 val;
switch (ar->hw_rev) {
case ATH10K_HW_QCA988X:
case ATH10K_HW_QCA6174:
case ATH10K_HW_QCA9377:
val = ath10k_pci_read32(ar, SOC_CORE_BASE_ADDRESS +
CORE_CTRL_ADDRESS);
val |= CORE_CTRL_PCIE_REG_31_MASK;
ath10k_pci_write32(ar, SOC_CORE_BASE_ADDRESS +
CORE_CTRL_ADDRESS, val);
break;
case ATH10K_HW_QCA99X0:
/* TODO: Find appropriate register configuration for QCA99X0
* to unmask irq/MSI.
*/
break;
}
}
static void ath10k_pci_irq_disable(struct ath10k *ar)
{
ath10k_ce_disable_interrupts(ar);
ath10k_pci_disable_and_clear_legacy_irq(ar);
ath10k_pci_irq_msi_fw_mask(ar);
}
static void ath10k_pci_irq_sync(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
int i;
for (i = 0; i < max(1, ar_pci->num_msi_intrs); i++)
synchronize_irq(ar_pci->pdev->irq + i);
}
static void ath10k_pci_irq_enable(struct ath10k *ar)
{
ath10k_ce_enable_interrupts(ar);
ath10k_pci_enable_legacy_irq(ar);
ath10k_pci_irq_msi_fw_unmask(ar);
}
static int ath10k_pci_hif_start(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot hif start\n");
ath10k_pci_irq_enable(ar);
ath10k_pci_rx_post(ar);
pcie_capability_write_word(ar_pci->pdev, PCI_EXP_LNKCTL,
ar_pci->link_ctl);
return 0;
}
static void ath10k_pci_rx_pipe_cleanup(struct ath10k_pci_pipe *pci_pipe)
{
struct ath10k *ar;
struct ath10k_ce_pipe *ce_pipe;
struct ath10k_ce_ring *ce_ring;
struct sk_buff *skb;
int i;
ar = pci_pipe->hif_ce_state;
ce_pipe = pci_pipe->ce_hdl;
ce_ring = ce_pipe->dest_ring;
if (!ce_ring)
return;
if (!pci_pipe->buf_sz)
return;
for (i = 0; i < ce_ring->nentries; i++) {
skb = ce_ring->per_transfer_context[i];
if (!skb)
continue;
ce_ring->per_transfer_context[i] = NULL;
dma_unmap_single(ar->dev, ATH10K_SKB_RXCB(skb)->paddr,
skb->len + skb_tailroom(skb),
DMA_FROM_DEVICE);
dev_kfree_skb_any(skb);
}
}
static void ath10k_pci_tx_pipe_cleanup(struct ath10k_pci_pipe *pci_pipe)
{
struct ath10k *ar;
struct ath10k_pci *ar_pci;
struct ath10k_ce_pipe *ce_pipe;
struct ath10k_ce_ring *ce_ring;
struct sk_buff *skb;
int i;
ar = pci_pipe->hif_ce_state;
ar_pci = ath10k_pci_priv(ar);
ce_pipe = pci_pipe->ce_hdl;
ce_ring = ce_pipe->src_ring;
if (!ce_ring)
return;
if (!pci_pipe->buf_sz)
return;
for (i = 0; i < ce_ring->nentries; i++) {
skb = ce_ring->per_transfer_context[i];
if (!skb)
continue;
ce_ring->per_transfer_context[i] = NULL;
ath10k_htc_tx_completion_handler(ar, skb);
}
}
/*
* Cleanup residual buffers for device shutdown:
* buffers that were enqueued for receive
* buffers that were to be sent
* Note: Buffers that had completed but which were
* not yet processed are on a completion queue. They
* are handled when the completion thread shuts down.
*/
static void ath10k_pci_buffer_cleanup(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
int pipe_num;
for (pipe_num = 0; pipe_num < CE_COUNT; pipe_num++) {
struct ath10k_pci_pipe *pipe_info;
pipe_info = &ar_pci->pipe_info[pipe_num];
ath10k_pci_rx_pipe_cleanup(pipe_info);
ath10k_pci_tx_pipe_cleanup(pipe_info);
}
}
static void ath10k_pci_ce_deinit(struct ath10k *ar)
{
int i;
for (i = 0; i < CE_COUNT; i++)
ath10k_ce_deinit_pipe(ar, i);
}
static void ath10k_pci_flush(struct ath10k *ar)
{
ath10k_pci_kill_tasklet(ar);
ath10k_pci_buffer_cleanup(ar);
}
static void ath10k_pci_hif_stop(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
unsigned long flags;
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot hif stop\n");
/* Most likely the device has HTT Rx ring configured. The only way to
* prevent the device from accessing (and possible corrupting) host
* memory is to reset the chip now.
*
* There's also no known way of masking MSI interrupts on the device.
* For ranged MSI the CE-related interrupts can be masked. However
* regardless how many MSI interrupts are assigned the first one
* is always used for firmware indications (crashes) and cannot be
* masked. To prevent the device from asserting the interrupt reset it
* before proceeding with cleanup.
*/
ath10k_pci_safe_chip_reset(ar);
ath10k_pci_irq_disable(ar);
ath10k_pci_irq_sync(ar);
ath10k_pci_flush(ar);
spin_lock_irqsave(&ar_pci->ps_lock, flags);
WARN_ON(ar_pci->ps_wake_refcount > 0);
spin_unlock_irqrestore(&ar_pci->ps_lock, flags);
}
static int ath10k_pci_hif_exchange_bmi_msg(struct ath10k *ar,
void *req, u32 req_len,
void *resp, u32 *resp_len)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
struct ath10k_pci_pipe *pci_tx = &ar_pci->pipe_info[BMI_CE_NUM_TO_TARG];
struct ath10k_pci_pipe *pci_rx = &ar_pci->pipe_info[BMI_CE_NUM_TO_HOST];
struct ath10k_ce_pipe *ce_tx = pci_tx->ce_hdl;
struct ath10k_ce_pipe *ce_rx = pci_rx->ce_hdl;
dma_addr_t req_paddr = 0;
dma_addr_t resp_paddr = 0;
struct bmi_xfer xfer = {};
void *treq, *tresp = NULL;
int ret = 0;
might_sleep();
if (resp && !resp_len)
return -EINVAL;
if (resp && resp_len && *resp_len == 0)
return -EINVAL;
treq = kmemdup(req, req_len, GFP_KERNEL);
if (!treq)
return -ENOMEM;
req_paddr = dma_map_single(ar->dev, treq, req_len, DMA_TO_DEVICE);
ret = dma_mapping_error(ar->dev, req_paddr);
if (ret) {
ret = -EIO;
goto err_dma;
}
if (resp && resp_len) {
tresp = kzalloc(*resp_len, GFP_KERNEL);
if (!tresp) {
ret = -ENOMEM;
goto err_req;
}
resp_paddr = dma_map_single(ar->dev, tresp, *resp_len,
DMA_FROM_DEVICE);
ret = dma_mapping_error(ar->dev, resp_paddr);
if (ret) {
ret = EIO;
goto err_req;
}
xfer.wait_for_resp = true;
xfer.resp_len = 0;
ath10k_ce_rx_post_buf(ce_rx, &xfer, resp_paddr);
}
ret = ath10k_ce_send(ce_tx, &xfer, req_paddr, req_len, -1, 0);
if (ret)
goto err_resp;
ret = ath10k_pci_bmi_wait(ce_tx, ce_rx, &xfer);
if (ret) {
u32 unused_buffer;
unsigned int unused_nbytes;
unsigned int unused_id;
ath10k_ce_cancel_send_next(ce_tx, NULL, &unused_buffer,
&unused_nbytes, &unused_id);
} else {
/* non-zero means we did not time out */
ret = 0;
}
err_resp:
if (resp) {
u32 unused_buffer;
ath10k_ce_revoke_recv_next(ce_rx, NULL, &unused_buffer);
dma_unmap_single(ar->dev, resp_paddr,
*resp_len, DMA_FROM_DEVICE);
}
err_req:
dma_unmap_single(ar->dev, req_paddr, req_len, DMA_TO_DEVICE);
if (ret == 0 && resp_len) {
*resp_len = min(*resp_len, xfer.resp_len);
memcpy(resp, tresp, xfer.resp_len);
}
err_dma:
kfree(treq);
kfree(tresp);
return ret;
}
static void ath10k_pci_bmi_send_done(struct ath10k_ce_pipe *ce_state)
{
struct bmi_xfer *xfer;
if (ath10k_ce_completed_send_next(ce_state, (void **)&xfer))
return;
xfer->tx_done = true;
}
static void ath10k_pci_bmi_recv_data(struct ath10k_ce_pipe *ce_state)
{
struct ath10k *ar = ce_state->ar;
struct bmi_xfer *xfer;
u32 ce_data;
unsigned int nbytes;
unsigned int transfer_id;
unsigned int flags;
if (ath10k_ce_completed_recv_next(ce_state, (void **)&xfer, &ce_data,
&nbytes, &transfer_id, &flags))
return;
if (WARN_ON_ONCE(!xfer))
return;
if (!xfer->wait_for_resp) {
ath10k_warn(ar, "unexpected: BMI data received; ignoring\n");
return;
}
xfer->resp_len = nbytes;
xfer->rx_done = true;
}
static int ath10k_pci_bmi_wait(struct ath10k_ce_pipe *tx_pipe,
struct ath10k_ce_pipe *rx_pipe,
struct bmi_xfer *xfer)
{
unsigned long timeout = jiffies + BMI_COMMUNICATION_TIMEOUT_HZ;
while (time_before_eq(jiffies, timeout)) {
ath10k_pci_bmi_send_done(tx_pipe);
ath10k_pci_bmi_recv_data(rx_pipe);
if (xfer->tx_done && (xfer->rx_done == xfer->wait_for_resp))
return 0;
schedule();
}
return -ETIMEDOUT;
}
/*
* Send an interrupt to the device to wake up the Target CPU
* so it has an opportunity to notice any changed state.
*/
static int ath10k_pci_wake_target_cpu(struct ath10k *ar)
{
u32 addr, val;
addr = SOC_CORE_BASE_ADDRESS | CORE_CTRL_ADDRESS;
val = ath10k_pci_read32(ar, addr);
val |= CORE_CTRL_CPU_INTR_MASK;
ath10k_pci_write32(ar, addr, val);
return 0;
}
static int ath10k_pci_get_num_banks(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
switch (ar_pci->pdev->device) {
case QCA988X_2_0_DEVICE_ID:
case QCA99X0_2_0_DEVICE_ID:
return 1;
case QCA6164_2_1_DEVICE_ID:
case QCA6174_2_1_DEVICE_ID:
switch (MS(ar->chip_id, SOC_CHIP_ID_REV)) {
case QCA6174_HW_1_0_CHIP_ID_REV:
case QCA6174_HW_1_1_CHIP_ID_REV:
case QCA6174_HW_2_1_CHIP_ID_REV:
case QCA6174_HW_2_2_CHIP_ID_REV:
return 3;
case QCA6174_HW_1_3_CHIP_ID_REV:
return 2;
case QCA6174_HW_3_0_CHIP_ID_REV:
case QCA6174_HW_3_1_CHIP_ID_REV:
case QCA6174_HW_3_2_CHIP_ID_REV:
return 9;
}
break;
case QCA9377_1_0_DEVICE_ID:
return 2;
}
ath10k_warn(ar, "unknown number of banks, assuming 1\n");
return 1;
}
static int ath10k_pci_init_config(struct ath10k *ar)
{
u32 interconnect_targ_addr;
u32 pcie_state_targ_addr = 0;
u32 pipe_cfg_targ_addr = 0;
u32 svc_to_pipe_map = 0;
u32 pcie_config_flags = 0;
u32 ealloc_value;
u32 ealloc_targ_addr;
u32 flag2_value;
u32 flag2_targ_addr;
int ret = 0;
/* Download to Target the CE Config and the service-to-CE map */
interconnect_targ_addr =
host_interest_item_address(HI_ITEM(hi_interconnect_state));
/* Supply Target-side CE configuration */
ret = ath10k_pci_diag_read32(ar, interconnect_targ_addr,
&pcie_state_targ_addr);
if (ret != 0) {
ath10k_err(ar, "Failed to get pcie state addr: %d\n", ret);
return ret;
}
if (pcie_state_targ_addr == 0) {
ret = -EIO;
ath10k_err(ar, "Invalid pcie state addr\n");
return ret;
}
ret = ath10k_pci_diag_read32(ar, (pcie_state_targ_addr +
offsetof(struct pcie_state,
pipe_cfg_addr)),
&pipe_cfg_targ_addr);
if (ret != 0) {
ath10k_err(ar, "Failed to get pipe cfg addr: %d\n", ret);
return ret;
}
if (pipe_cfg_targ_addr == 0) {
ret = -EIO;
ath10k_err(ar, "Invalid pipe cfg addr\n");
return ret;
}
ret = ath10k_pci_diag_write_mem(ar, pipe_cfg_targ_addr,
target_ce_config_wlan,
sizeof(struct ce_pipe_config) *
NUM_TARGET_CE_CONFIG_WLAN);
if (ret != 0) {
ath10k_err(ar, "Failed to write pipe cfg: %d\n", ret);
return ret;
}
ret = ath10k_pci_diag_read32(ar, (pcie_state_targ_addr +
offsetof(struct pcie_state,
svc_to_pipe_map)),
&svc_to_pipe_map);
if (ret != 0) {
ath10k_err(ar, "Failed to get svc/pipe map: %d\n", ret);
return ret;
}
if (svc_to_pipe_map == 0) {
ret = -EIO;
ath10k_err(ar, "Invalid svc_to_pipe map\n");
return ret;
}
ret = ath10k_pci_diag_write_mem(ar, svc_to_pipe_map,
target_service_to_ce_map_wlan,
sizeof(target_service_to_ce_map_wlan));
if (ret != 0) {
ath10k_err(ar, "Failed to write svc/pipe map: %d\n", ret);
return ret;
}
ret = ath10k_pci_diag_read32(ar, (pcie_state_targ_addr +
offsetof(struct pcie_state,
config_flags)),
&pcie_config_flags);
if (ret != 0) {
ath10k_err(ar, "Failed to get pcie config_flags: %d\n", ret);
return ret;
}
pcie_config_flags &= ~PCIE_CONFIG_FLAG_ENABLE_L1;
ret = ath10k_pci_diag_write32(ar, (pcie_state_targ_addr +
offsetof(struct pcie_state,
config_flags)),
pcie_config_flags);
if (ret != 0) {
ath10k_err(ar, "Failed to write pcie config_flags: %d\n", ret);
return ret;
}
/* configure early allocation */
ealloc_targ_addr = host_interest_item_address(HI_ITEM(hi_early_alloc));
ret = ath10k_pci_diag_read32(ar, ealloc_targ_addr, &ealloc_value);
if (ret != 0) {
ath10k_err(ar, "Faile to get early alloc val: %d\n", ret);
return ret;
}
/* first bank is switched to IRAM */
ealloc_value |= ((HI_EARLY_ALLOC_MAGIC << HI_EARLY_ALLOC_MAGIC_SHIFT) &
HI_EARLY_ALLOC_MAGIC_MASK);
ealloc_value |= ((ath10k_pci_get_num_banks(ar) <<
HI_EARLY_ALLOC_IRAM_BANKS_SHIFT) &
HI_EARLY_ALLOC_IRAM_BANKS_MASK);
ret = ath10k_pci_diag_write32(ar, ealloc_targ_addr, ealloc_value);
if (ret != 0) {
ath10k_err(ar, "Failed to set early alloc val: %d\n", ret);
return ret;
}
/* Tell Target to proceed with initialization */
flag2_targ_addr = host_interest_item_address(HI_ITEM(hi_option_flag2));
ret = ath10k_pci_diag_read32(ar, flag2_targ_addr, &flag2_value);
if (ret != 0) {
ath10k_err(ar, "Failed to get option val: %d\n", ret);
return ret;
}
flag2_value |= HI_OPTION_EARLY_CFG_DONE;
ret = ath10k_pci_diag_write32(ar, flag2_targ_addr, flag2_value);
if (ret != 0) {
ath10k_err(ar, "Failed to set option val: %d\n", ret);
return ret;
}
return 0;
}
static void ath10k_pci_override_ce_config(struct ath10k *ar)
{
struct ce_attr *attr;
struct ce_pipe_config *config;
/* For QCA6174 we're overriding the Copy Engine 5 configuration,
* since it is currently used for other feature.
*/
/* Override Host's Copy Engine 5 configuration */
attr = &host_ce_config_wlan[5];
attr->src_sz_max = 0;
attr->dest_nentries = 0;
/* Override Target firmware's Copy Engine configuration */
config = &target_ce_config_wlan[5];
config->pipedir = __cpu_to_le32(PIPEDIR_OUT);
config->nbytes_max = __cpu_to_le32(2048);
/* Map from service/endpoint to Copy Engine */
target_service_to_ce_map_wlan[15].pipenum = __cpu_to_le32(1);
}
static int ath10k_pci_alloc_pipes(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
struct ath10k_pci_pipe *pipe;
int i, ret;
for (i = 0; i < CE_COUNT; i++) {
pipe = &ar_pci->pipe_info[i];
pipe->ce_hdl = &ar_pci->ce_states[i];
pipe->pipe_num = i;
pipe->hif_ce_state = ar;
ret = ath10k_ce_alloc_pipe(ar, i, &host_ce_config_wlan[i]);
if (ret) {
ath10k_err(ar, "failed to allocate copy engine pipe %d: %d\n",
i, ret);
return ret;
}
/* Last CE is Diagnostic Window */
if (i == CE_DIAG_PIPE) {
ar_pci->ce_diag = pipe->ce_hdl;
continue;
}
pipe->buf_sz = (size_t)(host_ce_config_wlan[i].src_sz_max);
}
return 0;
}
static void ath10k_pci_free_pipes(struct ath10k *ar)
{
int i;
for (i = 0; i < CE_COUNT; i++)
ath10k_ce_free_pipe(ar, i);
}
static int ath10k_pci_init_pipes(struct ath10k *ar)
{
int i, ret;
for (i = 0; i < CE_COUNT; i++) {
ret = ath10k_ce_init_pipe(ar, i, &host_ce_config_wlan[i]);
if (ret) {
ath10k_err(ar, "failed to initialize copy engine pipe %d: %d\n",
i, ret);
return ret;
}
}
return 0;
}
static bool ath10k_pci_has_fw_crashed(struct ath10k *ar)
{
return ath10k_pci_read32(ar, FW_INDICATOR_ADDRESS) &
FW_IND_EVENT_PENDING;
}
static void ath10k_pci_fw_crashed_clear(struct ath10k *ar)
{
u32 val;
val = ath10k_pci_read32(ar, FW_INDICATOR_ADDRESS);
val &= ~FW_IND_EVENT_PENDING;
ath10k_pci_write32(ar, FW_INDICATOR_ADDRESS, val);
}
/* this function effectively clears target memory controller assert line */
static void ath10k_pci_warm_reset_si0(struct ath10k *ar)
{
u32 val;
val = ath10k_pci_soc_read32(ar, SOC_RESET_CONTROL_ADDRESS);
ath10k_pci_soc_write32(ar, SOC_RESET_CONTROL_ADDRESS,
val | SOC_RESET_CONTROL_SI0_RST_MASK);
val = ath10k_pci_soc_read32(ar, SOC_RESET_CONTROL_ADDRESS);
msleep(10);
val = ath10k_pci_soc_read32(ar, SOC_RESET_CONTROL_ADDRESS);
ath10k_pci_soc_write32(ar, SOC_RESET_CONTROL_ADDRESS,
val & ~SOC_RESET_CONTROL_SI0_RST_MASK);
val = ath10k_pci_soc_read32(ar, SOC_RESET_CONTROL_ADDRESS);
msleep(10);
}
static void ath10k_pci_warm_reset_cpu(struct ath10k *ar)
{
u32 val;
ath10k_pci_write32(ar, FW_INDICATOR_ADDRESS, 0);
val = ath10k_pci_read32(ar, RTC_SOC_BASE_ADDRESS +
SOC_RESET_CONTROL_ADDRESS);
ath10k_pci_write32(ar, RTC_SOC_BASE_ADDRESS + SOC_RESET_CONTROL_ADDRESS,
val | SOC_RESET_CONTROL_CPU_WARM_RST_MASK);
}
static void ath10k_pci_warm_reset_ce(struct ath10k *ar)
{
u32 val;
val = ath10k_pci_read32(ar, RTC_SOC_BASE_ADDRESS +
SOC_RESET_CONTROL_ADDRESS);
ath10k_pci_write32(ar, RTC_SOC_BASE_ADDRESS + SOC_RESET_CONTROL_ADDRESS,
val | SOC_RESET_CONTROL_CE_RST_MASK);
msleep(10);
ath10k_pci_write32(ar, RTC_SOC_BASE_ADDRESS + SOC_RESET_CONTROL_ADDRESS,
val & ~SOC_RESET_CONTROL_CE_RST_MASK);
}
static void ath10k_pci_warm_reset_clear_lf(struct ath10k *ar)
{
u32 val;
val = ath10k_pci_read32(ar, RTC_SOC_BASE_ADDRESS +
SOC_LF_TIMER_CONTROL0_ADDRESS);
ath10k_pci_write32(ar, RTC_SOC_BASE_ADDRESS +
SOC_LF_TIMER_CONTROL0_ADDRESS,
val & ~SOC_LF_TIMER_CONTROL0_ENABLE_MASK);
}
static int ath10k_pci_warm_reset(struct ath10k *ar)
{
int ret;
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot warm reset\n");
spin_lock_bh(&ar->data_lock);
ar->stats.fw_warm_reset_counter++;
spin_unlock_bh(&ar->data_lock);
ath10k_pci_irq_disable(ar);
/* Make sure the target CPU is not doing anything dangerous, e.g. if it
* were to access copy engine while host performs copy engine reset
* then it is possible for the device to confuse pci-e controller to
* the point of bringing host system to a complete stop (i.e. hang).
*/
ath10k_pci_warm_reset_si0(ar);
ath10k_pci_warm_reset_cpu(ar);
ath10k_pci_init_pipes(ar);
ath10k_pci_wait_for_target_init(ar);
ath10k_pci_warm_reset_clear_lf(ar);
ath10k_pci_warm_reset_ce(ar);
ath10k_pci_warm_reset_cpu(ar);
ath10k_pci_init_pipes(ar);
ret = ath10k_pci_wait_for_target_init(ar);
if (ret) {
ath10k_warn(ar, "failed to wait for target init: %d\n", ret);
return ret;
}
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot warm reset complete\n");
return 0;
}
static int ath10k_pci_safe_chip_reset(struct ath10k *ar)
{
if (QCA_REV_988X(ar) || QCA_REV_6174(ar)) {
return ath10k_pci_warm_reset(ar);
} else if (QCA_REV_99X0(ar)) {
ath10k_pci_irq_disable(ar);
return ath10k_pci_qca99x0_chip_reset(ar);
} else {
return -ENOTSUPP;
}
}
static int ath10k_pci_qca988x_chip_reset(struct ath10k *ar)
{
int i, ret;
u32 val;
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot 988x chip reset\n");
/* Some hardware revisions (e.g. CUS223v2) has issues with cold reset.
* It is thus preferred to use warm reset which is safer but may not be
* able to recover the device from all possible fail scenarios.
*
* Warm reset doesn't always work on first try so attempt it a few
* times before giving up.
*/
for (i = 0; i < ATH10K_PCI_NUM_WARM_RESET_ATTEMPTS; i++) {
ret = ath10k_pci_warm_reset(ar);
if (ret) {
ath10k_warn(ar, "failed to warm reset attempt %d of %d: %d\n",
i + 1, ATH10K_PCI_NUM_WARM_RESET_ATTEMPTS,
ret);
continue;
}
/* FIXME: Sometimes copy engine doesn't recover after warm
* reset. In most cases this needs cold reset. In some of these
* cases the device is in such a state that a cold reset may
* lock up the host.
*
* Reading any host interest register via copy engine is
* sufficient to verify if device is capable of booting
* firmware blob.
*/
ret = ath10k_pci_init_pipes(ar);
if (ret) {
ath10k_warn(ar, "failed to init copy engine: %d\n",
ret);
continue;
}
ret = ath10k_pci_diag_read32(ar, QCA988X_HOST_INTEREST_ADDRESS,
&val);
if (ret) {
ath10k_warn(ar, "failed to poke copy engine: %d\n",
ret);
continue;
}
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot chip reset complete (warm)\n");
return 0;
}
if (ath10k_pci_reset_mode == ATH10K_PCI_RESET_WARM_ONLY) {
ath10k_warn(ar, "refusing cold reset as requested\n");
return -EPERM;
}
ret = ath10k_pci_cold_reset(ar);
if (ret) {
ath10k_warn(ar, "failed to cold reset: %d\n", ret);
return ret;
}
ret = ath10k_pci_wait_for_target_init(ar);
if (ret) {
ath10k_warn(ar, "failed to wait for target after cold reset: %d\n",
ret);
return ret;
}
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot qca988x chip reset complete (cold)\n");
return 0;
}
static int ath10k_pci_qca6174_chip_reset(struct ath10k *ar)
{
int ret;
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot qca6174 chip reset\n");
/* FIXME: QCA6174 requires cold + warm reset to work. */
ret = ath10k_pci_cold_reset(ar);
if (ret) {
ath10k_warn(ar, "failed to cold reset: %d\n", ret);
return ret;
}
ret = ath10k_pci_wait_for_target_init(ar);
if (ret) {
ath10k_warn(ar, "failed to wait for target after cold reset: %d\n",
ret);
return ret;
}
ret = ath10k_pci_warm_reset(ar);
if (ret) {
ath10k_warn(ar, "failed to warm reset: %d\n", ret);
return ret;
}
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot qca6174 chip reset complete (cold)\n");
return 0;
}
static int ath10k_pci_qca99x0_chip_reset(struct ath10k *ar)
{
int ret;
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot qca99x0 chip reset\n");
ret = ath10k_pci_cold_reset(ar);
if (ret) {
ath10k_warn(ar, "failed to cold reset: %d\n", ret);
return ret;
}
ret = ath10k_pci_wait_for_target_init(ar);
if (ret) {
ath10k_warn(ar, "failed to wait for target after cold reset: %d\n",
ret);
return ret;
}
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot qca99x0 chip reset complete (cold)\n");
return 0;
}
static int ath10k_pci_chip_reset(struct ath10k *ar)
{
if (QCA_REV_988X(ar))
return ath10k_pci_qca988x_chip_reset(ar);
else if (QCA_REV_6174(ar))
return ath10k_pci_qca6174_chip_reset(ar);
else if (QCA_REV_9377(ar))
return ath10k_pci_qca6174_chip_reset(ar);
else if (QCA_REV_99X0(ar))
return ath10k_pci_qca99x0_chip_reset(ar);
else
return -ENOTSUPP;
}
static int ath10k_pci_hif_power_up(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
int ret;
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot hif power up\n");
pcie_capability_read_word(ar_pci->pdev, PCI_EXP_LNKCTL,
&ar_pci->link_ctl);
pcie_capability_write_word(ar_pci->pdev, PCI_EXP_LNKCTL,
ar_pci->link_ctl & ~PCI_EXP_LNKCTL_ASPMC);
/*
* Bring the target up cleanly.
*
* The target may be in an undefined state with an AUX-powered Target
* and a Host in WoW mode. If the Host crashes, loses power, or is
* restarted (without unloading the driver) then the Target is left
* (aux) powered and running. On a subsequent driver load, the Target
* is in an unexpected state. We try to catch that here in order to
* reset the Target and retry the probe.
*/
ret = ath10k_pci_chip_reset(ar);
if (ret) {
if (ath10k_pci_has_fw_crashed(ar)) {
ath10k_warn(ar, "firmware crashed during chip reset\n");
ath10k_pci_fw_crashed_clear(ar);
ath10k_pci_fw_crashed_dump(ar);
}
ath10k_err(ar, "failed to reset chip: %d\n", ret);
goto err_sleep;
}
ret = ath10k_pci_init_pipes(ar);
if (ret) {
ath10k_err(ar, "failed to initialize CE: %d\n", ret);
goto err_sleep;
}
ret = ath10k_pci_init_config(ar);
if (ret) {
ath10k_err(ar, "failed to setup init config: %d\n", ret);
goto err_ce;
}
ret = ath10k_pci_wake_target_cpu(ar);
if (ret) {
ath10k_err(ar, "could not wake up target CPU: %d\n", ret);
goto err_ce;
}
return 0;
err_ce:
ath10k_pci_ce_deinit(ar);
err_sleep:
return ret;
}
static void ath10k_pci_hif_power_down(struct ath10k *ar)
{
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot hif power down\n");
/* Currently hif_power_up performs effectively a reset and hif_stop
* resets the chip as well so there's no point in resetting here.
*/
}
#ifdef CONFIG_PM
static int ath10k_pci_hif_suspend(struct ath10k *ar)
{
/* The grace timer can still be counting down and ar->ps_awake be true.
* It is known that the device may be asleep after resuming regardless
* of the SoC powersave state before suspending. Hence make sure the
* device is asleep before proceeding.
*/
ath10k_pci_sleep_sync(ar);
return 0;
}
static int ath10k_pci_hif_resume(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
struct pci_dev *pdev = ar_pci->pdev;
u32 val;
int ret = 0;
if (ar_pci->pci_ps == 0) {
ret = ath10k_pci_force_wake(ar);
if (ret) {
ath10k_err(ar, "failed to wake up target: %d\n", ret);
return ret;
}
}
/* Suspend/Resume resets the PCI configuration space, so we have to
* re-disable the RETRY_TIMEOUT register (0x41) to keep PCI Tx retries
* from interfering with C3 CPU state. pci_restore_state won't help
* here since it only restores the first 64 bytes pci config header.
*/
pci_read_config_dword(pdev, 0x40, &val);
if ((val & 0x0000ff00) != 0)
pci_write_config_dword(pdev, 0x40, val & 0xffff00ff);
return ret;
}
#endif
static const struct ath10k_hif_ops ath10k_pci_hif_ops = {
.tx_sg = ath10k_pci_hif_tx_sg,
.diag_read = ath10k_pci_hif_diag_read,
.diag_write = ath10k_pci_diag_write_mem,
.exchange_bmi_msg = ath10k_pci_hif_exchange_bmi_msg,
.start = ath10k_pci_hif_start,
.stop = ath10k_pci_hif_stop,
.map_service_to_pipe = ath10k_pci_hif_map_service_to_pipe,
.get_default_pipe = ath10k_pci_hif_get_default_pipe,
.send_complete_check = ath10k_pci_hif_send_complete_check,
.get_free_queue_number = ath10k_pci_hif_get_free_queue_number,
.power_up = ath10k_pci_hif_power_up,
.power_down = ath10k_pci_hif_power_down,
.read32 = ath10k_pci_read32,
.write32 = ath10k_pci_write32,
#ifdef CONFIG_PM
.suspend = ath10k_pci_hif_suspend,
.resume = ath10k_pci_hif_resume,
#endif
};
static void ath10k_pci_ce_tasklet(unsigned long ptr)
{
struct ath10k_pci_pipe *pipe = (struct ath10k_pci_pipe *)ptr;
struct ath10k_pci *ar_pci = pipe->ar_pci;
ath10k_ce_per_engine_service(ar_pci->ar, pipe->pipe_num);
}
static void ath10k_msi_err_tasklet(unsigned long data)
{
struct ath10k *ar = (struct ath10k *)data;
if (!ath10k_pci_has_fw_crashed(ar)) {
ath10k_warn(ar, "received unsolicited fw crash interrupt\n");
return;
}
ath10k_pci_irq_disable(ar);
ath10k_pci_fw_crashed_clear(ar);
ath10k_pci_fw_crashed_dump(ar);
}
/*
* Handler for a per-engine interrupt on a PARTICULAR CE.
* This is used in cases where each CE has a private MSI interrupt.
*/
static irqreturn_t ath10k_pci_per_engine_handler(int irq, void *arg)
{
struct ath10k *ar = arg;
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
int ce_id = irq - ar_pci->pdev->irq - MSI_ASSIGN_CE_INITIAL;
if (ce_id < 0 || ce_id >= ARRAY_SIZE(ar_pci->pipe_info)) {
ath10k_warn(ar, "unexpected/invalid irq %d ce_id %d\n", irq,
ce_id);
return IRQ_HANDLED;
}
/*
* NOTE: We are able to derive ce_id from irq because we
* use a one-to-one mapping for CE's 0..5.
* CE's 6 & 7 do not use interrupts at all.
*
* This mapping must be kept in sync with the mapping
* used by firmware.
*/
tasklet_schedule(&ar_pci->pipe_info[ce_id].intr);
return IRQ_HANDLED;
}
static irqreturn_t ath10k_pci_msi_fw_handler(int irq, void *arg)
{
struct ath10k *ar = arg;
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
tasklet_schedule(&ar_pci->msi_fw_err);
return IRQ_HANDLED;
}
/*
* Top-level interrupt handler for all PCI interrupts from a Target.
* When a block of MSI interrupts is allocated, this top-level handler
* is not used; instead, we directly call the correct sub-handler.
*/
static irqreturn_t ath10k_pci_interrupt_handler(int irq, void *arg)
{
struct ath10k *ar = arg;
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
int ret;
if (ar_pci->pci_ps == 0) {
ret = ath10k_pci_force_wake(ar);
if (ret) {
ath10k_warn(ar, "failed to wake device up on irq: %d\n",
ret);
return IRQ_NONE;
}
}
if (ar_pci->num_msi_intrs == 0) {
if (!ath10k_pci_irq_pending(ar))
return IRQ_NONE;
ath10k_pci_disable_and_clear_legacy_irq(ar);
}
tasklet_schedule(&ar_pci->intr_tq);
return IRQ_HANDLED;
}
static void ath10k_pci_tasklet(unsigned long data)
{
struct ath10k *ar = (struct ath10k *)data;
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
if (ath10k_pci_has_fw_crashed(ar)) {
ath10k_pci_irq_disable(ar);
ath10k_pci_fw_crashed_clear(ar);
ath10k_pci_fw_crashed_dump(ar);
return;
}
ath10k_ce_per_engine_service_any(ar);
/* Re-enable legacy irq that was disabled in the irq handler */
if (ar_pci->num_msi_intrs == 0)
ath10k_pci_enable_legacy_irq(ar);
}
static int ath10k_pci_request_irq_msix(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
int ret, i;
ret = request_irq(ar_pci->pdev->irq + MSI_ASSIGN_FW,
ath10k_pci_msi_fw_handler,
IRQF_SHARED, "ath10k_pci", ar);
if (ret) {
ath10k_warn(ar, "failed to request MSI-X fw irq %d: %d\n",
ar_pci->pdev->irq + MSI_ASSIGN_FW, ret);
return ret;
}
for (i = MSI_ASSIGN_CE_INITIAL; i <= MSI_ASSIGN_CE_MAX; i++) {
ret = request_irq(ar_pci->pdev->irq + i,
ath10k_pci_per_engine_handler,
IRQF_SHARED, "ath10k_pci", ar);
if (ret) {
ath10k_warn(ar, "failed to request MSI-X ce irq %d: %d\n",
ar_pci->pdev->irq + i, ret);
for (i--; i >= MSI_ASSIGN_CE_INITIAL; i--)
free_irq(ar_pci->pdev->irq + i, ar);
free_irq(ar_pci->pdev->irq + MSI_ASSIGN_FW, ar);
return ret;
}
}
return 0;
}
static int ath10k_pci_request_irq_msi(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
int ret;
ret = request_irq(ar_pci->pdev->irq,
ath10k_pci_interrupt_handler,
IRQF_SHARED, "ath10k_pci", ar);
if (ret) {
ath10k_warn(ar, "failed to request MSI irq %d: %d\n",
ar_pci->pdev->irq, ret);
return ret;
}
return 0;
}
static int ath10k_pci_request_irq_legacy(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
int ret;
ret = request_irq(ar_pci->pdev->irq,
ath10k_pci_interrupt_handler,
IRQF_SHARED, "ath10k_pci", ar);
if (ret) {
ath10k_warn(ar, "failed to request legacy irq %d: %d\n",
ar_pci->pdev->irq, ret);
return ret;
}
return 0;
}
static int ath10k_pci_request_irq(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
switch (ar_pci->num_msi_intrs) {
case 0:
return ath10k_pci_request_irq_legacy(ar);
case 1:
return ath10k_pci_request_irq_msi(ar);
default:
return ath10k_pci_request_irq_msix(ar);
}
}
static void ath10k_pci_free_irq(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
int i;
/* There's at least one interrupt irregardless whether its legacy INTR
* or MSI or MSI-X */
for (i = 0; i < max(1, ar_pci->num_msi_intrs); i++)
free_irq(ar_pci->pdev->irq + i, ar);
}
static void ath10k_pci_init_irq_tasklets(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
int i;
tasklet_init(&ar_pci->intr_tq, ath10k_pci_tasklet, (unsigned long)ar);
tasklet_init(&ar_pci->msi_fw_err, ath10k_msi_err_tasklet,
(unsigned long)ar);
for (i = 0; i < CE_COUNT; i++) {
ar_pci->pipe_info[i].ar_pci = ar_pci;
tasklet_init(&ar_pci->pipe_info[i].intr, ath10k_pci_ce_tasklet,
(unsigned long)&ar_pci->pipe_info[i]);
}
}
static int ath10k_pci_init_irq(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
int ret;
ath10k_pci_init_irq_tasklets(ar);
if (ath10k_pci_irq_mode != ATH10K_PCI_IRQ_AUTO)
ath10k_info(ar, "limiting irq mode to: %d\n",
ath10k_pci_irq_mode);
/* Try MSI-X */
if (ath10k_pci_irq_mode == ATH10K_PCI_IRQ_AUTO) {
ar_pci->num_msi_intrs = MSI_ASSIGN_CE_MAX + 1;
ret = pci_enable_msi_range(ar_pci->pdev, ar_pci->num_msi_intrs,
ar_pci->num_msi_intrs);
if (ret > 0)
return 0;
/* fall-through */
}
/* Try MSI */
if (ath10k_pci_irq_mode != ATH10K_PCI_IRQ_LEGACY) {
ar_pci->num_msi_intrs = 1;
ret = pci_enable_msi(ar_pci->pdev);
if (ret == 0)
return 0;
/* fall-through */
}
/* Try legacy irq
*
* A potential race occurs here: The CORE_BASE write
* depends on target correctly decoding AXI address but
* host won't know when target writes BAR to CORE_CTRL.
* This write might get lost if target has NOT written BAR.
* For now, fix the race by repeating the write in below
* synchronization checking. */
ar_pci->num_msi_intrs = 0;
ath10k_pci_write32(ar, SOC_CORE_BASE_ADDRESS + PCIE_INTR_ENABLE_ADDRESS,
PCIE_INTR_FIRMWARE_MASK | PCIE_INTR_CE_MASK_ALL);
return 0;
}
static void ath10k_pci_deinit_irq_legacy(struct ath10k *ar)
{
ath10k_pci_write32(ar, SOC_CORE_BASE_ADDRESS + PCIE_INTR_ENABLE_ADDRESS,
0);
}
static int ath10k_pci_deinit_irq(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
switch (ar_pci->num_msi_intrs) {
case 0:
ath10k_pci_deinit_irq_legacy(ar);
break;
default:
pci_disable_msi(ar_pci->pdev);
break;
}
return 0;
}
static int ath10k_pci_wait_for_target_init(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
unsigned long timeout;
u32 val;
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot waiting target to initialise\n");
timeout = jiffies + msecs_to_jiffies(ATH10K_PCI_TARGET_WAIT);
do {
val = ath10k_pci_read32(ar, FW_INDICATOR_ADDRESS);
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot target indicator %x\n",
val);
/* target should never return this */
if (val == 0xffffffff)
continue;
/* the device has crashed so don't bother trying anymore */
if (val & FW_IND_EVENT_PENDING)
break;
if (val & FW_IND_INITIALIZED)
break;
if (ar_pci->num_msi_intrs == 0)
/* Fix potential race by repeating CORE_BASE writes */
ath10k_pci_enable_legacy_irq(ar);
mdelay(10);
} while (time_before(jiffies, timeout));
ath10k_pci_disable_and_clear_legacy_irq(ar);
ath10k_pci_irq_msi_fw_mask(ar);
if (val == 0xffffffff) {
ath10k_err(ar, "failed to read device register, device is gone\n");
return -EIO;
}
if (val & FW_IND_EVENT_PENDING) {
ath10k_warn(ar, "device has crashed during init\n");
return -ECOMM;
}
if (!(val & FW_IND_INITIALIZED)) {
ath10k_err(ar, "failed to receive initialized event from target: %08x\n",
val);
return -ETIMEDOUT;
}
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot target initialised\n");
return 0;
}
static int ath10k_pci_cold_reset(struct ath10k *ar)
{
u32 val;
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot cold reset\n");
spin_lock_bh(&ar->data_lock);
ar->stats.fw_cold_reset_counter++;
spin_unlock_bh(&ar->data_lock);
/* Put Target, including PCIe, into RESET. */
val = ath10k_pci_reg_read32(ar, SOC_GLOBAL_RESET_ADDRESS);
val |= 1;
ath10k_pci_reg_write32(ar, SOC_GLOBAL_RESET_ADDRESS, val);
/* After writing into SOC_GLOBAL_RESET to put device into
* reset and pulling out of reset pcie may not be stable
* for any immediate pcie register access and cause bus error,
* add delay before any pcie access request to fix this issue.
*/
msleep(20);
/* Pull Target, including PCIe, out of RESET. */
val &= ~1;
ath10k_pci_reg_write32(ar, SOC_GLOBAL_RESET_ADDRESS, val);
msleep(20);
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot cold reset complete\n");
return 0;
}
static int ath10k_pci_claim(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
struct pci_dev *pdev = ar_pci->pdev;
int ret;
pci_set_drvdata(pdev, ar);
ret = pci_enable_device(pdev);
if (ret) {
ath10k_err(ar, "failed to enable pci device: %d\n", ret);
return ret;
}
ret = pci_request_region(pdev, BAR_NUM, "ath");
if (ret) {
ath10k_err(ar, "failed to request region BAR%d: %d\n", BAR_NUM,
ret);
goto err_device;
}
/* Target expects 32 bit DMA. Enforce it. */
ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (ret) {
ath10k_err(ar, "failed to set dma mask to 32-bit: %d\n", ret);
goto err_region;
}
ret = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
if (ret) {
ath10k_err(ar, "failed to set consistent dma mask to 32-bit: %d\n",
ret);
goto err_region;
}
pci_set_master(pdev);
/* Arrange for access to Target SoC registers. */
ar_pci->mem_len = pci_resource_len(pdev, BAR_NUM);
ar_pci->mem = pci_iomap(pdev, BAR_NUM, 0);
if (!ar_pci->mem) {
ath10k_err(ar, "failed to iomap BAR%d\n", BAR_NUM);
ret = -EIO;
goto err_master;
}
ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot pci_mem 0x%p\n", ar_pci->mem);
return 0;
err_master:
pci_clear_master(pdev);
err_region:
pci_release_region(pdev, BAR_NUM);
err_device:
pci_disable_device(pdev);
return ret;
}
static void ath10k_pci_release(struct ath10k *ar)
{
struct ath10k_pci *ar_pci = ath10k_pci_priv(ar);
struct pci_dev *pdev = ar_pci->pdev;
pci_iounmap(pdev, ar_pci->mem);
pci_release_region(pdev, BAR_NUM);
pci_clear_master(pdev);
pci_disable_device(pdev);
}
static bool ath10k_pci_chip_is_supported(u32 dev_id, u32 chip_id)
{
const struct ath10k_pci_supp_chip *supp_chip;
int i;
u32 rev_id = MS(chip_id, SOC_CHIP_ID_REV);
for (i = 0; i < ARRAY_SIZE(ath10k_pci_supp_chips); i++) {
supp_chip = &ath10k_pci_supp_chips[i];
if (supp_chip->dev_id == dev_id &&
supp_chip->rev_id == rev_id)
return true;
}
return false;
}
static int ath10k_pci_probe(struct pci_dev *pdev,
const struct pci_device_id *pci_dev)
{
int ret = 0;
struct ath10k *ar;
struct ath10k_pci *ar_pci;
enum ath10k_hw_rev hw_rev;
u32 chip_id;
bool pci_ps;
switch (pci_dev->device) {
case QCA988X_2_0_DEVICE_ID:
hw_rev = ATH10K_HW_QCA988X;
pci_ps = false;
break;
case QCA6164_2_1_DEVICE_ID:
case QCA6174_2_1_DEVICE_ID:
hw_rev = ATH10K_HW_QCA6174;
pci_ps = true;
break;
case QCA99X0_2_0_DEVICE_ID:
hw_rev = ATH10K_HW_QCA99X0;
pci_ps = false;
break;
case QCA9377_1_0_DEVICE_ID:
hw_rev = ATH10K_HW_QCA9377;
pci_ps = true;
break;
default:
WARN_ON(1);
return -ENOTSUPP;
}
ar = ath10k_core_create(sizeof(*ar_pci), &pdev->dev, ATH10K_BUS_PCI,
hw_rev, &ath10k_pci_hif_ops);
if (!ar) {
dev_err(&pdev->dev, "failed to allocate core\n");
return -ENOMEM;
}
ath10k_dbg(ar, ATH10K_DBG_BOOT, "pci probe %04x:%04x %04x:%04x\n",
pdev->vendor, pdev->device,
pdev->subsystem_vendor, pdev->subsystem_device);
ar_pci = ath10k_pci_priv(ar);
ar_pci->pdev = pdev;
ar_pci->dev = &pdev->dev;
ar_pci->ar = ar;
ar->dev_id = pci_dev->device;
ar_pci->pci_ps = pci_ps;
ar->id.vendor = pdev->vendor;
ar->id.device = pdev->device;
ar->id.subsystem_vendor = pdev->subsystem_vendor;
ar->id.subsystem_device = pdev->subsystem_device;
spin_lock_init(&ar_pci->ce_lock);
spin_lock_init(&ar_pci->ps_lock);
setup_timer(&ar_pci->rx_post_retry, ath10k_pci_rx_replenish_retry,
(unsigned long)ar);
setup_timer(&ar_pci->ps_timer, ath10k_pci_ps_timer,
(unsigned long)ar);
ret = ath10k_pci_claim(ar);
if (ret) {
ath10k_err(ar, "failed to claim device: %d\n", ret);
goto err_core_destroy;
}
if (QCA_REV_6174(ar))
ath10k_pci_override_ce_config(ar);
ret = ath10k_pci_alloc_pipes(ar);
if (ret) {
ath10k_err(ar, "failed to allocate copy engine pipes: %d\n",
ret);
goto err_sleep;
}
ath10k_pci_ce_deinit(ar);
ath10k_pci_irq_disable(ar);
if (ar_pci->pci_ps == 0) {
ret = ath10k_pci_force_wake(ar);
if (ret) {
ath10k_warn(ar, "failed to wake up device : %d\n", ret);
goto err_free_pipes;
}
}
ret = ath10k_pci_init_irq(ar);
if (ret) {
ath10k_err(ar, "failed to init irqs: %d\n", ret);
goto err_free_pipes;
}
ath10k_info(ar, "pci irq %s interrupts %d irq_mode %d reset_mode %d\n",
ath10k_pci_get_irq_method(ar), ar_pci->num_msi_intrs,
ath10k_pci_irq_mode, ath10k_pci_reset_mode);
ret = ath10k_pci_request_irq(ar);
if (ret) {
ath10k_warn(ar, "failed to request irqs: %d\n", ret);
goto err_deinit_irq;
}
ret = ath10k_pci_chip_reset(ar);
if (ret) {
ath10k_err(ar, "failed to reset chip: %d\n", ret);
goto err_free_irq;
}
chip_id = ath10k_pci_soc_read32(ar, SOC_CHIP_ID_ADDRESS);
if (chip_id == 0xffffffff) {
ath10k_err(ar, "failed to get chip id\n");
goto err_free_irq;
}
if (!ath10k_pci_chip_is_supported(pdev->device, chip_id)) {
ath10k_err(ar, "device %04x with chip_id %08x isn't supported\n",
pdev->device, chip_id);
goto err_free_irq;
}
ret = ath10k_core_register(ar, chip_id);
if (ret) {
ath10k_err(ar, "failed to register driver core: %d\n", ret);
goto err_free_irq;
}
return 0;
err_free_irq:
ath10k_pci_free_irq(ar);
ath10k_pci_kill_tasklet(ar);
err_deinit_irq:
ath10k_pci_deinit_irq(ar);
err_free_pipes:
ath10k_pci_free_pipes(ar);
err_sleep:
ath10k_pci_sleep_sync(ar);
ath10k_pci_release(ar);
err_core_destroy:
ath10k_core_destroy(ar);
return ret;
}
static void ath10k_pci_remove(struct pci_dev *pdev)
{
struct ath10k *ar = pci_get_drvdata(pdev);
struct ath10k_pci *ar_pci;
ath10k_dbg(ar, ATH10K_DBG_PCI, "pci remove\n");
if (!ar)
return;
ar_pci = ath10k_pci_priv(ar);
if (!ar_pci)
return;
ath10k_core_unregister(ar);
ath10k_pci_free_irq(ar);
ath10k_pci_kill_tasklet(ar);
ath10k_pci_deinit_irq(ar);
ath10k_pci_ce_deinit(ar);
ath10k_pci_free_pipes(ar);
ath10k_pci_sleep_sync(ar);
ath10k_pci_release(ar);
ath10k_core_destroy(ar);
}
MODULE_DEVICE_TABLE(pci, ath10k_pci_id_table);
static struct pci_driver ath10k_pci_driver = {
.name = "ath10k_pci",
.id_table = ath10k_pci_id_table,
.probe = ath10k_pci_probe,
.remove = ath10k_pci_remove,
};
static int __init ath10k_pci_init(void)
{
int ret;
ret = pci_register_driver(&ath10k_pci_driver);
if (ret)
printk(KERN_ERR "failed to register ath10k pci driver: %d\n",
ret);
return ret;
}
module_init(ath10k_pci_init);
static void __exit ath10k_pci_exit(void)
{
pci_unregister_driver(&ath10k_pci_driver);
}
module_exit(ath10k_pci_exit);
MODULE_AUTHOR("Qualcomm Atheros");
MODULE_DESCRIPTION("Driver support for Atheros QCA988X PCIe devices");
MODULE_LICENSE("Dual BSD/GPL");
/* QCA988x 2.0 firmware files */
MODULE_FIRMWARE(QCA988X_HW_2_0_FW_DIR "/" QCA988X_HW_2_0_FW_FILE);
MODULE_FIRMWARE(QCA988X_HW_2_0_FW_DIR "/" ATH10K_FW_API2_FILE);
MODULE_FIRMWARE(QCA988X_HW_2_0_FW_DIR "/" ATH10K_FW_API3_FILE);
MODULE_FIRMWARE(QCA988X_HW_2_0_FW_DIR "/" ATH10K_FW_API4_FILE);
MODULE_FIRMWARE(QCA988X_HW_2_0_FW_DIR "/" ATH10K_FW_API5_FILE);
MODULE_FIRMWARE(QCA988X_HW_2_0_FW_DIR "/" QCA988X_HW_2_0_BOARD_DATA_FILE);
MODULE_FIRMWARE(QCA988X_HW_2_0_FW_DIR "/" ATH10K_BOARD_API2_FILE);
/* QCA6174 2.1 firmware files */
MODULE_FIRMWARE(QCA6174_HW_2_1_FW_DIR "/" ATH10K_FW_API4_FILE);
MODULE_FIRMWARE(QCA6174_HW_2_1_FW_DIR "/" ATH10K_FW_API5_FILE);
MODULE_FIRMWARE(QCA6174_HW_2_1_FW_DIR "/" QCA6174_HW_2_1_BOARD_DATA_FILE);
MODULE_FIRMWARE(QCA6174_HW_2_1_FW_DIR "/" ATH10K_BOARD_API2_FILE);
/* QCA6174 3.1 firmware files */
MODULE_FIRMWARE(QCA6174_HW_3_0_FW_DIR "/" ATH10K_FW_API4_FILE);
MODULE_FIRMWARE(QCA6174_HW_3_0_FW_DIR "/" ATH10K_FW_API5_FILE);
MODULE_FIRMWARE(QCA6174_HW_3_0_FW_DIR "/" QCA6174_HW_3_0_BOARD_DATA_FILE);
MODULE_FIRMWARE(QCA6174_HW_3_0_FW_DIR "/" ATH10K_BOARD_API2_FILE);
/* QCA9377 1.0 firmware files */
MODULE_FIRMWARE(QCA9377_HW_1_0_FW_DIR "/" ATH10K_FW_API5_FILE);
MODULE_FIRMWARE(QCA9377_HW_1_0_FW_DIR "/" QCA9377_HW_1_0_BOARD_DATA_FILE);
| gpl-2.0 |
TeamEpsilon/linux-3.8 | drivers/net/ethernet/intel/igbvf/netdev.c | 101 | 79370 | /*******************************************************************************
Intel(R) 82576 Virtual Function Linux driver
Copyright(c) 2009 - 2012 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/vmalloc.h>
#include <linux/pagemap.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/tcp.h>
#include <linux/ipv6.h>
#include <linux/slab.h>
#include <net/checksum.h>
#include <net/ip6_checksum.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/if_vlan.h>
#include <linux/prefetch.h>
#include "igbvf.h"
#define DRV_VERSION "2.0.2-k"
char igbvf_driver_name[] = "igbvf";
const char igbvf_driver_version[] = DRV_VERSION;
static const char igbvf_driver_string[] =
"Intel(R) Gigabit Virtual Function Network Driver";
static const char igbvf_copyright[] =
"Copyright (c) 2009 - 2012 Intel Corporation.";
#define DEFAULT_MSG_ENABLE (NETIF_MSG_DRV|NETIF_MSG_PROBE|NETIF_MSG_LINK)
static int debug = -1;
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)");
static int igbvf_poll(struct napi_struct *napi, int budget);
static void igbvf_reset(struct igbvf_adapter *);
static void igbvf_set_interrupt_capability(struct igbvf_adapter *);
static void igbvf_reset_interrupt_capability(struct igbvf_adapter *);
static struct igbvf_info igbvf_vf_info = {
.mac = e1000_vfadapt,
.flags = 0,
.pba = 10,
.init_ops = e1000_init_function_pointers_vf,
};
static struct igbvf_info igbvf_i350_vf_info = {
.mac = e1000_vfadapt_i350,
.flags = 0,
.pba = 10,
.init_ops = e1000_init_function_pointers_vf,
};
static const struct igbvf_info *igbvf_info_tbl[] = {
[board_vf] = &igbvf_vf_info,
[board_i350_vf] = &igbvf_i350_vf_info,
};
/**
* igbvf_desc_unused - calculate if we have unused descriptors
**/
static int igbvf_desc_unused(struct igbvf_ring *ring)
{
if (ring->next_to_clean > ring->next_to_use)
return ring->next_to_clean - ring->next_to_use - 1;
return ring->count + ring->next_to_clean - ring->next_to_use - 1;
}
/**
* igbvf_receive_skb - helper function to handle Rx indications
* @adapter: board private structure
* @status: descriptor status field as written by hardware
* @vlan: descriptor vlan field as written by hardware (no le/be conversion)
* @skb: pointer to sk_buff to be indicated to stack
**/
static void igbvf_receive_skb(struct igbvf_adapter *adapter,
struct net_device *netdev,
struct sk_buff *skb,
u32 status, u16 vlan)
{
u16 vid;
if (status & E1000_RXD_STAT_VP) {
if ((adapter->flags & IGBVF_FLAG_RX_LB_VLAN_BSWAP) &&
(status & E1000_RXDEXT_STATERR_LB))
vid = be16_to_cpu(vlan) & E1000_RXD_SPC_VLAN_MASK;
else
vid = le16_to_cpu(vlan) & E1000_RXD_SPC_VLAN_MASK;
if (test_bit(vid, adapter->active_vlans))
__vlan_hwaccel_put_tag(skb, vid);
}
napi_gro_receive(&adapter->rx_ring->napi, skb);
}
static inline void igbvf_rx_checksum_adv(struct igbvf_adapter *adapter,
u32 status_err, struct sk_buff *skb)
{
skb_checksum_none_assert(skb);
/* Ignore Checksum bit is set or checksum is disabled through ethtool */
if ((status_err & E1000_RXD_STAT_IXSM) ||
(adapter->flags & IGBVF_FLAG_RX_CSUM_DISABLED))
return;
/* TCP/UDP checksum error bit is set */
if (status_err &
(E1000_RXDEXT_STATERR_TCPE | E1000_RXDEXT_STATERR_IPE)) {
/* let the stack verify checksum errors */
adapter->hw_csum_err++;
return;
}
/* It must be a TCP or UDP packet with a valid checksum */
if (status_err & (E1000_RXD_STAT_TCPCS | E1000_RXD_STAT_UDPCS))
skb->ip_summed = CHECKSUM_UNNECESSARY;
adapter->hw_csum_good++;
}
/**
* igbvf_alloc_rx_buffers - Replace used receive buffers; packet split
* @rx_ring: address of ring structure to repopulate
* @cleaned_count: number of buffers to repopulate
**/
static void igbvf_alloc_rx_buffers(struct igbvf_ring *rx_ring,
int cleaned_count)
{
struct igbvf_adapter *adapter = rx_ring->adapter;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
union e1000_adv_rx_desc *rx_desc;
struct igbvf_buffer *buffer_info;
struct sk_buff *skb;
unsigned int i;
int bufsz;
i = rx_ring->next_to_use;
buffer_info = &rx_ring->buffer_info[i];
if (adapter->rx_ps_hdr_size)
bufsz = adapter->rx_ps_hdr_size;
else
bufsz = adapter->rx_buffer_len;
while (cleaned_count--) {
rx_desc = IGBVF_RX_DESC_ADV(*rx_ring, i);
if (adapter->rx_ps_hdr_size && !buffer_info->page_dma) {
if (!buffer_info->page) {
buffer_info->page = alloc_page(GFP_ATOMIC);
if (!buffer_info->page) {
adapter->alloc_rx_buff_failed++;
goto no_buffers;
}
buffer_info->page_offset = 0;
} else {
buffer_info->page_offset ^= PAGE_SIZE / 2;
}
buffer_info->page_dma =
dma_map_page(&pdev->dev, buffer_info->page,
buffer_info->page_offset,
PAGE_SIZE / 2,
DMA_FROM_DEVICE);
if (dma_mapping_error(&pdev->dev,
buffer_info->page_dma)) {
__free_page(buffer_info->page);
buffer_info->page = NULL;
dev_err(&pdev->dev, "RX DMA map failed\n");
break;
}
}
if (!buffer_info->skb) {
skb = netdev_alloc_skb_ip_align(netdev, bufsz);
if (!skb) {
adapter->alloc_rx_buff_failed++;
goto no_buffers;
}
buffer_info->skb = skb;
buffer_info->dma = dma_map_single(&pdev->dev, skb->data,
bufsz,
DMA_FROM_DEVICE);
if (dma_mapping_error(&pdev->dev, buffer_info->dma)) {
dev_kfree_skb(buffer_info->skb);
buffer_info->skb = NULL;
dev_err(&pdev->dev, "RX DMA map failed\n");
goto no_buffers;
}
}
/* Refresh the desc even if buffer_addrs didn't change because
* each write-back erases this info. */
if (adapter->rx_ps_hdr_size) {
rx_desc->read.pkt_addr =
cpu_to_le64(buffer_info->page_dma);
rx_desc->read.hdr_addr = cpu_to_le64(buffer_info->dma);
} else {
rx_desc->read.pkt_addr =
cpu_to_le64(buffer_info->dma);
rx_desc->read.hdr_addr = 0;
}
i++;
if (i == rx_ring->count)
i = 0;
buffer_info = &rx_ring->buffer_info[i];
}
no_buffers:
if (rx_ring->next_to_use != i) {
rx_ring->next_to_use = i;
if (i == 0)
i = (rx_ring->count - 1);
else
i--;
/* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64). */
wmb();
writel(i, adapter->hw.hw_addr + rx_ring->tail);
}
}
/**
* igbvf_clean_rx_irq - Send received data up the network stack; legacy
* @adapter: board private structure
*
* the return value indicates whether actual cleaning was done, there
* is no guarantee that everything was cleaned
**/
static bool igbvf_clean_rx_irq(struct igbvf_adapter *adapter,
int *work_done, int work_to_do)
{
struct igbvf_ring *rx_ring = adapter->rx_ring;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
union e1000_adv_rx_desc *rx_desc, *next_rxd;
struct igbvf_buffer *buffer_info, *next_buffer;
struct sk_buff *skb;
bool cleaned = false;
int cleaned_count = 0;
unsigned int total_bytes = 0, total_packets = 0;
unsigned int i;
u32 length, hlen, staterr;
i = rx_ring->next_to_clean;
rx_desc = IGBVF_RX_DESC_ADV(*rx_ring, i);
staterr = le32_to_cpu(rx_desc->wb.upper.status_error);
while (staterr & E1000_RXD_STAT_DD) {
if (*work_done >= work_to_do)
break;
(*work_done)++;
rmb(); /* read descriptor and rx_buffer_info after status DD */
buffer_info = &rx_ring->buffer_info[i];
/* HW will not DMA in data larger than the given buffer, even
* if it parses the (NFS, of course) header to be larger. In
* that case, it fills the header buffer and spills the rest
* into the page.
*/
hlen = (le16_to_cpu(rx_desc->wb.lower.lo_dword.hs_rss.hdr_info) &
E1000_RXDADV_HDRBUFLEN_MASK) >> E1000_RXDADV_HDRBUFLEN_SHIFT;
if (hlen > adapter->rx_ps_hdr_size)
hlen = adapter->rx_ps_hdr_size;
length = le16_to_cpu(rx_desc->wb.upper.length);
cleaned = true;
cleaned_count++;
skb = buffer_info->skb;
prefetch(skb->data - NET_IP_ALIGN);
buffer_info->skb = NULL;
if (!adapter->rx_ps_hdr_size) {
dma_unmap_single(&pdev->dev, buffer_info->dma,
adapter->rx_buffer_len,
DMA_FROM_DEVICE);
buffer_info->dma = 0;
skb_put(skb, length);
goto send_up;
}
if (!skb_shinfo(skb)->nr_frags) {
dma_unmap_single(&pdev->dev, buffer_info->dma,
adapter->rx_ps_hdr_size,
DMA_FROM_DEVICE);
skb_put(skb, hlen);
}
if (length) {
dma_unmap_page(&pdev->dev, buffer_info->page_dma,
PAGE_SIZE / 2,
DMA_FROM_DEVICE);
buffer_info->page_dma = 0;
skb_fill_page_desc(skb, skb_shinfo(skb)->nr_frags,
buffer_info->page,
buffer_info->page_offset,
length);
if ((adapter->rx_buffer_len > (PAGE_SIZE / 2)) ||
(page_count(buffer_info->page) != 1))
buffer_info->page = NULL;
else
get_page(buffer_info->page);
skb->len += length;
skb->data_len += length;
skb->truesize += PAGE_SIZE / 2;
}
send_up:
i++;
if (i == rx_ring->count)
i = 0;
next_rxd = IGBVF_RX_DESC_ADV(*rx_ring, i);
prefetch(next_rxd);
next_buffer = &rx_ring->buffer_info[i];
if (!(staterr & E1000_RXD_STAT_EOP)) {
buffer_info->skb = next_buffer->skb;
buffer_info->dma = next_buffer->dma;
next_buffer->skb = skb;
next_buffer->dma = 0;
goto next_desc;
}
if (staterr & E1000_RXDEXT_ERR_FRAME_ERR_MASK) {
dev_kfree_skb_irq(skb);
goto next_desc;
}
total_bytes += skb->len;
total_packets++;
igbvf_rx_checksum_adv(adapter, staterr, skb);
skb->protocol = eth_type_trans(skb, netdev);
igbvf_receive_skb(adapter, netdev, skb, staterr,
rx_desc->wb.upper.vlan);
next_desc:
rx_desc->wb.upper.status_error = 0;
/* return some buffers to hardware, one at a time is too slow */
if (cleaned_count >= IGBVF_RX_BUFFER_WRITE) {
igbvf_alloc_rx_buffers(rx_ring, cleaned_count);
cleaned_count = 0;
}
/* use prefetched values */
rx_desc = next_rxd;
buffer_info = next_buffer;
staterr = le32_to_cpu(rx_desc->wb.upper.status_error);
}
rx_ring->next_to_clean = i;
cleaned_count = igbvf_desc_unused(rx_ring);
if (cleaned_count)
igbvf_alloc_rx_buffers(rx_ring, cleaned_count);
adapter->total_rx_packets += total_packets;
adapter->total_rx_bytes += total_bytes;
adapter->net_stats.rx_bytes += total_bytes;
adapter->net_stats.rx_packets += total_packets;
return cleaned;
}
static void igbvf_put_txbuf(struct igbvf_adapter *adapter,
struct igbvf_buffer *buffer_info)
{
if (buffer_info->dma) {
if (buffer_info->mapped_as_page)
dma_unmap_page(&adapter->pdev->dev,
buffer_info->dma,
buffer_info->length,
DMA_TO_DEVICE);
else
dma_unmap_single(&adapter->pdev->dev,
buffer_info->dma,
buffer_info->length,
DMA_TO_DEVICE);
buffer_info->dma = 0;
}
if (buffer_info->skb) {
dev_kfree_skb_any(buffer_info->skb);
buffer_info->skb = NULL;
}
buffer_info->time_stamp = 0;
}
/**
* igbvf_setup_tx_resources - allocate Tx resources (Descriptors)
* @adapter: board private structure
*
* Return 0 on success, negative on failure
**/
int igbvf_setup_tx_resources(struct igbvf_adapter *adapter,
struct igbvf_ring *tx_ring)
{
struct pci_dev *pdev = adapter->pdev;
int size;
size = sizeof(struct igbvf_buffer) * tx_ring->count;
tx_ring->buffer_info = vzalloc(size);
if (!tx_ring->buffer_info)
goto err;
/* round up to nearest 4K */
tx_ring->size = tx_ring->count * sizeof(union e1000_adv_tx_desc);
tx_ring->size = ALIGN(tx_ring->size, 4096);
tx_ring->desc = dma_alloc_coherent(&pdev->dev, tx_ring->size,
&tx_ring->dma, GFP_KERNEL);
if (!tx_ring->desc)
goto err;
tx_ring->adapter = adapter;
tx_ring->next_to_use = 0;
tx_ring->next_to_clean = 0;
return 0;
err:
vfree(tx_ring->buffer_info);
dev_err(&adapter->pdev->dev,
"Unable to allocate memory for the transmit descriptor ring\n");
return -ENOMEM;
}
/**
* igbvf_setup_rx_resources - allocate Rx resources (Descriptors)
* @adapter: board private structure
*
* Returns 0 on success, negative on failure
**/
int igbvf_setup_rx_resources(struct igbvf_adapter *adapter,
struct igbvf_ring *rx_ring)
{
struct pci_dev *pdev = adapter->pdev;
int size, desc_len;
size = sizeof(struct igbvf_buffer) * rx_ring->count;
rx_ring->buffer_info = vzalloc(size);
if (!rx_ring->buffer_info)
goto err;
desc_len = sizeof(union e1000_adv_rx_desc);
/* Round up to nearest 4K */
rx_ring->size = rx_ring->count * desc_len;
rx_ring->size = ALIGN(rx_ring->size, 4096);
rx_ring->desc = dma_alloc_coherent(&pdev->dev, rx_ring->size,
&rx_ring->dma, GFP_KERNEL);
if (!rx_ring->desc)
goto err;
rx_ring->next_to_clean = 0;
rx_ring->next_to_use = 0;
rx_ring->adapter = adapter;
return 0;
err:
vfree(rx_ring->buffer_info);
rx_ring->buffer_info = NULL;
dev_err(&adapter->pdev->dev,
"Unable to allocate memory for the receive descriptor ring\n");
return -ENOMEM;
}
/**
* igbvf_clean_tx_ring - Free Tx Buffers
* @tx_ring: ring to be cleaned
**/
static void igbvf_clean_tx_ring(struct igbvf_ring *tx_ring)
{
struct igbvf_adapter *adapter = tx_ring->adapter;
struct igbvf_buffer *buffer_info;
unsigned long size;
unsigned int i;
if (!tx_ring->buffer_info)
return;
/* Free all the Tx ring sk_buffs */
for (i = 0; i < tx_ring->count; i++) {
buffer_info = &tx_ring->buffer_info[i];
igbvf_put_txbuf(adapter, buffer_info);
}
size = sizeof(struct igbvf_buffer) * tx_ring->count;
memset(tx_ring->buffer_info, 0, size);
/* Zero out the descriptor ring */
memset(tx_ring->desc, 0, tx_ring->size);
tx_ring->next_to_use = 0;
tx_ring->next_to_clean = 0;
writel(0, adapter->hw.hw_addr + tx_ring->head);
writel(0, adapter->hw.hw_addr + tx_ring->tail);
}
/**
* igbvf_free_tx_resources - Free Tx Resources per Queue
* @tx_ring: ring to free resources from
*
* Free all transmit software resources
**/
void igbvf_free_tx_resources(struct igbvf_ring *tx_ring)
{
struct pci_dev *pdev = tx_ring->adapter->pdev;
igbvf_clean_tx_ring(tx_ring);
vfree(tx_ring->buffer_info);
tx_ring->buffer_info = NULL;
dma_free_coherent(&pdev->dev, tx_ring->size, tx_ring->desc,
tx_ring->dma);
tx_ring->desc = NULL;
}
/**
* igbvf_clean_rx_ring - Free Rx Buffers per Queue
* @adapter: board private structure
**/
static void igbvf_clean_rx_ring(struct igbvf_ring *rx_ring)
{
struct igbvf_adapter *adapter = rx_ring->adapter;
struct igbvf_buffer *buffer_info;
struct pci_dev *pdev = adapter->pdev;
unsigned long size;
unsigned int i;
if (!rx_ring->buffer_info)
return;
/* Free all the Rx ring sk_buffs */
for (i = 0; i < rx_ring->count; i++) {
buffer_info = &rx_ring->buffer_info[i];
if (buffer_info->dma) {
if (adapter->rx_ps_hdr_size){
dma_unmap_single(&pdev->dev, buffer_info->dma,
adapter->rx_ps_hdr_size,
DMA_FROM_DEVICE);
} else {
dma_unmap_single(&pdev->dev, buffer_info->dma,
adapter->rx_buffer_len,
DMA_FROM_DEVICE);
}
buffer_info->dma = 0;
}
if (buffer_info->skb) {
dev_kfree_skb(buffer_info->skb);
buffer_info->skb = NULL;
}
if (buffer_info->page) {
if (buffer_info->page_dma)
dma_unmap_page(&pdev->dev,
buffer_info->page_dma,
PAGE_SIZE / 2,
DMA_FROM_DEVICE);
put_page(buffer_info->page);
buffer_info->page = NULL;
buffer_info->page_dma = 0;
buffer_info->page_offset = 0;
}
}
size = sizeof(struct igbvf_buffer) * rx_ring->count;
memset(rx_ring->buffer_info, 0, size);
/* Zero out the descriptor ring */
memset(rx_ring->desc, 0, rx_ring->size);
rx_ring->next_to_clean = 0;
rx_ring->next_to_use = 0;
writel(0, adapter->hw.hw_addr + rx_ring->head);
writel(0, adapter->hw.hw_addr + rx_ring->tail);
}
/**
* igbvf_free_rx_resources - Free Rx Resources
* @rx_ring: ring to clean the resources from
*
* Free all receive software resources
**/
void igbvf_free_rx_resources(struct igbvf_ring *rx_ring)
{
struct pci_dev *pdev = rx_ring->adapter->pdev;
igbvf_clean_rx_ring(rx_ring);
vfree(rx_ring->buffer_info);
rx_ring->buffer_info = NULL;
dma_free_coherent(&pdev->dev, rx_ring->size, rx_ring->desc,
rx_ring->dma);
rx_ring->desc = NULL;
}
/**
* igbvf_update_itr - update the dynamic ITR value based on statistics
* @adapter: pointer to adapter
* @itr_setting: current adapter->itr
* @packets: the number of packets during this measurement interval
* @bytes: the number of bytes during this measurement interval
*
* Stores a new ITR value based on packets and byte
* counts during the last interrupt. The advantage of per interrupt
* computation is faster updates and more accurate ITR for the current
* traffic pattern. Constants in this function were computed
* based on theoretical maximum wire speed and thresholds were set based
* on testing data as well as attempting to minimize response time
* while increasing bulk throughput.
**/
static enum latency_range igbvf_update_itr(struct igbvf_adapter *adapter,
enum latency_range itr_setting,
int packets, int bytes)
{
enum latency_range retval = itr_setting;
if (packets == 0)
goto update_itr_done;
switch (itr_setting) {
case lowest_latency:
/* handle TSO and jumbo frames */
if (bytes/packets > 8000)
retval = bulk_latency;
else if ((packets < 5) && (bytes > 512))
retval = low_latency;
break;
case low_latency: /* 50 usec aka 20000 ints/s */
if (bytes > 10000) {
/* this if handles the TSO accounting */
if (bytes/packets > 8000)
retval = bulk_latency;
else if ((packets < 10) || ((bytes/packets) > 1200))
retval = bulk_latency;
else if ((packets > 35))
retval = lowest_latency;
} else if (bytes/packets > 2000) {
retval = bulk_latency;
} else if (packets <= 2 && bytes < 512) {
retval = lowest_latency;
}
break;
case bulk_latency: /* 250 usec aka 4000 ints/s */
if (bytes > 25000) {
if (packets > 35)
retval = low_latency;
} else if (bytes < 6000) {
retval = low_latency;
}
break;
default:
break;
}
update_itr_done:
return retval;
}
static int igbvf_range_to_itr(enum latency_range current_range)
{
int new_itr;
switch (current_range) {
/* counts and packets in update_itr are dependent on these numbers */
case lowest_latency:
new_itr = IGBVF_70K_ITR;
break;
case low_latency:
new_itr = IGBVF_20K_ITR;
break;
case bulk_latency:
new_itr = IGBVF_4K_ITR;
break;
default:
new_itr = IGBVF_START_ITR;
break;
}
return new_itr;
}
static void igbvf_set_itr(struct igbvf_adapter *adapter)
{
u32 new_itr;
adapter->tx_ring->itr_range =
igbvf_update_itr(adapter,
adapter->tx_ring->itr_val,
adapter->total_tx_packets,
adapter->total_tx_bytes);
/* conservative mode (itr 3) eliminates the lowest_latency setting */
if (adapter->requested_itr == 3 &&
adapter->tx_ring->itr_range == lowest_latency)
adapter->tx_ring->itr_range = low_latency;
new_itr = igbvf_range_to_itr(adapter->tx_ring->itr_range);
if (new_itr != adapter->tx_ring->itr_val) {
u32 current_itr = adapter->tx_ring->itr_val;
/*
* this attempts to bias the interrupt rate towards Bulk
* by adding intermediate steps when interrupt rate is
* increasing
*/
new_itr = new_itr > current_itr ?
min(current_itr + (new_itr >> 2), new_itr) :
new_itr;
adapter->tx_ring->itr_val = new_itr;
adapter->tx_ring->set_itr = 1;
}
adapter->rx_ring->itr_range =
igbvf_update_itr(adapter, adapter->rx_ring->itr_val,
adapter->total_rx_packets,
adapter->total_rx_bytes);
if (adapter->requested_itr == 3 &&
adapter->rx_ring->itr_range == lowest_latency)
adapter->rx_ring->itr_range = low_latency;
new_itr = igbvf_range_to_itr(adapter->rx_ring->itr_range);
if (new_itr != adapter->rx_ring->itr_val) {
u32 current_itr = adapter->rx_ring->itr_val;
new_itr = new_itr > current_itr ?
min(current_itr + (new_itr >> 2), new_itr) :
new_itr;
adapter->rx_ring->itr_val = new_itr;
adapter->rx_ring->set_itr = 1;
}
}
/**
* igbvf_clean_tx_irq - Reclaim resources after transmit completes
* @adapter: board private structure
*
* returns true if ring is completely cleaned
**/
static bool igbvf_clean_tx_irq(struct igbvf_ring *tx_ring)
{
struct igbvf_adapter *adapter = tx_ring->adapter;
struct net_device *netdev = adapter->netdev;
struct igbvf_buffer *buffer_info;
struct sk_buff *skb;
union e1000_adv_tx_desc *tx_desc, *eop_desc;
unsigned int total_bytes = 0, total_packets = 0;
unsigned int i, eop, count = 0;
bool cleaned = false;
i = tx_ring->next_to_clean;
eop = tx_ring->buffer_info[i].next_to_watch;
eop_desc = IGBVF_TX_DESC_ADV(*tx_ring, eop);
while ((eop_desc->wb.status & cpu_to_le32(E1000_TXD_STAT_DD)) &&
(count < tx_ring->count)) {
rmb(); /* read buffer_info after eop_desc status */
for (cleaned = false; !cleaned; count++) {
tx_desc = IGBVF_TX_DESC_ADV(*tx_ring, i);
buffer_info = &tx_ring->buffer_info[i];
cleaned = (i == eop);
skb = buffer_info->skb;
if (skb) {
unsigned int segs, bytecount;
/* gso_segs is currently only valid for tcp */
segs = skb_shinfo(skb)->gso_segs ?: 1;
/* multiply data chunks by size of headers */
bytecount = ((segs - 1) * skb_headlen(skb)) +
skb->len;
total_packets += segs;
total_bytes += bytecount;
}
igbvf_put_txbuf(adapter, buffer_info);
tx_desc->wb.status = 0;
i++;
if (i == tx_ring->count)
i = 0;
}
eop = tx_ring->buffer_info[i].next_to_watch;
eop_desc = IGBVF_TX_DESC_ADV(*tx_ring, eop);
}
tx_ring->next_to_clean = i;
if (unlikely(count &&
netif_carrier_ok(netdev) &&
igbvf_desc_unused(tx_ring) >= IGBVF_TX_QUEUE_WAKE)) {
/* Make sure that anybody stopping the queue after this
* sees the new next_to_clean.
*/
smp_mb();
if (netif_queue_stopped(netdev) &&
!(test_bit(__IGBVF_DOWN, &adapter->state))) {
netif_wake_queue(netdev);
++adapter->restart_queue;
}
}
adapter->net_stats.tx_bytes += total_bytes;
adapter->net_stats.tx_packets += total_packets;
return count < tx_ring->count;
}
static irqreturn_t igbvf_msix_other(int irq, void *data)
{
struct net_device *netdev = data;
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
adapter->int_counter1++;
netif_carrier_off(netdev);
hw->mac.get_link_status = 1;
if (!test_bit(__IGBVF_DOWN, &adapter->state))
mod_timer(&adapter->watchdog_timer, jiffies + 1);
ew32(EIMS, adapter->eims_other);
return IRQ_HANDLED;
}
static irqreturn_t igbvf_intr_msix_tx(int irq, void *data)
{
struct net_device *netdev = data;
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
struct igbvf_ring *tx_ring = adapter->tx_ring;
if (tx_ring->set_itr) {
writel(tx_ring->itr_val,
adapter->hw.hw_addr + tx_ring->itr_register);
adapter->tx_ring->set_itr = 0;
}
adapter->total_tx_bytes = 0;
adapter->total_tx_packets = 0;
/* auto mask will automatically reenable the interrupt when we write
* EICS */
if (!igbvf_clean_tx_irq(tx_ring))
/* Ring was not completely cleaned, so fire another interrupt */
ew32(EICS, tx_ring->eims_value);
else
ew32(EIMS, tx_ring->eims_value);
return IRQ_HANDLED;
}
static irqreturn_t igbvf_intr_msix_rx(int irq, void *data)
{
struct net_device *netdev = data;
struct igbvf_adapter *adapter = netdev_priv(netdev);
adapter->int_counter0++;
/* Write the ITR value calculated at the end of the
* previous interrupt.
*/
if (adapter->rx_ring->set_itr) {
writel(adapter->rx_ring->itr_val,
adapter->hw.hw_addr + adapter->rx_ring->itr_register);
adapter->rx_ring->set_itr = 0;
}
if (napi_schedule_prep(&adapter->rx_ring->napi)) {
adapter->total_rx_bytes = 0;
adapter->total_rx_packets = 0;
__napi_schedule(&adapter->rx_ring->napi);
}
return IRQ_HANDLED;
}
#define IGBVF_NO_QUEUE -1
static void igbvf_assign_vector(struct igbvf_adapter *adapter, int rx_queue,
int tx_queue, int msix_vector)
{
struct e1000_hw *hw = &adapter->hw;
u32 ivar, index;
/* 82576 uses a table-based method for assigning vectors.
Each queue has a single entry in the table to which we write
a vector number along with a "valid" bit. Sadly, the layout
of the table is somewhat counterintuitive. */
if (rx_queue > IGBVF_NO_QUEUE) {
index = (rx_queue >> 1);
ivar = array_er32(IVAR0, index);
if (rx_queue & 0x1) {
/* vector goes into third byte of register */
ivar = ivar & 0xFF00FFFF;
ivar |= (msix_vector | E1000_IVAR_VALID) << 16;
} else {
/* vector goes into low byte of register */
ivar = ivar & 0xFFFFFF00;
ivar |= msix_vector | E1000_IVAR_VALID;
}
adapter->rx_ring[rx_queue].eims_value = 1 << msix_vector;
array_ew32(IVAR0, index, ivar);
}
if (tx_queue > IGBVF_NO_QUEUE) {
index = (tx_queue >> 1);
ivar = array_er32(IVAR0, index);
if (tx_queue & 0x1) {
/* vector goes into high byte of register */
ivar = ivar & 0x00FFFFFF;
ivar |= (msix_vector | E1000_IVAR_VALID) << 24;
} else {
/* vector goes into second byte of register */
ivar = ivar & 0xFFFF00FF;
ivar |= (msix_vector | E1000_IVAR_VALID) << 8;
}
adapter->tx_ring[tx_queue].eims_value = 1 << msix_vector;
array_ew32(IVAR0, index, ivar);
}
}
/**
* igbvf_configure_msix - Configure MSI-X hardware
*
* igbvf_configure_msix sets up the hardware to properly
* generate MSI-X interrupts.
**/
static void igbvf_configure_msix(struct igbvf_adapter *adapter)
{
u32 tmp;
struct e1000_hw *hw = &adapter->hw;
struct igbvf_ring *tx_ring = adapter->tx_ring;
struct igbvf_ring *rx_ring = adapter->rx_ring;
int vector = 0;
adapter->eims_enable_mask = 0;
igbvf_assign_vector(adapter, IGBVF_NO_QUEUE, 0, vector++);
adapter->eims_enable_mask |= tx_ring->eims_value;
writel(tx_ring->itr_val, hw->hw_addr + tx_ring->itr_register);
igbvf_assign_vector(adapter, 0, IGBVF_NO_QUEUE, vector++);
adapter->eims_enable_mask |= rx_ring->eims_value;
writel(rx_ring->itr_val, hw->hw_addr + rx_ring->itr_register);
/* set vector for other causes, i.e. link changes */
tmp = (vector++ | E1000_IVAR_VALID);
ew32(IVAR_MISC, tmp);
adapter->eims_enable_mask = (1 << (vector)) - 1;
adapter->eims_other = 1 << (vector - 1);
e1e_flush();
}
static void igbvf_reset_interrupt_capability(struct igbvf_adapter *adapter)
{
if (adapter->msix_entries) {
pci_disable_msix(adapter->pdev);
kfree(adapter->msix_entries);
adapter->msix_entries = NULL;
}
}
/**
* igbvf_set_interrupt_capability - set MSI or MSI-X if supported
*
* Attempt to configure interrupts using the best available
* capabilities of the hardware and kernel.
**/
static void igbvf_set_interrupt_capability(struct igbvf_adapter *adapter)
{
int err = -ENOMEM;
int i;
/* we allocate 3 vectors, 1 for tx, 1 for rx, one for pf messages */
adapter->msix_entries = kcalloc(3, sizeof(struct msix_entry),
GFP_KERNEL);
if (adapter->msix_entries) {
for (i = 0; i < 3; i++)
adapter->msix_entries[i].entry = i;
err = pci_enable_msix(adapter->pdev,
adapter->msix_entries, 3);
}
if (err) {
/* MSI-X failed */
dev_err(&adapter->pdev->dev,
"Failed to initialize MSI-X interrupts.\n");
igbvf_reset_interrupt_capability(adapter);
}
}
/**
* igbvf_request_msix - Initialize MSI-X interrupts
*
* igbvf_request_msix allocates MSI-X vectors and requests interrupts from the
* kernel.
**/
static int igbvf_request_msix(struct igbvf_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int err = 0, vector = 0;
if (strlen(netdev->name) < (IFNAMSIZ - 5)) {
sprintf(adapter->tx_ring->name, "%s-tx-0", netdev->name);
sprintf(adapter->rx_ring->name, "%s-rx-0", netdev->name);
} else {
memcpy(adapter->tx_ring->name, netdev->name, IFNAMSIZ);
memcpy(adapter->rx_ring->name, netdev->name, IFNAMSIZ);
}
err = request_irq(adapter->msix_entries[vector].vector,
igbvf_intr_msix_tx, 0, adapter->tx_ring->name,
netdev);
if (err)
goto out;
adapter->tx_ring->itr_register = E1000_EITR(vector);
adapter->tx_ring->itr_val = adapter->current_itr;
vector++;
err = request_irq(adapter->msix_entries[vector].vector,
igbvf_intr_msix_rx, 0, adapter->rx_ring->name,
netdev);
if (err)
goto out;
adapter->rx_ring->itr_register = E1000_EITR(vector);
adapter->rx_ring->itr_val = adapter->current_itr;
vector++;
err = request_irq(adapter->msix_entries[vector].vector,
igbvf_msix_other, 0, netdev->name, netdev);
if (err)
goto out;
igbvf_configure_msix(adapter);
return 0;
out:
return err;
}
/**
* igbvf_alloc_queues - Allocate memory for all rings
* @adapter: board private structure to initialize
**/
static int igbvf_alloc_queues(struct igbvf_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
adapter->tx_ring = kzalloc(sizeof(struct igbvf_ring), GFP_KERNEL);
if (!adapter->tx_ring)
return -ENOMEM;
adapter->rx_ring = kzalloc(sizeof(struct igbvf_ring), GFP_KERNEL);
if (!adapter->rx_ring) {
kfree(adapter->tx_ring);
return -ENOMEM;
}
netif_napi_add(netdev, &adapter->rx_ring->napi, igbvf_poll, 64);
return 0;
}
/**
* igbvf_request_irq - initialize interrupts
*
* Attempts to configure interrupts using the best available
* capabilities of the hardware and kernel.
**/
static int igbvf_request_irq(struct igbvf_adapter *adapter)
{
int err = -1;
/* igbvf supports msi-x only */
if (adapter->msix_entries)
err = igbvf_request_msix(adapter);
if (!err)
return err;
dev_err(&adapter->pdev->dev,
"Unable to allocate interrupt, Error: %d\n", err);
return err;
}
static void igbvf_free_irq(struct igbvf_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int vector;
if (adapter->msix_entries) {
for (vector = 0; vector < 3; vector++)
free_irq(adapter->msix_entries[vector].vector, netdev);
}
}
/**
* igbvf_irq_disable - Mask off interrupt generation on the NIC
**/
static void igbvf_irq_disable(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
ew32(EIMC, ~0);
if (adapter->msix_entries)
ew32(EIAC, 0);
}
/**
* igbvf_irq_enable - Enable default interrupt generation settings
**/
static void igbvf_irq_enable(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
ew32(EIAC, adapter->eims_enable_mask);
ew32(EIAM, adapter->eims_enable_mask);
ew32(EIMS, adapter->eims_enable_mask);
}
/**
* igbvf_poll - NAPI Rx polling callback
* @napi: struct associated with this polling callback
* @budget: amount of packets driver is allowed to process this poll
**/
static int igbvf_poll(struct napi_struct *napi, int budget)
{
struct igbvf_ring *rx_ring = container_of(napi, struct igbvf_ring, napi);
struct igbvf_adapter *adapter = rx_ring->adapter;
struct e1000_hw *hw = &adapter->hw;
int work_done = 0;
igbvf_clean_rx_irq(adapter, &work_done, budget);
/* If not enough Rx work done, exit the polling mode */
if (work_done < budget) {
napi_complete(napi);
if (adapter->requested_itr & 3)
igbvf_set_itr(adapter);
if (!test_bit(__IGBVF_DOWN, &adapter->state))
ew32(EIMS, adapter->rx_ring->eims_value);
}
return work_done;
}
/**
* igbvf_set_rlpml - set receive large packet maximum length
* @adapter: board private structure
*
* Configure the maximum size of packets that will be received
*/
static void igbvf_set_rlpml(struct igbvf_adapter *adapter)
{
int max_frame_size;
struct e1000_hw *hw = &adapter->hw;
max_frame_size = adapter->max_frame_size + VLAN_TAG_SIZE;
e1000_rlpml_set_vf(hw, max_frame_size);
}
static int igbvf_vlan_rx_add_vid(struct net_device *netdev, u16 vid)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
if (hw->mac.ops.set_vfta(hw, vid, true)) {
dev_err(&adapter->pdev->dev, "Failed to add vlan id %d\n", vid);
return -EINVAL;
}
set_bit(vid, adapter->active_vlans);
return 0;
}
static int igbvf_vlan_rx_kill_vid(struct net_device *netdev, u16 vid)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
if (hw->mac.ops.set_vfta(hw, vid, false)) {
dev_err(&adapter->pdev->dev,
"Failed to remove vlan id %d\n", vid);
return -EINVAL;
}
clear_bit(vid, adapter->active_vlans);
return 0;
}
static void igbvf_restore_vlan(struct igbvf_adapter *adapter)
{
u16 vid;
for_each_set_bit(vid, adapter->active_vlans, VLAN_N_VID)
igbvf_vlan_rx_add_vid(adapter->netdev, vid);
}
/**
* igbvf_configure_tx - Configure Transmit Unit after Reset
* @adapter: board private structure
*
* Configure the Tx unit of the MAC after a reset.
**/
static void igbvf_configure_tx(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct igbvf_ring *tx_ring = adapter->tx_ring;
u64 tdba;
u32 txdctl, dca_txctrl;
/* disable transmits */
txdctl = er32(TXDCTL(0));
ew32(TXDCTL(0), txdctl & ~E1000_TXDCTL_QUEUE_ENABLE);
e1e_flush();
msleep(10);
/* Setup the HW Tx Head and Tail descriptor pointers */
ew32(TDLEN(0), tx_ring->count * sizeof(union e1000_adv_tx_desc));
tdba = tx_ring->dma;
ew32(TDBAL(0), (tdba & DMA_BIT_MASK(32)));
ew32(TDBAH(0), (tdba >> 32));
ew32(TDH(0), 0);
ew32(TDT(0), 0);
tx_ring->head = E1000_TDH(0);
tx_ring->tail = E1000_TDT(0);
/* Turn off Relaxed Ordering on head write-backs. The writebacks
* MUST be delivered in order or it will completely screw up
* our bookeeping.
*/
dca_txctrl = er32(DCA_TXCTRL(0));
dca_txctrl &= ~E1000_DCA_TXCTRL_TX_WB_RO_EN;
ew32(DCA_TXCTRL(0), dca_txctrl);
/* enable transmits */
txdctl |= E1000_TXDCTL_QUEUE_ENABLE;
ew32(TXDCTL(0), txdctl);
/* Setup Transmit Descriptor Settings for eop descriptor */
adapter->txd_cmd = E1000_ADVTXD_DCMD_EOP | E1000_ADVTXD_DCMD_IFCS;
/* enable Report Status bit */
adapter->txd_cmd |= E1000_ADVTXD_DCMD_RS;
}
/**
* igbvf_setup_srrctl - configure the receive control registers
* @adapter: Board private structure
**/
static void igbvf_setup_srrctl(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 srrctl = 0;
srrctl &= ~(E1000_SRRCTL_DESCTYPE_MASK |
E1000_SRRCTL_BSIZEHDR_MASK |
E1000_SRRCTL_BSIZEPKT_MASK);
/* Enable queue drop to avoid head of line blocking */
srrctl |= E1000_SRRCTL_DROP_EN;
/* Setup buffer sizes */
srrctl |= ALIGN(adapter->rx_buffer_len, 1024) >>
E1000_SRRCTL_BSIZEPKT_SHIFT;
if (adapter->rx_buffer_len < 2048) {
adapter->rx_ps_hdr_size = 0;
srrctl |= E1000_SRRCTL_DESCTYPE_ADV_ONEBUF;
} else {
adapter->rx_ps_hdr_size = 128;
srrctl |= adapter->rx_ps_hdr_size <<
E1000_SRRCTL_BSIZEHDRSIZE_SHIFT;
srrctl |= E1000_SRRCTL_DESCTYPE_HDR_SPLIT_ALWAYS;
}
ew32(SRRCTL(0), srrctl);
}
/**
* igbvf_configure_rx - Configure Receive Unit after Reset
* @adapter: board private structure
*
* Configure the Rx unit of the MAC after a reset.
**/
static void igbvf_configure_rx(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct igbvf_ring *rx_ring = adapter->rx_ring;
u64 rdba;
u32 rdlen, rxdctl;
/* disable receives */
rxdctl = er32(RXDCTL(0));
ew32(RXDCTL(0), rxdctl & ~E1000_RXDCTL_QUEUE_ENABLE);
e1e_flush();
msleep(10);
rdlen = rx_ring->count * sizeof(union e1000_adv_rx_desc);
/*
* Setup the HW Rx Head and Tail Descriptor Pointers and
* the Base and Length of the Rx Descriptor Ring
*/
rdba = rx_ring->dma;
ew32(RDBAL(0), (rdba & DMA_BIT_MASK(32)));
ew32(RDBAH(0), (rdba >> 32));
ew32(RDLEN(0), rx_ring->count * sizeof(union e1000_adv_rx_desc));
rx_ring->head = E1000_RDH(0);
rx_ring->tail = E1000_RDT(0);
ew32(RDH(0), 0);
ew32(RDT(0), 0);
rxdctl |= E1000_RXDCTL_QUEUE_ENABLE;
rxdctl &= 0xFFF00000;
rxdctl |= IGBVF_RX_PTHRESH;
rxdctl |= IGBVF_RX_HTHRESH << 8;
rxdctl |= IGBVF_RX_WTHRESH << 16;
igbvf_set_rlpml(adapter);
/* enable receives */
ew32(RXDCTL(0), rxdctl);
}
/**
* igbvf_set_multi - Multicast and Promiscuous mode set
* @netdev: network interface device structure
*
* The set_multi entry point is called whenever the multicast address
* list or the network interface flags are updated. This routine is
* responsible for configuring the hardware for proper multicast,
* promiscuous mode, and all-multi behavior.
**/
static void igbvf_set_multi(struct net_device *netdev)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
struct netdev_hw_addr *ha;
u8 *mta_list = NULL;
int i;
if (!netdev_mc_empty(netdev)) {
mta_list = kmalloc(netdev_mc_count(netdev) * 6, GFP_ATOMIC);
if (!mta_list) {
dev_err(&adapter->pdev->dev,
"failed to allocate multicast filter list\n");
return;
}
}
/* prepare a packed array of only addresses. */
i = 0;
netdev_for_each_mc_addr(ha, netdev)
memcpy(mta_list + (i++ * ETH_ALEN), ha->addr, ETH_ALEN);
hw->mac.ops.update_mc_addr_list(hw, mta_list, i, 0, 0);
kfree(mta_list);
}
/**
* igbvf_configure - configure the hardware for Rx and Tx
* @adapter: private board structure
**/
static void igbvf_configure(struct igbvf_adapter *adapter)
{
igbvf_set_multi(adapter->netdev);
igbvf_restore_vlan(adapter);
igbvf_configure_tx(adapter);
igbvf_setup_srrctl(adapter);
igbvf_configure_rx(adapter);
igbvf_alloc_rx_buffers(adapter->rx_ring,
igbvf_desc_unused(adapter->rx_ring));
}
/* igbvf_reset - bring the hardware into a known good state
*
* This function boots the hardware and enables some settings that
* require a configuration cycle of the hardware - those cannot be
* set/changed during runtime. After reset the device needs to be
* properly configured for Rx, Tx etc.
*/
static void igbvf_reset(struct igbvf_adapter *adapter)
{
struct e1000_mac_info *mac = &adapter->hw.mac;
struct net_device *netdev = adapter->netdev;
struct e1000_hw *hw = &adapter->hw;
/* Allow time for pending master requests to run */
if (mac->ops.reset_hw(hw))
dev_err(&adapter->pdev->dev, "PF still resetting\n");
mac->ops.init_hw(hw);
if (is_valid_ether_addr(adapter->hw.mac.addr)) {
memcpy(netdev->dev_addr, adapter->hw.mac.addr,
netdev->addr_len);
memcpy(netdev->perm_addr, adapter->hw.mac.addr,
netdev->addr_len);
}
adapter->last_reset = jiffies;
}
int igbvf_up(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
/* hardware has been reset, we need to reload some things */
igbvf_configure(adapter);
clear_bit(__IGBVF_DOWN, &adapter->state);
napi_enable(&adapter->rx_ring->napi);
if (adapter->msix_entries)
igbvf_configure_msix(adapter);
/* Clear any pending interrupts. */
er32(EICR);
igbvf_irq_enable(adapter);
/* start the watchdog */
hw->mac.get_link_status = 1;
mod_timer(&adapter->watchdog_timer, jiffies + 1);
return 0;
}
void igbvf_down(struct igbvf_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct e1000_hw *hw = &adapter->hw;
u32 rxdctl, txdctl;
/*
* signal that we're down so the interrupt handler does not
* reschedule our watchdog timer
*/
set_bit(__IGBVF_DOWN, &adapter->state);
/* disable receives in the hardware */
rxdctl = er32(RXDCTL(0));
ew32(RXDCTL(0), rxdctl & ~E1000_RXDCTL_QUEUE_ENABLE);
netif_stop_queue(netdev);
/* disable transmits in the hardware */
txdctl = er32(TXDCTL(0));
ew32(TXDCTL(0), txdctl & ~E1000_TXDCTL_QUEUE_ENABLE);
/* flush both disables and wait for them to finish */
e1e_flush();
msleep(10);
napi_disable(&adapter->rx_ring->napi);
igbvf_irq_disable(adapter);
del_timer_sync(&adapter->watchdog_timer);
netif_carrier_off(netdev);
/* record the stats before reset*/
igbvf_update_stats(adapter);
adapter->link_speed = 0;
adapter->link_duplex = 0;
igbvf_reset(adapter);
igbvf_clean_tx_ring(adapter->tx_ring);
igbvf_clean_rx_ring(adapter->rx_ring);
}
void igbvf_reinit_locked(struct igbvf_adapter *adapter)
{
might_sleep();
while (test_and_set_bit(__IGBVF_RESETTING, &adapter->state))
msleep(1);
igbvf_down(adapter);
igbvf_up(adapter);
clear_bit(__IGBVF_RESETTING, &adapter->state);
}
/**
* igbvf_sw_init - Initialize general software structures (struct igbvf_adapter)
* @adapter: board private structure to initialize
*
* igbvf_sw_init initializes the Adapter private data structure.
* Fields are initialized based on PCI device information and
* OS network device settings (MTU size).
**/
static int igbvf_sw_init(struct igbvf_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
s32 rc;
adapter->rx_buffer_len = ETH_FRAME_LEN + VLAN_HLEN + ETH_FCS_LEN;
adapter->rx_ps_hdr_size = 0;
adapter->max_frame_size = netdev->mtu + ETH_HLEN + ETH_FCS_LEN;
adapter->min_frame_size = ETH_ZLEN + ETH_FCS_LEN;
adapter->tx_int_delay = 8;
adapter->tx_abs_int_delay = 32;
adapter->rx_int_delay = 0;
adapter->rx_abs_int_delay = 8;
adapter->requested_itr = 3;
adapter->current_itr = IGBVF_START_ITR;
/* Set various function pointers */
adapter->ei->init_ops(&adapter->hw);
rc = adapter->hw.mac.ops.init_params(&adapter->hw);
if (rc)
return rc;
rc = adapter->hw.mbx.ops.init_params(&adapter->hw);
if (rc)
return rc;
igbvf_set_interrupt_capability(adapter);
if (igbvf_alloc_queues(adapter))
return -ENOMEM;
spin_lock_init(&adapter->tx_queue_lock);
/* Explicitly disable IRQ since the NIC can be in any state. */
igbvf_irq_disable(adapter);
spin_lock_init(&adapter->stats_lock);
set_bit(__IGBVF_DOWN, &adapter->state);
return 0;
}
static void igbvf_initialize_last_counter_stats(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
adapter->stats.last_gprc = er32(VFGPRC);
adapter->stats.last_gorc = er32(VFGORC);
adapter->stats.last_gptc = er32(VFGPTC);
adapter->stats.last_gotc = er32(VFGOTC);
adapter->stats.last_mprc = er32(VFMPRC);
adapter->stats.last_gotlbc = er32(VFGOTLBC);
adapter->stats.last_gptlbc = er32(VFGPTLBC);
adapter->stats.last_gorlbc = er32(VFGORLBC);
adapter->stats.last_gprlbc = er32(VFGPRLBC);
adapter->stats.base_gprc = er32(VFGPRC);
adapter->stats.base_gorc = er32(VFGORC);
adapter->stats.base_gptc = er32(VFGPTC);
adapter->stats.base_gotc = er32(VFGOTC);
adapter->stats.base_mprc = er32(VFMPRC);
adapter->stats.base_gotlbc = er32(VFGOTLBC);
adapter->stats.base_gptlbc = er32(VFGPTLBC);
adapter->stats.base_gorlbc = er32(VFGORLBC);
adapter->stats.base_gprlbc = er32(VFGPRLBC);
}
/**
* igbvf_open - Called when a network interface is made active
* @netdev: network interface device structure
*
* Returns 0 on success, negative value on failure
*
* The open entry point is called when a network interface is made
* active by the system (IFF_UP). At this point all resources needed
* for transmit and receive operations are allocated, the interrupt
* handler is registered with the OS, the watchdog timer is started,
* and the stack is notified that the interface is ready.
**/
static int igbvf_open(struct net_device *netdev)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
int err;
/* disallow open during test */
if (test_bit(__IGBVF_TESTING, &adapter->state))
return -EBUSY;
/* allocate transmit descriptors */
err = igbvf_setup_tx_resources(adapter, adapter->tx_ring);
if (err)
goto err_setup_tx;
/* allocate receive descriptors */
err = igbvf_setup_rx_resources(adapter, adapter->rx_ring);
if (err)
goto err_setup_rx;
/*
* before we allocate an interrupt, we must be ready to handle it.
* Setting DEBUG_SHIRQ in the kernel makes it fire an interrupt
* as soon as we call pci_request_irq, so we have to setup our
* clean_rx handler before we do so.
*/
igbvf_configure(adapter);
err = igbvf_request_irq(adapter);
if (err)
goto err_req_irq;
/* From here on the code is the same as igbvf_up() */
clear_bit(__IGBVF_DOWN, &adapter->state);
napi_enable(&adapter->rx_ring->napi);
/* clear any pending interrupts */
er32(EICR);
igbvf_irq_enable(adapter);
/* start the watchdog */
hw->mac.get_link_status = 1;
mod_timer(&adapter->watchdog_timer, jiffies + 1);
return 0;
err_req_irq:
igbvf_free_rx_resources(adapter->rx_ring);
err_setup_rx:
igbvf_free_tx_resources(adapter->tx_ring);
err_setup_tx:
igbvf_reset(adapter);
return err;
}
/**
* igbvf_close - Disables a network interface
* @netdev: network interface device structure
*
* Returns 0, this is not allowed to fail
*
* The close entry point is called when an interface is de-activated
* by the OS. The hardware is still under the drivers control, but
* needs to be disabled. A global MAC reset is issued to stop the
* hardware, and all transmit and receive resources are freed.
**/
static int igbvf_close(struct net_device *netdev)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
WARN_ON(test_bit(__IGBVF_RESETTING, &adapter->state));
igbvf_down(adapter);
igbvf_free_irq(adapter);
igbvf_free_tx_resources(adapter->tx_ring);
igbvf_free_rx_resources(adapter->rx_ring);
return 0;
}
/**
* igbvf_set_mac - Change the Ethernet Address of the NIC
* @netdev: network interface device structure
* @p: pointer to an address structure
*
* Returns 0 on success, negative on failure
**/
static int igbvf_set_mac(struct net_device *netdev, void *p)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
struct sockaddr *addr = p;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(hw->mac.addr, addr->sa_data, netdev->addr_len);
hw->mac.ops.rar_set(hw, hw->mac.addr, 0);
if (memcmp(addr->sa_data, hw->mac.addr, 6))
return -EADDRNOTAVAIL;
memcpy(netdev->dev_addr, addr->sa_data, netdev->addr_len);
netdev->addr_assign_type &= ~NET_ADDR_RANDOM;
return 0;
}
#define UPDATE_VF_COUNTER(reg, name) \
{ \
u32 current_counter = er32(reg); \
if (current_counter < adapter->stats.last_##name) \
adapter->stats.name += 0x100000000LL; \
adapter->stats.last_##name = current_counter; \
adapter->stats.name &= 0xFFFFFFFF00000000LL; \
adapter->stats.name |= current_counter; \
}
/**
* igbvf_update_stats - Update the board statistics counters
* @adapter: board private structure
**/
void igbvf_update_stats(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct pci_dev *pdev = adapter->pdev;
/*
* Prevent stats update while adapter is being reset, link is down
* or if the pci connection is down.
*/
if (adapter->link_speed == 0)
return;
if (test_bit(__IGBVF_RESETTING, &adapter->state))
return;
if (pci_channel_offline(pdev))
return;
UPDATE_VF_COUNTER(VFGPRC, gprc);
UPDATE_VF_COUNTER(VFGORC, gorc);
UPDATE_VF_COUNTER(VFGPTC, gptc);
UPDATE_VF_COUNTER(VFGOTC, gotc);
UPDATE_VF_COUNTER(VFMPRC, mprc);
UPDATE_VF_COUNTER(VFGOTLBC, gotlbc);
UPDATE_VF_COUNTER(VFGPTLBC, gptlbc);
UPDATE_VF_COUNTER(VFGORLBC, gorlbc);
UPDATE_VF_COUNTER(VFGPRLBC, gprlbc);
/* Fill out the OS statistics structure */
adapter->net_stats.multicast = adapter->stats.mprc;
}
static void igbvf_print_link_info(struct igbvf_adapter *adapter)
{
dev_info(&adapter->pdev->dev, "Link is Up %d Mbps %s Duplex\n",
adapter->link_speed,
adapter->link_duplex == FULL_DUPLEX ? "Full" : "Half");
}
static bool igbvf_has_link(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
s32 ret_val = E1000_SUCCESS;
bool link_active;
/* If interface is down, stay link down */
if (test_bit(__IGBVF_DOWN, &adapter->state))
return false;
ret_val = hw->mac.ops.check_for_link(hw);
link_active = !hw->mac.get_link_status;
/* if check for link returns error we will need to reset */
if (ret_val && time_after(jiffies, adapter->last_reset + (10 * HZ)))
schedule_work(&adapter->reset_task);
return link_active;
}
/**
* igbvf_watchdog - Timer Call-back
* @data: pointer to adapter cast into an unsigned long
**/
static void igbvf_watchdog(unsigned long data)
{
struct igbvf_adapter *adapter = (struct igbvf_adapter *) data;
/* Do the rest outside of interrupt context */
schedule_work(&adapter->watchdog_task);
}
static void igbvf_watchdog_task(struct work_struct *work)
{
struct igbvf_adapter *adapter = container_of(work,
struct igbvf_adapter,
watchdog_task);
struct net_device *netdev = adapter->netdev;
struct e1000_mac_info *mac = &adapter->hw.mac;
struct igbvf_ring *tx_ring = adapter->tx_ring;
struct e1000_hw *hw = &adapter->hw;
u32 link;
int tx_pending = 0;
link = igbvf_has_link(adapter);
if (link) {
if (!netif_carrier_ok(netdev)) {
mac->ops.get_link_up_info(&adapter->hw,
&adapter->link_speed,
&adapter->link_duplex);
igbvf_print_link_info(adapter);
netif_carrier_on(netdev);
netif_wake_queue(netdev);
}
} else {
if (netif_carrier_ok(netdev)) {
adapter->link_speed = 0;
adapter->link_duplex = 0;
dev_info(&adapter->pdev->dev, "Link is Down\n");
netif_carrier_off(netdev);
netif_stop_queue(netdev);
}
}
if (netif_carrier_ok(netdev)) {
igbvf_update_stats(adapter);
} else {
tx_pending = (igbvf_desc_unused(tx_ring) + 1 <
tx_ring->count);
if (tx_pending) {
/*
* We've lost link, so the controller stops DMA,
* but we've got queued Tx work that's never going
* to get done, so reset controller to flush Tx.
* (Do the reset outside of interrupt context).
*/
adapter->tx_timeout_count++;
schedule_work(&adapter->reset_task);
}
}
/* Cause software interrupt to ensure Rx ring is cleaned */
ew32(EICS, adapter->rx_ring->eims_value);
/* Reset the timer */
if (!test_bit(__IGBVF_DOWN, &adapter->state))
mod_timer(&adapter->watchdog_timer,
round_jiffies(jiffies + (2 * HZ)));
}
#define IGBVF_TX_FLAGS_CSUM 0x00000001
#define IGBVF_TX_FLAGS_VLAN 0x00000002
#define IGBVF_TX_FLAGS_TSO 0x00000004
#define IGBVF_TX_FLAGS_IPV4 0x00000008
#define IGBVF_TX_FLAGS_VLAN_MASK 0xffff0000
#define IGBVF_TX_FLAGS_VLAN_SHIFT 16
static int igbvf_tso(struct igbvf_adapter *adapter,
struct igbvf_ring *tx_ring,
struct sk_buff *skb, u32 tx_flags, u8 *hdr_len)
{
struct e1000_adv_tx_context_desc *context_desc;
unsigned int i;
int err;
struct igbvf_buffer *buffer_info;
u32 info = 0, tu_cmd = 0;
u32 mss_l4len_idx, l4len;
*hdr_len = 0;
if (skb_header_cloned(skb)) {
err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
if (err) {
dev_err(&adapter->pdev->dev,
"igbvf_tso returning an error\n");
return err;
}
}
l4len = tcp_hdrlen(skb);
*hdr_len += l4len;
if (skb->protocol == htons(ETH_P_IP)) {
struct iphdr *iph = ip_hdr(skb);
iph->tot_len = 0;
iph->check = 0;
tcp_hdr(skb)->check = ~csum_tcpudp_magic(iph->saddr,
iph->daddr, 0,
IPPROTO_TCP,
0);
} else if (skb_is_gso_v6(skb)) {
ipv6_hdr(skb)->payload_len = 0;
tcp_hdr(skb)->check = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr,
0, IPPROTO_TCP, 0);
}
i = tx_ring->next_to_use;
buffer_info = &tx_ring->buffer_info[i];
context_desc = IGBVF_TX_CTXTDESC_ADV(*tx_ring, i);
/* VLAN MACLEN IPLEN */
if (tx_flags & IGBVF_TX_FLAGS_VLAN)
info |= (tx_flags & IGBVF_TX_FLAGS_VLAN_MASK);
info |= (skb_network_offset(skb) << E1000_ADVTXD_MACLEN_SHIFT);
*hdr_len += skb_network_offset(skb);
info |= (skb_transport_header(skb) - skb_network_header(skb));
*hdr_len += (skb_transport_header(skb) - skb_network_header(skb));
context_desc->vlan_macip_lens = cpu_to_le32(info);
/* ADV DTYP TUCMD MKRLOC/ISCSIHEDLEN */
tu_cmd |= (E1000_TXD_CMD_DEXT | E1000_ADVTXD_DTYP_CTXT);
if (skb->protocol == htons(ETH_P_IP))
tu_cmd |= E1000_ADVTXD_TUCMD_IPV4;
tu_cmd |= E1000_ADVTXD_TUCMD_L4T_TCP;
context_desc->type_tucmd_mlhl = cpu_to_le32(tu_cmd);
/* MSS L4LEN IDX */
mss_l4len_idx = (skb_shinfo(skb)->gso_size << E1000_ADVTXD_MSS_SHIFT);
mss_l4len_idx |= (l4len << E1000_ADVTXD_L4LEN_SHIFT);
context_desc->mss_l4len_idx = cpu_to_le32(mss_l4len_idx);
context_desc->seqnum_seed = 0;
buffer_info->time_stamp = jiffies;
buffer_info->next_to_watch = i;
buffer_info->dma = 0;
i++;
if (i == tx_ring->count)
i = 0;
tx_ring->next_to_use = i;
return true;
}
static inline bool igbvf_tx_csum(struct igbvf_adapter *adapter,
struct igbvf_ring *tx_ring,
struct sk_buff *skb, u32 tx_flags)
{
struct e1000_adv_tx_context_desc *context_desc;
unsigned int i;
struct igbvf_buffer *buffer_info;
u32 info = 0, tu_cmd = 0;
if ((skb->ip_summed == CHECKSUM_PARTIAL) ||
(tx_flags & IGBVF_TX_FLAGS_VLAN)) {
i = tx_ring->next_to_use;
buffer_info = &tx_ring->buffer_info[i];
context_desc = IGBVF_TX_CTXTDESC_ADV(*tx_ring, i);
if (tx_flags & IGBVF_TX_FLAGS_VLAN)
info |= (tx_flags & IGBVF_TX_FLAGS_VLAN_MASK);
info |= (skb_network_offset(skb) << E1000_ADVTXD_MACLEN_SHIFT);
if (skb->ip_summed == CHECKSUM_PARTIAL)
info |= (skb_transport_header(skb) -
skb_network_header(skb));
context_desc->vlan_macip_lens = cpu_to_le32(info);
tu_cmd |= (E1000_TXD_CMD_DEXT | E1000_ADVTXD_DTYP_CTXT);
if (skb->ip_summed == CHECKSUM_PARTIAL) {
switch (skb->protocol) {
case __constant_htons(ETH_P_IP):
tu_cmd |= E1000_ADVTXD_TUCMD_IPV4;
if (ip_hdr(skb)->protocol == IPPROTO_TCP)
tu_cmd |= E1000_ADVTXD_TUCMD_L4T_TCP;
break;
case __constant_htons(ETH_P_IPV6):
if (ipv6_hdr(skb)->nexthdr == IPPROTO_TCP)
tu_cmd |= E1000_ADVTXD_TUCMD_L4T_TCP;
break;
default:
break;
}
}
context_desc->type_tucmd_mlhl = cpu_to_le32(tu_cmd);
context_desc->seqnum_seed = 0;
context_desc->mss_l4len_idx = 0;
buffer_info->time_stamp = jiffies;
buffer_info->next_to_watch = i;
buffer_info->dma = 0;
i++;
if (i == tx_ring->count)
i = 0;
tx_ring->next_to_use = i;
return true;
}
return false;
}
static int igbvf_maybe_stop_tx(struct net_device *netdev, int size)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
/* there is enough descriptors then we don't need to worry */
if (igbvf_desc_unused(adapter->tx_ring) >= size)
return 0;
netif_stop_queue(netdev);
smp_mb();
/* We need to check again just in case room has been made available */
if (igbvf_desc_unused(adapter->tx_ring) < size)
return -EBUSY;
netif_wake_queue(netdev);
++adapter->restart_queue;
return 0;
}
#define IGBVF_MAX_TXD_PWR 16
#define IGBVF_MAX_DATA_PER_TXD (1 << IGBVF_MAX_TXD_PWR)
static inline int igbvf_tx_map_adv(struct igbvf_adapter *adapter,
struct igbvf_ring *tx_ring,
struct sk_buff *skb,
unsigned int first)
{
struct igbvf_buffer *buffer_info;
struct pci_dev *pdev = adapter->pdev;
unsigned int len = skb_headlen(skb);
unsigned int count = 0, i;
unsigned int f;
i = tx_ring->next_to_use;
buffer_info = &tx_ring->buffer_info[i];
BUG_ON(len >= IGBVF_MAX_DATA_PER_TXD);
buffer_info->length = len;
/* set time_stamp *before* dma to help avoid a possible race */
buffer_info->time_stamp = jiffies;
buffer_info->next_to_watch = i;
buffer_info->mapped_as_page = false;
buffer_info->dma = dma_map_single(&pdev->dev, skb->data, len,
DMA_TO_DEVICE);
if (dma_mapping_error(&pdev->dev, buffer_info->dma))
goto dma_error;
for (f = 0; f < skb_shinfo(skb)->nr_frags; f++) {
const struct skb_frag_struct *frag;
count++;
i++;
if (i == tx_ring->count)
i = 0;
frag = &skb_shinfo(skb)->frags[f];
len = skb_frag_size(frag);
buffer_info = &tx_ring->buffer_info[i];
BUG_ON(len >= IGBVF_MAX_DATA_PER_TXD);
buffer_info->length = len;
buffer_info->time_stamp = jiffies;
buffer_info->next_to_watch = i;
buffer_info->mapped_as_page = true;
buffer_info->dma = skb_frag_dma_map(&pdev->dev, frag, 0, len,
DMA_TO_DEVICE);
if (dma_mapping_error(&pdev->dev, buffer_info->dma))
goto dma_error;
}
tx_ring->buffer_info[i].skb = skb;
tx_ring->buffer_info[first].next_to_watch = i;
return ++count;
dma_error:
dev_err(&pdev->dev, "TX DMA map failed\n");
/* clear timestamp and dma mappings for failed buffer_info mapping */
buffer_info->dma = 0;
buffer_info->time_stamp = 0;
buffer_info->length = 0;
buffer_info->next_to_watch = 0;
buffer_info->mapped_as_page = false;
if (count)
count--;
/* clear timestamp and dma mappings for remaining portion of packet */
while (count--) {
if (i==0)
i += tx_ring->count;
i--;
buffer_info = &tx_ring->buffer_info[i];
igbvf_put_txbuf(adapter, buffer_info);
}
return 0;
}
static inline void igbvf_tx_queue_adv(struct igbvf_adapter *adapter,
struct igbvf_ring *tx_ring,
int tx_flags, int count, u32 paylen,
u8 hdr_len)
{
union e1000_adv_tx_desc *tx_desc = NULL;
struct igbvf_buffer *buffer_info;
u32 olinfo_status = 0, cmd_type_len;
unsigned int i;
cmd_type_len = (E1000_ADVTXD_DTYP_DATA | E1000_ADVTXD_DCMD_IFCS |
E1000_ADVTXD_DCMD_DEXT);
if (tx_flags & IGBVF_TX_FLAGS_VLAN)
cmd_type_len |= E1000_ADVTXD_DCMD_VLE;
if (tx_flags & IGBVF_TX_FLAGS_TSO) {
cmd_type_len |= E1000_ADVTXD_DCMD_TSE;
/* insert tcp checksum */
olinfo_status |= E1000_TXD_POPTS_TXSM << 8;
/* insert ip checksum */
if (tx_flags & IGBVF_TX_FLAGS_IPV4)
olinfo_status |= E1000_TXD_POPTS_IXSM << 8;
} else if (tx_flags & IGBVF_TX_FLAGS_CSUM) {
olinfo_status |= E1000_TXD_POPTS_TXSM << 8;
}
olinfo_status |= ((paylen - hdr_len) << E1000_ADVTXD_PAYLEN_SHIFT);
i = tx_ring->next_to_use;
while (count--) {
buffer_info = &tx_ring->buffer_info[i];
tx_desc = IGBVF_TX_DESC_ADV(*tx_ring, i);
tx_desc->read.buffer_addr = cpu_to_le64(buffer_info->dma);
tx_desc->read.cmd_type_len =
cpu_to_le32(cmd_type_len | buffer_info->length);
tx_desc->read.olinfo_status = cpu_to_le32(olinfo_status);
i++;
if (i == tx_ring->count)
i = 0;
}
tx_desc->read.cmd_type_len |= cpu_to_le32(adapter->txd_cmd);
/* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64). */
wmb();
tx_ring->next_to_use = i;
writel(i, adapter->hw.hw_addr + tx_ring->tail);
/* we need this if more than one processor can write to our tail
* at a time, it syncronizes IO on IA64/Altix systems */
mmiowb();
}
static netdev_tx_t igbvf_xmit_frame_ring_adv(struct sk_buff *skb,
struct net_device *netdev,
struct igbvf_ring *tx_ring)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
unsigned int first, tx_flags = 0;
u8 hdr_len = 0;
int count = 0;
int tso = 0;
if (test_bit(__IGBVF_DOWN, &adapter->state)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
if (skb->len <= 0) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
/*
* need: count + 4 desc gap to keep tail from touching
* + 2 desc gap to keep tail from touching head,
* + 1 desc for skb->data,
* + 1 desc for context descriptor,
* head, otherwise try next time
*/
if (igbvf_maybe_stop_tx(netdev, skb_shinfo(skb)->nr_frags + 4)) {
/* this is a hard error */
return NETDEV_TX_BUSY;
}
if (vlan_tx_tag_present(skb)) {
tx_flags |= IGBVF_TX_FLAGS_VLAN;
tx_flags |= (vlan_tx_tag_get(skb) << IGBVF_TX_FLAGS_VLAN_SHIFT);
}
if (skb->protocol == htons(ETH_P_IP))
tx_flags |= IGBVF_TX_FLAGS_IPV4;
first = tx_ring->next_to_use;
tso = skb_is_gso(skb) ?
igbvf_tso(adapter, tx_ring, skb, tx_flags, &hdr_len) : 0;
if (unlikely(tso < 0)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
if (tso)
tx_flags |= IGBVF_TX_FLAGS_TSO;
else if (igbvf_tx_csum(adapter, tx_ring, skb, tx_flags) &&
(skb->ip_summed == CHECKSUM_PARTIAL))
tx_flags |= IGBVF_TX_FLAGS_CSUM;
/*
* count reflects descriptors mapped, if 0 then mapping error
* has occurred and we need to rewind the descriptor queue
*/
count = igbvf_tx_map_adv(adapter, tx_ring, skb, first);
if (count) {
igbvf_tx_queue_adv(adapter, tx_ring, tx_flags, count,
skb->len, hdr_len);
/* Make sure there is space in the ring for the next send. */
igbvf_maybe_stop_tx(netdev, MAX_SKB_FRAGS + 4);
} else {
dev_kfree_skb_any(skb);
tx_ring->buffer_info[first].time_stamp = 0;
tx_ring->next_to_use = first;
}
return NETDEV_TX_OK;
}
static netdev_tx_t igbvf_xmit_frame(struct sk_buff *skb,
struct net_device *netdev)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct igbvf_ring *tx_ring;
if (test_bit(__IGBVF_DOWN, &adapter->state)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
tx_ring = &adapter->tx_ring[0];
return igbvf_xmit_frame_ring_adv(skb, netdev, tx_ring);
}
/**
* igbvf_tx_timeout - Respond to a Tx Hang
* @netdev: network interface device structure
**/
static void igbvf_tx_timeout(struct net_device *netdev)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
/* Do the reset outside of interrupt context */
adapter->tx_timeout_count++;
schedule_work(&adapter->reset_task);
}
static void igbvf_reset_task(struct work_struct *work)
{
struct igbvf_adapter *adapter;
adapter = container_of(work, struct igbvf_adapter, reset_task);
igbvf_reinit_locked(adapter);
}
/**
* igbvf_get_stats - Get System Network Statistics
* @netdev: network interface device structure
*
* Returns the address of the device statistics structure.
* The statistics are actually updated from the timer callback.
**/
static struct net_device_stats *igbvf_get_stats(struct net_device *netdev)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
/* only return the current stats */
return &adapter->net_stats;
}
/**
* igbvf_change_mtu - Change the Maximum Transfer Unit
* @netdev: network interface device structure
* @new_mtu: new value for maximum frame size
*
* Returns 0 on success, negative on failure
**/
static int igbvf_change_mtu(struct net_device *netdev, int new_mtu)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
int max_frame = new_mtu + ETH_HLEN + ETH_FCS_LEN;
if ((new_mtu < 68) || (max_frame > MAX_JUMBO_FRAME_SIZE)) {
dev_err(&adapter->pdev->dev, "Invalid MTU setting\n");
return -EINVAL;
}
#define MAX_STD_JUMBO_FRAME_SIZE 9234
if (max_frame > MAX_STD_JUMBO_FRAME_SIZE) {
dev_err(&adapter->pdev->dev, "MTU > 9216 not supported.\n");
return -EINVAL;
}
while (test_and_set_bit(__IGBVF_RESETTING, &adapter->state))
msleep(1);
/* igbvf_down has a dependency on max_frame_size */
adapter->max_frame_size = max_frame;
if (netif_running(netdev))
igbvf_down(adapter);
/*
* NOTE: netdev_alloc_skb reserves 16 bytes, and typically NET_IP_ALIGN
* means we reserve 2 more, this pushes us to allocate from the next
* larger slab size.
* i.e. RXBUFFER_2048 --> size-4096 slab
* However with the new *_jumbo_rx* routines, jumbo receives will use
* fragmented skbs
*/
if (max_frame <= 1024)
adapter->rx_buffer_len = 1024;
else if (max_frame <= 2048)
adapter->rx_buffer_len = 2048;
else
#if (PAGE_SIZE / 2) > 16384
adapter->rx_buffer_len = 16384;
#else
adapter->rx_buffer_len = PAGE_SIZE / 2;
#endif
/* adjust allocation if LPE protects us, and we aren't using SBP */
if ((max_frame == ETH_FRAME_LEN + ETH_FCS_LEN) ||
(max_frame == ETH_FRAME_LEN + VLAN_HLEN + ETH_FCS_LEN))
adapter->rx_buffer_len = ETH_FRAME_LEN + VLAN_HLEN +
ETH_FCS_LEN;
dev_info(&adapter->pdev->dev, "changing MTU from %d to %d\n",
netdev->mtu, new_mtu);
netdev->mtu = new_mtu;
if (netif_running(netdev))
igbvf_up(adapter);
else
igbvf_reset(adapter);
clear_bit(__IGBVF_RESETTING, &adapter->state);
return 0;
}
static int igbvf_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
switch (cmd) {
default:
return -EOPNOTSUPP;
}
}
static int igbvf_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igbvf_adapter *adapter = netdev_priv(netdev);
#ifdef CONFIG_PM
int retval = 0;
#endif
netif_device_detach(netdev);
if (netif_running(netdev)) {
WARN_ON(test_bit(__IGBVF_RESETTING, &adapter->state));
igbvf_down(adapter);
igbvf_free_irq(adapter);
}
#ifdef CONFIG_PM
retval = pci_save_state(pdev);
if (retval)
return retval;
#endif
pci_disable_device(pdev);
return 0;
}
#ifdef CONFIG_PM
static int igbvf_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igbvf_adapter *adapter = netdev_priv(netdev);
u32 err;
pci_restore_state(pdev);
err = pci_enable_device_mem(pdev);
if (err) {
dev_err(&pdev->dev, "Cannot enable PCI device from suspend\n");
return err;
}
pci_set_master(pdev);
if (netif_running(netdev)) {
err = igbvf_request_irq(adapter);
if (err)
return err;
}
igbvf_reset(adapter);
if (netif_running(netdev))
igbvf_up(adapter);
netif_device_attach(netdev);
return 0;
}
#endif
static void igbvf_shutdown(struct pci_dev *pdev)
{
igbvf_suspend(pdev, PMSG_SUSPEND);
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/*
* Polling 'interrupt' - used by things like netconsole to send skbs
* without having to re-enable interrupts. It's not called while
* the interrupt routine is executing.
*/
static void igbvf_netpoll(struct net_device *netdev)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
disable_irq(adapter->pdev->irq);
igbvf_clean_tx_irq(adapter->tx_ring);
enable_irq(adapter->pdev->irq);
}
#endif
/**
* igbvf_io_error_detected - called when PCI error is detected
* @pdev: Pointer to PCI device
* @state: The current pci connection state
*
* This function is called after a PCI bus error affecting
* this device has been detected.
*/
static pci_ers_result_t igbvf_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igbvf_adapter *adapter = netdev_priv(netdev);
netif_device_detach(netdev);
if (state == pci_channel_io_perm_failure)
return PCI_ERS_RESULT_DISCONNECT;
if (netif_running(netdev))
igbvf_down(adapter);
pci_disable_device(pdev);
/* Request a slot slot reset. */
return PCI_ERS_RESULT_NEED_RESET;
}
/**
* igbvf_io_slot_reset - called after the pci bus has been reset.
* @pdev: Pointer to PCI device
*
* Restart the card from scratch, as if from a cold-boot. Implementation
* resembles the first-half of the igbvf_resume routine.
*/
static pci_ers_result_t igbvf_io_slot_reset(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igbvf_adapter *adapter = netdev_priv(netdev);
if (pci_enable_device_mem(pdev)) {
dev_err(&pdev->dev,
"Cannot re-enable PCI device after reset.\n");
return PCI_ERS_RESULT_DISCONNECT;
}
pci_set_master(pdev);
igbvf_reset(adapter);
return PCI_ERS_RESULT_RECOVERED;
}
/**
* igbvf_io_resume - called when traffic can start flowing again.
* @pdev: Pointer to PCI device
*
* This callback is called when the error recovery driver tells us that
* its OK to resume normal operation. Implementation resembles the
* second-half of the igbvf_resume routine.
*/
static void igbvf_io_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igbvf_adapter *adapter = netdev_priv(netdev);
if (netif_running(netdev)) {
if (igbvf_up(adapter)) {
dev_err(&pdev->dev,
"can't bring device back up after reset\n");
return;
}
}
netif_device_attach(netdev);
}
static void igbvf_print_device_info(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
if (hw->mac.type == e1000_vfadapt_i350)
dev_info(&pdev->dev, "Intel(R) I350 Virtual Function\n");
else
dev_info(&pdev->dev, "Intel(R) 82576 Virtual Function\n");
dev_info(&pdev->dev, "Address: %pM\n", netdev->dev_addr);
}
static int igbvf_set_features(struct net_device *netdev,
netdev_features_t features)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
if (features & NETIF_F_RXCSUM)
adapter->flags &= ~IGBVF_FLAG_RX_CSUM_DISABLED;
else
adapter->flags |= IGBVF_FLAG_RX_CSUM_DISABLED;
return 0;
}
static const struct net_device_ops igbvf_netdev_ops = {
.ndo_open = igbvf_open,
.ndo_stop = igbvf_close,
.ndo_start_xmit = igbvf_xmit_frame,
.ndo_get_stats = igbvf_get_stats,
.ndo_set_rx_mode = igbvf_set_multi,
.ndo_set_mac_address = igbvf_set_mac,
.ndo_change_mtu = igbvf_change_mtu,
.ndo_do_ioctl = igbvf_ioctl,
.ndo_tx_timeout = igbvf_tx_timeout,
.ndo_vlan_rx_add_vid = igbvf_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = igbvf_vlan_rx_kill_vid,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = igbvf_netpoll,
#endif
.ndo_set_features = igbvf_set_features,
};
/**
* igbvf_probe - Device Initialization Routine
* @pdev: PCI device information struct
* @ent: entry in igbvf_pci_tbl
*
* Returns 0 on success, negative on failure
*
* igbvf_probe initializes an adapter identified by a pci_dev structure.
* The OS initialization, configuring of the adapter private structure,
* and a hardware reset occur.
**/
static int igbvf_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct net_device *netdev;
struct igbvf_adapter *adapter;
struct e1000_hw *hw;
const struct igbvf_info *ei = igbvf_info_tbl[ent->driver_data];
static int cards_found;
int err, pci_using_dac;
err = pci_enable_device_mem(pdev);
if (err)
return err;
pci_using_dac = 0;
err = dma_set_mask(&pdev->dev, DMA_BIT_MASK(64));
if (!err) {
err = dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(64));
if (!err)
pci_using_dac = 1;
} else {
err = dma_set_mask(&pdev->dev, DMA_BIT_MASK(32));
if (err) {
err = dma_set_coherent_mask(&pdev->dev,
DMA_BIT_MASK(32));
if (err) {
dev_err(&pdev->dev, "No usable DMA "
"configuration, aborting\n");
goto err_dma;
}
}
}
err = pci_request_regions(pdev, igbvf_driver_name);
if (err)
goto err_pci_reg;
pci_set_master(pdev);
err = -ENOMEM;
netdev = alloc_etherdev(sizeof(struct igbvf_adapter));
if (!netdev)
goto err_alloc_etherdev;
SET_NETDEV_DEV(netdev, &pdev->dev);
pci_set_drvdata(pdev, netdev);
adapter = netdev_priv(netdev);
hw = &adapter->hw;
adapter->netdev = netdev;
adapter->pdev = pdev;
adapter->ei = ei;
adapter->pba = ei->pba;
adapter->flags = ei->flags;
adapter->hw.back = adapter;
adapter->hw.mac.type = ei->mac;
adapter->msg_enable = netif_msg_init(debug, DEFAULT_MSG_ENABLE);
/* PCI config space info */
hw->vendor_id = pdev->vendor;
hw->device_id = pdev->device;
hw->subsystem_vendor_id = pdev->subsystem_vendor;
hw->subsystem_device_id = pdev->subsystem_device;
hw->revision_id = pdev->revision;
err = -EIO;
adapter->hw.hw_addr = ioremap(pci_resource_start(pdev, 0),
pci_resource_len(pdev, 0));
if (!adapter->hw.hw_addr)
goto err_ioremap;
if (ei->get_variants) {
err = ei->get_variants(adapter);
if (err)
goto err_ioremap;
}
/* setup adapter struct */
err = igbvf_sw_init(adapter);
if (err)
goto err_sw_init;
/* construct the net_device struct */
netdev->netdev_ops = &igbvf_netdev_ops;
igbvf_set_ethtool_ops(netdev);
netdev->watchdog_timeo = 5 * HZ;
strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1);
adapter->bd_number = cards_found++;
netdev->hw_features = NETIF_F_SG |
NETIF_F_IP_CSUM |
NETIF_F_IPV6_CSUM |
NETIF_F_TSO |
NETIF_F_TSO6 |
NETIF_F_RXCSUM;
netdev->features = netdev->hw_features |
NETIF_F_HW_VLAN_TX |
NETIF_F_HW_VLAN_RX |
NETIF_F_HW_VLAN_FILTER;
if (pci_using_dac)
netdev->features |= NETIF_F_HIGHDMA;
netdev->vlan_features |= NETIF_F_TSO;
netdev->vlan_features |= NETIF_F_TSO6;
netdev->vlan_features |= NETIF_F_IP_CSUM;
netdev->vlan_features |= NETIF_F_IPV6_CSUM;
netdev->vlan_features |= NETIF_F_SG;
/*reset the controller to put the device in a known good state */
err = hw->mac.ops.reset_hw(hw);
if (err) {
dev_info(&pdev->dev,
"PF still in reset state, assigning new address."
" Is the PF interface up?\n");
eth_hw_addr_random(netdev);
memcpy(adapter->hw.mac.addr, netdev->dev_addr,
netdev->addr_len);
} else {
err = hw->mac.ops.read_mac_addr(hw);
if (err) {
dev_err(&pdev->dev, "Error reading MAC address\n");
goto err_hw_init;
}
memcpy(netdev->dev_addr, adapter->hw.mac.addr,
netdev->addr_len);
}
if (!is_valid_ether_addr(netdev->dev_addr)) {
dev_err(&pdev->dev, "Invalid MAC Address: %pM\n",
netdev->dev_addr);
err = -EIO;
goto err_hw_init;
}
memcpy(netdev->perm_addr, netdev->dev_addr, netdev->addr_len);
setup_timer(&adapter->watchdog_timer, &igbvf_watchdog,
(unsigned long) adapter);
INIT_WORK(&adapter->reset_task, igbvf_reset_task);
INIT_WORK(&adapter->watchdog_task, igbvf_watchdog_task);
/* ring size defaults */
adapter->rx_ring->count = 1024;
adapter->tx_ring->count = 1024;
/* reset the hardware with the new settings */
igbvf_reset(adapter);
/* set hardware-specific flags */
if (adapter->hw.mac.type == e1000_vfadapt_i350)
adapter->flags |= IGBVF_FLAG_RX_LB_VLAN_BSWAP;
strcpy(netdev->name, "eth%d");
err = register_netdev(netdev);
if (err)
goto err_hw_init;
/* tell the stack to leave us alone until igbvf_open() is called */
netif_carrier_off(netdev);
netif_stop_queue(netdev);
igbvf_print_device_info(adapter);
igbvf_initialize_last_counter_stats(adapter);
return 0;
err_hw_init:
kfree(adapter->tx_ring);
kfree(adapter->rx_ring);
err_sw_init:
igbvf_reset_interrupt_capability(adapter);
iounmap(adapter->hw.hw_addr);
err_ioremap:
free_netdev(netdev);
err_alloc_etherdev:
pci_release_regions(pdev);
err_pci_reg:
err_dma:
pci_disable_device(pdev);
return err;
}
/**
* igbvf_remove - Device Removal Routine
* @pdev: PCI device information struct
*
* igbvf_remove is called by the PCI subsystem to alert the driver
* that it should release a PCI device. The could be caused by a
* Hot-Plug event, or because the driver is going to be removed from
* memory.
**/
static void igbvf_remove(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
/*
* The watchdog timer may be rescheduled, so explicitly
* disable it from being rescheduled.
*/
set_bit(__IGBVF_DOWN, &adapter->state);
del_timer_sync(&adapter->watchdog_timer);
cancel_work_sync(&adapter->reset_task);
cancel_work_sync(&adapter->watchdog_task);
unregister_netdev(netdev);
igbvf_reset_interrupt_capability(adapter);
/*
* it is important to delete the napi struct prior to freeing the
* rx ring so that you do not end up with null pointer refs
*/
netif_napi_del(&adapter->rx_ring->napi);
kfree(adapter->tx_ring);
kfree(adapter->rx_ring);
iounmap(hw->hw_addr);
if (hw->flash_address)
iounmap(hw->flash_address);
pci_release_regions(pdev);
free_netdev(netdev);
pci_disable_device(pdev);
}
/* PCI Error Recovery (ERS) */
static const struct pci_error_handlers igbvf_err_handler = {
.error_detected = igbvf_io_error_detected,
.slot_reset = igbvf_io_slot_reset,
.resume = igbvf_io_resume,
};
static DEFINE_PCI_DEVICE_TABLE(igbvf_pci_tbl) = {
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_VF), board_vf },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_I350_VF), board_i350_vf },
{ } /* terminate list */
};
MODULE_DEVICE_TABLE(pci, igbvf_pci_tbl);
/* PCI Device API Driver */
static struct pci_driver igbvf_driver = {
.name = igbvf_driver_name,
.id_table = igbvf_pci_tbl,
.probe = igbvf_probe,
.remove = igbvf_remove,
#ifdef CONFIG_PM
/* Power Management Hooks */
.suspend = igbvf_suspend,
.resume = igbvf_resume,
#endif
.shutdown = igbvf_shutdown,
.err_handler = &igbvf_err_handler
};
/**
* igbvf_init_module - Driver Registration Routine
*
* igbvf_init_module is the first routine called when the driver is
* loaded. All it does is register with the PCI subsystem.
**/
static int __init igbvf_init_module(void)
{
int ret;
pr_info("%s - version %s\n", igbvf_driver_string, igbvf_driver_version);
pr_info("%s\n", igbvf_copyright);
ret = pci_register_driver(&igbvf_driver);
return ret;
}
module_init(igbvf_init_module);
/**
* igbvf_exit_module - Driver Exit Cleanup Routine
*
* igbvf_exit_module is called just before the driver is removed
* from memory.
**/
static void __exit igbvf_exit_module(void)
{
pci_unregister_driver(&igbvf_driver);
}
module_exit(igbvf_exit_module);
MODULE_AUTHOR("Intel Corporation, <e1000-devel@lists.sourceforge.net>");
MODULE_DESCRIPTION("Intel(R) Gigabit Virtual Function Network Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
/* netdev.c */
| gpl-2.0 |
houstar/linux-3.8.8 | net/netfilter/nfnetlink_log.c | 101 | 25787 | /*
* This is a module which is used for logging packets to userspace via
* nfetlink.
*
* (C) 2005 by Harald Welte <laforge@netfilter.org>
*
* Based on the old ipv4-only ipt_ULOG.c:
* (C) 2000-2004 by Harald Welte <laforge@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.
*/
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/if_arp.h>
#include <linux/init.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/netdevice.h>
#include <linux/netfilter.h>
#include <linux/netlink.h>
#include <linux/netfilter/nfnetlink.h>
#include <linux/netfilter/nfnetlink_log.h>
#include <linux/spinlock.h>
#include <linux/sysctl.h>
#include <linux/proc_fs.h>
#include <linux/security.h>
#include <linux/list.h>
#include <linux/jhash.h>
#include <linux/random.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <net/netfilter/nf_log.h>
#include <net/netfilter/nfnetlink_log.h>
#include <linux/atomic.h>
#ifdef CONFIG_BRIDGE_NETFILTER
#include "../bridge/br_private.h"
#endif
#define NFULNL_NLBUFSIZ_DEFAULT NLMSG_GOODSIZE
#define NFULNL_TIMEOUT_DEFAULT 100 /* every second */
#define NFULNL_QTHRESH_DEFAULT 100 /* 100 packets */
#define NFULNL_COPY_RANGE_MAX 0xFFFF /* max packet size is limited by 16-bit struct nfattr nfa_len field */
#define PRINTR(x, args...) do { if (net_ratelimit()) \
printk(x, ## args); } while (0);
struct nfulnl_instance {
struct hlist_node hlist; /* global list of instances */
spinlock_t lock;
atomic_t use; /* use count */
unsigned int qlen; /* number of nlmsgs in skb */
struct sk_buff *skb; /* pre-allocatd skb */
struct timer_list timer;
struct user_namespace *peer_user_ns; /* User namespace of the peer process */
int peer_portid; /* PORTID of the peer process */
/* configurable parameters */
unsigned int flushtimeout; /* timeout until queue flush */
unsigned int nlbufsiz; /* netlink buffer allocation size */
unsigned int qthreshold; /* threshold of the queue */
u_int32_t copy_range;
u_int32_t seq; /* instance-local sequential counter */
u_int16_t group_num; /* number of this queue */
u_int16_t flags;
u_int8_t copy_mode;
struct rcu_head rcu;
};
static DEFINE_SPINLOCK(instances_lock);
static atomic_t global_seq;
#define INSTANCE_BUCKETS 16
static struct hlist_head instance_table[INSTANCE_BUCKETS];
static unsigned int hash_init;
static inline u_int8_t instance_hashfn(u_int16_t group_num)
{
return ((group_num & 0xff) % INSTANCE_BUCKETS);
}
static struct nfulnl_instance *
__instance_lookup(u_int16_t group_num)
{
struct hlist_head *head;
struct hlist_node *pos;
struct nfulnl_instance *inst;
head = &instance_table[instance_hashfn(group_num)];
hlist_for_each_entry_rcu(inst, pos, head, hlist) {
if (inst->group_num == group_num)
return inst;
}
return NULL;
}
static inline void
instance_get(struct nfulnl_instance *inst)
{
atomic_inc(&inst->use);
}
static struct nfulnl_instance *
instance_lookup_get(u_int16_t group_num)
{
struct nfulnl_instance *inst;
rcu_read_lock_bh();
inst = __instance_lookup(group_num);
if (inst && !atomic_inc_not_zero(&inst->use))
inst = NULL;
rcu_read_unlock_bh();
return inst;
}
static void nfulnl_instance_free_rcu(struct rcu_head *head)
{
kfree(container_of(head, struct nfulnl_instance, rcu));
module_put(THIS_MODULE);
}
static void
instance_put(struct nfulnl_instance *inst)
{
if (inst && atomic_dec_and_test(&inst->use))
call_rcu_bh(&inst->rcu, nfulnl_instance_free_rcu);
}
static void nfulnl_timer(unsigned long data);
static struct nfulnl_instance *
instance_create(u_int16_t group_num, int portid, struct user_namespace *user_ns)
{
struct nfulnl_instance *inst;
int err;
spin_lock_bh(&instances_lock);
if (__instance_lookup(group_num)) {
err = -EEXIST;
goto out_unlock;
}
inst = kzalloc(sizeof(*inst), GFP_ATOMIC);
if (!inst) {
err = -ENOMEM;
goto out_unlock;
}
if (!try_module_get(THIS_MODULE)) {
kfree(inst);
err = -EAGAIN;
goto out_unlock;
}
INIT_HLIST_NODE(&inst->hlist);
spin_lock_init(&inst->lock);
/* needs to be two, since we _put() after creation */
atomic_set(&inst->use, 2);
setup_timer(&inst->timer, nfulnl_timer, (unsigned long)inst);
inst->peer_user_ns = user_ns;
inst->peer_portid = portid;
inst->group_num = group_num;
inst->qthreshold = NFULNL_QTHRESH_DEFAULT;
inst->flushtimeout = NFULNL_TIMEOUT_DEFAULT;
inst->nlbufsiz = NFULNL_NLBUFSIZ_DEFAULT;
inst->copy_mode = NFULNL_COPY_PACKET;
inst->copy_range = NFULNL_COPY_RANGE_MAX;
hlist_add_head_rcu(&inst->hlist,
&instance_table[instance_hashfn(group_num)]);
spin_unlock_bh(&instances_lock);
return inst;
out_unlock:
spin_unlock_bh(&instances_lock);
return ERR_PTR(err);
}
static void __nfulnl_flush(struct nfulnl_instance *inst);
/* called with BH disabled */
static void
__instance_destroy(struct nfulnl_instance *inst)
{
/* first pull it out of the global list */
hlist_del_rcu(&inst->hlist);
/* then flush all pending packets from skb */
spin_lock(&inst->lock);
/* lockless readers wont be able to use us */
inst->copy_mode = NFULNL_COPY_DISABLED;
if (inst->skb)
__nfulnl_flush(inst);
spin_unlock(&inst->lock);
/* and finally put the refcount */
instance_put(inst);
}
static inline void
instance_destroy(struct nfulnl_instance *inst)
{
spin_lock_bh(&instances_lock);
__instance_destroy(inst);
spin_unlock_bh(&instances_lock);
}
static int
nfulnl_set_mode(struct nfulnl_instance *inst, u_int8_t mode,
unsigned int range)
{
int status = 0;
spin_lock_bh(&inst->lock);
switch (mode) {
case NFULNL_COPY_NONE:
case NFULNL_COPY_META:
inst->copy_mode = mode;
inst->copy_range = 0;
break;
case NFULNL_COPY_PACKET:
inst->copy_mode = mode;
inst->copy_range = min_t(unsigned int,
range, NFULNL_COPY_RANGE_MAX);
break;
default:
status = -EINVAL;
break;
}
spin_unlock_bh(&inst->lock);
return status;
}
static int
nfulnl_set_nlbufsiz(struct nfulnl_instance *inst, u_int32_t nlbufsiz)
{
int status;
spin_lock_bh(&inst->lock);
if (nlbufsiz < NFULNL_NLBUFSIZ_DEFAULT)
status = -ERANGE;
else if (nlbufsiz > 131072)
status = -ERANGE;
else {
inst->nlbufsiz = nlbufsiz;
status = 0;
}
spin_unlock_bh(&inst->lock);
return status;
}
static int
nfulnl_set_timeout(struct nfulnl_instance *inst, u_int32_t timeout)
{
spin_lock_bh(&inst->lock);
inst->flushtimeout = timeout;
spin_unlock_bh(&inst->lock);
return 0;
}
static int
nfulnl_set_qthresh(struct nfulnl_instance *inst, u_int32_t qthresh)
{
spin_lock_bh(&inst->lock);
inst->qthreshold = qthresh;
spin_unlock_bh(&inst->lock);
return 0;
}
static int
nfulnl_set_flags(struct nfulnl_instance *inst, u_int16_t flags)
{
spin_lock_bh(&inst->lock);
inst->flags = flags;
spin_unlock_bh(&inst->lock);
return 0;
}
static struct sk_buff *
nfulnl_alloc_skb(unsigned int inst_size, unsigned int pkt_size)
{
struct sk_buff *skb;
unsigned int n;
/* alloc skb which should be big enough for a whole multipart
* message. WARNING: has to be <= 128k due to slab restrictions */
n = max(inst_size, pkt_size);
skb = alloc_skb(n, GFP_ATOMIC);
if (!skb) {
if (n > pkt_size) {
/* try to allocate only as much as we need for current
* packet */
skb = alloc_skb(pkt_size, GFP_ATOMIC);
if (!skb)
pr_err("nfnetlink_log: can't even alloc %u bytes\n",
pkt_size);
}
}
return skb;
}
static int
__nfulnl_send(struct nfulnl_instance *inst)
{
int status = -1;
if (inst->qlen > 1) {
struct nlmsghdr *nlh = nlmsg_put(inst->skb, 0, 0,
NLMSG_DONE,
sizeof(struct nfgenmsg),
0);
if (!nlh)
goto out;
}
status = nfnetlink_unicast(inst->skb, &init_net, inst->peer_portid,
MSG_DONTWAIT);
inst->qlen = 0;
inst->skb = NULL;
out:
return status;
}
static void
__nfulnl_flush(struct nfulnl_instance *inst)
{
/* timer holds a reference */
if (del_timer(&inst->timer))
instance_put(inst);
if (inst->skb)
__nfulnl_send(inst);
}
static void
nfulnl_timer(unsigned long data)
{
struct nfulnl_instance *inst = (struct nfulnl_instance *)data;
spin_lock_bh(&inst->lock);
if (inst->skb)
__nfulnl_send(inst);
spin_unlock_bh(&inst->lock);
instance_put(inst);
}
/* This is an inline function, we don't really care about a long
* list of arguments */
static inline int
__build_packet_message(struct nfulnl_instance *inst,
const struct sk_buff *skb,
unsigned int data_len,
u_int8_t pf,
unsigned int hooknum,
const struct net_device *indev,
const struct net_device *outdev,
const char *prefix, unsigned int plen)
{
struct nfulnl_msg_packet_hdr pmsg;
struct nlmsghdr *nlh;
struct nfgenmsg *nfmsg;
sk_buff_data_t old_tail = inst->skb->tail;
struct sock *sk;
const unsigned char *hwhdrp;
nlh = nlmsg_put(inst->skb, 0, 0,
NFNL_SUBSYS_ULOG << 8 | NFULNL_MSG_PACKET,
sizeof(struct nfgenmsg), 0);
if (!nlh)
return -1;
nfmsg = nlmsg_data(nlh);
nfmsg->nfgen_family = pf;
nfmsg->version = NFNETLINK_V0;
nfmsg->res_id = htons(inst->group_num);
pmsg.hw_protocol = skb->protocol;
pmsg.hook = hooknum;
if (nla_put(inst->skb, NFULA_PACKET_HDR, sizeof(pmsg), &pmsg))
goto nla_put_failure;
if (prefix &&
nla_put(inst->skb, NFULA_PREFIX, plen, prefix))
goto nla_put_failure;
if (indev) {
#ifndef CONFIG_BRIDGE_NETFILTER
if (nla_put_be32(inst->skb, NFULA_IFINDEX_INDEV,
htonl(indev->ifindex)))
goto nla_put_failure;
#else
if (pf == PF_BRIDGE) {
/* Case 1: outdev is physical input device, we need to
* look for bridge group (when called from
* netfilter_bridge) */
if (nla_put_be32(inst->skb, NFULA_IFINDEX_PHYSINDEV,
htonl(indev->ifindex)) ||
/* this is the bridge group "brX" */
/* rcu_read_lock()ed by nf_hook_slow or nf_log_packet */
nla_put_be32(inst->skb, NFULA_IFINDEX_INDEV,
htonl(br_port_get_rcu(indev)->br->dev->ifindex)))
goto nla_put_failure;
} else {
/* Case 2: indev is bridge group, we need to look for
* physical device (when called from ipv4) */
if (nla_put_be32(inst->skb, NFULA_IFINDEX_INDEV,
htonl(indev->ifindex)))
goto nla_put_failure;
if (skb->nf_bridge && skb->nf_bridge->physindev &&
nla_put_be32(inst->skb, NFULA_IFINDEX_PHYSINDEV,
htonl(skb->nf_bridge->physindev->ifindex)))
goto nla_put_failure;
}
#endif
}
if (outdev) {
#ifndef CONFIG_BRIDGE_NETFILTER
if (nla_put_be32(inst->skb, NFULA_IFINDEX_OUTDEV,
htonl(outdev->ifindex)))
goto nla_put_failure;
#else
if (pf == PF_BRIDGE) {
/* Case 1: outdev is physical output device, we need to
* look for bridge group (when called from
* netfilter_bridge) */
if (nla_put_be32(inst->skb, NFULA_IFINDEX_PHYSOUTDEV,
htonl(outdev->ifindex)) ||
/* this is the bridge group "brX" */
/* rcu_read_lock()ed by nf_hook_slow or nf_log_packet */
nla_put_be32(inst->skb, NFULA_IFINDEX_OUTDEV,
htonl(br_port_get_rcu(outdev)->br->dev->ifindex)))
goto nla_put_failure;
} else {
/* Case 2: indev is a bridge group, we need to look
* for physical device (when called from ipv4) */
if (nla_put_be32(inst->skb, NFULA_IFINDEX_OUTDEV,
htonl(outdev->ifindex)))
goto nla_put_failure;
if (skb->nf_bridge && skb->nf_bridge->physoutdev &&
nla_put_be32(inst->skb, NFULA_IFINDEX_PHYSOUTDEV,
htonl(skb->nf_bridge->physoutdev->ifindex)))
goto nla_put_failure;
}
#endif
}
if (skb->mark &&
nla_put_be32(inst->skb, NFULA_MARK, htonl(skb->mark)))
goto nla_put_failure;
if (indev && skb->dev &&
skb->mac_header != skb->network_header) {
struct nfulnl_msg_packet_hw phw;
int len = dev_parse_header(skb, phw.hw_addr);
if (len > 0) {
phw.hw_addrlen = htons(len);
if (nla_put(inst->skb, NFULA_HWADDR, sizeof(phw), &phw))
goto nla_put_failure;
}
}
if (indev && skb_mac_header_was_set(skb)) {
if (nla_put_be16(inst->skb, NFULA_HWTYPE, htons(skb->dev->type)) ||
nla_put_be16(inst->skb, NFULA_HWLEN,
htons(skb->dev->hard_header_len)))
goto nla_put_failure;
hwhdrp = skb_mac_header(skb);
if (skb->dev->type == ARPHRD_SIT)
hwhdrp -= ETH_HLEN;
if (hwhdrp >= skb->head &&
nla_put(inst->skb, NFULA_HWHEADER,
skb->dev->hard_header_len, hwhdrp))
goto nla_put_failure;
}
if (skb->tstamp.tv64) {
struct nfulnl_msg_packet_timestamp ts;
struct timeval tv = ktime_to_timeval(skb->tstamp);
ts.sec = cpu_to_be64(tv.tv_sec);
ts.usec = cpu_to_be64(tv.tv_usec);
if (nla_put(inst->skb, NFULA_TIMESTAMP, sizeof(ts), &ts))
goto nla_put_failure;
}
/* UID */
sk = skb->sk;
if (sk && sk->sk_state != TCP_TIME_WAIT) {
read_lock_bh(&sk->sk_callback_lock);
if (sk->sk_socket && sk->sk_socket->file) {
struct file *file = sk->sk_socket->file;
const struct cred *cred = file->f_cred;
struct user_namespace *user_ns = inst->peer_user_ns;
__be32 uid = htonl(from_kuid_munged(user_ns, cred->fsuid));
__be32 gid = htonl(from_kgid_munged(user_ns, cred->fsgid));
read_unlock_bh(&sk->sk_callback_lock);
if (nla_put_be32(inst->skb, NFULA_UID, uid) ||
nla_put_be32(inst->skb, NFULA_GID, gid))
goto nla_put_failure;
} else
read_unlock_bh(&sk->sk_callback_lock);
}
/* local sequence number */
if ((inst->flags & NFULNL_CFG_F_SEQ) &&
nla_put_be32(inst->skb, NFULA_SEQ, htonl(inst->seq++)))
goto nla_put_failure;
/* global sequence number */
if ((inst->flags & NFULNL_CFG_F_SEQ_GLOBAL) &&
nla_put_be32(inst->skb, NFULA_SEQ_GLOBAL,
htonl(atomic_inc_return(&global_seq))))
goto nla_put_failure;
if (data_len) {
struct nlattr *nla;
int size = nla_attr_size(data_len);
if (skb_tailroom(inst->skb) < nla_total_size(data_len)) {
printk(KERN_WARNING "nfnetlink_log: no tailroom!\n");
return -1;
}
nla = (struct nlattr *)skb_put(inst->skb, nla_total_size(data_len));
nla->nla_type = NFULA_PAYLOAD;
nla->nla_len = size;
if (skb_copy_bits(skb, 0, nla_data(nla), data_len))
BUG();
}
nlh->nlmsg_len = inst->skb->tail - old_tail;
return 0;
nla_put_failure:
PRINTR(KERN_ERR "nfnetlink_log: error creating log nlmsg\n");
return -1;
}
#define RCV_SKB_FAIL(err) do { netlink_ack(skb, nlh, (err)); return; } while (0)
static struct nf_loginfo default_loginfo = {
.type = NF_LOG_TYPE_ULOG,
.u = {
.ulog = {
.copy_len = 0xffff,
.group = 0,
.qthreshold = 1,
},
},
};
/* log handler for internal netfilter logging api */
void
nfulnl_log_packet(u_int8_t pf,
unsigned int hooknum,
const struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
const struct nf_loginfo *li_user,
const char *prefix)
{
unsigned int size, data_len;
struct nfulnl_instance *inst;
const struct nf_loginfo *li;
unsigned int qthreshold;
unsigned int plen;
if (li_user && li_user->type == NF_LOG_TYPE_ULOG)
li = li_user;
else
li = &default_loginfo;
inst = instance_lookup_get(li->u.ulog.group);
if (!inst)
return;
plen = 0;
if (prefix)
plen = strlen(prefix) + 1;
/* FIXME: do we want to make the size calculation conditional based on
* what is actually present? way more branches and checks, but more
* memory efficient... */
size = NLMSG_SPACE(sizeof(struct nfgenmsg))
+ nla_total_size(sizeof(struct nfulnl_msg_packet_hdr))
+ nla_total_size(sizeof(u_int32_t)) /* ifindex */
+ nla_total_size(sizeof(u_int32_t)) /* ifindex */
#ifdef CONFIG_BRIDGE_NETFILTER
+ nla_total_size(sizeof(u_int32_t)) /* ifindex */
+ nla_total_size(sizeof(u_int32_t)) /* ifindex */
#endif
+ nla_total_size(sizeof(u_int32_t)) /* mark */
+ nla_total_size(sizeof(u_int32_t)) /* uid */
+ nla_total_size(sizeof(u_int32_t)) /* gid */
+ nla_total_size(plen) /* prefix */
+ nla_total_size(sizeof(struct nfulnl_msg_packet_hw))
+ nla_total_size(sizeof(struct nfulnl_msg_packet_timestamp));
if (in && skb_mac_header_was_set(skb)) {
size += nla_total_size(skb->dev->hard_header_len)
+ nla_total_size(sizeof(u_int16_t)) /* hwtype */
+ nla_total_size(sizeof(u_int16_t)); /* hwlen */
}
spin_lock_bh(&inst->lock);
if (inst->flags & NFULNL_CFG_F_SEQ)
size += nla_total_size(sizeof(u_int32_t));
if (inst->flags & NFULNL_CFG_F_SEQ_GLOBAL)
size += nla_total_size(sizeof(u_int32_t));
qthreshold = inst->qthreshold;
/* per-rule qthreshold overrides per-instance */
if (li->u.ulog.qthreshold)
if (qthreshold > li->u.ulog.qthreshold)
qthreshold = li->u.ulog.qthreshold;
switch (inst->copy_mode) {
case NFULNL_COPY_META:
case NFULNL_COPY_NONE:
data_len = 0;
break;
case NFULNL_COPY_PACKET:
if (inst->copy_range == 0
|| inst->copy_range > skb->len)
data_len = skb->len;
else
data_len = inst->copy_range;
size += nla_total_size(data_len);
break;
case NFULNL_COPY_DISABLED:
default:
goto unlock_and_release;
}
if (inst->skb &&
size > skb_tailroom(inst->skb) - sizeof(struct nfgenmsg)) {
/* either the queue len is too high or we don't have
* enough room in the skb left. flush to userspace. */
__nfulnl_flush(inst);
}
if (!inst->skb) {
inst->skb = nfulnl_alloc_skb(inst->nlbufsiz, size);
if (!inst->skb)
goto alloc_failure;
}
inst->qlen++;
__build_packet_message(inst, skb, data_len, pf,
hooknum, in, out, prefix, plen);
if (inst->qlen >= qthreshold)
__nfulnl_flush(inst);
/* timer_pending always called within inst->lock, so there
* is no chance of a race here */
else if (!timer_pending(&inst->timer)) {
instance_get(inst);
inst->timer.expires = jiffies + (inst->flushtimeout*HZ/100);
add_timer(&inst->timer);
}
unlock_and_release:
spin_unlock_bh(&inst->lock);
instance_put(inst);
return;
alloc_failure:
/* FIXME: statistics */
goto unlock_and_release;
}
EXPORT_SYMBOL_GPL(nfulnl_log_packet);
static int
nfulnl_rcv_nl_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct netlink_notify *n = ptr;
if (event == NETLINK_URELEASE && n->protocol == NETLINK_NETFILTER) {
int i;
/* destroy all instances for this portid */
spin_lock_bh(&instances_lock);
for (i = 0; i < INSTANCE_BUCKETS; i++) {
struct hlist_node *tmp, *t2;
struct nfulnl_instance *inst;
struct hlist_head *head = &instance_table[i];
hlist_for_each_entry_safe(inst, tmp, t2, head, hlist) {
if ((net_eq(n->net, &init_net)) &&
(n->portid == inst->peer_portid))
__instance_destroy(inst);
}
}
spin_unlock_bh(&instances_lock);
}
return NOTIFY_DONE;
}
static struct notifier_block nfulnl_rtnl_notifier = {
.notifier_call = nfulnl_rcv_nl_event,
};
static int
nfulnl_recv_unsupp(struct sock *ctnl, struct sk_buff *skb,
const struct nlmsghdr *nlh,
const struct nlattr * const nfqa[])
{
return -ENOTSUPP;
}
static struct nf_logger nfulnl_logger __read_mostly = {
.name = "nfnetlink_log",
.logfn = &nfulnl_log_packet,
.me = THIS_MODULE,
};
static const struct nla_policy nfula_cfg_policy[NFULA_CFG_MAX+1] = {
[NFULA_CFG_CMD] = { .len = sizeof(struct nfulnl_msg_config_cmd) },
[NFULA_CFG_MODE] = { .len = sizeof(struct nfulnl_msg_config_mode) },
[NFULA_CFG_TIMEOUT] = { .type = NLA_U32 },
[NFULA_CFG_QTHRESH] = { .type = NLA_U32 },
[NFULA_CFG_NLBUFSIZ] = { .type = NLA_U32 },
[NFULA_CFG_FLAGS] = { .type = NLA_U16 },
};
static int
nfulnl_recv_config(struct sock *ctnl, struct sk_buff *skb,
const struct nlmsghdr *nlh,
const struct nlattr * const nfula[])
{
struct nfgenmsg *nfmsg = nlmsg_data(nlh);
u_int16_t group_num = ntohs(nfmsg->res_id);
struct nfulnl_instance *inst;
struct nfulnl_msg_config_cmd *cmd = NULL;
int ret = 0;
if (nfula[NFULA_CFG_CMD]) {
u_int8_t pf = nfmsg->nfgen_family;
cmd = nla_data(nfula[NFULA_CFG_CMD]);
/* Commands without queue context */
switch (cmd->command) {
case NFULNL_CFG_CMD_PF_BIND:
return nf_log_bind_pf(pf, &nfulnl_logger);
case NFULNL_CFG_CMD_PF_UNBIND:
nf_log_unbind_pf(pf);
return 0;
}
}
inst = instance_lookup_get(group_num);
if (inst && inst->peer_portid != NETLINK_CB(skb).portid) {
ret = -EPERM;
goto out_put;
}
if (cmd != NULL) {
switch (cmd->command) {
case NFULNL_CFG_CMD_BIND:
if (inst) {
ret = -EBUSY;
goto out_put;
}
inst = instance_create(group_num,
NETLINK_CB(skb).portid,
sk_user_ns(NETLINK_CB(skb).ssk));
if (IS_ERR(inst)) {
ret = PTR_ERR(inst);
goto out;
}
break;
case NFULNL_CFG_CMD_UNBIND:
if (!inst) {
ret = -ENODEV;
goto out;
}
instance_destroy(inst);
goto out_put;
default:
ret = -ENOTSUPP;
break;
}
}
if (nfula[NFULA_CFG_MODE]) {
struct nfulnl_msg_config_mode *params;
params = nla_data(nfula[NFULA_CFG_MODE]);
if (!inst) {
ret = -ENODEV;
goto out;
}
nfulnl_set_mode(inst, params->copy_mode,
ntohl(params->copy_range));
}
if (nfula[NFULA_CFG_TIMEOUT]) {
__be32 timeout = nla_get_be32(nfula[NFULA_CFG_TIMEOUT]);
if (!inst) {
ret = -ENODEV;
goto out;
}
nfulnl_set_timeout(inst, ntohl(timeout));
}
if (nfula[NFULA_CFG_NLBUFSIZ]) {
__be32 nlbufsiz = nla_get_be32(nfula[NFULA_CFG_NLBUFSIZ]);
if (!inst) {
ret = -ENODEV;
goto out;
}
nfulnl_set_nlbufsiz(inst, ntohl(nlbufsiz));
}
if (nfula[NFULA_CFG_QTHRESH]) {
__be32 qthresh = nla_get_be32(nfula[NFULA_CFG_QTHRESH]);
if (!inst) {
ret = -ENODEV;
goto out;
}
nfulnl_set_qthresh(inst, ntohl(qthresh));
}
if (nfula[NFULA_CFG_FLAGS]) {
__be16 flags = nla_get_be16(nfula[NFULA_CFG_FLAGS]);
if (!inst) {
ret = -ENODEV;
goto out;
}
nfulnl_set_flags(inst, ntohs(flags));
}
out_put:
instance_put(inst);
out:
return ret;
}
static const struct nfnl_callback nfulnl_cb[NFULNL_MSG_MAX] = {
[NFULNL_MSG_PACKET] = { .call = nfulnl_recv_unsupp,
.attr_count = NFULA_MAX, },
[NFULNL_MSG_CONFIG] = { .call = nfulnl_recv_config,
.attr_count = NFULA_CFG_MAX,
.policy = nfula_cfg_policy },
};
static const struct nfnetlink_subsystem nfulnl_subsys = {
.name = "log",
.subsys_id = NFNL_SUBSYS_ULOG,
.cb_count = NFULNL_MSG_MAX,
.cb = nfulnl_cb,
};
#ifdef CONFIG_PROC_FS
struct iter_state {
unsigned int bucket;
};
static struct hlist_node *get_first(struct iter_state *st)
{
if (!st)
return NULL;
for (st->bucket = 0; st->bucket < INSTANCE_BUCKETS; st->bucket++) {
if (!hlist_empty(&instance_table[st->bucket]))
return rcu_dereference_bh(hlist_first_rcu(&instance_table[st->bucket]));
}
return NULL;
}
static struct hlist_node *get_next(struct iter_state *st, struct hlist_node *h)
{
h = rcu_dereference_bh(hlist_next_rcu(h));
while (!h) {
if (++st->bucket >= INSTANCE_BUCKETS)
return NULL;
h = rcu_dereference_bh(hlist_first_rcu(&instance_table[st->bucket]));
}
return h;
}
static struct hlist_node *get_idx(struct iter_state *st, loff_t pos)
{
struct hlist_node *head;
head = get_first(st);
if (head)
while (pos && (head = get_next(st, head)))
pos--;
return pos ? NULL : head;
}
static void *seq_start(struct seq_file *seq, loff_t *pos)
__acquires(rcu_bh)
{
rcu_read_lock_bh();
return get_idx(seq->private, *pos);
}
static void *seq_next(struct seq_file *s, void *v, loff_t *pos)
{
(*pos)++;
return get_next(s->private, v);
}
static void seq_stop(struct seq_file *s, void *v)
__releases(rcu_bh)
{
rcu_read_unlock_bh();
}
static int seq_show(struct seq_file *s, void *v)
{
const struct nfulnl_instance *inst = v;
return seq_printf(s, "%5d %6d %5d %1d %5d %6d %2d\n",
inst->group_num,
inst->peer_portid, inst->qlen,
inst->copy_mode, inst->copy_range,
inst->flushtimeout, atomic_read(&inst->use));
}
static const struct seq_operations nful_seq_ops = {
.start = seq_start,
.next = seq_next,
.stop = seq_stop,
.show = seq_show,
};
static int nful_open(struct inode *inode, struct file *file)
{
return seq_open_private(file, &nful_seq_ops,
sizeof(struct iter_state));
}
static const struct file_operations nful_file_ops = {
.owner = THIS_MODULE,
.open = nful_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_private,
};
#endif /* PROC_FS */
static int __init nfnetlink_log_init(void)
{
int i, status = -ENOMEM;
for (i = 0; i < INSTANCE_BUCKETS; i++)
INIT_HLIST_HEAD(&instance_table[i]);
/* it's not really all that important to have a random value, so
* we can do this from the init function, even if there hasn't
* been that much entropy yet */
get_random_bytes(&hash_init, sizeof(hash_init));
netlink_register_notifier(&nfulnl_rtnl_notifier);
status = nfnetlink_subsys_register(&nfulnl_subsys);
if (status < 0) {
printk(KERN_ERR "log: failed to create netlink socket\n");
goto cleanup_netlink_notifier;
}
status = nf_log_register(NFPROTO_UNSPEC, &nfulnl_logger);
if (status < 0) {
printk(KERN_ERR "log: failed to register logger\n");
goto cleanup_subsys;
}
#ifdef CONFIG_PROC_FS
if (!proc_create("nfnetlink_log", 0440,
proc_net_netfilter, &nful_file_ops)) {
status = -ENOMEM;
goto cleanup_logger;
}
#endif
return status;
#ifdef CONFIG_PROC_FS
cleanup_logger:
nf_log_unregister(&nfulnl_logger);
#endif
cleanup_subsys:
nfnetlink_subsys_unregister(&nfulnl_subsys);
cleanup_netlink_notifier:
netlink_unregister_notifier(&nfulnl_rtnl_notifier);
return status;
}
static void __exit nfnetlink_log_fini(void)
{
nf_log_unregister(&nfulnl_logger);
#ifdef CONFIG_PROC_FS
remove_proc_entry("nfnetlink_log", proc_net_netfilter);
#endif
nfnetlink_subsys_unregister(&nfulnl_subsys);
netlink_unregister_notifier(&nfulnl_rtnl_notifier);
}
MODULE_DESCRIPTION("netfilter userspace logging");
MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
MODULE_LICENSE("GPL");
MODULE_ALIAS_NFNL_SUBSYS(NFNL_SUBSYS_ULOG);
module_init(nfnetlink_log_init);
module_exit(nfnetlink_log_fini);
| gpl-2.0 |
darknighte/linux | arch/x86/crypto/sha512_ssse3_glue.c | 357 | 9403 | /*
* Cryptographic API.
*
* Glue code for the SHA512 Secure Hash Algorithm assembler
* implementation using supplemental SSE3 / AVX / AVX2 instructions.
*
* This file is based on sha512_generic.c
*
* Copyright (C) 2013 Intel Corporation
* Author: Tim Chen <tim.c.chen@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; either version 2 of the License, or (at your option)
* any later version.
*
* 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.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <crypto/internal/hash.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/cryptohash.h>
#include <linux/types.h>
#include <crypto/sha.h>
#include <crypto/sha512_base.h>
#include <asm/fpu/api.h>
#include <linux/string.h>
asmlinkage void sha512_transform_ssse3(u64 *digest, const char *data,
u64 rounds);
typedef void (sha512_transform_fn)(u64 *digest, const char *data, u64 rounds);
static int sha512_update(struct shash_desc *desc, const u8 *data,
unsigned int len, sha512_transform_fn *sha512_xform)
{
struct sha512_state *sctx = shash_desc_ctx(desc);
if (!irq_fpu_usable() ||
(sctx->count[0] % SHA512_BLOCK_SIZE) + len < SHA512_BLOCK_SIZE)
return crypto_sha512_update(desc, data, len);
/* make sure casting to sha512_block_fn() is safe */
BUILD_BUG_ON(offsetof(struct sha512_state, state) != 0);
kernel_fpu_begin();
sha512_base_do_update(desc, data, len,
(sha512_block_fn *)sha512_xform);
kernel_fpu_end();
return 0;
}
static int sha512_finup(struct shash_desc *desc, const u8 *data,
unsigned int len, u8 *out, sha512_transform_fn *sha512_xform)
{
if (!irq_fpu_usable())
return crypto_sha512_finup(desc, data, len, out);
kernel_fpu_begin();
if (len)
sha512_base_do_update(desc, data, len,
(sha512_block_fn *)sha512_xform);
sha512_base_do_finalize(desc, (sha512_block_fn *)sha512_xform);
kernel_fpu_end();
return sha512_base_finish(desc, out);
}
static int sha512_ssse3_update(struct shash_desc *desc, const u8 *data,
unsigned int len)
{
return sha512_update(desc, data, len, sha512_transform_ssse3);
}
static int sha512_ssse3_finup(struct shash_desc *desc, const u8 *data,
unsigned int len, u8 *out)
{
return sha512_finup(desc, data, len, out, sha512_transform_ssse3);
}
/* Add padding and return the message digest. */
static int sha512_ssse3_final(struct shash_desc *desc, u8 *out)
{
return sha512_ssse3_finup(desc, NULL, 0, out);
}
static struct shash_alg sha512_ssse3_algs[] = { {
.digestsize = SHA512_DIGEST_SIZE,
.init = sha512_base_init,
.update = sha512_ssse3_update,
.final = sha512_ssse3_final,
.finup = sha512_ssse3_finup,
.descsize = sizeof(struct sha512_state),
.base = {
.cra_name = "sha512",
.cra_driver_name = "sha512-ssse3",
.cra_priority = 150,
.cra_flags = CRYPTO_ALG_TYPE_SHASH,
.cra_blocksize = SHA512_BLOCK_SIZE,
.cra_module = THIS_MODULE,
}
}, {
.digestsize = SHA384_DIGEST_SIZE,
.init = sha384_base_init,
.update = sha512_ssse3_update,
.final = sha512_ssse3_final,
.finup = sha512_ssse3_finup,
.descsize = sizeof(struct sha512_state),
.base = {
.cra_name = "sha384",
.cra_driver_name = "sha384-ssse3",
.cra_priority = 150,
.cra_flags = CRYPTO_ALG_TYPE_SHASH,
.cra_blocksize = SHA384_BLOCK_SIZE,
.cra_module = THIS_MODULE,
}
} };
static int register_sha512_ssse3(void)
{
if (boot_cpu_has(X86_FEATURE_SSSE3))
return crypto_register_shashes(sha512_ssse3_algs,
ARRAY_SIZE(sha512_ssse3_algs));
return 0;
}
static void unregister_sha512_ssse3(void)
{
if (boot_cpu_has(X86_FEATURE_SSSE3))
crypto_unregister_shashes(sha512_ssse3_algs,
ARRAY_SIZE(sha512_ssse3_algs));
}
#ifdef CONFIG_AS_AVX
asmlinkage void sha512_transform_avx(u64 *digest, const char *data,
u64 rounds);
static bool avx_usable(void)
{
if (!cpu_has_xfeatures(XFEATURE_MASK_SSE | XFEATURE_MASK_YMM, NULL)) {
if (boot_cpu_has(X86_FEATURE_AVX))
pr_info("AVX detected but unusable.\n");
return false;
}
return true;
}
static int sha512_avx_update(struct shash_desc *desc, const u8 *data,
unsigned int len)
{
return sha512_update(desc, data, len, sha512_transform_avx);
}
static int sha512_avx_finup(struct shash_desc *desc, const u8 *data,
unsigned int len, u8 *out)
{
return sha512_finup(desc, data, len, out, sha512_transform_avx);
}
/* Add padding and return the message digest. */
static int sha512_avx_final(struct shash_desc *desc, u8 *out)
{
return sha512_avx_finup(desc, NULL, 0, out);
}
static struct shash_alg sha512_avx_algs[] = { {
.digestsize = SHA512_DIGEST_SIZE,
.init = sha512_base_init,
.update = sha512_avx_update,
.final = sha512_avx_final,
.finup = sha512_avx_finup,
.descsize = sizeof(struct sha512_state),
.base = {
.cra_name = "sha512",
.cra_driver_name = "sha512-avx",
.cra_priority = 160,
.cra_flags = CRYPTO_ALG_TYPE_SHASH,
.cra_blocksize = SHA512_BLOCK_SIZE,
.cra_module = THIS_MODULE,
}
}, {
.digestsize = SHA384_DIGEST_SIZE,
.init = sha384_base_init,
.update = sha512_avx_update,
.final = sha512_avx_final,
.finup = sha512_avx_finup,
.descsize = sizeof(struct sha512_state),
.base = {
.cra_name = "sha384",
.cra_driver_name = "sha384-avx",
.cra_priority = 160,
.cra_flags = CRYPTO_ALG_TYPE_SHASH,
.cra_blocksize = SHA384_BLOCK_SIZE,
.cra_module = THIS_MODULE,
}
} };
static int register_sha512_avx(void)
{
if (avx_usable())
return crypto_register_shashes(sha512_avx_algs,
ARRAY_SIZE(sha512_avx_algs));
return 0;
}
static void unregister_sha512_avx(void)
{
if (avx_usable())
crypto_unregister_shashes(sha512_avx_algs,
ARRAY_SIZE(sha512_avx_algs));
}
#else
static inline int register_sha512_avx(void) { return 0; }
static inline void unregister_sha512_avx(void) { }
#endif
#if defined(CONFIG_AS_AVX2) && defined(CONFIG_AS_AVX)
asmlinkage void sha512_transform_rorx(u64 *digest, const char *data,
u64 rounds);
static int sha512_avx2_update(struct shash_desc *desc, const u8 *data,
unsigned int len)
{
return sha512_update(desc, data, len, sha512_transform_rorx);
}
static int sha512_avx2_finup(struct shash_desc *desc, const u8 *data,
unsigned int len, u8 *out)
{
return sha512_finup(desc, data, len, out, sha512_transform_rorx);
}
/* Add padding and return the message digest. */
static int sha512_avx2_final(struct shash_desc *desc, u8 *out)
{
return sha512_avx2_finup(desc, NULL, 0, out);
}
static struct shash_alg sha512_avx2_algs[] = { {
.digestsize = SHA512_DIGEST_SIZE,
.init = sha512_base_init,
.update = sha512_avx2_update,
.final = sha512_avx2_final,
.finup = sha512_avx2_finup,
.descsize = sizeof(struct sha512_state),
.base = {
.cra_name = "sha512",
.cra_driver_name = "sha512-avx2",
.cra_priority = 170,
.cra_flags = CRYPTO_ALG_TYPE_SHASH,
.cra_blocksize = SHA512_BLOCK_SIZE,
.cra_module = THIS_MODULE,
}
}, {
.digestsize = SHA384_DIGEST_SIZE,
.init = sha384_base_init,
.update = sha512_avx2_update,
.final = sha512_avx2_final,
.finup = sha512_avx2_finup,
.descsize = sizeof(struct sha512_state),
.base = {
.cra_name = "sha384",
.cra_driver_name = "sha384-avx2",
.cra_priority = 170,
.cra_flags = CRYPTO_ALG_TYPE_SHASH,
.cra_blocksize = SHA384_BLOCK_SIZE,
.cra_module = THIS_MODULE,
}
} };
static bool avx2_usable(void)
{
if (avx_usable() && boot_cpu_has(X86_FEATURE_AVX2) &&
boot_cpu_has(X86_FEATURE_BMI2))
return true;
return false;
}
static int register_sha512_avx2(void)
{
if (avx2_usable())
return crypto_register_shashes(sha512_avx2_algs,
ARRAY_SIZE(sha512_avx2_algs));
return 0;
}
static void unregister_sha512_avx2(void)
{
if (avx2_usable())
crypto_unregister_shashes(sha512_avx2_algs,
ARRAY_SIZE(sha512_avx2_algs));
}
#else
static inline int register_sha512_avx2(void) { return 0; }
static inline void unregister_sha512_avx2(void) { }
#endif
static int __init sha512_ssse3_mod_init(void)
{
if (register_sha512_ssse3())
goto fail;
if (register_sha512_avx()) {
unregister_sha512_ssse3();
goto fail;
}
if (register_sha512_avx2()) {
unregister_sha512_avx();
unregister_sha512_ssse3();
goto fail;
}
return 0;
fail:
return -ENODEV;
}
static void __exit sha512_ssse3_mod_fini(void)
{
unregister_sha512_avx2();
unregister_sha512_avx();
unregister_sha512_ssse3();
}
module_init(sha512_ssse3_mod_init);
module_exit(sha512_ssse3_mod_fini);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("SHA512 Secure Hash Algorithm, Supplemental SSE3 accelerated");
MODULE_ALIAS_CRYPTO("sha512");
MODULE_ALIAS_CRYPTO("sha512-ssse3");
MODULE_ALIAS_CRYPTO("sha512-avx");
MODULE_ALIAS_CRYPTO("sha512-avx2");
MODULE_ALIAS_CRYPTO("sha384");
MODULE_ALIAS_CRYPTO("sha384-ssse3");
MODULE_ALIAS_CRYPTO("sha384-avx");
MODULE_ALIAS_CRYPTO("sha384-avx2");
| gpl-2.0 |
hannesweisbach/linux-atlas | arch/mips/kvm/hypcall.c | 869 | 1347 | /*
* 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.
*
* KVM/MIPS: Hypercall handling.
*
* Copyright (C) 2015 Imagination Technologies Ltd.
*/
#include <linux/kernel.h>
#include <linux/kvm_host.h>
#include <linux/kvm_para.h>
#define MAX_HYPCALL_ARGS 4
enum emulation_result kvm_mips_emul_hypcall(struct kvm_vcpu *vcpu,
union mips_instruction inst)
{
unsigned int code = (inst.co_format.code >> 5) & 0x3ff;
kvm_debug("[%#lx] HYPCALL %#03x\n", vcpu->arch.pc, code);
switch (code) {
case 0:
return EMULATE_HYPERCALL;
default:
return EMULATE_FAIL;
};
}
static int kvm_mips_hypercall(struct kvm_vcpu *vcpu, unsigned long num,
const unsigned long *args, unsigned long *hret)
{
/* Report unimplemented hypercall to guest */
*hret = -KVM_ENOSYS;
return RESUME_GUEST;
}
int kvm_mips_handle_hypcall(struct kvm_vcpu *vcpu)
{
unsigned long num, args[MAX_HYPCALL_ARGS];
/* read hypcall number and arguments */
num = vcpu->arch.gprs[2]; /* v0 */
args[0] = vcpu->arch.gprs[4]; /* a0 */
args[1] = vcpu->arch.gprs[5]; /* a1 */
args[2] = vcpu->arch.gprs[6]; /* a2 */
args[3] = vcpu->arch.gprs[7]; /* a3 */
return kvm_mips_hypercall(vcpu, num,
args, &vcpu->arch.gprs[2] /* v0 */);
}
| gpl-2.0 |
flaming-toast/unrm | drivers/usb/core/message.c | 869 | 61292 | /*
* message.c - synchronous message handling
*/
#include <linux/pci.h> /* for scatterlist macros */
#include <linux/usb.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/timer.h>
#include <linux/ctype.h>
#include <linux/nls.h>
#include <linux/device.h>
#include <linux/scatterlist.h>
#include <linux/usb/quirks.h>
#include <linux/usb/hcd.h> /* for usbcore internals */
#include <asm/byteorder.h>
#include "usb.h"
static void cancel_async_set_config(struct usb_device *udev);
struct api_context {
struct completion done;
int status;
};
static void usb_api_blocking_completion(struct urb *urb)
{
struct api_context *ctx = urb->context;
ctx->status = urb->status;
complete(&ctx->done);
}
/*
* Starts urb and waits for completion or timeout. Note that this call
* is NOT interruptible. Many device driver i/o requests should be
* interruptible and therefore these drivers should implement their
* own interruptible routines.
*/
static int usb_start_wait_urb(struct urb *urb, int timeout, int *actual_length)
{
struct api_context ctx;
unsigned long expire;
int retval;
init_completion(&ctx.done);
urb->context = &ctx;
urb->actual_length = 0;
retval = usb_submit_urb(urb, GFP_NOIO);
if (unlikely(retval))
goto out;
expire = timeout ? msecs_to_jiffies(timeout) : MAX_SCHEDULE_TIMEOUT;
if (!wait_for_completion_timeout(&ctx.done, expire)) {
usb_kill_urb(urb);
retval = (ctx.status == -ENOENT ? -ETIMEDOUT : ctx.status);
dev_dbg(&urb->dev->dev,
"%s timed out on ep%d%s len=%u/%u\n",
current->comm,
usb_endpoint_num(&urb->ep->desc),
usb_urb_dir_in(urb) ? "in" : "out",
urb->actual_length,
urb->transfer_buffer_length);
} else
retval = ctx.status;
out:
if (actual_length)
*actual_length = urb->actual_length;
usb_free_urb(urb);
return retval;
}
/*-------------------------------------------------------------------*/
/* returns status (negative) or length (positive) */
static int usb_internal_control_msg(struct usb_device *usb_dev,
unsigned int pipe,
struct usb_ctrlrequest *cmd,
void *data, int len, int timeout)
{
struct urb *urb;
int retv;
int length;
urb = usb_alloc_urb(0, GFP_NOIO);
if (!urb)
return -ENOMEM;
usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
len, usb_api_blocking_completion, NULL);
retv = usb_start_wait_urb(urb, timeout, &length);
if (retv < 0)
return retv;
else
return length;
}
/**
* usb_control_msg - Builds a control urb, sends it off and waits for completion
* @dev: pointer to the usb device to send the message to
* @pipe: endpoint "pipe" to send the message to
* @request: USB message request value
* @requesttype: USB message request type value
* @value: USB message value
* @index: USB message index value
* @data: pointer to the data to send
* @size: length in bytes of the data to send
* @timeout: time in msecs to wait for the message to complete before timing
* out (if 0 the wait is forever)
*
* Context: !in_interrupt ()
*
* This function sends a simple control message to a specified endpoint and
* waits for the message to complete, or timeout.
*
* Don't use this function from within an interrupt context, like a bottom half
* handler. If you need an asynchronous message, or need to send a message
* from within interrupt context, use usb_submit_urb().
* If a thread in your driver uses this call, make sure your disconnect()
* method can wait for it to complete. Since you don't have a handle on the
* URB used, you can't cancel the request.
*
* Return: If successful, the number of bytes transferred. Otherwise, a negative
* error number.
*/
int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request,
__u8 requesttype, __u16 value, __u16 index, void *data,
__u16 size, int timeout)
{
struct usb_ctrlrequest *dr;
int ret;
dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
if (!dr)
return -ENOMEM;
dr->bRequestType = requesttype;
dr->bRequest = request;
dr->wValue = cpu_to_le16(value);
dr->wIndex = cpu_to_le16(index);
dr->wLength = cpu_to_le16(size);
ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
kfree(dr);
return ret;
}
EXPORT_SYMBOL_GPL(usb_control_msg);
/**
* usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion
* @usb_dev: pointer to the usb device to send the message to
* @pipe: endpoint "pipe" to send the message to
* @data: pointer to the data to send
* @len: length in bytes of the data to send
* @actual_length: pointer to a location to put the actual length transferred
* in bytes
* @timeout: time in msecs to wait for the message to complete before
* timing out (if 0 the wait is forever)
*
* Context: !in_interrupt ()
*
* This function sends a simple interrupt message to a specified endpoint and
* waits for the message to complete, or timeout.
*
* Don't use this function from within an interrupt context, like a bottom half
* handler. If you need an asynchronous message, or need to send a message
* from within interrupt context, use usb_submit_urb() If a thread in your
* driver uses this call, make sure your disconnect() method can wait for it to
* complete. Since you don't have a handle on the URB used, you can't cancel
* the request.
*
* Return:
* If successful, 0. Otherwise a negative error number. The number of actual
* bytes transferred will be stored in the @actual_length parameter.
*/
int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe,
void *data, int len, int *actual_length, int timeout)
{
return usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout);
}
EXPORT_SYMBOL_GPL(usb_interrupt_msg);
/**
* usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
* @usb_dev: pointer to the usb device to send the message to
* @pipe: endpoint "pipe" to send the message to
* @data: pointer to the data to send
* @len: length in bytes of the data to send
* @actual_length: pointer to a location to put the actual length transferred
* in bytes
* @timeout: time in msecs to wait for the message to complete before
* timing out (if 0 the wait is forever)
*
* Context: !in_interrupt ()
*
* This function sends a simple bulk message to a specified endpoint
* and waits for the message to complete, or timeout.
*
* Don't use this function from within an interrupt context, like a bottom half
* handler. If you need an asynchronous message, or need to send a message
* from within interrupt context, use usb_submit_urb() If a thread in your
* driver uses this call, make sure your disconnect() method can wait for it to
* complete. Since you don't have a handle on the URB used, you can't cancel
* the request.
*
* Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT ioctl,
* users are forced to abuse this routine by using it to submit URBs for
* interrupt endpoints. We will take the liberty of creating an interrupt URB
* (with the default interval) if the target is an interrupt endpoint.
*
* Return:
* If successful, 0. Otherwise a negative error number. The number of actual
* bytes transferred will be stored in the @actual_length parameter.
*
*/
int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
void *data, int len, int *actual_length, int timeout)
{
struct urb *urb;
struct usb_host_endpoint *ep;
ep = usb_pipe_endpoint(usb_dev, pipe);
if (!ep || len < 0)
return -EINVAL;
urb = usb_alloc_urb(0, GFP_KERNEL);
if (!urb)
return -ENOMEM;
if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
USB_ENDPOINT_XFER_INT) {
pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
usb_fill_int_urb(urb, usb_dev, pipe, data, len,
usb_api_blocking_completion, NULL,
ep->desc.bInterval);
} else
usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
usb_api_blocking_completion, NULL);
return usb_start_wait_urb(urb, timeout, actual_length);
}
EXPORT_SYMBOL_GPL(usb_bulk_msg);
/*-------------------------------------------------------------------*/
static void sg_clean(struct usb_sg_request *io)
{
if (io->urbs) {
while (io->entries--)
usb_free_urb(io->urbs[io->entries]);
kfree(io->urbs);
io->urbs = NULL;
}
io->dev = NULL;
}
static void sg_complete(struct urb *urb)
{
struct usb_sg_request *io = urb->context;
int status = urb->status;
spin_lock(&io->lock);
/* In 2.5 we require hcds' endpoint queues not to progress after fault
* reports, until the completion callback (this!) returns. That lets
* device driver code (like this routine) unlink queued urbs first,
* if it needs to, since the HC won't work on them at all. So it's
* not possible for page N+1 to overwrite page N, and so on.
*
* That's only for "hard" faults; "soft" faults (unlinks) sometimes
* complete before the HCD can get requests away from hardware,
* though never during cleanup after a hard fault.
*/
if (io->status
&& (io->status != -ECONNRESET
|| status != -ECONNRESET)
&& urb->actual_length) {
dev_err(io->dev->bus->controller,
"dev %s ep%d%s scatterlist error %d/%d\n",
io->dev->devpath,
usb_endpoint_num(&urb->ep->desc),
usb_urb_dir_in(urb) ? "in" : "out",
status, io->status);
/* BUG (); */
}
if (io->status == 0 && status && status != -ECONNRESET) {
int i, found, retval;
io->status = status;
/* the previous urbs, and this one, completed already.
* unlink pending urbs so they won't rx/tx bad data.
* careful: unlink can sometimes be synchronous...
*/
spin_unlock(&io->lock);
for (i = 0, found = 0; i < io->entries; i++) {
if (!io->urbs[i] || !io->urbs[i]->dev)
continue;
if (found) {
retval = usb_unlink_urb(io->urbs[i]);
if (retval != -EINPROGRESS &&
retval != -ENODEV &&
retval != -EBUSY &&
retval != -EIDRM)
dev_err(&io->dev->dev,
"%s, unlink --> %d\n",
__func__, retval);
} else if (urb == io->urbs[i])
found = 1;
}
spin_lock(&io->lock);
}
/* on the last completion, signal usb_sg_wait() */
io->bytes += urb->actual_length;
io->count--;
if (!io->count)
complete(&io->complete);
spin_unlock(&io->lock);
}
/**
* usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
* @io: request block being initialized. until usb_sg_wait() returns,
* treat this as a pointer to an opaque block of memory,
* @dev: the usb device that will send or receive the data
* @pipe: endpoint "pipe" used to transfer the data
* @period: polling rate for interrupt endpoints, in frames or
* (for high speed endpoints) microframes; ignored for bulk
* @sg: scatterlist entries
* @nents: how many entries in the scatterlist
* @length: how many bytes to send from the scatterlist, or zero to
* send every byte identified in the list.
* @mem_flags: SLAB_* flags affecting memory allocations in this call
*
* This initializes a scatter/gather request, allocating resources such as
* I/O mappings and urb memory (except maybe memory used by USB controller
* drivers).
*
* The request must be issued using usb_sg_wait(), which waits for the I/O to
* complete (or to be canceled) and then cleans up all resources allocated by
* usb_sg_init().
*
* The request may be canceled with usb_sg_cancel(), either before or after
* usb_sg_wait() is called.
*
* Return: Zero for success, else a negative errno value.
*/
int usb_sg_init(struct usb_sg_request *io, struct usb_device *dev,
unsigned pipe, unsigned period, struct scatterlist *sg,
int nents, size_t length, gfp_t mem_flags)
{
int i;
int urb_flags;
int use_sg;
if (!io || !dev || !sg
|| usb_pipecontrol(pipe)
|| usb_pipeisoc(pipe)
|| nents <= 0)
return -EINVAL;
spin_lock_init(&io->lock);
io->dev = dev;
io->pipe = pipe;
if (dev->bus->sg_tablesize > 0) {
use_sg = true;
io->entries = 1;
} else {
use_sg = false;
io->entries = nents;
}
/* initialize all the urbs we'll use */
io->urbs = kmalloc(io->entries * sizeof(*io->urbs), mem_flags);
if (!io->urbs)
goto nomem;
urb_flags = URB_NO_INTERRUPT;
if (usb_pipein(pipe))
urb_flags |= URB_SHORT_NOT_OK;
for_each_sg(sg, sg, io->entries, i) {
struct urb *urb;
unsigned len;
urb = usb_alloc_urb(0, mem_flags);
if (!urb) {
io->entries = i;
goto nomem;
}
io->urbs[i] = urb;
urb->dev = NULL;
urb->pipe = pipe;
urb->interval = period;
urb->transfer_flags = urb_flags;
urb->complete = sg_complete;
urb->context = io;
urb->sg = sg;
if (use_sg) {
/* There is no single transfer buffer */
urb->transfer_buffer = NULL;
urb->num_sgs = nents;
/* A length of zero means transfer the whole sg list */
len = length;
if (len == 0) {
struct scatterlist *sg2;
int j;
for_each_sg(sg, sg2, nents, j)
len += sg2->length;
}
} else {
/*
* Some systems can't use DMA; they use PIO instead.
* For their sakes, transfer_buffer is set whenever
* possible.
*/
if (!PageHighMem(sg_page(sg)))
urb->transfer_buffer = sg_virt(sg);
else
urb->transfer_buffer = NULL;
len = sg->length;
if (length) {
len = min_t(size_t, len, length);
length -= len;
if (length == 0)
io->entries = i + 1;
}
}
urb->transfer_buffer_length = len;
}
io->urbs[--i]->transfer_flags &= ~URB_NO_INTERRUPT;
/* transaction state */
io->count = io->entries;
io->status = 0;
io->bytes = 0;
init_completion(&io->complete);
return 0;
nomem:
sg_clean(io);
return -ENOMEM;
}
EXPORT_SYMBOL_GPL(usb_sg_init);
/**
* usb_sg_wait - synchronously execute scatter/gather request
* @io: request block handle, as initialized with usb_sg_init().
* some fields become accessible when this call returns.
* Context: !in_interrupt ()
*
* This function blocks until the specified I/O operation completes. It
* leverages the grouping of the related I/O requests to get good transfer
* rates, by queueing the requests. At higher speeds, such queuing can
* significantly improve USB throughput.
*
* There are three kinds of completion for this function.
* (1) success, where io->status is zero. The number of io->bytes
* transferred is as requested.
* (2) error, where io->status is a negative errno value. The number
* of io->bytes transferred before the error is usually less
* than requested, and can be nonzero.
* (3) cancellation, a type of error with status -ECONNRESET that
* is initiated by usb_sg_cancel().
*
* When this function returns, all memory allocated through usb_sg_init() or
* this call will have been freed. The request block parameter may still be
* passed to usb_sg_cancel(), or it may be freed. It could also be
* reinitialized and then reused.
*
* Data Transfer Rates:
*
* Bulk transfers are valid for full or high speed endpoints.
* The best full speed data rate is 19 packets of 64 bytes each
* per frame, or 1216 bytes per millisecond.
* The best high speed data rate is 13 packets of 512 bytes each
* per microframe, or 52 KBytes per millisecond.
*
* The reason to use interrupt transfers through this API would most likely
* be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
* could be transferred. That capability is less useful for low or full
* speed interrupt endpoints, which allow at most one packet per millisecond,
* of at most 8 or 64 bytes (respectively).
*
* It is not necessary to call this function to reserve bandwidth for devices
* under an xHCI host controller, as the bandwidth is reserved when the
* configuration or interface alt setting is selected.
*/
void usb_sg_wait(struct usb_sg_request *io)
{
int i;
int entries = io->entries;
/* queue the urbs. */
spin_lock_irq(&io->lock);
i = 0;
while (i < entries && !io->status) {
int retval;
io->urbs[i]->dev = io->dev;
retval = usb_submit_urb(io->urbs[i], GFP_ATOMIC);
/* after we submit, let completions or cancellations fire;
* we handshake using io->status.
*/
spin_unlock_irq(&io->lock);
switch (retval) {
/* maybe we retrying will recover */
case -ENXIO: /* hc didn't queue this one */
case -EAGAIN:
case -ENOMEM:
retval = 0;
yield();
break;
/* no error? continue immediately.
*
* NOTE: to work better with UHCI (4K I/O buffer may
* need 3K of TDs) it may be good to limit how many
* URBs are queued at once; N milliseconds?
*/
case 0:
++i;
cpu_relax();
break;
/* fail any uncompleted urbs */
default:
io->urbs[i]->status = retval;
dev_dbg(&io->dev->dev, "%s, submit --> %d\n",
__func__, retval);
usb_sg_cancel(io);
}
spin_lock_irq(&io->lock);
if (retval && (io->status == 0 || io->status == -ECONNRESET))
io->status = retval;
}
io->count -= entries - i;
if (io->count == 0)
complete(&io->complete);
spin_unlock_irq(&io->lock);
/* OK, yes, this could be packaged as non-blocking.
* So could the submit loop above ... but it's easier to
* solve neither problem than to solve both!
*/
wait_for_completion(&io->complete);
sg_clean(io);
}
EXPORT_SYMBOL_GPL(usb_sg_wait);
/**
* usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
* @io: request block, initialized with usb_sg_init()
*
* This stops a request after it has been started by usb_sg_wait().
* It can also prevents one initialized by usb_sg_init() from starting,
* so that call just frees resources allocated to the request.
*/
void usb_sg_cancel(struct usb_sg_request *io)
{
unsigned long flags;
spin_lock_irqsave(&io->lock, flags);
/* shut everything down, if it didn't already */
if (!io->status) {
int i;
io->status = -ECONNRESET;
spin_unlock(&io->lock);
for (i = 0; i < io->entries; i++) {
int retval;
if (!io->urbs[i]->dev)
continue;
retval = usb_unlink_urb(io->urbs[i]);
if (retval != -EINPROGRESS
&& retval != -ENODEV
&& retval != -EBUSY
&& retval != -EIDRM)
dev_warn(&io->dev->dev, "%s, unlink --> %d\n",
__func__, retval);
}
spin_lock(&io->lock);
}
spin_unlock_irqrestore(&io->lock, flags);
}
EXPORT_SYMBOL_GPL(usb_sg_cancel);
/*-------------------------------------------------------------------*/
/**
* usb_get_descriptor - issues a generic GET_DESCRIPTOR request
* @dev: the device whose descriptor is being retrieved
* @type: the descriptor type (USB_DT_*)
* @index: the number of the descriptor
* @buf: where to put the descriptor
* @size: how big is "buf"?
* Context: !in_interrupt ()
*
* Gets a USB descriptor. Convenience functions exist to simplify
* getting some types of descriptors. Use
* usb_get_string() or usb_string() for USB_DT_STRING.
* Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
* are part of the device structure.
* In addition to a number of USB-standard descriptors, some
* devices also use class-specific or vendor-specific descriptors.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Return: The number of bytes received on success, or else the status code
* returned by the underlying usb_control_msg() call.
*/
int usb_get_descriptor(struct usb_device *dev, unsigned char type,
unsigned char index, void *buf, int size)
{
int i;
int result;
memset(buf, 0, size); /* Make sure we parse really received data */
for (i = 0; i < 3; ++i) {
/* retry on length 0 or error; some devices are flakey */
result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
(type << 8) + index, 0, buf, size,
USB_CTRL_GET_TIMEOUT);
if (result <= 0 && result != -ETIMEDOUT)
continue;
if (result > 1 && ((u8 *)buf)[1] != type) {
result = -ENODATA;
continue;
}
break;
}
return result;
}
EXPORT_SYMBOL_GPL(usb_get_descriptor);
/**
* usb_get_string - gets a string descriptor
* @dev: the device whose string descriptor is being retrieved
* @langid: code for language chosen (from string descriptor zero)
* @index: the number of the descriptor
* @buf: where to put the string
* @size: how big is "buf"?
* Context: !in_interrupt ()
*
* Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
* in little-endian byte order).
* The usb_string() function will often be a convenient way to turn
* these strings into kernel-printable form.
*
* Strings may be referenced in device, configuration, interface, or other
* descriptors, and could also be used in vendor-specific ways.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Return: The number of bytes received on success, or else the status code
* returned by the underlying usb_control_msg() call.
*/
static int usb_get_string(struct usb_device *dev, unsigned short langid,
unsigned char index, void *buf, int size)
{
int i;
int result;
for (i = 0; i < 3; ++i) {
/* retry on length 0 or stall; some devices are flakey */
result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
(USB_DT_STRING << 8) + index, langid, buf, size,
USB_CTRL_GET_TIMEOUT);
if (result == 0 || result == -EPIPE)
continue;
if (result > 1 && ((u8 *) buf)[1] != USB_DT_STRING) {
result = -ENODATA;
continue;
}
break;
}
return result;
}
static void usb_try_string_workarounds(unsigned char *buf, int *length)
{
int newlength, oldlength = *length;
for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
if (!isprint(buf[newlength]) || buf[newlength + 1])
break;
if (newlength > 2) {
buf[0] = newlength;
*length = newlength;
}
}
static int usb_string_sub(struct usb_device *dev, unsigned int langid,
unsigned int index, unsigned char *buf)
{
int rc;
/* Try to read the string descriptor by asking for the maximum
* possible number of bytes */
if (dev->quirks & USB_QUIRK_STRING_FETCH_255)
rc = -EIO;
else
rc = usb_get_string(dev, langid, index, buf, 255);
/* If that failed try to read the descriptor length, then
* ask for just that many bytes */
if (rc < 2) {
rc = usb_get_string(dev, langid, index, buf, 2);
if (rc == 2)
rc = usb_get_string(dev, langid, index, buf, buf[0]);
}
if (rc >= 2) {
if (!buf[0] && !buf[1])
usb_try_string_workarounds(buf, &rc);
/* There might be extra junk at the end of the descriptor */
if (buf[0] < rc)
rc = buf[0];
rc = rc - (rc & 1); /* force a multiple of two */
}
if (rc < 2)
rc = (rc < 0 ? rc : -EINVAL);
return rc;
}
static int usb_get_langid(struct usb_device *dev, unsigned char *tbuf)
{
int err;
if (dev->have_langid)
return 0;
if (dev->string_langid < 0)
return -EPIPE;
err = usb_string_sub(dev, 0, 0, tbuf);
/* If the string was reported but is malformed, default to english
* (0x0409) */
if (err == -ENODATA || (err > 0 && err < 4)) {
dev->string_langid = 0x0409;
dev->have_langid = 1;
dev_err(&dev->dev,
"language id specifier not provided by device, defaulting to English\n");
return 0;
}
/* In case of all other errors, we assume the device is not able to
* deal with strings at all. Set string_langid to -1 in order to
* prevent any string to be retrieved from the device */
if (err < 0) {
dev_err(&dev->dev, "string descriptor 0 read error: %d\n",
err);
dev->string_langid = -1;
return -EPIPE;
}
/* always use the first langid listed */
dev->string_langid = tbuf[2] | (tbuf[3] << 8);
dev->have_langid = 1;
dev_dbg(&dev->dev, "default language 0x%04x\n",
dev->string_langid);
return 0;
}
/**
* usb_string - returns UTF-8 version of a string descriptor
* @dev: the device whose string descriptor is being retrieved
* @index: the number of the descriptor
* @buf: where to put the string
* @size: how big is "buf"?
* Context: !in_interrupt ()
*
* This converts the UTF-16LE encoded strings returned by devices, from
* usb_get_string_descriptor(), to null-terminated UTF-8 encoded ones
* that are more usable in most kernel contexts. Note that this function
* chooses strings in the first language supported by the device.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Return: length of the string (>= 0) or usb_control_msg status (< 0).
*/
int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
{
unsigned char *tbuf;
int err;
if (dev->state == USB_STATE_SUSPENDED)
return -EHOSTUNREACH;
if (size <= 0 || !buf || !index)
return -EINVAL;
buf[0] = 0;
tbuf = kmalloc(256, GFP_NOIO);
if (!tbuf)
return -ENOMEM;
err = usb_get_langid(dev, tbuf);
if (err < 0)
goto errout;
err = usb_string_sub(dev, dev->string_langid, index, tbuf);
if (err < 0)
goto errout;
size--; /* leave room for trailing NULL char in output buffer */
err = utf16s_to_utf8s((wchar_t *) &tbuf[2], (err - 2) / 2,
UTF16_LITTLE_ENDIAN, buf, size);
buf[err] = 0;
if (tbuf[1] != USB_DT_STRING)
dev_dbg(&dev->dev,
"wrong descriptor type %02x for string %d (\"%s\")\n",
tbuf[1], index, buf);
errout:
kfree(tbuf);
return err;
}
EXPORT_SYMBOL_GPL(usb_string);
/* one UTF-8-encoded 16-bit character has at most three bytes */
#define MAX_USB_STRING_SIZE (127 * 3 + 1)
/**
* usb_cache_string - read a string descriptor and cache it for later use
* @udev: the device whose string descriptor is being read
* @index: the descriptor index
*
* Return: A pointer to a kmalloc'ed buffer containing the descriptor string,
* or %NULL if the index is 0 or the string could not be read.
*/
char *usb_cache_string(struct usb_device *udev, int index)
{
char *buf;
char *smallbuf = NULL;
int len;
if (index <= 0)
return NULL;
buf = kmalloc(MAX_USB_STRING_SIZE, GFP_NOIO);
if (buf) {
len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE);
if (len > 0) {
smallbuf = kmalloc(++len, GFP_NOIO);
if (!smallbuf)
return buf;
memcpy(smallbuf, buf, len);
}
kfree(buf);
}
return smallbuf;
}
/*
* usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
* @dev: the device whose device descriptor is being updated
* @size: how much of the descriptor to read
* Context: !in_interrupt ()
*
* Updates the copy of the device descriptor stored in the device structure,
* which dedicates space for this purpose.
*
* Not exported, only for use by the core. If drivers really want to read
* the device descriptor directly, they can call usb_get_descriptor() with
* type = USB_DT_DEVICE and index = 0.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Return: The number of bytes received on success, or else the status code
* returned by the underlying usb_control_msg() call.
*/
int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
{
struct usb_device_descriptor *desc;
int ret;
if (size > sizeof(*desc))
return -EINVAL;
desc = kmalloc(sizeof(*desc), GFP_NOIO);
if (!desc)
return -ENOMEM;
ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
if (ret >= 0)
memcpy(&dev->descriptor, desc, size);
kfree(desc);
return ret;
}
/**
* usb_get_status - issues a GET_STATUS call
* @dev: the device whose status is being checked
* @type: USB_RECIP_*; for device, interface, or endpoint
* @target: zero (for device), else interface or endpoint number
* @data: pointer to two bytes of bitmap data
* Context: !in_interrupt ()
*
* Returns device, interface, or endpoint status. Normally only of
* interest to see if the device is self powered, or has enabled the
* remote wakeup facility; or whether a bulk or interrupt endpoint
* is halted ("stalled").
*
* Bits in these status bitmaps are set using the SET_FEATURE request,
* and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
* function should be used to clear halt ("stall") status.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Returns 0 and the status value in *@data (in host byte order) on success,
* or else the status code from the underlying usb_control_msg() call.
*/
int usb_get_status(struct usb_device *dev, int type, int target, void *data)
{
int ret;
__le16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
if (!status)
return -ENOMEM;
ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
sizeof(*status), USB_CTRL_GET_TIMEOUT);
if (ret == 2) {
*(u16 *) data = le16_to_cpu(*status);
ret = 0;
} else if (ret >= 0) {
ret = -EIO;
}
kfree(status);
return ret;
}
EXPORT_SYMBOL_GPL(usb_get_status);
/**
* usb_clear_halt - tells device to clear endpoint halt/stall condition
* @dev: device whose endpoint is halted
* @pipe: endpoint "pipe" being cleared
* Context: !in_interrupt ()
*
* This is used to clear halt conditions for bulk and interrupt endpoints,
* as reported by URB completion status. Endpoints that are halted are
* sometimes referred to as being "stalled". Such endpoints are unable
* to transmit or receive data until the halt status is cleared. Any URBs
* queued for such an endpoint should normally be unlinked by the driver
* before clearing the halt condition, as described in sections 5.7.5
* and 5.8.5 of the USB 2.0 spec.
*
* Note that control and isochronous endpoints don't halt, although control
* endpoints report "protocol stall" (for unsupported requests) using the
* same status code used to report a true stall.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Return: Zero on success, or else the status code returned by the
* underlying usb_control_msg() call.
*/
int usb_clear_halt(struct usb_device *dev, int pipe)
{
int result;
int endp = usb_pipeendpoint(pipe);
if (usb_pipein(pipe))
endp |= USB_DIR_IN;
/* we don't care if it wasn't halted first. in fact some devices
* (like some ibmcam model 1 units) seem to expect hosts to make
* this request for iso endpoints, which can't halt!
*/
result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
USB_ENDPOINT_HALT, endp, NULL, 0,
USB_CTRL_SET_TIMEOUT);
/* don't un-halt or force to DATA0 except on success */
if (result < 0)
return result;
/* NOTE: seems like Microsoft and Apple don't bother verifying
* the clear "took", so some devices could lock up if you check...
* such as the Hagiwara FlashGate DUAL. So we won't bother.
*
* NOTE: make sure the logic here doesn't diverge much from
* the copy in usb-storage, for as long as we need two copies.
*/
usb_reset_endpoint(dev, endp);
return 0;
}
EXPORT_SYMBOL_GPL(usb_clear_halt);
static int create_intf_ep_devs(struct usb_interface *intf)
{
struct usb_device *udev = interface_to_usbdev(intf);
struct usb_host_interface *alt = intf->cur_altsetting;
int i;
if (intf->ep_devs_created || intf->unregistering)
return 0;
for (i = 0; i < alt->desc.bNumEndpoints; ++i)
(void) usb_create_ep_devs(&intf->dev, &alt->endpoint[i], udev);
intf->ep_devs_created = 1;
return 0;
}
static void remove_intf_ep_devs(struct usb_interface *intf)
{
struct usb_host_interface *alt = intf->cur_altsetting;
int i;
if (!intf->ep_devs_created)
return;
for (i = 0; i < alt->desc.bNumEndpoints; ++i)
usb_remove_ep_devs(&alt->endpoint[i]);
intf->ep_devs_created = 0;
}
/**
* usb_disable_endpoint -- Disable an endpoint by address
* @dev: the device whose endpoint is being disabled
* @epaddr: the endpoint's address. Endpoint number for output,
* endpoint number + USB_DIR_IN for input
* @reset_hardware: flag to erase any endpoint state stored in the
* controller hardware
*
* Disables the endpoint for URB submission and nukes all pending URBs.
* If @reset_hardware is set then also deallocates hcd/hardware state
* for the endpoint.
*/
void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr,
bool reset_hardware)
{
unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
struct usb_host_endpoint *ep;
if (!dev)
return;
if (usb_endpoint_out(epaddr)) {
ep = dev->ep_out[epnum];
if (reset_hardware)
dev->ep_out[epnum] = NULL;
} else {
ep = dev->ep_in[epnum];
if (reset_hardware)
dev->ep_in[epnum] = NULL;
}
if (ep) {
ep->enabled = 0;
usb_hcd_flush_endpoint(dev, ep);
if (reset_hardware)
usb_hcd_disable_endpoint(dev, ep);
}
}
/**
* usb_reset_endpoint - Reset an endpoint's state.
* @dev: the device whose endpoint is to be reset
* @epaddr: the endpoint's address. Endpoint number for output,
* endpoint number + USB_DIR_IN for input
*
* Resets any host-side endpoint state such as the toggle bit,
* sequence number or current window.
*/
void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr)
{
unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
struct usb_host_endpoint *ep;
if (usb_endpoint_out(epaddr))
ep = dev->ep_out[epnum];
else
ep = dev->ep_in[epnum];
if (ep)
usb_hcd_reset_endpoint(dev, ep);
}
EXPORT_SYMBOL_GPL(usb_reset_endpoint);
/**
* usb_disable_interface -- Disable all endpoints for an interface
* @dev: the device whose interface is being disabled
* @intf: pointer to the interface descriptor
* @reset_hardware: flag to erase any endpoint state stored in the
* controller hardware
*
* Disables all the endpoints for the interface's current altsetting.
*/
void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf,
bool reset_hardware)
{
struct usb_host_interface *alt = intf->cur_altsetting;
int i;
for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
usb_disable_endpoint(dev,
alt->endpoint[i].desc.bEndpointAddress,
reset_hardware);
}
}
/**
* usb_disable_device - Disable all the endpoints for a USB device
* @dev: the device whose endpoints are being disabled
* @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
*
* Disables all the device's endpoints, potentially including endpoint 0.
* Deallocates hcd/hardware state for the endpoints (nuking all or most
* pending urbs) and usbcore state for the interfaces, so that usbcore
* must usb_set_configuration() before any interfaces could be used.
*/
void usb_disable_device(struct usb_device *dev, int skip_ep0)
{
int i;
struct usb_hcd *hcd = bus_to_hcd(dev->bus);
/* getting rid of interfaces will disconnect
* any drivers bound to them (a key side effect)
*/
if (dev->actconfig) {
/*
* FIXME: In order to avoid self-deadlock involving the
* bandwidth_mutex, we have to mark all the interfaces
* before unregistering any of them.
*/
for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++)
dev->actconfig->interface[i]->unregistering = 1;
for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
struct usb_interface *interface;
/* remove this interface if it has been registered */
interface = dev->actconfig->interface[i];
if (!device_is_registered(&interface->dev))
continue;
dev_dbg(&dev->dev, "unregistering interface %s\n",
dev_name(&interface->dev));
remove_intf_ep_devs(interface);
device_del(&interface->dev);
}
/* Now that the interfaces are unbound, nobody should
* try to access them.
*/
for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
put_device(&dev->actconfig->interface[i]->dev);
dev->actconfig->interface[i] = NULL;
}
if (dev->usb2_hw_lpm_enabled == 1)
usb_set_usb2_hardware_lpm(dev, 0);
usb_unlocked_disable_lpm(dev);
usb_disable_ltm(dev);
dev->actconfig = NULL;
if (dev->state == USB_STATE_CONFIGURED)
usb_set_device_state(dev, USB_STATE_ADDRESS);
}
dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__,
skip_ep0 ? "non-ep0" : "all");
if (hcd->driver->check_bandwidth) {
/* First pass: Cancel URBs, leave endpoint pointers intact. */
for (i = skip_ep0; i < 16; ++i) {
usb_disable_endpoint(dev, i, false);
usb_disable_endpoint(dev, i + USB_DIR_IN, false);
}
/* Remove endpoints from the host controller internal state */
mutex_lock(hcd->bandwidth_mutex);
usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
mutex_unlock(hcd->bandwidth_mutex);
/* Second pass: remove endpoint pointers */
}
for (i = skip_ep0; i < 16; ++i) {
usb_disable_endpoint(dev, i, true);
usb_disable_endpoint(dev, i + USB_DIR_IN, true);
}
}
/**
* usb_enable_endpoint - Enable an endpoint for USB communications
* @dev: the device whose interface is being enabled
* @ep: the endpoint
* @reset_ep: flag to reset the endpoint state
*
* Resets the endpoint state if asked, and sets dev->ep_{in,out} pointers.
* For control endpoints, both the input and output sides are handled.
*/
void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep,
bool reset_ep)
{
int epnum = usb_endpoint_num(&ep->desc);
int is_out = usb_endpoint_dir_out(&ep->desc);
int is_control = usb_endpoint_xfer_control(&ep->desc);
if (reset_ep)
usb_hcd_reset_endpoint(dev, ep);
if (is_out || is_control)
dev->ep_out[epnum] = ep;
if (!is_out || is_control)
dev->ep_in[epnum] = ep;
ep->enabled = 1;
}
/**
* usb_enable_interface - Enable all the endpoints for an interface
* @dev: the device whose interface is being enabled
* @intf: pointer to the interface descriptor
* @reset_eps: flag to reset the endpoints' state
*
* Enables all the endpoints for the interface's current altsetting.
*/
void usb_enable_interface(struct usb_device *dev,
struct usb_interface *intf, bool reset_eps)
{
struct usb_host_interface *alt = intf->cur_altsetting;
int i;
for (i = 0; i < alt->desc.bNumEndpoints; ++i)
usb_enable_endpoint(dev, &alt->endpoint[i], reset_eps);
}
/**
* usb_set_interface - Makes a particular alternate setting be current
* @dev: the device whose interface is being updated
* @interface: the interface being updated
* @alternate: the setting being chosen.
* Context: !in_interrupt ()
*
* This is used to enable data transfers on interfaces that may not
* be enabled by default. Not all devices support such configurability.
* Only the driver bound to an interface may change its setting.
*
* Within any given configuration, each interface may have several
* alternative settings. These are often used to control levels of
* bandwidth consumption. For example, the default setting for a high
* speed interrupt endpoint may not send more than 64 bytes per microframe,
* while interrupt transfers of up to 3KBytes per microframe are legal.
* Also, isochronous endpoints may never be part of an
* interface's default setting. To access such bandwidth, alternate
* interface settings must be made current.
*
* Note that in the Linux USB subsystem, bandwidth associated with
* an endpoint in a given alternate setting is not reserved until an URB
* is submitted that needs that bandwidth. Some other operating systems
* allocate bandwidth early, when a configuration is chosen.
*
* This call is synchronous, and may not be used in an interrupt context.
* Also, drivers must not change altsettings while urbs are scheduled for
* endpoints in that interface; all such urbs must first be completed
* (perhaps forced by unlinking).
*
* Return: Zero on success, or else the status code returned by the
* underlying usb_control_msg() call.
*/
int usb_set_interface(struct usb_device *dev, int interface, int alternate)
{
struct usb_interface *iface;
struct usb_host_interface *alt;
struct usb_hcd *hcd = bus_to_hcd(dev->bus);
int i, ret, manual = 0;
unsigned int epaddr;
unsigned int pipe;
if (dev->state == USB_STATE_SUSPENDED)
return -EHOSTUNREACH;
iface = usb_ifnum_to_if(dev, interface);
if (!iface) {
dev_dbg(&dev->dev, "selecting invalid interface %d\n",
interface);
return -EINVAL;
}
if (iface->unregistering)
return -ENODEV;
alt = usb_altnum_to_altsetting(iface, alternate);
if (!alt) {
dev_warn(&dev->dev, "selecting invalid altsetting %d\n",
alternate);
return -EINVAL;
}
/* Make sure we have enough bandwidth for this alternate interface.
* Remove the current alt setting and add the new alt setting.
*/
mutex_lock(hcd->bandwidth_mutex);
/* Disable LPM, and re-enable it once the new alt setting is installed,
* so that the xHCI driver can recalculate the U1/U2 timeouts.
*/
if (usb_disable_lpm(dev)) {
dev_err(&iface->dev, "%s Failed to disable LPM\n.", __func__);
mutex_unlock(hcd->bandwidth_mutex);
return -ENOMEM;
}
/* Changing alt-setting also frees any allocated streams */
for (i = 0; i < iface->cur_altsetting->desc.bNumEndpoints; i++)
iface->cur_altsetting->endpoint[i].streams = 0;
ret = usb_hcd_alloc_bandwidth(dev, NULL, iface->cur_altsetting, alt);
if (ret < 0) {
dev_info(&dev->dev, "Not enough bandwidth for altsetting %d\n",
alternate);
usb_enable_lpm(dev);
mutex_unlock(hcd->bandwidth_mutex);
return ret;
}
if (dev->quirks & USB_QUIRK_NO_SET_INTF)
ret = -EPIPE;
else
ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
alternate, interface, NULL, 0, 5000);
/* 9.4.10 says devices don't need this and are free to STALL the
* request if the interface only has one alternate setting.
*/
if (ret == -EPIPE && iface->num_altsetting == 1) {
dev_dbg(&dev->dev,
"manual set_interface for iface %d, alt %d\n",
interface, alternate);
manual = 1;
} else if (ret < 0) {
/* Re-instate the old alt setting */
usb_hcd_alloc_bandwidth(dev, NULL, alt, iface->cur_altsetting);
usb_enable_lpm(dev);
mutex_unlock(hcd->bandwidth_mutex);
return ret;
}
mutex_unlock(hcd->bandwidth_mutex);
/* FIXME drivers shouldn't need to replicate/bugfix the logic here
* when they implement async or easily-killable versions of this or
* other "should-be-internal" functions (like clear_halt).
* should hcd+usbcore postprocess control requests?
*/
/* prevent submissions using previous endpoint settings */
if (iface->cur_altsetting != alt) {
remove_intf_ep_devs(iface);
usb_remove_sysfs_intf_files(iface);
}
usb_disable_interface(dev, iface, true);
iface->cur_altsetting = alt;
/* Now that the interface is installed, re-enable LPM. */
usb_unlocked_enable_lpm(dev);
/* If the interface only has one altsetting and the device didn't
* accept the request, we attempt to carry out the equivalent action
* by manually clearing the HALT feature for each endpoint in the
* new altsetting.
*/
if (manual) {
int i;
for (i = 0; i < alt->desc.bNumEndpoints; i++) {
epaddr = alt->endpoint[i].desc.bEndpointAddress;
pipe = __create_pipe(dev,
USB_ENDPOINT_NUMBER_MASK & epaddr) |
(usb_endpoint_out(epaddr) ?
USB_DIR_OUT : USB_DIR_IN);
usb_clear_halt(dev, pipe);
}
}
/* 9.1.1.5: reset toggles for all endpoints in the new altsetting
*
* Note:
* Despite EP0 is always present in all interfaces/AS, the list of
* endpoints from the descriptor does not contain EP0. Due to its
* omnipresence one might expect EP0 being considered "affected" by
* any SetInterface request and hence assume toggles need to be reset.
* However, EP0 toggles are re-synced for every individual transfer
* during the SETUP stage - hence EP0 toggles are "don't care" here.
* (Likewise, EP0 never "halts" on well designed devices.)
*/
usb_enable_interface(dev, iface, true);
if (device_is_registered(&iface->dev)) {
usb_create_sysfs_intf_files(iface);
create_intf_ep_devs(iface);
}
return 0;
}
EXPORT_SYMBOL_GPL(usb_set_interface);
/**
* usb_reset_configuration - lightweight device reset
* @dev: the device whose configuration is being reset
*
* This issues a standard SET_CONFIGURATION request to the device using
* the current configuration. The effect is to reset most USB-related
* state in the device, including interface altsettings (reset to zero),
* endpoint halts (cleared), and endpoint state (only for bulk and interrupt
* endpoints). Other usbcore state is unchanged, including bindings of
* usb device drivers to interfaces.
*
* Because this affects multiple interfaces, avoid using this with composite
* (multi-interface) devices. Instead, the driver for each interface may
* use usb_set_interface() on the interfaces it claims. Be careful though;
* some devices don't support the SET_INTERFACE request, and others won't
* reset all the interface state (notably endpoint state). Resetting the whole
* configuration would affect other drivers' interfaces.
*
* The caller must own the device lock.
*
* Return: Zero on success, else a negative error code.
*/
int usb_reset_configuration(struct usb_device *dev)
{
int i, retval;
struct usb_host_config *config;
struct usb_hcd *hcd = bus_to_hcd(dev->bus);
if (dev->state == USB_STATE_SUSPENDED)
return -EHOSTUNREACH;
/* caller must have locked the device and must own
* the usb bus readlock (so driver bindings are stable);
* calls during probe() are fine
*/
for (i = 1; i < 16; ++i) {
usb_disable_endpoint(dev, i, true);
usb_disable_endpoint(dev, i + USB_DIR_IN, true);
}
config = dev->actconfig;
retval = 0;
mutex_lock(hcd->bandwidth_mutex);
/* Disable LPM, and re-enable it once the configuration is reset, so
* that the xHCI driver can recalculate the U1/U2 timeouts.
*/
if (usb_disable_lpm(dev)) {
dev_err(&dev->dev, "%s Failed to disable LPM\n.", __func__);
mutex_unlock(hcd->bandwidth_mutex);
return -ENOMEM;
}
/* Make sure we have enough bandwidth for each alternate setting 0 */
for (i = 0; i < config->desc.bNumInterfaces; i++) {
struct usb_interface *intf = config->interface[i];
struct usb_host_interface *alt;
alt = usb_altnum_to_altsetting(intf, 0);
if (!alt)
alt = &intf->altsetting[0];
if (alt != intf->cur_altsetting)
retval = usb_hcd_alloc_bandwidth(dev, NULL,
intf->cur_altsetting, alt);
if (retval < 0)
break;
}
/* If not, reinstate the old alternate settings */
if (retval < 0) {
reset_old_alts:
for (i--; i >= 0; i--) {
struct usb_interface *intf = config->interface[i];
struct usb_host_interface *alt;
alt = usb_altnum_to_altsetting(intf, 0);
if (!alt)
alt = &intf->altsetting[0];
if (alt != intf->cur_altsetting)
usb_hcd_alloc_bandwidth(dev, NULL,
alt, intf->cur_altsetting);
}
usb_enable_lpm(dev);
mutex_unlock(hcd->bandwidth_mutex);
return retval;
}
retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_SET_CONFIGURATION, 0,
config->desc.bConfigurationValue, 0,
NULL, 0, USB_CTRL_SET_TIMEOUT);
if (retval < 0)
goto reset_old_alts;
mutex_unlock(hcd->bandwidth_mutex);
/* re-init hc/hcd interface/endpoint state */
for (i = 0; i < config->desc.bNumInterfaces; i++) {
struct usb_interface *intf = config->interface[i];
struct usb_host_interface *alt;
alt = usb_altnum_to_altsetting(intf, 0);
/* No altsetting 0? We'll assume the first altsetting.
* We could use a GetInterface call, but if a device is
* so non-compliant that it doesn't have altsetting 0
* then I wouldn't trust its reply anyway.
*/
if (!alt)
alt = &intf->altsetting[0];
if (alt != intf->cur_altsetting) {
remove_intf_ep_devs(intf);
usb_remove_sysfs_intf_files(intf);
}
intf->cur_altsetting = alt;
usb_enable_interface(dev, intf, true);
if (device_is_registered(&intf->dev)) {
usb_create_sysfs_intf_files(intf);
create_intf_ep_devs(intf);
}
}
/* Now that the interfaces are installed, re-enable LPM. */
usb_unlocked_enable_lpm(dev);
return 0;
}
EXPORT_SYMBOL_GPL(usb_reset_configuration);
static void usb_release_interface(struct device *dev)
{
struct usb_interface *intf = to_usb_interface(dev);
struct usb_interface_cache *intfc =
altsetting_to_usb_interface_cache(intf->altsetting);
kref_put(&intfc->ref, usb_release_interface_cache);
usb_put_dev(interface_to_usbdev(intf));
kfree(intf);
}
static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env)
{
struct usb_device *usb_dev;
struct usb_interface *intf;
struct usb_host_interface *alt;
intf = to_usb_interface(dev);
usb_dev = interface_to_usbdev(intf);
alt = intf->cur_altsetting;
if (add_uevent_var(env, "INTERFACE=%d/%d/%d",
alt->desc.bInterfaceClass,
alt->desc.bInterfaceSubClass,
alt->desc.bInterfaceProtocol))
return -ENOMEM;
if (add_uevent_var(env,
"MODALIAS=usb:"
"v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02Xin%02X",
le16_to_cpu(usb_dev->descriptor.idVendor),
le16_to_cpu(usb_dev->descriptor.idProduct),
le16_to_cpu(usb_dev->descriptor.bcdDevice),
usb_dev->descriptor.bDeviceClass,
usb_dev->descriptor.bDeviceSubClass,
usb_dev->descriptor.bDeviceProtocol,
alt->desc.bInterfaceClass,
alt->desc.bInterfaceSubClass,
alt->desc.bInterfaceProtocol,
alt->desc.bInterfaceNumber))
return -ENOMEM;
return 0;
}
struct device_type usb_if_device_type = {
.name = "usb_interface",
.release = usb_release_interface,
.uevent = usb_if_uevent,
};
static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev,
struct usb_host_config *config,
u8 inum)
{
struct usb_interface_assoc_descriptor *retval = NULL;
struct usb_interface_assoc_descriptor *intf_assoc;
int first_intf;
int last_intf;
int i;
for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) {
intf_assoc = config->intf_assoc[i];
if (intf_assoc->bInterfaceCount == 0)
continue;
first_intf = intf_assoc->bFirstInterface;
last_intf = first_intf + (intf_assoc->bInterfaceCount - 1);
if (inum >= first_intf && inum <= last_intf) {
if (!retval)
retval = intf_assoc;
else
dev_err(&dev->dev, "Interface #%d referenced"
" by multiple IADs\n", inum);
}
}
return retval;
}
/*
* Internal function to queue a device reset
* See usb_queue_reset_device() for more details
*/
static void __usb_queue_reset_device(struct work_struct *ws)
{
int rc;
struct usb_interface *iface =
container_of(ws, struct usb_interface, reset_ws);
struct usb_device *udev = interface_to_usbdev(iface);
rc = usb_lock_device_for_reset(udev, iface);
if (rc >= 0) {
usb_reset_device(udev);
usb_unlock_device(udev);
}
usb_put_intf(iface); /* Undo _get_ in usb_queue_reset_device() */
}
/*
* usb_set_configuration - Makes a particular device setting be current
* @dev: the device whose configuration is being updated
* @configuration: the configuration being chosen.
* Context: !in_interrupt(), caller owns the device lock
*
* This is used to enable non-default device modes. Not all devices
* use this kind of configurability; many devices only have one
* configuration.
*
* @configuration is the value of the configuration to be installed.
* According to the USB spec (e.g. section 9.1.1.5), configuration values
* must be non-zero; a value of zero indicates that the device in
* unconfigured. However some devices erroneously use 0 as one of their
* configuration values. To help manage such devices, this routine will
* accept @configuration = -1 as indicating the device should be put in
* an unconfigured state.
*
* USB device configurations may affect Linux interoperability,
* power consumption and the functionality available. For example,
* the default configuration is limited to using 100mA of bus power,
* so that when certain device functionality requires more power,
* and the device is bus powered, that functionality should be in some
* non-default device configuration. Other device modes may also be
* reflected as configuration options, such as whether two ISDN
* channels are available independently; and choosing between open
* standard device protocols (like CDC) or proprietary ones.
*
* Note that a non-authorized device (dev->authorized == 0) will only
* be put in unconfigured mode.
*
* Note that USB has an additional level of device configurability,
* associated with interfaces. That configurability is accessed using
* usb_set_interface().
*
* This call is synchronous. The calling context must be able to sleep,
* must own the device lock, and must not hold the driver model's USB
* bus mutex; usb interface driver probe() methods cannot use this routine.
*
* Returns zero on success, or else the status code returned by the
* underlying call that failed. On successful completion, each interface
* in the original device configuration has been destroyed, and each one
* in the new configuration has been probed by all relevant usb device
* drivers currently known to the kernel.
*/
int usb_set_configuration(struct usb_device *dev, int configuration)
{
int i, ret;
struct usb_host_config *cp = NULL;
struct usb_interface **new_interfaces = NULL;
struct usb_hcd *hcd = bus_to_hcd(dev->bus);
int n, nintf;
if (dev->authorized == 0 || configuration == -1)
configuration = 0;
else {
for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
if (dev->config[i].desc.bConfigurationValue ==
configuration) {
cp = &dev->config[i];
break;
}
}
}
if ((!cp && configuration != 0))
return -EINVAL;
/* The USB spec says configuration 0 means unconfigured.
* But if a device includes a configuration numbered 0,
* we will accept it as a correctly configured state.
* Use -1 if you really want to unconfigure the device.
*/
if (cp && configuration == 0)
dev_warn(&dev->dev, "config 0 descriptor??\n");
/* Allocate memory for new interfaces before doing anything else,
* so that if we run out then nothing will have changed. */
n = nintf = 0;
if (cp) {
nintf = cp->desc.bNumInterfaces;
new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
GFP_NOIO);
if (!new_interfaces) {
dev_err(&dev->dev, "Out of memory\n");
return -ENOMEM;
}
for (; n < nintf; ++n) {
new_interfaces[n] = kzalloc(
sizeof(struct usb_interface),
GFP_NOIO);
if (!new_interfaces[n]) {
dev_err(&dev->dev, "Out of memory\n");
ret = -ENOMEM;
free_interfaces:
while (--n >= 0)
kfree(new_interfaces[n]);
kfree(new_interfaces);
return ret;
}
}
i = dev->bus_mA - usb_get_max_power(dev, cp);
if (i < 0)
dev_warn(&dev->dev, "new config #%d exceeds power "
"limit by %dmA\n",
configuration, -i);
}
/* Wake up the device so we can send it the Set-Config request */
ret = usb_autoresume_device(dev);
if (ret)
goto free_interfaces;
/* if it's already configured, clear out old state first.
* getting rid of old interfaces means unbinding their drivers.
*/
if (dev->state != USB_STATE_ADDRESS)
usb_disable_device(dev, 1); /* Skip ep0 */
/* Get rid of pending async Set-Config requests for this device */
cancel_async_set_config(dev);
/* Make sure we have bandwidth (and available HCD resources) for this
* configuration. Remove endpoints from the schedule if we're dropping
* this configuration to set configuration 0. After this point, the
* host controller will not allow submissions to dropped endpoints. If
* this call fails, the device state is unchanged.
*/
mutex_lock(hcd->bandwidth_mutex);
/* Disable LPM, and re-enable it once the new configuration is
* installed, so that the xHCI driver can recalculate the U1/U2
* timeouts.
*/
if (dev->actconfig && usb_disable_lpm(dev)) {
dev_err(&dev->dev, "%s Failed to disable LPM\n.", __func__);
mutex_unlock(hcd->bandwidth_mutex);
ret = -ENOMEM;
goto free_interfaces;
}
ret = usb_hcd_alloc_bandwidth(dev, cp, NULL, NULL);
if (ret < 0) {
if (dev->actconfig)
usb_enable_lpm(dev);
mutex_unlock(hcd->bandwidth_mutex);
usb_autosuspend_device(dev);
goto free_interfaces;
}
/*
* Initialize the new interface structures and the
* hc/hcd/usbcore interface/endpoint state.
*/
for (i = 0; i < nintf; ++i) {
struct usb_interface_cache *intfc;
struct usb_interface *intf;
struct usb_host_interface *alt;
cp->interface[i] = intf = new_interfaces[i];
intfc = cp->intf_cache[i];
intf->altsetting = intfc->altsetting;
intf->num_altsetting = intfc->num_altsetting;
kref_get(&intfc->ref);
alt = usb_altnum_to_altsetting(intf, 0);
/* No altsetting 0? We'll assume the first altsetting.
* We could use a GetInterface call, but if a device is
* so non-compliant that it doesn't have altsetting 0
* then I wouldn't trust its reply anyway.
*/
if (!alt)
alt = &intf->altsetting[0];
intf->intf_assoc =
find_iad(dev, cp, alt->desc.bInterfaceNumber);
intf->cur_altsetting = alt;
usb_enable_interface(dev, intf, true);
intf->dev.parent = &dev->dev;
intf->dev.driver = NULL;
intf->dev.bus = &usb_bus_type;
intf->dev.type = &usb_if_device_type;
intf->dev.groups = usb_interface_groups;
intf->dev.dma_mask = dev->dev.dma_mask;
INIT_WORK(&intf->reset_ws, __usb_queue_reset_device);
intf->minor = -1;
device_initialize(&intf->dev);
pm_runtime_no_callbacks(&intf->dev);
dev_set_name(&intf->dev, "%d-%s:%d.%d",
dev->bus->busnum, dev->devpath,
configuration, alt->desc.bInterfaceNumber);
usb_get_dev(dev);
}
kfree(new_interfaces);
ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
NULL, 0, USB_CTRL_SET_TIMEOUT);
if (ret < 0 && cp) {
/*
* All the old state is gone, so what else can we do?
* The device is probably useless now anyway.
*/
usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
for (i = 0; i < nintf; ++i) {
usb_disable_interface(dev, cp->interface[i], true);
put_device(&cp->interface[i]->dev);
cp->interface[i] = NULL;
}
cp = NULL;
}
dev->actconfig = cp;
mutex_unlock(hcd->bandwidth_mutex);
if (!cp) {
usb_set_device_state(dev, USB_STATE_ADDRESS);
/* Leave LPM disabled while the device is unconfigured. */
usb_autosuspend_device(dev);
return ret;
}
usb_set_device_state(dev, USB_STATE_CONFIGURED);
if (cp->string == NULL &&
!(dev->quirks & USB_QUIRK_CONFIG_INTF_STRINGS))
cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
/* Now that the interfaces are installed, re-enable LPM. */
usb_unlocked_enable_lpm(dev);
/* Enable LTM if it was turned off by usb_disable_device. */
usb_enable_ltm(dev);
/* Now that all the interfaces are set up, register them
* to trigger binding of drivers to interfaces. probe()
* routines may install different altsettings and may
* claim() any interfaces not yet bound. Many class drivers
* need that: CDC, audio, video, etc.
*/
for (i = 0; i < nintf; ++i) {
struct usb_interface *intf = cp->interface[i];
dev_dbg(&dev->dev,
"adding %s (config #%d, interface %d)\n",
dev_name(&intf->dev), configuration,
intf->cur_altsetting->desc.bInterfaceNumber);
device_enable_async_suspend(&intf->dev);
ret = device_add(&intf->dev);
if (ret != 0) {
dev_err(&dev->dev, "device_add(%s) --> %d\n",
dev_name(&intf->dev), ret);
continue;
}
create_intf_ep_devs(intf);
}
usb_autosuspend_device(dev);
return 0;
}
EXPORT_SYMBOL_GPL(usb_set_configuration);
static LIST_HEAD(set_config_list);
static DEFINE_SPINLOCK(set_config_lock);
struct set_config_request {
struct usb_device *udev;
int config;
struct work_struct work;
struct list_head node;
};
/* Worker routine for usb_driver_set_configuration() */
static void driver_set_config_work(struct work_struct *work)
{
struct set_config_request *req =
container_of(work, struct set_config_request, work);
struct usb_device *udev = req->udev;
usb_lock_device(udev);
spin_lock(&set_config_lock);
list_del(&req->node);
spin_unlock(&set_config_lock);
if (req->config >= -1) /* Is req still valid? */
usb_set_configuration(udev, req->config);
usb_unlock_device(udev);
usb_put_dev(udev);
kfree(req);
}
/* Cancel pending Set-Config requests for a device whose configuration
* was just changed
*/
static void cancel_async_set_config(struct usb_device *udev)
{
struct set_config_request *req;
spin_lock(&set_config_lock);
list_for_each_entry(req, &set_config_list, node) {
if (req->udev == udev)
req->config = -999; /* Mark as cancelled */
}
spin_unlock(&set_config_lock);
}
/**
* usb_driver_set_configuration - Provide a way for drivers to change device configurations
* @udev: the device whose configuration is being updated
* @config: the configuration being chosen.
* Context: In process context, must be able to sleep
*
* Device interface drivers are not allowed to change device configurations.
* This is because changing configurations will destroy the interface the
* driver is bound to and create new ones; it would be like a floppy-disk
* driver telling the computer to replace the floppy-disk drive with a
* tape drive!
*
* Still, in certain specialized circumstances the need may arise. This
* routine gets around the normal restrictions by using a work thread to
* submit the change-config request.
*
* Return: 0 if the request was successfully queued, error code otherwise.
* The caller has no way to know whether the queued request will eventually
* succeed.
*/
int usb_driver_set_configuration(struct usb_device *udev, int config)
{
struct set_config_request *req;
req = kmalloc(sizeof(*req), GFP_KERNEL);
if (!req)
return -ENOMEM;
req->udev = udev;
req->config = config;
INIT_WORK(&req->work, driver_set_config_work);
spin_lock(&set_config_lock);
list_add(&req->node, &set_config_list);
spin_unlock(&set_config_lock);
usb_get_dev(udev);
schedule_work(&req->work);
return 0;
}
EXPORT_SYMBOL_GPL(usb_driver_set_configuration);
| gpl-2.0 |
caplio/HTCJ-diff-test | fs/nfs/nfs3proc.c | 869 | 22694 | /*
* linux/fs/nfs/nfs3proc.c
*
* Client-side NFSv3 procedures stubs.
*
* Copyright (C) 1997, Olaf Kirch
*/
#include <linux/mm.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/sunrpc/clnt.h>
#include <linux/slab.h>
#include <linux/nfs.h>
#include <linux/nfs3.h>
#include <linux/nfs_fs.h>
#include <linux/nfs_page.h>
#include <linux/lockd/bind.h>
#include <linux/nfs_mount.h>
#include "iostat.h"
#include "internal.h"
#define NFSDBG_FACILITY NFSDBG_PROC
/* A wrapper to handle the EJUKEBOX and EKEYEXPIRED error messages */
static int
nfs3_rpc_wrapper(struct rpc_clnt *clnt, struct rpc_message *msg, int flags)
{
int res;
do {
res = rpc_call_sync(clnt, msg, flags);
if (res != -EJUKEBOX && res != -EKEYEXPIRED)
break;
schedule_timeout_killable(NFS_JUKEBOX_RETRY_TIME);
res = -ERESTARTSYS;
} while (!fatal_signal_pending(current));
return res;
}
#define rpc_call_sync(clnt, msg, flags) nfs3_rpc_wrapper(clnt, msg, flags)
static int
nfs3_async_handle_jukebox(struct rpc_task *task, struct inode *inode)
{
if (task->tk_status != -EJUKEBOX && task->tk_status != -EKEYEXPIRED)
return 0;
if (task->tk_status == -EJUKEBOX)
nfs_inc_stats(inode, NFSIOS_DELAY);
task->tk_status = 0;
rpc_restart_call(task);
rpc_delay(task, NFS_JUKEBOX_RETRY_TIME);
return 1;
}
static int
do_proc_get_root(struct rpc_clnt *client, struct nfs_fh *fhandle,
struct nfs_fsinfo *info)
{
struct rpc_message msg = {
.rpc_proc = &nfs3_procedures[NFS3PROC_FSINFO],
.rpc_argp = fhandle,
.rpc_resp = info,
};
int status;
dprintk("%s: call fsinfo\n", __func__);
nfs_fattr_init(info->fattr);
status = rpc_call_sync(client, &msg, 0);
dprintk("%s: reply fsinfo: %d\n", __func__, status);
if (!(info->fattr->valid & NFS_ATTR_FATTR)) {
msg.rpc_proc = &nfs3_procedures[NFS3PROC_GETATTR];
msg.rpc_resp = info->fattr;
status = rpc_call_sync(client, &msg, 0);
dprintk("%s: reply getattr: %d\n", __func__, status);
}
return status;
}
/*
* Bare-bones access to getattr: this is for nfs_get_root/nfs_get_sb
*/
static int
nfs3_proc_get_root(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fsinfo *info)
{
int status;
status = do_proc_get_root(server->client, fhandle, info);
if (status && server->nfs_client->cl_rpcclient != server->client)
status = do_proc_get_root(server->nfs_client->cl_rpcclient, fhandle, info);
return status;
}
/*
* One function for each procedure in the NFS protocol.
*/
static int
nfs3_proc_getattr(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fattr *fattr)
{
struct rpc_message msg = {
.rpc_proc = &nfs3_procedures[NFS3PROC_GETATTR],
.rpc_argp = fhandle,
.rpc_resp = fattr,
};
int status;
dprintk("NFS call getattr\n");
nfs_fattr_init(fattr);
status = rpc_call_sync(server->client, &msg, 0);
dprintk("NFS reply getattr: %d\n", status);
return status;
}
static int
nfs3_proc_setattr(struct dentry *dentry, struct nfs_fattr *fattr,
struct iattr *sattr)
{
struct inode *inode = dentry->d_inode;
struct nfs3_sattrargs arg = {
.fh = NFS_FH(inode),
.sattr = sattr,
};
struct rpc_message msg = {
.rpc_proc = &nfs3_procedures[NFS3PROC_SETATTR],
.rpc_argp = &arg,
.rpc_resp = fattr,
};
int status;
dprintk("NFS call setattr\n");
if (sattr->ia_valid & ATTR_FILE)
msg.rpc_cred = nfs_file_cred(sattr->ia_file);
nfs_fattr_init(fattr);
status = rpc_call_sync(NFS_CLIENT(inode), &msg, 0);
if (status == 0)
nfs_setattr_update_inode(inode, sattr);
dprintk("NFS reply setattr: %d\n", status);
return status;
}
static int
nfs3_proc_lookup(struct rpc_clnt *clnt, struct inode *dir, struct qstr *name,
struct nfs_fh *fhandle, struct nfs_fattr *fattr)
{
struct nfs3_diropargs arg = {
.fh = NFS_FH(dir),
.name = name->name,
.len = name->len
};
struct nfs3_diropres res = {
.fh = fhandle,
.fattr = fattr
};
struct rpc_message msg = {
.rpc_proc = &nfs3_procedures[NFS3PROC_LOOKUP],
.rpc_argp = &arg,
.rpc_resp = &res,
};
int status;
dprintk("NFS call lookup %s\n", name->name);
res.dir_attr = nfs_alloc_fattr();
if (res.dir_attr == NULL)
return -ENOMEM;
nfs_fattr_init(fattr);
status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0);
nfs_refresh_inode(dir, res.dir_attr);
if (status >= 0 && !(fattr->valid & NFS_ATTR_FATTR)) {
msg.rpc_proc = &nfs3_procedures[NFS3PROC_GETATTR];
msg.rpc_argp = fhandle;
msg.rpc_resp = fattr;
status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0);
}
nfs_free_fattr(res.dir_attr);
dprintk("NFS reply lookup: %d\n", status);
return status;
}
static int nfs3_proc_access(struct inode *inode, struct nfs_access_entry *entry)
{
struct nfs3_accessargs arg = {
.fh = NFS_FH(inode),
};
struct nfs3_accessres res;
struct rpc_message msg = {
.rpc_proc = &nfs3_procedures[NFS3PROC_ACCESS],
.rpc_argp = &arg,
.rpc_resp = &res,
.rpc_cred = entry->cred,
};
int mode = entry->mask;
int status = -ENOMEM;
dprintk("NFS call access\n");
if (mode & MAY_READ)
arg.access |= NFS3_ACCESS_READ;
if (S_ISDIR(inode->i_mode)) {
if (mode & MAY_WRITE)
arg.access |= NFS3_ACCESS_MODIFY | NFS3_ACCESS_EXTEND | NFS3_ACCESS_DELETE;
if (mode & MAY_EXEC)
arg.access |= NFS3_ACCESS_LOOKUP;
} else {
if (mode & MAY_WRITE)
arg.access |= NFS3_ACCESS_MODIFY | NFS3_ACCESS_EXTEND;
if (mode & MAY_EXEC)
arg.access |= NFS3_ACCESS_EXECUTE;
}
res.fattr = nfs_alloc_fattr();
if (res.fattr == NULL)
goto out;
status = rpc_call_sync(NFS_CLIENT(inode), &msg, 0);
nfs_refresh_inode(inode, res.fattr);
if (status == 0) {
entry->mask = 0;
if (res.access & NFS3_ACCESS_READ)
entry->mask |= MAY_READ;
if (res.access & (NFS3_ACCESS_MODIFY | NFS3_ACCESS_EXTEND | NFS3_ACCESS_DELETE))
entry->mask |= MAY_WRITE;
if (res.access & (NFS3_ACCESS_LOOKUP|NFS3_ACCESS_EXECUTE))
entry->mask |= MAY_EXEC;
}
nfs_free_fattr(res.fattr);
out:
dprintk("NFS reply access: %d\n", status);
return status;
}
static int nfs3_proc_readlink(struct inode *inode, struct page *page,
unsigned int pgbase, unsigned int pglen)
{
struct nfs_fattr *fattr;
struct nfs3_readlinkargs args = {
.fh = NFS_FH(inode),
.pgbase = pgbase,
.pglen = pglen,
.pages = &page
};
struct rpc_message msg = {
.rpc_proc = &nfs3_procedures[NFS3PROC_READLINK],
.rpc_argp = &args,
};
int status = -ENOMEM;
dprintk("NFS call readlink\n");
fattr = nfs_alloc_fattr();
if (fattr == NULL)
goto out;
msg.rpc_resp = fattr;
status = rpc_call_sync(NFS_CLIENT(inode), &msg, 0);
nfs_refresh_inode(inode, fattr);
nfs_free_fattr(fattr);
out:
dprintk("NFS reply readlink: %d\n", status);
return status;
}
struct nfs3_createdata {
struct rpc_message msg;
union {
struct nfs3_createargs create;
struct nfs3_mkdirargs mkdir;
struct nfs3_symlinkargs symlink;
struct nfs3_mknodargs mknod;
} arg;
struct nfs3_diropres res;
struct nfs_fh fh;
struct nfs_fattr fattr;
struct nfs_fattr dir_attr;
};
static struct nfs3_createdata *nfs3_alloc_createdata(void)
{
struct nfs3_createdata *data;
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (data != NULL) {
data->msg.rpc_argp = &data->arg;
data->msg.rpc_resp = &data->res;
data->res.fh = &data->fh;
data->res.fattr = &data->fattr;
data->res.dir_attr = &data->dir_attr;
nfs_fattr_init(data->res.fattr);
nfs_fattr_init(data->res.dir_attr);
}
return data;
}
static int nfs3_do_create(struct inode *dir, struct dentry *dentry, struct nfs3_createdata *data)
{
int status;
status = rpc_call_sync(NFS_CLIENT(dir), &data->msg, 0);
nfs_post_op_update_inode(dir, data->res.dir_attr);
if (status == 0)
status = nfs_instantiate(dentry, data->res.fh, data->res.fattr);
return status;
}
static void nfs3_free_createdata(struct nfs3_createdata *data)
{
kfree(data);
}
/*
* Create a regular file.
*/
static int
nfs3_proc_create(struct inode *dir, struct dentry *dentry, struct iattr *sattr,
int flags, struct nfs_open_context *ctx)
{
struct nfs3_createdata *data;
mode_t mode = sattr->ia_mode;
int status = -ENOMEM;
dprintk("NFS call create %s\n", dentry->d_name.name);
data = nfs3_alloc_createdata();
if (data == NULL)
goto out;
data->msg.rpc_proc = &nfs3_procedures[NFS3PROC_CREATE];
data->arg.create.fh = NFS_FH(dir);
data->arg.create.name = dentry->d_name.name;
data->arg.create.len = dentry->d_name.len;
data->arg.create.sattr = sattr;
data->arg.create.createmode = NFS3_CREATE_UNCHECKED;
if (flags & O_EXCL) {
data->arg.create.createmode = NFS3_CREATE_EXCLUSIVE;
data->arg.create.verifier[0] = jiffies;
data->arg.create.verifier[1] = current->pid;
}
sattr->ia_mode &= ~current_umask();
for (;;) {
status = nfs3_do_create(dir, dentry, data);
if (status != -ENOTSUPP)
break;
/* If the server doesn't support the exclusive creation
* semantics, try again with simple 'guarded' mode. */
switch (data->arg.create.createmode) {
case NFS3_CREATE_EXCLUSIVE:
data->arg.create.createmode = NFS3_CREATE_GUARDED;
break;
case NFS3_CREATE_GUARDED:
data->arg.create.createmode = NFS3_CREATE_UNCHECKED;
break;
case NFS3_CREATE_UNCHECKED:
goto out;
}
nfs_fattr_init(data->res.dir_attr);
nfs_fattr_init(data->res.fattr);
}
if (status != 0)
goto out;
/* When we created the file with exclusive semantics, make
* sure we set the attributes afterwards. */
if (data->arg.create.createmode == NFS3_CREATE_EXCLUSIVE) {
dprintk("NFS call setattr (post-create)\n");
if (!(sattr->ia_valid & ATTR_ATIME_SET))
sattr->ia_valid |= ATTR_ATIME;
if (!(sattr->ia_valid & ATTR_MTIME_SET))
sattr->ia_valid |= ATTR_MTIME;
/* Note: we could use a guarded setattr here, but I'm
* not sure this buys us anything (and I'd have
* to revamp the NFSv3 XDR code) */
status = nfs3_proc_setattr(dentry, data->res.fattr, sattr);
nfs_post_op_update_inode(dentry->d_inode, data->res.fattr);
dprintk("NFS reply setattr (post-create): %d\n", status);
if (status != 0)
goto out;
}
status = nfs3_proc_set_default_acl(dir, dentry->d_inode, mode);
out:
nfs3_free_createdata(data);
dprintk("NFS reply create: %d\n", status);
return status;
}
static int
nfs3_proc_remove(struct inode *dir, struct qstr *name)
{
struct nfs_removeargs arg = {
.fh = NFS_FH(dir),
.name.len = name->len,
.name.name = name->name,
};
struct nfs_removeres res;
struct rpc_message msg = {
.rpc_proc = &nfs3_procedures[NFS3PROC_REMOVE],
.rpc_argp = &arg,
.rpc_resp = &res,
};
int status = -ENOMEM;
dprintk("NFS call remove %s\n", name->name);
res.dir_attr = nfs_alloc_fattr();
if (res.dir_attr == NULL)
goto out;
status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0);
nfs_post_op_update_inode(dir, res.dir_attr);
nfs_free_fattr(res.dir_attr);
out:
dprintk("NFS reply remove: %d\n", status);
return status;
}
static void
nfs3_proc_unlink_setup(struct rpc_message *msg, struct inode *dir)
{
msg->rpc_proc = &nfs3_procedures[NFS3PROC_REMOVE];
}
static int
nfs3_proc_unlink_done(struct rpc_task *task, struct inode *dir)
{
struct nfs_removeres *res;
if (nfs3_async_handle_jukebox(task, dir))
return 0;
res = task->tk_msg.rpc_resp;
nfs_post_op_update_inode(dir, res->dir_attr);
return 1;
}
static void
nfs3_proc_rename_setup(struct rpc_message *msg, struct inode *dir)
{
msg->rpc_proc = &nfs3_procedures[NFS3PROC_RENAME];
}
static int
nfs3_proc_rename_done(struct rpc_task *task, struct inode *old_dir,
struct inode *new_dir)
{
struct nfs_renameres *res;
if (nfs3_async_handle_jukebox(task, old_dir))
return 0;
res = task->tk_msg.rpc_resp;
nfs_post_op_update_inode(old_dir, res->old_fattr);
nfs_post_op_update_inode(new_dir, res->new_fattr);
return 1;
}
static int
nfs3_proc_rename(struct inode *old_dir, struct qstr *old_name,
struct inode *new_dir, struct qstr *new_name)
{
struct nfs_renameargs arg = {
.old_dir = NFS_FH(old_dir),
.old_name = old_name,
.new_dir = NFS_FH(new_dir),
.new_name = new_name,
};
struct nfs_renameres res;
struct rpc_message msg = {
.rpc_proc = &nfs3_procedures[NFS3PROC_RENAME],
.rpc_argp = &arg,
.rpc_resp = &res,
};
int status = -ENOMEM;
dprintk("NFS call rename %s -> %s\n", old_name->name, new_name->name);
res.old_fattr = nfs_alloc_fattr();
res.new_fattr = nfs_alloc_fattr();
if (res.old_fattr == NULL || res.new_fattr == NULL)
goto out;
status = rpc_call_sync(NFS_CLIENT(old_dir), &msg, 0);
nfs_post_op_update_inode(old_dir, res.old_fattr);
nfs_post_op_update_inode(new_dir, res.new_fattr);
out:
nfs_free_fattr(res.old_fattr);
nfs_free_fattr(res.new_fattr);
dprintk("NFS reply rename: %d\n", status);
return status;
}
static int
nfs3_proc_link(struct inode *inode, struct inode *dir, struct qstr *name)
{
struct nfs3_linkargs arg = {
.fromfh = NFS_FH(inode),
.tofh = NFS_FH(dir),
.toname = name->name,
.tolen = name->len
};
struct nfs3_linkres res;
struct rpc_message msg = {
.rpc_proc = &nfs3_procedures[NFS3PROC_LINK],
.rpc_argp = &arg,
.rpc_resp = &res,
};
int status = -ENOMEM;
dprintk("NFS call link %s\n", name->name);
res.fattr = nfs_alloc_fattr();
res.dir_attr = nfs_alloc_fattr();
if (res.fattr == NULL || res.dir_attr == NULL)
goto out;
status = rpc_call_sync(NFS_CLIENT(inode), &msg, 0);
nfs_post_op_update_inode(dir, res.dir_attr);
nfs_post_op_update_inode(inode, res.fattr);
out:
nfs_free_fattr(res.dir_attr);
nfs_free_fattr(res.fattr);
dprintk("NFS reply link: %d\n", status);
return status;
}
static int
nfs3_proc_symlink(struct inode *dir, struct dentry *dentry, struct page *page,
unsigned int len, struct iattr *sattr)
{
struct nfs3_createdata *data;
int status = -ENOMEM;
if (len > NFS3_MAXPATHLEN)
return -ENAMETOOLONG;
dprintk("NFS call symlink %s\n", dentry->d_name.name);
data = nfs3_alloc_createdata();
if (data == NULL)
goto out;
data->msg.rpc_proc = &nfs3_procedures[NFS3PROC_SYMLINK];
data->arg.symlink.fromfh = NFS_FH(dir);
data->arg.symlink.fromname = dentry->d_name.name;
data->arg.symlink.fromlen = dentry->d_name.len;
data->arg.symlink.pages = &page;
data->arg.symlink.pathlen = len;
data->arg.symlink.sattr = sattr;
status = nfs3_do_create(dir, dentry, data);
nfs3_free_createdata(data);
out:
dprintk("NFS reply symlink: %d\n", status);
return status;
}
static int
nfs3_proc_mkdir(struct inode *dir, struct dentry *dentry, struct iattr *sattr)
{
struct nfs3_createdata *data;
int mode = sattr->ia_mode;
int status = -ENOMEM;
dprintk("NFS call mkdir %s\n", dentry->d_name.name);
sattr->ia_mode &= ~current_umask();
data = nfs3_alloc_createdata();
if (data == NULL)
goto out;
data->msg.rpc_proc = &nfs3_procedures[NFS3PROC_MKDIR];
data->arg.mkdir.fh = NFS_FH(dir);
data->arg.mkdir.name = dentry->d_name.name;
data->arg.mkdir.len = dentry->d_name.len;
data->arg.mkdir.sattr = sattr;
status = nfs3_do_create(dir, dentry, data);
if (status != 0)
goto out;
status = nfs3_proc_set_default_acl(dir, dentry->d_inode, mode);
out:
nfs3_free_createdata(data);
dprintk("NFS reply mkdir: %d\n", status);
return status;
}
static int
nfs3_proc_rmdir(struct inode *dir, struct qstr *name)
{
struct nfs_fattr *dir_attr;
struct nfs3_diropargs arg = {
.fh = NFS_FH(dir),
.name = name->name,
.len = name->len
};
struct rpc_message msg = {
.rpc_proc = &nfs3_procedures[NFS3PROC_RMDIR],
.rpc_argp = &arg,
};
int status = -ENOMEM;
dprintk("NFS call rmdir %s\n", name->name);
dir_attr = nfs_alloc_fattr();
if (dir_attr == NULL)
goto out;
msg.rpc_resp = dir_attr;
status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0);
nfs_post_op_update_inode(dir, dir_attr);
nfs_free_fattr(dir_attr);
out:
dprintk("NFS reply rmdir: %d\n", status);
return status;
}
/*
* The READDIR implementation is somewhat hackish - we pass the user buffer
* to the encode function, which installs it in the receive iovec.
* The decode function itself doesn't perform any decoding, it just makes
* sure the reply is syntactically correct.
*
* Also note that this implementation handles both plain readdir and
* readdirplus.
*/
static int
nfs3_proc_readdir(struct dentry *dentry, struct rpc_cred *cred,
u64 cookie, struct page **pages, unsigned int count, int plus)
{
struct inode *dir = dentry->d_inode;
__be32 *verf = NFS_COOKIEVERF(dir);
struct nfs3_readdirargs arg = {
.fh = NFS_FH(dir),
.cookie = cookie,
.verf = {verf[0], verf[1]},
.plus = plus,
.count = count,
.pages = pages
};
struct nfs3_readdirres res = {
.verf = verf,
.plus = plus
};
struct rpc_message msg = {
.rpc_proc = &nfs3_procedures[NFS3PROC_READDIR],
.rpc_argp = &arg,
.rpc_resp = &res,
.rpc_cred = cred
};
int status = -ENOMEM;
if (plus)
msg.rpc_proc = &nfs3_procedures[NFS3PROC_READDIRPLUS];
dprintk("NFS call readdir%s %d\n",
plus? "plus" : "", (unsigned int) cookie);
res.dir_attr = nfs_alloc_fattr();
if (res.dir_attr == NULL)
goto out;
status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0);
nfs_invalidate_atime(dir);
nfs_refresh_inode(dir, res.dir_attr);
nfs_free_fattr(res.dir_attr);
out:
dprintk("NFS reply readdir%s: %d\n",
plus? "plus" : "", status);
return status;
}
static int
nfs3_proc_mknod(struct inode *dir, struct dentry *dentry, struct iattr *sattr,
dev_t rdev)
{
struct nfs3_createdata *data;
mode_t mode = sattr->ia_mode;
int status = -ENOMEM;
dprintk("NFS call mknod %s %u:%u\n", dentry->d_name.name,
MAJOR(rdev), MINOR(rdev));
sattr->ia_mode &= ~current_umask();
data = nfs3_alloc_createdata();
if (data == NULL)
goto out;
data->msg.rpc_proc = &nfs3_procedures[NFS3PROC_MKNOD];
data->arg.mknod.fh = NFS_FH(dir);
data->arg.mknod.name = dentry->d_name.name;
data->arg.mknod.len = dentry->d_name.len;
data->arg.mknod.sattr = sattr;
data->arg.mknod.rdev = rdev;
switch (sattr->ia_mode & S_IFMT) {
case S_IFBLK:
data->arg.mknod.type = NF3BLK;
break;
case S_IFCHR:
data->arg.mknod.type = NF3CHR;
break;
case S_IFIFO:
data->arg.mknod.type = NF3FIFO;
break;
case S_IFSOCK:
data->arg.mknod.type = NF3SOCK;
break;
default:
status = -EINVAL;
goto out;
}
status = nfs3_do_create(dir, dentry, data);
if (status != 0)
goto out;
status = nfs3_proc_set_default_acl(dir, dentry->d_inode, mode);
out:
nfs3_free_createdata(data);
dprintk("NFS reply mknod: %d\n", status);
return status;
}
static int
nfs3_proc_statfs(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fsstat *stat)
{
struct rpc_message msg = {
.rpc_proc = &nfs3_procedures[NFS3PROC_FSSTAT],
.rpc_argp = fhandle,
.rpc_resp = stat,
};
int status;
dprintk("NFS call fsstat\n");
nfs_fattr_init(stat->fattr);
status = rpc_call_sync(server->client, &msg, 0);
dprintk("NFS reply fsstat: %d\n", status);
return status;
}
static int
do_proc_fsinfo(struct rpc_clnt *client, struct nfs_fh *fhandle,
struct nfs_fsinfo *info)
{
struct rpc_message msg = {
.rpc_proc = &nfs3_procedures[NFS3PROC_FSINFO],
.rpc_argp = fhandle,
.rpc_resp = info,
};
int status;
dprintk("NFS call fsinfo\n");
nfs_fattr_init(info->fattr);
status = rpc_call_sync(client, &msg, 0);
dprintk("NFS reply fsinfo: %d\n", status);
return status;
}
/*
* Bare-bones access to fsinfo: this is for nfs_get_root/nfs_get_sb via
* nfs_create_server
*/
static int
nfs3_proc_fsinfo(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fsinfo *info)
{
int status;
status = do_proc_fsinfo(server->client, fhandle, info);
if (status && server->nfs_client->cl_rpcclient != server->client)
status = do_proc_fsinfo(server->nfs_client->cl_rpcclient, fhandle, info);
return status;
}
static int
nfs3_proc_pathconf(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_pathconf *info)
{
struct rpc_message msg = {
.rpc_proc = &nfs3_procedures[NFS3PROC_PATHCONF],
.rpc_argp = fhandle,
.rpc_resp = info,
};
int status;
dprintk("NFS call pathconf\n");
nfs_fattr_init(info->fattr);
status = rpc_call_sync(server->client, &msg, 0);
dprintk("NFS reply pathconf: %d\n", status);
return status;
}
static int nfs3_read_done(struct rpc_task *task, struct nfs_read_data *data)
{
if (nfs3_async_handle_jukebox(task, data->inode))
return -EAGAIN;
nfs_invalidate_atime(data->inode);
nfs_refresh_inode(data->inode, &data->fattr);
return 0;
}
static void nfs3_proc_read_setup(struct nfs_read_data *data, struct rpc_message *msg)
{
msg->rpc_proc = &nfs3_procedures[NFS3PROC_READ];
}
static int nfs3_write_done(struct rpc_task *task, struct nfs_write_data *data)
{
if (nfs3_async_handle_jukebox(task, data->inode))
return -EAGAIN;
if (task->tk_status >= 0)
nfs_post_op_update_inode_force_wcc(data->inode, data->res.fattr);
return 0;
}
static void nfs3_proc_write_setup(struct nfs_write_data *data, struct rpc_message *msg)
{
msg->rpc_proc = &nfs3_procedures[NFS3PROC_WRITE];
}
static int nfs3_commit_done(struct rpc_task *task, struct nfs_write_data *data)
{
if (nfs3_async_handle_jukebox(task, data->inode))
return -EAGAIN;
nfs_refresh_inode(data->inode, data->res.fattr);
return 0;
}
static void nfs3_proc_commit_setup(struct nfs_write_data *data, struct rpc_message *msg)
{
msg->rpc_proc = &nfs3_procedures[NFS3PROC_COMMIT];
}
static int
nfs3_proc_lock(struct file *filp, int cmd, struct file_lock *fl)
{
struct inode *inode = filp->f_path.dentry->d_inode;
return nlmclnt_proc(NFS_SERVER(inode)->nlm_host, cmd, fl);
}
const struct nfs_rpc_ops nfs_v3_clientops = {
.version = 3, /* protocol version */
.dentry_ops = &nfs_dentry_operations,
.dir_inode_ops = &nfs3_dir_inode_operations,
.file_inode_ops = &nfs3_file_inode_operations,
.file_ops = &nfs_file_operations,
.getroot = nfs3_proc_get_root,
.getattr = nfs3_proc_getattr,
.setattr = nfs3_proc_setattr,
.lookup = nfs3_proc_lookup,
.access = nfs3_proc_access,
.readlink = nfs3_proc_readlink,
.create = nfs3_proc_create,
.remove = nfs3_proc_remove,
.unlink_setup = nfs3_proc_unlink_setup,
.unlink_done = nfs3_proc_unlink_done,
.rename = nfs3_proc_rename,
.rename_setup = nfs3_proc_rename_setup,
.rename_done = nfs3_proc_rename_done,
.link = nfs3_proc_link,
.symlink = nfs3_proc_symlink,
.mkdir = nfs3_proc_mkdir,
.rmdir = nfs3_proc_rmdir,
.readdir = nfs3_proc_readdir,
.mknod = nfs3_proc_mknod,
.statfs = nfs3_proc_statfs,
.fsinfo = nfs3_proc_fsinfo,
.pathconf = nfs3_proc_pathconf,
.decode_dirent = nfs3_decode_dirent,
.read_setup = nfs3_proc_read_setup,
.read_done = nfs3_read_done,
.write_setup = nfs3_proc_write_setup,
.write_done = nfs3_write_done,
.commit_setup = nfs3_proc_commit_setup,
.commit_done = nfs3_commit_done,
.lock = nfs3_proc_lock,
.clear_acl_cache = nfs3_forget_cached_acls,
.close_context = nfs_close_context,
.init_client = nfs_init_client,
};
| gpl-2.0 |
hsaito/linux | drivers/mtd/bcm47xxpart.c | 869 | 8685 | /*
* BCM47XX MTD partitioning
*
* Copyright © 2012 Rafał Miłecki <zajec5@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <uapi/linux/magic.h>
/*
* NAND flash on Netgear R6250 was verified to contain 15 partitions.
* This will result in allocating too big array for some old devices, but the
* memory will be freed soon anyway (see mtd_device_parse_register).
*/
#define BCM47XXPART_MAX_PARTS 20
/*
* Amount of bytes we read when analyzing each block of flash memory.
* Set it big enough to allow detecting partition and reading important data.
*/
#define BCM47XXPART_BYTES_TO_READ 0x4e8
/* Magics */
#define BOARD_DATA_MAGIC 0x5246504D /* MPFR */
#define BOARD_DATA_MAGIC2 0xBD0D0BBD
#define CFE_MAGIC 0x43464531 /* 1EFC */
#define FACTORY_MAGIC 0x59544346 /* FCTY */
#define NVRAM_HEADER 0x48534C46 /* FLSH */
#define POT_MAGIC1 0x54544f50 /* POTT */
#define POT_MAGIC2 0x504f /* OP */
#define ML_MAGIC1 0x39685a42
#define ML_MAGIC2 0x26594131
#define TRX_MAGIC 0x30524448
#define SHSQ_MAGIC 0x71736873 /* shsq (weird ZTE H218N endianness) */
#define UBI_EC_MAGIC 0x23494255 /* UBI# */
struct trx_header {
uint32_t magic;
uint32_t length;
uint32_t crc32;
uint16_t flags;
uint16_t version;
uint32_t offset[3];
} __packed;
static void bcm47xxpart_add_part(struct mtd_partition *part, const char *name,
u64 offset, uint32_t mask_flags)
{
part->name = name;
part->offset = offset;
part->mask_flags = mask_flags;
}
static const char *bcm47xxpart_trx_data_part_name(struct mtd_info *master,
size_t offset)
{
uint32_t buf;
size_t bytes_read;
if (mtd_read(master, offset, sizeof(buf), &bytes_read,
(uint8_t *)&buf) < 0) {
pr_err("mtd_read error while parsing (offset: 0x%X)!\n",
offset);
goto out_default;
}
if (buf == UBI_EC_MAGIC)
return "ubi";
out_default:
return "rootfs";
}
static int bcm47xxpart_parse(struct mtd_info *master,
struct mtd_partition **pparts,
struct mtd_part_parser_data *data)
{
struct mtd_partition *parts;
uint8_t i, curr_part = 0;
uint32_t *buf;
size_t bytes_read;
uint32_t offset;
uint32_t blocksize = master->erasesize;
struct trx_header *trx;
int trx_part = -1;
int last_trx_part = -1;
int possible_nvram_sizes[] = { 0x8000, 0xF000, 0x10000, };
/*
* Some really old flashes (like AT45DB*) had smaller erasesize-s, but
* partitions were aligned to at least 0x1000 anyway.
*/
if (blocksize < 0x1000)
blocksize = 0x1000;
/* Alloc */
parts = kzalloc(sizeof(struct mtd_partition) * BCM47XXPART_MAX_PARTS,
GFP_KERNEL);
if (!parts)
return -ENOMEM;
buf = kzalloc(BCM47XXPART_BYTES_TO_READ, GFP_KERNEL);
if (!buf) {
kfree(parts);
return -ENOMEM;
}
/* Parse block by block looking for magics */
for (offset = 0; offset <= master->size - blocksize;
offset += blocksize) {
/* Nothing more in higher memory */
if (offset >= 0x2000000)
break;
if (curr_part >= BCM47XXPART_MAX_PARTS) {
pr_warn("Reached maximum number of partitions, scanning stopped!\n");
break;
}
/* Read beginning of the block */
if (mtd_read(master, offset, BCM47XXPART_BYTES_TO_READ,
&bytes_read, (uint8_t *)buf) < 0) {
pr_err("mtd_read error while parsing (offset: 0x%X)!\n",
offset);
continue;
}
/* Magic or small NVRAM at 0x400 */
if ((buf[0x4e0 / 4] == CFE_MAGIC && buf[0x4e4 / 4] == CFE_MAGIC) ||
(buf[0x400 / 4] == NVRAM_HEADER)) {
bcm47xxpart_add_part(&parts[curr_part++], "boot",
offset, MTD_WRITEABLE);
continue;
}
/*
* board_data starts with board_id which differs across boards,
* but we can use 'MPFR' (hopefully) magic at 0x100
*/
if (buf[0x100 / 4] == BOARD_DATA_MAGIC) {
bcm47xxpart_add_part(&parts[curr_part++], "board_data",
offset, MTD_WRITEABLE);
continue;
}
/* Found on Huawei E970 */
if (buf[0x000 / 4] == FACTORY_MAGIC) {
bcm47xxpart_add_part(&parts[curr_part++], "factory",
offset, MTD_WRITEABLE);
continue;
}
/* POT(TOP) */
if (buf[0x000 / 4] == POT_MAGIC1 &&
(buf[0x004 / 4] & 0xFFFF) == POT_MAGIC2) {
bcm47xxpart_add_part(&parts[curr_part++], "POT", offset,
MTD_WRITEABLE);
continue;
}
/* ML */
if (buf[0x010 / 4] == ML_MAGIC1 &&
buf[0x014 / 4] == ML_MAGIC2) {
bcm47xxpart_add_part(&parts[curr_part++], "ML", offset,
MTD_WRITEABLE);
continue;
}
/* TRX */
if (buf[0x000 / 4] == TRX_MAGIC) {
if (BCM47XXPART_MAX_PARTS - curr_part < 4) {
pr_warn("Not enough partitions left to register trx, scanning stopped!\n");
break;
}
trx = (struct trx_header *)buf;
trx_part = curr_part;
bcm47xxpart_add_part(&parts[curr_part++], "firmware",
offset, 0);
i = 0;
/* We have LZMA loader if offset[2] points to sth */
if (trx->offset[2]) {
bcm47xxpart_add_part(&parts[curr_part++],
"loader",
offset + trx->offset[i],
0);
i++;
}
if (trx->offset[i]) {
bcm47xxpart_add_part(&parts[curr_part++],
"linux",
offset + trx->offset[i],
0);
i++;
}
/*
* Pure rootfs size is known and can be calculated as:
* trx->length - trx->offset[i]. We don't fill it as
* we want to have jffs2 (overlay) in the same mtd.
*/
if (trx->offset[i]) {
const char *name;
name = bcm47xxpart_trx_data_part_name(master, offset + trx->offset[i]);
bcm47xxpart_add_part(&parts[curr_part++],
name,
offset + trx->offset[i],
0);
i++;
}
last_trx_part = curr_part - 1;
/*
* We have whole TRX scanned, skip to the next part. Use
* roundown (not roundup), as the loop will increase
* offset in next step.
*/
offset = rounddown(offset + trx->length, blocksize);
continue;
}
/* Squashfs on devices not using TRX */
if (le32_to_cpu(buf[0x000 / 4]) == SQUASHFS_MAGIC ||
buf[0x000 / 4] == SHSQ_MAGIC) {
bcm47xxpart_add_part(&parts[curr_part++], "rootfs",
offset, 0);
continue;
}
/*
* New (ARM?) devices may have NVRAM in some middle block. Last
* block will be checked later, so skip it.
*/
if (offset != master->size - blocksize &&
buf[0x000 / 4] == NVRAM_HEADER) {
bcm47xxpart_add_part(&parts[curr_part++], "nvram",
offset, 0);
continue;
}
/* Read middle of the block */
if (mtd_read(master, offset + 0x8000, 0x4,
&bytes_read, (uint8_t *)buf) < 0) {
pr_err("mtd_read error while parsing (offset: 0x%X)!\n",
offset);
continue;
}
/* Some devices (ex. WNDR3700v3) don't have a standard 'MPFR' */
if (buf[0x000 / 4] == BOARD_DATA_MAGIC2) {
bcm47xxpart_add_part(&parts[curr_part++], "board_data",
offset, MTD_WRITEABLE);
continue;
}
}
/* Look for NVRAM at the end of the last block. */
for (i = 0; i < ARRAY_SIZE(possible_nvram_sizes); i++) {
if (curr_part >= BCM47XXPART_MAX_PARTS) {
pr_warn("Reached maximum number of partitions, scanning stopped!\n");
break;
}
offset = master->size - possible_nvram_sizes[i];
if (mtd_read(master, offset, 0x4, &bytes_read,
(uint8_t *)buf) < 0) {
pr_err("mtd_read error while reading at offset 0x%X!\n",
offset);
continue;
}
/* Standard NVRAM */
if (buf[0] == NVRAM_HEADER) {
bcm47xxpart_add_part(&parts[curr_part++], "nvram",
master->size - blocksize, 0);
break;
}
}
kfree(buf);
/*
* Assume that partitions end at the beginning of the one they are
* followed by.
*/
for (i = 0; i < curr_part; i++) {
u64 next_part_offset = (i < curr_part - 1) ?
parts[i + 1].offset : master->size;
parts[i].size = next_part_offset - parts[i].offset;
if (i == last_trx_part && trx_part >= 0)
parts[trx_part].size = next_part_offset -
parts[trx_part].offset;
}
*pparts = parts;
return curr_part;
};
static struct mtd_part_parser bcm47xxpart_mtd_parser = {
.owner = THIS_MODULE,
.parse_fn = bcm47xxpart_parse,
.name = "bcm47xxpart",
};
static int __init bcm47xxpart_init(void)
{
register_mtd_parser(&bcm47xxpart_mtd_parser);
return 0;
}
static void __exit bcm47xxpart_exit(void)
{
deregister_mtd_parser(&bcm47xxpart_mtd_parser);
}
module_init(bcm47xxpart_init);
module_exit(bcm47xxpart_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("MTD partitioning for BCM47XX flash memories");
| gpl-2.0 |
viaembedded/vab820-kernel-bsp-old | drivers/net/wan/pci200syn.c | 1637 | 11475 | /*
* Goramo PCI200SYN synchronous serial card driver for Linux
*
* Copyright (C) 2002-2008 Krzysztof Halasa <khc@pm.waw.pl>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License
* as published by the Free Software Foundation.
*
* For information see <http://www.kernel.org/pub/linux/utils/net/hdlc/>
*
* Sources of information:
* Hitachi HD64572 SCA-II User's Manual
* PLX Technology Inc. PCI9052 Data Book
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/capability.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/in.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/moduleparam.h>
#include <linux/netdevice.h>
#include <linux/hdlc.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <asm/io.h>
#include "hd64572.h"
#undef DEBUG_PKT
#define DEBUG_RINGS
#define PCI200SYN_PLX_SIZE 0x80 /* PLX control window size (128b) */
#define PCI200SYN_SCA_SIZE 0x400 /* SCA window size (1Kb) */
#define MAX_TX_BUFFERS 10
static int pci_clock_freq = 33000000;
#define CLOCK_BASE pci_clock_freq
/*
* PLX PCI9052 local configuration and shared runtime registers.
* This structure can be used to access 9052 registers (memory mapped).
*/
typedef struct {
u32 loc_addr_range[4]; /* 00-0Ch : Local Address Ranges */
u32 loc_rom_range; /* 10h : Local ROM Range */
u32 loc_addr_base[4]; /* 14-20h : Local Address Base Addrs */
u32 loc_rom_base; /* 24h : Local ROM Base */
u32 loc_bus_descr[4]; /* 28-34h : Local Bus Descriptors */
u32 rom_bus_descr; /* 38h : ROM Bus Descriptor */
u32 cs_base[4]; /* 3C-48h : Chip Select Base Addrs */
u32 intr_ctrl_stat; /* 4Ch : Interrupt Control/Status */
u32 init_ctrl; /* 50h : EEPROM ctrl, Init Ctrl, etc */
}plx9052;
typedef struct port_s {
struct napi_struct napi;
struct net_device *netdev;
struct card_s *card;
spinlock_t lock; /* TX lock */
sync_serial_settings settings;
int rxpart; /* partial frame received, next frame invalid*/
unsigned short encoding;
unsigned short parity;
u16 rxin; /* rx ring buffer 'in' pointer */
u16 txin; /* tx ring buffer 'in' and 'last' pointers */
u16 txlast;
u8 rxs, txs, tmc; /* SCA registers */
u8 chan; /* physical port # - 0 or 1 */
}port_t;
typedef struct card_s {
u8 __iomem *rambase; /* buffer memory base (virtual) */
u8 __iomem *scabase; /* SCA memory base (virtual) */
plx9052 __iomem *plxbase;/* PLX registers memory base (virtual) */
u16 rx_ring_buffers; /* number of buffers in a ring */
u16 tx_ring_buffers;
u16 buff_offset; /* offset of first buffer of first channel */
u8 irq; /* interrupt request level */
port_t ports[2];
}card_t;
#define get_port(card, port) (&card->ports[port])
#define sca_flush(card) (sca_in(IER0, card));
static inline void new_memcpy_toio(char __iomem *dest, char *src, int length)
{
int len;
do {
len = length > 256 ? 256 : length;
memcpy_toio(dest, src, len);
dest += len;
src += len;
length -= len;
readb(dest);
} while (len);
}
#undef memcpy_toio
#define memcpy_toio new_memcpy_toio
#include "hd64572.c"
static void pci200_set_iface(port_t *port)
{
card_t *card = port->card;
u16 msci = get_msci(port);
u8 rxs = port->rxs & CLK_BRG_MASK;
u8 txs = port->txs & CLK_BRG_MASK;
sca_out(EXS_TES1, (port->chan ? MSCI1_OFFSET : MSCI0_OFFSET) + EXS,
port->card);
switch(port->settings.clock_type) {
case CLOCK_INT:
rxs |= CLK_BRG; /* BRG output */
txs |= CLK_PIN_OUT | CLK_TX_RXCLK; /* RX clock */
break;
case CLOCK_TXINT:
rxs |= CLK_LINE; /* RXC input */
txs |= CLK_PIN_OUT | CLK_BRG; /* BRG output */
break;
case CLOCK_TXFROMRX:
rxs |= CLK_LINE; /* RXC input */
txs |= CLK_PIN_OUT | CLK_TX_RXCLK; /* RX clock */
break;
default: /* EXTernal clock */
rxs |= CLK_LINE; /* RXC input */
txs |= CLK_PIN_OUT | CLK_LINE; /* TXC input */
break;
}
port->rxs = rxs;
port->txs = txs;
sca_out(rxs, msci + RXS, card);
sca_out(txs, msci + TXS, card);
sca_set_port(port);
}
static int pci200_open(struct net_device *dev)
{
port_t *port = dev_to_port(dev);
int result = hdlc_open(dev);
if (result)
return result;
sca_open(dev);
pci200_set_iface(port);
sca_flush(port->card);
return 0;
}
static int pci200_close(struct net_device *dev)
{
sca_close(dev);
sca_flush(dev_to_port(dev)->card);
hdlc_close(dev);
return 0;
}
static int pci200_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
const size_t size = sizeof(sync_serial_settings);
sync_serial_settings new_line;
sync_serial_settings __user *line = ifr->ifr_settings.ifs_ifsu.sync;
port_t *port = dev_to_port(dev);
#ifdef DEBUG_RINGS
if (cmd == SIOCDEVPRIVATE) {
sca_dump_rings(dev);
return 0;
}
#endif
if (cmd != SIOCWANDEV)
return hdlc_ioctl(dev, ifr, cmd);
switch(ifr->ifr_settings.type) {
case IF_GET_IFACE:
ifr->ifr_settings.type = IF_IFACE_V35;
if (ifr->ifr_settings.size < size) {
ifr->ifr_settings.size = size; /* data size wanted */
return -ENOBUFS;
}
if (copy_to_user(line, &port->settings, size))
return -EFAULT;
return 0;
case IF_IFACE_V35:
case IF_IFACE_SYNC_SERIAL:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&new_line, line, size))
return -EFAULT;
if (new_line.clock_type != CLOCK_EXT &&
new_line.clock_type != CLOCK_TXFROMRX &&
new_line.clock_type != CLOCK_INT &&
new_line.clock_type != CLOCK_TXINT)
return -EINVAL; /* No such clock setting */
if (new_line.loopback != 0 && new_line.loopback != 1)
return -EINVAL;
memcpy(&port->settings, &new_line, size); /* Update settings */
pci200_set_iface(port);
sca_flush(port->card);
return 0;
default:
return hdlc_ioctl(dev, ifr, cmd);
}
}
static void pci200_pci_remove_one(struct pci_dev *pdev)
{
int i;
card_t *card = pci_get_drvdata(pdev);
for (i = 0; i < 2; i++)
if (card->ports[i].card)
unregister_hdlc_device(card->ports[i].netdev);
if (card->irq)
free_irq(card->irq, card);
if (card->rambase)
iounmap(card->rambase);
if (card->scabase)
iounmap(card->scabase);
if (card->plxbase)
iounmap(card->plxbase);
pci_release_regions(pdev);
pci_disable_device(pdev);
if (card->ports[0].netdev)
free_netdev(card->ports[0].netdev);
if (card->ports[1].netdev)
free_netdev(card->ports[1].netdev);
kfree(card);
}
static const struct net_device_ops pci200_ops = {
.ndo_open = pci200_open,
.ndo_stop = pci200_close,
.ndo_change_mtu = hdlc_change_mtu,
.ndo_start_xmit = hdlc_start_xmit,
.ndo_do_ioctl = pci200_ioctl,
};
static int pci200_pci_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
card_t *card;
u32 __iomem *p;
int i;
u32 ramsize;
u32 ramphys; /* buffer memory base */
u32 scaphys; /* SCA memory base */
u32 plxphys; /* PLX registers memory base */
i = pci_enable_device(pdev);
if (i)
return i;
i = pci_request_regions(pdev, "PCI200SYN");
if (i) {
pci_disable_device(pdev);
return i;
}
card = kzalloc(sizeof(card_t), GFP_KERNEL);
if (card == NULL) {
pci_release_regions(pdev);
pci_disable_device(pdev);
return -ENOBUFS;
}
pci_set_drvdata(pdev, card);
card->ports[0].netdev = alloc_hdlcdev(&card->ports[0]);
card->ports[1].netdev = alloc_hdlcdev(&card->ports[1]);
if (!card->ports[0].netdev || !card->ports[1].netdev) {
pr_err("unable to allocate memory\n");
pci200_pci_remove_one(pdev);
return -ENOMEM;
}
if (pci_resource_len(pdev, 0) != PCI200SYN_PLX_SIZE ||
pci_resource_len(pdev, 2) != PCI200SYN_SCA_SIZE ||
pci_resource_len(pdev, 3) < 16384) {
pr_err("invalid card EEPROM parameters\n");
pci200_pci_remove_one(pdev);
return -EFAULT;
}
plxphys = pci_resource_start(pdev,0) & PCI_BASE_ADDRESS_MEM_MASK;
card->plxbase = ioremap(plxphys, PCI200SYN_PLX_SIZE);
scaphys = pci_resource_start(pdev,2) & PCI_BASE_ADDRESS_MEM_MASK;
card->scabase = ioremap(scaphys, PCI200SYN_SCA_SIZE);
ramphys = pci_resource_start(pdev,3) & PCI_BASE_ADDRESS_MEM_MASK;
card->rambase = pci_ioremap_bar(pdev, 3);
if (card->plxbase == NULL ||
card->scabase == NULL ||
card->rambase == NULL) {
pr_err("ioremap() failed\n");
pci200_pci_remove_one(pdev);
return -EFAULT;
}
/* Reset PLX */
p = &card->plxbase->init_ctrl;
writel(readl(p) | 0x40000000, p);
readl(p); /* Flush the write - do not use sca_flush */
udelay(1);
writel(readl(p) & ~0x40000000, p);
readl(p); /* Flush the write - do not use sca_flush */
udelay(1);
ramsize = sca_detect_ram(card, card->rambase,
pci_resource_len(pdev, 3));
/* number of TX + RX buffers for one port - this is dual port card */
i = ramsize / (2 * (sizeof(pkt_desc) + HDLC_MAX_MRU));
card->tx_ring_buffers = min(i / 2, MAX_TX_BUFFERS);
card->rx_ring_buffers = i - card->tx_ring_buffers;
card->buff_offset = 2 * sizeof(pkt_desc) * (card->tx_ring_buffers +
card->rx_ring_buffers);
pr_info("%u KB RAM at 0x%x, IRQ%u, using %u TX + %u RX packets rings\n",
ramsize / 1024, ramphys,
pdev->irq, card->tx_ring_buffers, card->rx_ring_buffers);
if (card->tx_ring_buffers < 1) {
pr_err("RAM test failed\n");
pci200_pci_remove_one(pdev);
return -EFAULT;
}
/* Enable interrupts on the PCI bridge */
p = &card->plxbase->intr_ctrl_stat;
writew(readw(p) | 0x0040, p);
/* Allocate IRQ */
if (request_irq(pdev->irq, sca_intr, IRQF_SHARED, "pci200syn", card)) {
pr_warn("could not allocate IRQ%d\n", pdev->irq);
pci200_pci_remove_one(pdev);
return -EBUSY;
}
card->irq = pdev->irq;
sca_init(card, 0);
for (i = 0; i < 2; i++) {
port_t *port = &card->ports[i];
struct net_device *dev = port->netdev;
hdlc_device *hdlc = dev_to_hdlc(dev);
port->chan = i;
spin_lock_init(&port->lock);
dev->irq = card->irq;
dev->mem_start = ramphys;
dev->mem_end = ramphys + ramsize - 1;
dev->tx_queue_len = 50;
dev->netdev_ops = &pci200_ops;
hdlc->attach = sca_attach;
hdlc->xmit = sca_xmit;
port->settings.clock_type = CLOCK_EXT;
port->card = card;
sca_init_port(port);
if (register_hdlc_device(dev)) {
pr_err("unable to register hdlc device\n");
port->card = NULL;
pci200_pci_remove_one(pdev);
return -ENOBUFS;
}
netdev_info(dev, "PCI200SYN channel %d\n", port->chan);
}
sca_flush(card);
return 0;
}
static const struct pci_device_id pci200_pci_tbl[] = {
{ PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_9050, PCI_VENDOR_ID_PLX,
PCI_DEVICE_ID_PLX_PCI200SYN, 0, 0, 0 },
{ 0, }
};
static struct pci_driver pci200_pci_driver = {
.name = "PCI200SYN",
.id_table = pci200_pci_tbl,
.probe = pci200_pci_init_one,
.remove = pci200_pci_remove_one,
};
static int __init pci200_init_module(void)
{
if (pci_clock_freq < 1000000 || pci_clock_freq > 80000000) {
pr_err("Invalid PCI clock frequency\n");
return -EINVAL;
}
return pci_register_driver(&pci200_pci_driver);
}
static void __exit pci200_cleanup_module(void)
{
pci_unregister_driver(&pci200_pci_driver);
}
MODULE_AUTHOR("Krzysztof Halasa <khc@pm.waw.pl>");
MODULE_DESCRIPTION("Goramo PCI200SYN serial port driver");
MODULE_LICENSE("GPL v2");
MODULE_DEVICE_TABLE(pci, pci200_pci_tbl);
module_param(pci_clock_freq, int, 0444);
MODULE_PARM_DESC(pci_clock_freq, "System PCI clock frequency in Hz");
module_init(pci200_init_module);
module_exit(pci200_cleanup_module);
| gpl-2.0 |
AOKP/kernel_samsung_jf | drivers/sensorhub/sensors_core.c | 1637 | 3854 | /*
* Universal sensors core class
*
* Author : Ryunkyun Park <ryun.park@samsung.com>
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/err.h>
struct class *sensors_class;
EXPORT_SYMBOL_GPL(sensors_class);
struct class *sensors_event_class;
EXPORT_SYMBOL_GPL(sensors_event_class);
static atomic_t sensor_count;
static struct device *symlink_dev;
/*
* Create sysfs interface
*/
static void set_sensor_attr(struct device *dev,
struct device_attribute *attributes[])
{
int i;
for (i = 0; attributes[i] != NULL; i++)
if ((device_create_file(dev, attributes[i])) < 0)
pr_err("[SENSOR CORE] fail device_create_file"\
"(dev, attributes[%d])\n", i);
}
int sensors_create_symlink(struct kobject *target,
const char *name)
{
int err = 0;
if (symlink_dev == NULL)
pr_err("%s, symlink_dev is NULL!!!\n", __func__);
err = sysfs_create_link(&symlink_dev->kobj, target, name);
if (err < 0) {
pr_err("%s, %s failed!(%d)\n", __func__, name, err);
return err;
}
return err;
}
EXPORT_SYMBOL_GPL(sensors_create_symlink);
void sensors_remove_symlink(struct kobject *target,
const char *name)
{
if (symlink_dev == NULL)
pr_err("%s, symlink_dev is NULL!!!\n", __func__);
sysfs_delete_link(&symlink_dev->kobj, target, name);
}
EXPORT_SYMBOL_GPL(sensors_remove_symlink);
int sensors_register(struct device *dev, void * drvdata,
struct device_attribute *attributes[], char *name)
{
int ret = 0;
if (!sensors_class) {
sensors_class = class_create(THIS_MODULE, "sensors");
if (IS_ERR(sensors_class))
return PTR_ERR(sensors_class);
}
dev = device_create(sensors_class, NULL, 0, drvdata, "%s", name);
if (IS_ERR(dev)) {
ret = PTR_ERR(dev);
pr_err("[SENSORS CORE] device_create failed!"\
"[%d]\n", ret);
return ret;
}
set_sensor_attr(dev, attributes);
atomic_inc(&sensor_count);
return 0;
}
EXPORT_SYMBOL_GPL(sensors_register);
void sensors_unregister(struct device *dev,
struct device_attribute *attributes[])
{
int i;
for (i = 0; attributes[i] != NULL; i++)
device_remove_file(dev, attributes[i]);
}
EXPORT_SYMBOL_GPL(sensors_unregister);
void destroy_sensor_class(void)
{
if (sensors_class) {
class_destroy(sensors_class);
sensors_class = NULL;
}
if (sensors_event_class) {
device_destroy(sensors_event_class, symlink_dev->devt);
class_destroy(sensors_event_class);
sensors_event_class = NULL;
}
}
EXPORT_SYMBOL_GPL(destroy_sensor_class);
static int __init sensors_class_init(void)
{
pr_info("[SENSORS CORE] sensors_class_init\n");
sensors_class = class_create(THIS_MODULE, "sensors");
if (IS_ERR(sensors_class)) {
pr_err("%s, create sensors_class is failed.(err=%ld)\n",
__func__, IS_ERR(sensors_class));
return PTR_ERR(sensors_class);
}
/* For symbolic link */
sensors_event_class = class_create(THIS_MODULE, "sensor_event");
if (IS_ERR(sensors_event_class)) {
pr_err("%s, create sensors_class is failed.(err=%ld)\n",
__func__, IS_ERR(sensors_event_class));
return PTR_ERR(sensors_event_class);
}
symlink_dev = device_create(sensors_event_class, NULL, 0, NULL,
"%s", "symlink2");
if (IS_ERR(symlink_dev)) {
pr_err("[SENSORS CORE] symlink_dev create failed!"\
"[%ld]\n", IS_ERR(symlink_dev));
return PTR_ERR(symlink_dev);
}
atomic_set(&sensor_count, 0);
sensors_class->dev_uevent = NULL;
return 0;
}
static void __exit sensors_class_exit(void)
{
if (sensors_class || sensors_event_class) {
class_destroy(sensors_class);
sensors_class = NULL;
class_destroy(sensors_event_class);
sensors_event_class = NULL;
}
}
subsys_initcall(sensors_class_init);
module_exit(sensors_class_exit);
MODULE_DESCRIPTION("Universal sensors core class");
MODULE_AUTHOR("Ryunkyun Park <ryun.park@samsung.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
markolino631/lge_kernel_msm7x27 | fs/jfs/ioctl.c | 1893 | 3260 | /*
* linux/fs/jfs/ioctl.c
*
* Copyright (C) 2006 Herbert Poetzl
* adapted from Remy Card's ext2/ioctl.c
*/
#include <linux/fs.h>
#include <linux/ctype.h>
#include <linux/capability.h>
#include <linux/mount.h>
#include <linux/time.h>
#include <linux/sched.h>
#include <asm/current.h>
#include <asm/uaccess.h>
#include "jfs_incore.h"
#include "jfs_dinode.h"
#include "jfs_inode.h"
static struct {
long jfs_flag;
long ext2_flag;
} jfs_map[] = {
{JFS_NOATIME_FL, FS_NOATIME_FL},
{JFS_DIRSYNC_FL, FS_DIRSYNC_FL},
{JFS_SYNC_FL, FS_SYNC_FL},
{JFS_SECRM_FL, FS_SECRM_FL},
{JFS_UNRM_FL, FS_UNRM_FL},
{JFS_APPEND_FL, FS_APPEND_FL},
{JFS_IMMUTABLE_FL, FS_IMMUTABLE_FL},
{0, 0},
};
static long jfs_map_ext2(unsigned long flags, int from)
{
int index=0;
long mapped=0;
while (jfs_map[index].jfs_flag) {
if (from) {
if (jfs_map[index].ext2_flag & flags)
mapped |= jfs_map[index].jfs_flag;
} else {
if (jfs_map[index].jfs_flag & flags)
mapped |= jfs_map[index].ext2_flag;
}
index++;
}
return mapped;
}
long jfs_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
struct inode *inode = filp->f_dentry->d_inode;
struct jfs_inode_info *jfs_inode = JFS_IP(inode);
unsigned int flags;
switch (cmd) {
case JFS_IOC_GETFLAGS:
jfs_get_inode_flags(jfs_inode);
flags = jfs_inode->mode2 & JFS_FL_USER_VISIBLE;
flags = jfs_map_ext2(flags, 0);
return put_user(flags, (int __user *) arg);
case JFS_IOC_SETFLAGS: {
unsigned int oldflags;
int err;
err = mnt_want_write(filp->f_path.mnt);
if (err)
return err;
if (!is_owner_or_cap(inode)) {
err = -EACCES;
goto setflags_out;
}
if (get_user(flags, (int __user *) arg)) {
err = -EFAULT;
goto setflags_out;
}
flags = jfs_map_ext2(flags, 1);
if (!S_ISDIR(inode->i_mode))
flags &= ~JFS_DIRSYNC_FL;
/* Is it quota file? Do not allow user to mess with it */
if (IS_NOQUOTA(inode)) {
err = -EPERM;
goto setflags_out;
}
/* Lock against other parallel changes of flags */
mutex_lock(&inode->i_mutex);
jfs_get_inode_flags(jfs_inode);
oldflags = jfs_inode->mode2;
/*
* The IMMUTABLE and APPEND_ONLY flags can only be changed by
* the relevant capability.
*/
if ((oldflags & JFS_IMMUTABLE_FL) ||
((flags ^ oldflags) &
(JFS_APPEND_FL | JFS_IMMUTABLE_FL))) {
if (!capable(CAP_LINUX_IMMUTABLE)) {
mutex_unlock(&inode->i_mutex);
err = -EPERM;
goto setflags_out;
}
}
flags = flags & JFS_FL_USER_MODIFIABLE;
flags |= oldflags & ~JFS_FL_USER_MODIFIABLE;
jfs_inode->mode2 = flags;
jfs_set_inode_flags(inode);
mutex_unlock(&inode->i_mutex);
inode->i_ctime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
setflags_out:
mnt_drop_write(filp->f_path.mnt);
return err;
}
default:
return -ENOTTY;
}
}
#ifdef CONFIG_COMPAT
long jfs_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
/* While these ioctl numbers defined with 'long' and have different
* numbers than the 64bit ABI,
* the actual implementation only deals with ints and is compatible.
*/
switch (cmd) {
case JFS_IOC_GETFLAGS32:
cmd = JFS_IOC_GETFLAGS;
break;
case JFS_IOC_SETFLAGS32:
cmd = JFS_IOC_SETFLAGS;
break;
}
return jfs_ioctl(filp, cmd, arg);
}
#endif
| gpl-2.0 |
vl197602/android_kernel_cyanogen_msm8916 | net/netfilter/xt_addrtype.c | 2149 | 6761 | /*
* iptables module to match inet_addr_type() of an ip.
*
* Copyright (c) 2004 Patrick McHardy <kaber@trash.net>
* (C) 2007 Laszlo Attila Toth <panther@balabit.hu>
*
* 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/kernel.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/ip.h>
#include <net/route.h>
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
#include <net/ipv6.h>
#include <net/ip6_route.h>
#include <net/ip6_fib.h>
#endif
#include <linux/netfilter_ipv6.h>
#include <linux/netfilter/xt_addrtype.h>
#include <linux/netfilter/x_tables.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
MODULE_DESCRIPTION("Xtables: address type match");
MODULE_ALIAS("ipt_addrtype");
MODULE_ALIAS("ip6t_addrtype");
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
static u32 match_lookup_rt6(struct net *net, const struct net_device *dev,
const struct in6_addr *addr, u16 mask)
{
const struct nf_afinfo *afinfo;
struct flowi6 flow;
struct rt6_info *rt;
u32 ret = 0;
int route_err;
memset(&flow, 0, sizeof(flow));
flow.daddr = *addr;
if (dev)
flow.flowi6_oif = dev->ifindex;
rcu_read_lock();
afinfo = nf_get_afinfo(NFPROTO_IPV6);
if (afinfo != NULL) {
const struct nf_ipv6_ops *v6ops;
if (dev && (mask & XT_ADDRTYPE_LOCAL)) {
v6ops = nf_get_ipv6_ops();
if (v6ops && v6ops->chk_addr(net, addr, dev, true))
ret = XT_ADDRTYPE_LOCAL;
}
route_err = afinfo->route(net, (struct dst_entry **)&rt,
flowi6_to_flowi(&flow), false);
} else {
route_err = 1;
}
rcu_read_unlock();
if (route_err)
return XT_ADDRTYPE_UNREACHABLE;
if (rt->rt6i_flags & RTF_REJECT)
ret = XT_ADDRTYPE_UNREACHABLE;
if (dev == NULL && rt->rt6i_flags & RTF_LOCAL)
ret |= XT_ADDRTYPE_LOCAL;
if (rt->rt6i_flags & RTF_ANYCAST)
ret |= XT_ADDRTYPE_ANYCAST;
dst_release(&rt->dst);
return ret;
}
static bool match_type6(struct net *net, const struct net_device *dev,
const struct in6_addr *addr, u16 mask)
{
int addr_type = ipv6_addr_type(addr);
if ((mask & XT_ADDRTYPE_MULTICAST) &&
!(addr_type & IPV6_ADDR_MULTICAST))
return false;
if ((mask & XT_ADDRTYPE_UNICAST) && !(addr_type & IPV6_ADDR_UNICAST))
return false;
if ((mask & XT_ADDRTYPE_UNSPEC) && addr_type != IPV6_ADDR_ANY)
return false;
if ((XT_ADDRTYPE_LOCAL | XT_ADDRTYPE_ANYCAST |
XT_ADDRTYPE_UNREACHABLE) & mask)
return !!(mask & match_lookup_rt6(net, dev, addr, mask));
return true;
}
static bool
addrtype_mt6(struct net *net, const struct net_device *dev,
const struct sk_buff *skb, const struct xt_addrtype_info_v1 *info)
{
const struct ipv6hdr *iph = ipv6_hdr(skb);
bool ret = true;
if (info->source)
ret &= match_type6(net, dev, &iph->saddr, info->source) ^
(info->flags & XT_ADDRTYPE_INVERT_SOURCE);
if (ret && info->dest)
ret &= match_type6(net, dev, &iph->daddr, info->dest) ^
!!(info->flags & XT_ADDRTYPE_INVERT_DEST);
return ret;
}
#endif
static inline bool match_type(struct net *net, const struct net_device *dev,
__be32 addr, u_int16_t mask)
{
return !!(mask & (1 << inet_dev_addr_type(net, dev, addr)));
}
static bool
addrtype_mt_v0(const struct sk_buff *skb, struct xt_action_param *par)
{
struct net *net = dev_net(par->in ? par->in : par->out);
const struct xt_addrtype_info *info = par->matchinfo;
const struct iphdr *iph = ip_hdr(skb);
bool ret = true;
if (info->source)
ret &= match_type(net, NULL, iph->saddr, info->source) ^
info->invert_source;
if (info->dest)
ret &= match_type(net, NULL, iph->daddr, info->dest) ^
info->invert_dest;
return ret;
}
static bool
addrtype_mt_v1(const struct sk_buff *skb, struct xt_action_param *par)
{
struct net *net = dev_net(par->in ? par->in : par->out);
const struct xt_addrtype_info_v1 *info = par->matchinfo;
const struct iphdr *iph;
const struct net_device *dev = NULL;
bool ret = true;
if (info->flags & XT_ADDRTYPE_LIMIT_IFACE_IN)
dev = par->in;
else if (info->flags & XT_ADDRTYPE_LIMIT_IFACE_OUT)
dev = par->out;
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
if (par->family == NFPROTO_IPV6)
return addrtype_mt6(net, dev, skb, info);
#endif
iph = ip_hdr(skb);
if (info->source)
ret &= match_type(net, dev, iph->saddr, info->source) ^
(info->flags & XT_ADDRTYPE_INVERT_SOURCE);
if (ret && info->dest)
ret &= match_type(net, dev, iph->daddr, info->dest) ^
!!(info->flags & XT_ADDRTYPE_INVERT_DEST);
return ret;
}
static int addrtype_mt_checkentry_v1(const struct xt_mtchk_param *par)
{
struct xt_addrtype_info_v1 *info = par->matchinfo;
if (info->flags & XT_ADDRTYPE_LIMIT_IFACE_IN &&
info->flags & XT_ADDRTYPE_LIMIT_IFACE_OUT) {
pr_info("both incoming and outgoing "
"interface limitation cannot be selected\n");
return -EINVAL;
}
if (par->hook_mask & ((1 << NF_INET_PRE_ROUTING) |
(1 << NF_INET_LOCAL_IN)) &&
info->flags & XT_ADDRTYPE_LIMIT_IFACE_OUT) {
pr_info("output interface limitation "
"not valid in PREROUTING and INPUT\n");
return -EINVAL;
}
if (par->hook_mask & ((1 << NF_INET_POST_ROUTING) |
(1 << NF_INET_LOCAL_OUT)) &&
info->flags & XT_ADDRTYPE_LIMIT_IFACE_IN) {
pr_info("input interface limitation "
"not valid in POSTROUTING and OUTPUT\n");
return -EINVAL;
}
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
if (par->family == NFPROTO_IPV6) {
if ((info->source | info->dest) & XT_ADDRTYPE_BLACKHOLE) {
pr_err("ipv6 BLACKHOLE matching not supported\n");
return -EINVAL;
}
if ((info->source | info->dest) >= XT_ADDRTYPE_PROHIBIT) {
pr_err("ipv6 PROHIBT (THROW, NAT ..) matching not supported\n");
return -EINVAL;
}
if ((info->source | info->dest) & XT_ADDRTYPE_BROADCAST) {
pr_err("ipv6 does not support BROADCAST matching\n");
return -EINVAL;
}
}
#endif
return 0;
}
static struct xt_match addrtype_mt_reg[] __read_mostly = {
{
.name = "addrtype",
.family = NFPROTO_IPV4,
.match = addrtype_mt_v0,
.matchsize = sizeof(struct xt_addrtype_info),
.me = THIS_MODULE
},
{
.name = "addrtype",
.family = NFPROTO_UNSPEC,
.revision = 1,
.match = addrtype_mt_v1,
.checkentry = addrtype_mt_checkentry_v1,
.matchsize = sizeof(struct xt_addrtype_info_v1),
.me = THIS_MODULE
}
};
static int __init addrtype_mt_init(void)
{
return xt_register_matches(addrtype_mt_reg,
ARRAY_SIZE(addrtype_mt_reg));
}
static void __exit addrtype_mt_exit(void)
{
xt_unregister_matches(addrtype_mt_reg, ARRAY_SIZE(addrtype_mt_reg));
}
module_init(addrtype_mt_init);
module_exit(addrtype_mt_exit);
| gpl-2.0 |
htc-mirror/endeavor-ics-qmr-2.6.39-69960c7 | drivers/cdrom/viocd.c | 3173 | 19632 | /* -*- linux-c -*-
* drivers/cdrom/viocd.c
*
* iSeries Virtual CD Rom
*
* Authors: Dave Boutcher <boutcher@us.ibm.com>
* Ryan Arnold <ryanarn@us.ibm.com>
* Colin Devilbiss <devilbis@us.ibm.com>
* Stephen Rothwell
*
* (C) Copyright 2000-2004 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) anyu later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* This routine provides access to CD ROM drives owned and managed by an
* OS/400 partition running on the same box as this Linux partition.
*
* All operations are performed by sending messages back and forth to
* the OS/400 partition.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/major.h>
#include <linux/blkdev.h>
#include <linux/cdrom.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/dma-mapping.h>
#include <linux/module.h>
#include <linux/completion.h>
#include <linux/proc_fs.h>
#include <linux/mutex.h>
#include <linux/seq_file.h>
#include <linux/scatterlist.h>
#include <asm/vio.h>
#include <asm/iseries/hv_types.h>
#include <asm/iseries/hv_lp_event.h>
#include <asm/iseries/vio.h>
#include <asm/firmware.h>
#define VIOCD_DEVICE "iseries/vcd"
#define VIOCD_VERS "1.06"
/*
* Should probably make this a module parameter....sigh
*/
#define VIOCD_MAX_CD HVMAXARCHITECTEDVIRTUALCDROMS
static DEFINE_MUTEX(viocd_mutex);
static const struct vio_error_entry viocd_err_table[] = {
{0x0201, EINVAL, "Invalid Range"},
{0x0202, EINVAL, "Invalid Token"},
{0x0203, EIO, "DMA Error"},
{0x0204, EIO, "Use Error"},
{0x0205, EIO, "Release Error"},
{0x0206, EINVAL, "Invalid CD"},
{0x020C, EROFS, "Read Only Device"},
{0x020D, ENOMEDIUM, "Changed or Missing Volume (or Varied Off?)"},
{0x020E, EIO, "Optical System Error (Varied Off?)"},
{0x02FF, EIO, "Internal Error"},
{0x3010, EIO, "Changed Volume"},
{0xC100, EIO, "Optical System Error"},
{0x0000, 0, NULL},
};
/*
* This is the structure we use to exchange info between driver and interrupt
* handler
*/
struct viocd_waitevent {
struct completion com;
int rc;
u16 sub_result;
int changed;
};
/* this is a lookup table for the true capabilities of a device */
struct capability_entry {
char *type;
int capability;
};
static struct capability_entry capability_table[] __initdata = {
{ "6330", CDC_LOCK | CDC_DVD_RAM | CDC_RAM },
{ "6331", CDC_LOCK | CDC_DVD_RAM | CDC_RAM },
{ "6333", CDC_LOCK | CDC_DVD_RAM | CDC_RAM },
{ "632A", CDC_LOCK | CDC_DVD_RAM | CDC_RAM },
{ "6321", CDC_LOCK },
{ "632B", 0 },
{ NULL , CDC_LOCK },
};
/* These are our internal structures for keeping track of devices */
static int viocd_numdev;
struct disk_info {
struct gendisk *viocd_disk;
struct cdrom_device_info viocd_info;
struct device *dev;
const char *rsrcname;
const char *type;
const char *model;
};
static struct disk_info viocd_diskinfo[VIOCD_MAX_CD];
#define DEVICE_NR(di) ((di) - &viocd_diskinfo[0])
static spinlock_t viocd_reqlock;
#define MAX_CD_REQ 1
/* procfs support */
static int proc_viocd_show(struct seq_file *m, void *v)
{
int i;
for (i = 0; i < viocd_numdev; i++) {
seq_printf(m, "viocd device %d is iSeries resource %10.10s"
"type %4.4s, model %3.3s\n",
i, viocd_diskinfo[i].rsrcname,
viocd_diskinfo[i].type,
viocd_diskinfo[i].model);
}
return 0;
}
static int proc_viocd_open(struct inode *inode, struct file *file)
{
return single_open(file, proc_viocd_show, NULL);
}
static const struct file_operations proc_viocd_operations = {
.owner = THIS_MODULE,
.open = proc_viocd_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int viocd_blk_open(struct block_device *bdev, fmode_t mode)
{
struct disk_info *di = bdev->bd_disk->private_data;
int ret;
mutex_lock(&viocd_mutex);
ret = cdrom_open(&di->viocd_info, bdev, mode);
mutex_unlock(&viocd_mutex);
return ret;
}
static int viocd_blk_release(struct gendisk *disk, fmode_t mode)
{
struct disk_info *di = disk->private_data;
mutex_lock(&viocd_mutex);
cdrom_release(&di->viocd_info, mode);
mutex_unlock(&viocd_mutex);
return 0;
}
static int viocd_blk_ioctl(struct block_device *bdev, fmode_t mode,
unsigned cmd, unsigned long arg)
{
struct disk_info *di = bdev->bd_disk->private_data;
int ret;
mutex_lock(&viocd_mutex);
ret = cdrom_ioctl(&di->viocd_info, bdev, mode, cmd, arg);
mutex_unlock(&viocd_mutex);
return ret;
}
static unsigned int viocd_blk_check_events(struct gendisk *disk,
unsigned int clearing)
{
struct disk_info *di = disk->private_data;
return cdrom_check_events(&di->viocd_info, clearing);
}
static const struct block_device_operations viocd_fops = {
.owner = THIS_MODULE,
.open = viocd_blk_open,
.release = viocd_blk_release,
.ioctl = viocd_blk_ioctl,
.check_events = viocd_blk_check_events,
};
static int viocd_open(struct cdrom_device_info *cdi, int purpose)
{
struct disk_info *diskinfo = cdi->handle;
int device_no = DEVICE_NR(diskinfo);
HvLpEvent_Rc hvrc;
struct viocd_waitevent we;
init_completion(&we.com);
hvrc = HvCallEvent_signalLpEventFast(viopath_hostLp,
HvLpEvent_Type_VirtualIo,
viomajorsubtype_cdio | viocdopen,
HvLpEvent_AckInd_DoAck, HvLpEvent_AckType_ImmediateAck,
viopath_sourceinst(viopath_hostLp),
viopath_targetinst(viopath_hostLp),
(u64)&we, VIOVERSION << 16, ((u64)device_no << 48),
0, 0, 0);
if (hvrc != 0) {
pr_warning("bad rc on HvCallEvent_signalLpEventFast %d\n",
(int)hvrc);
return -EIO;
}
wait_for_completion(&we.com);
if (we.rc) {
const struct vio_error_entry *err =
vio_lookup_rc(viocd_err_table, we.sub_result);
pr_warning("bad rc %d:0x%04X on open: %s\n",
we.rc, we.sub_result, err->msg);
return -err->errno;
}
return 0;
}
static void viocd_release(struct cdrom_device_info *cdi)
{
int device_no = DEVICE_NR((struct disk_info *)cdi->handle);
HvLpEvent_Rc hvrc;
hvrc = HvCallEvent_signalLpEventFast(viopath_hostLp,
HvLpEvent_Type_VirtualIo,
viomajorsubtype_cdio | viocdclose,
HvLpEvent_AckInd_NoAck, HvLpEvent_AckType_ImmediateAck,
viopath_sourceinst(viopath_hostLp),
viopath_targetinst(viopath_hostLp), 0,
VIOVERSION << 16, ((u64)device_no << 48), 0, 0, 0);
if (hvrc != 0)
pr_warning("bad rc on HvCallEvent_signalLpEventFast %d\n",
(int)hvrc);
}
/* Send a read or write request to OS/400 */
static int send_request(struct request *req)
{
HvLpEvent_Rc hvrc;
struct disk_info *diskinfo = req->rq_disk->private_data;
u64 len;
dma_addr_t dmaaddr;
int direction;
u16 cmd;
struct scatterlist sg;
BUG_ON(req->nr_phys_segments > 1);
if (rq_data_dir(req) == READ) {
direction = DMA_FROM_DEVICE;
cmd = viomajorsubtype_cdio | viocdread;
} else {
direction = DMA_TO_DEVICE;
cmd = viomajorsubtype_cdio | viocdwrite;
}
sg_init_table(&sg, 1);
if (blk_rq_map_sg(req->q, req, &sg) == 0) {
pr_warning("error setting up scatter/gather list\n");
return -1;
}
if (dma_map_sg(diskinfo->dev, &sg, 1, direction) == 0) {
pr_warning("error allocating sg tce\n");
return -1;
}
dmaaddr = sg_dma_address(&sg);
len = sg_dma_len(&sg);
hvrc = HvCallEvent_signalLpEventFast(viopath_hostLp,
HvLpEvent_Type_VirtualIo, cmd,
HvLpEvent_AckInd_DoAck,
HvLpEvent_AckType_ImmediateAck,
viopath_sourceinst(viopath_hostLp),
viopath_targetinst(viopath_hostLp),
(u64)req, VIOVERSION << 16,
((u64)DEVICE_NR(diskinfo) << 48) | dmaaddr,
(u64)blk_rq_pos(req) * 512, len, 0);
if (hvrc != HvLpEvent_Rc_Good) {
pr_warning("hv error on op %d\n", (int)hvrc);
return -1;
}
return 0;
}
static int rwreq;
static void do_viocd_request(struct request_queue *q)
{
struct request *req;
while ((rwreq == 0) && ((req = blk_fetch_request(q)) != NULL)) {
if (req->cmd_type != REQ_TYPE_FS)
__blk_end_request_all(req, -EIO);
else if (send_request(req) < 0) {
pr_warning("unable to send message to OS/400!\n");
__blk_end_request_all(req, -EIO);
} else
rwreq++;
}
}
static unsigned int viocd_check_events(struct cdrom_device_info *cdi,
unsigned int clearing, int disc_nr)
{
struct viocd_waitevent we;
HvLpEvent_Rc hvrc;
int device_no = DEVICE_NR((struct disk_info *)cdi->handle);
init_completion(&we.com);
/* Send the open event to OS/400 */
hvrc = HvCallEvent_signalLpEventFast(viopath_hostLp,
HvLpEvent_Type_VirtualIo,
viomajorsubtype_cdio | viocdcheck,
HvLpEvent_AckInd_DoAck, HvLpEvent_AckType_ImmediateAck,
viopath_sourceinst(viopath_hostLp),
viopath_targetinst(viopath_hostLp),
(u64)&we, VIOVERSION << 16, ((u64)device_no << 48),
0, 0, 0);
if (hvrc != 0) {
pr_warning("bad rc on HvCallEvent_signalLpEventFast %d\n",
(int)hvrc);
return 0;
}
wait_for_completion(&we.com);
/* Check the return code. If bad, assume no change */
if (we.rc) {
const struct vio_error_entry *err =
vio_lookup_rc(viocd_err_table, we.sub_result);
pr_warning("bad rc %d:0x%04X on check_change: %s; Assuming no change\n",
we.rc, we.sub_result, err->msg);
return 0;
}
return we.changed ? DISK_EVENT_MEDIA_CHANGE : 0;
}
static int viocd_lock_door(struct cdrom_device_info *cdi, int locking)
{
HvLpEvent_Rc hvrc;
u64 device_no = DEVICE_NR((struct disk_info *)cdi->handle);
/* NOTE: flags is 1 or 0 so it won't overwrite the device_no */
u64 flags = !!locking;
struct viocd_waitevent we;
init_completion(&we.com);
/* Send the lockdoor event to OS/400 */
hvrc = HvCallEvent_signalLpEventFast(viopath_hostLp,
HvLpEvent_Type_VirtualIo,
viomajorsubtype_cdio | viocdlockdoor,
HvLpEvent_AckInd_DoAck, HvLpEvent_AckType_ImmediateAck,
viopath_sourceinst(viopath_hostLp),
viopath_targetinst(viopath_hostLp),
(u64)&we, VIOVERSION << 16,
(device_no << 48) | (flags << 32), 0, 0, 0);
if (hvrc != 0) {
pr_warning("bad rc on HvCallEvent_signalLpEventFast %d\n",
(int)hvrc);
return -EIO;
}
wait_for_completion(&we.com);
if (we.rc != 0)
return -EIO;
return 0;
}
static int viocd_packet(struct cdrom_device_info *cdi,
struct packet_command *cgc)
{
unsigned int buflen = cgc->buflen;
int ret = -EIO;
switch (cgc->cmd[0]) {
case GPCMD_READ_DISC_INFO:
{
disc_information *di = (disc_information *)cgc->buffer;
if (buflen >= 2) {
di->disc_information_length = cpu_to_be16(1);
ret = 0;
}
if (buflen >= 3)
di->erasable =
(cdi->ops->capability & ~cdi->mask
& (CDC_DVD_RAM | CDC_RAM)) != 0;
}
break;
case GPCMD_GET_CONFIGURATION:
if (cgc->cmd[3] == CDF_RWRT) {
struct rwrt_feature_desc *rfd = (struct rwrt_feature_desc *)(cgc->buffer + sizeof(struct feature_header));
if ((buflen >=
(sizeof(struct feature_header) + sizeof(*rfd))) &&
(cdi->ops->capability & ~cdi->mask
& (CDC_DVD_RAM | CDC_RAM))) {
rfd->feature_code = cpu_to_be16(CDF_RWRT);
rfd->curr = 1;
ret = 0;
}
}
break;
default:
if (cgc->sense) {
/* indicate Unknown code */
cgc->sense->sense_key = 0x05;
cgc->sense->asc = 0x20;
cgc->sense->ascq = 0x00;
}
break;
}
cgc->stat = ret;
return ret;
}
static void restart_all_queues(int first_index)
{
int i;
for (i = first_index + 1; i < viocd_numdev; i++)
if (viocd_diskinfo[i].viocd_disk)
blk_run_queue(viocd_diskinfo[i].viocd_disk->queue);
for (i = 0; i <= first_index; i++)
if (viocd_diskinfo[i].viocd_disk)
blk_run_queue(viocd_diskinfo[i].viocd_disk->queue);
}
/* This routine handles incoming CD LP events */
static void vio_handle_cd_event(struct HvLpEvent *event)
{
struct viocdlpevent *bevent;
struct viocd_waitevent *pwe;
struct disk_info *di;
unsigned long flags;
struct request *req;
if (event == NULL)
/* Notification that a partition went away! */
return;
/* First, we should NEVER get an int here...only acks */
if (hvlpevent_is_int(event)) {
pr_warning("Yikes! got an int in viocd event handler!\n");
if (hvlpevent_need_ack(event)) {
event->xRc = HvLpEvent_Rc_InvalidSubtype;
HvCallEvent_ackLpEvent(event);
}
}
bevent = (struct viocdlpevent *)event;
switch (event->xSubtype & VIOMINOR_SUBTYPE_MASK) {
case viocdopen:
if (event->xRc == 0) {
di = &viocd_diskinfo[bevent->disk];
blk_queue_logical_block_size(di->viocd_disk->queue,
bevent->block_size);
set_capacity(di->viocd_disk,
bevent->media_size *
bevent->block_size / 512);
}
/* FALLTHROUGH !! */
case viocdlockdoor:
pwe = (struct viocd_waitevent *)event->xCorrelationToken;
return_complete:
pwe->rc = event->xRc;
pwe->sub_result = bevent->sub_result;
complete(&pwe->com);
break;
case viocdcheck:
pwe = (struct viocd_waitevent *)event->xCorrelationToken;
pwe->changed = bevent->flags;
goto return_complete;
case viocdclose:
break;
case viocdwrite:
case viocdread:
/*
* Since this is running in interrupt mode, we need to
* make sure we're not stepping on any global I/O operations
*/
di = &viocd_diskinfo[bevent->disk];
spin_lock_irqsave(&viocd_reqlock, flags);
dma_unmap_single(di->dev, bevent->token, bevent->len,
((event->xSubtype & VIOMINOR_SUBTYPE_MASK) == viocdread)
? DMA_FROM_DEVICE : DMA_TO_DEVICE);
req = (struct request *)bevent->event.xCorrelationToken;
rwreq--;
if (event->xRc != HvLpEvent_Rc_Good) {
const struct vio_error_entry *err =
vio_lookup_rc(viocd_err_table,
bevent->sub_result);
pr_warning("request %p failed with rc %d:0x%04X: %s\n",
req, event->xRc,
bevent->sub_result, err->msg);
__blk_end_request_all(req, -EIO);
} else
__blk_end_request_all(req, 0);
/* restart handling of incoming requests */
spin_unlock_irqrestore(&viocd_reqlock, flags);
restart_all_queues(bevent->disk);
break;
default:
pr_warning("message with invalid subtype %0x04X!\n",
event->xSubtype & VIOMINOR_SUBTYPE_MASK);
if (hvlpevent_need_ack(event)) {
event->xRc = HvLpEvent_Rc_InvalidSubtype;
HvCallEvent_ackLpEvent(event);
}
}
}
static int viocd_audio_ioctl(struct cdrom_device_info *cdi, unsigned int cmd,
void *arg)
{
return -EINVAL;
}
static struct cdrom_device_ops viocd_dops = {
.open = viocd_open,
.release = viocd_release,
.check_events = viocd_check_events,
.lock_door = viocd_lock_door,
.generic_packet = viocd_packet,
.audio_ioctl = viocd_audio_ioctl,
.capability = CDC_CLOSE_TRAY | CDC_OPEN_TRAY | CDC_LOCK | CDC_SELECT_SPEED | CDC_SELECT_DISC | CDC_MULTI_SESSION | CDC_MCN | CDC_MEDIA_CHANGED | CDC_PLAY_AUDIO | CDC_RESET | CDC_DRIVE_STATUS | CDC_GENERIC_PACKET | CDC_CD_R | CDC_CD_RW | CDC_DVD | CDC_DVD_R | CDC_DVD_RAM | CDC_RAM
};
static int find_capability(const char *type)
{
struct capability_entry *entry;
for(entry = capability_table; entry->type; ++entry)
if(!strncmp(entry->type, type, 4))
break;
return entry->capability;
}
static int viocd_probe(struct vio_dev *vdev, const struct vio_device_id *id)
{
struct gendisk *gendisk;
int deviceno;
struct disk_info *d;
struct cdrom_device_info *c;
struct request_queue *q;
struct device_node *node = vdev->dev.of_node;
deviceno = vdev->unit_address;
if (deviceno >= VIOCD_MAX_CD)
return -ENODEV;
if (!node)
return -ENODEV;
if (deviceno >= viocd_numdev)
viocd_numdev = deviceno + 1;
d = &viocd_diskinfo[deviceno];
d->rsrcname = of_get_property(node, "linux,vio_rsrcname", NULL);
d->type = of_get_property(node, "linux,vio_type", NULL);
d->model = of_get_property(node, "linux,vio_model", NULL);
c = &d->viocd_info;
c->ops = &viocd_dops;
c->speed = 4;
c->capacity = 1;
c->handle = d;
c->mask = ~find_capability(d->type);
sprintf(c->name, VIOCD_DEVICE "%c", 'a' + deviceno);
if (register_cdrom(c) != 0) {
pr_warning("Cannot register viocd CD-ROM %s!\n", c->name);
goto out;
}
pr_info("cd %s is iSeries resource %10.10s type %4.4s, model %3.3s\n",
c->name, d->rsrcname, d->type, d->model);
q = blk_init_queue(do_viocd_request, &viocd_reqlock);
if (q == NULL) {
pr_warning("Cannot allocate queue for %s!\n", c->name);
goto out_unregister_cdrom;
}
gendisk = alloc_disk(1);
if (gendisk == NULL) {
pr_warning("Cannot create gendisk for %s!\n", c->name);
goto out_cleanup_queue;
}
gendisk->major = VIOCD_MAJOR;
gendisk->first_minor = deviceno;
strncpy(gendisk->disk_name, c->name,
sizeof(gendisk->disk_name));
blk_queue_max_segments(q, 1);
blk_queue_max_hw_sectors(q, 4096 / 512);
gendisk->queue = q;
gendisk->fops = &viocd_fops;
gendisk->flags = GENHD_FL_CD | GENHD_FL_REMOVABLE |
GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE;
set_capacity(gendisk, 0);
gendisk->private_data = d;
d->viocd_disk = gendisk;
d->dev = &vdev->dev;
gendisk->driverfs_dev = d->dev;
add_disk(gendisk);
return 0;
out_cleanup_queue:
blk_cleanup_queue(q);
out_unregister_cdrom:
unregister_cdrom(c);
out:
return -ENODEV;
}
static int viocd_remove(struct vio_dev *vdev)
{
struct disk_info *d = &viocd_diskinfo[vdev->unit_address];
unregister_cdrom(&d->viocd_info);
del_gendisk(d->viocd_disk);
blk_cleanup_queue(d->viocd_disk->queue);
put_disk(d->viocd_disk);
return 0;
}
/**
* viocd_device_table: Used by vio.c to match devices that we
* support.
*/
static struct vio_device_id viocd_device_table[] __devinitdata = {
{ "block", "IBM,iSeries-viocd" },
{ "", "" }
};
MODULE_DEVICE_TABLE(vio, viocd_device_table);
static struct vio_driver viocd_driver = {
.id_table = viocd_device_table,
.probe = viocd_probe,
.remove = viocd_remove,
.driver = {
.name = "viocd",
.owner = THIS_MODULE,
}
};
static int __init viocd_init(void)
{
int ret = 0;
if (!firmware_has_feature(FW_FEATURE_ISERIES))
return -ENODEV;
if (viopath_hostLp == HvLpIndexInvalid) {
vio_set_hostlp();
/* If we don't have a host, bail out */
if (viopath_hostLp == HvLpIndexInvalid)
return -ENODEV;
}
pr_info("vers " VIOCD_VERS ", hosting partition %d\n", viopath_hostLp);
if (register_blkdev(VIOCD_MAJOR, VIOCD_DEVICE) != 0) {
pr_warning("Unable to get major %d for %s\n",
VIOCD_MAJOR, VIOCD_DEVICE);
return -EIO;
}
ret = viopath_open(viopath_hostLp, viomajorsubtype_cdio,
MAX_CD_REQ + 2);
if (ret) {
pr_warning("error opening path to host partition %d\n",
viopath_hostLp);
goto out_unregister;
}
/* Initialize our request handler */
vio_setHandler(viomajorsubtype_cdio, vio_handle_cd_event);
spin_lock_init(&viocd_reqlock);
ret = vio_register_driver(&viocd_driver);
if (ret)
goto out_free_info;
proc_create("iSeries/viocd", S_IFREG|S_IRUGO, NULL,
&proc_viocd_operations);
return 0;
out_free_info:
vio_clearHandler(viomajorsubtype_cdio);
viopath_close(viopath_hostLp, viomajorsubtype_cdio, MAX_CD_REQ + 2);
out_unregister:
unregister_blkdev(VIOCD_MAJOR, VIOCD_DEVICE);
return ret;
}
static void __exit viocd_exit(void)
{
remove_proc_entry("iSeries/viocd", NULL);
vio_unregister_driver(&viocd_driver);
viopath_close(viopath_hostLp, viomajorsubtype_cdio, MAX_CD_REQ + 2);
vio_clearHandler(viomajorsubtype_cdio);
unregister_blkdev(VIOCD_MAJOR, VIOCD_DEVICE);
}
module_init(viocd_init);
module_exit(viocd_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
cybernet/rhel7-kernel | kernel/drivers/gpu/drm/nouveau/core/subdev/vm/nv44.c | 3173 | 6933 | /*
* 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
*/
#include <core/gpuobj.h>
#include <core/option.h>
#include <subdev/timer.h>
#include <subdev/vm.h>
#include "nv04.h"
#define NV44_GART_SIZE (512 * 1024 * 1024)
#define NV44_GART_PAGE ( 4 * 1024)
/*******************************************************************************
* VM map/unmap callbacks
******************************************************************************/
static void
nv44_vm_fill(struct nouveau_gpuobj *pgt, dma_addr_t null,
dma_addr_t *list, u32 pte, u32 cnt)
{
u32 base = (pte << 2) & ~0x0000000f;
u32 tmp[4];
tmp[0] = nv_ro32(pgt, base + 0x0);
tmp[1] = nv_ro32(pgt, base + 0x4);
tmp[2] = nv_ro32(pgt, base + 0x8);
tmp[3] = nv_ro32(pgt, base + 0xc);
while (cnt--) {
u32 addr = list ? (*list++ >> 12) : (null >> 12);
switch (pte++ & 0x3) {
case 0:
tmp[0] &= ~0x07ffffff;
tmp[0] |= addr;
break;
case 1:
tmp[0] &= ~0xf8000000;
tmp[0] |= addr << 27;
tmp[1] &= ~0x003fffff;
tmp[1] |= addr >> 5;
break;
case 2:
tmp[1] &= ~0xffc00000;
tmp[1] |= addr << 22;
tmp[2] &= ~0x0001ffff;
tmp[2] |= addr >> 10;
break;
case 3:
tmp[2] &= ~0xfffe0000;
tmp[2] |= addr << 17;
tmp[3] &= ~0x00000fff;
tmp[3] |= addr >> 15;
break;
}
}
nv_wo32(pgt, base + 0x0, tmp[0]);
nv_wo32(pgt, base + 0x4, tmp[1]);
nv_wo32(pgt, base + 0x8, tmp[2]);
nv_wo32(pgt, base + 0xc, tmp[3] | 0x40000000);
}
static void
nv44_vm_map_sg(struct nouveau_vma *vma, struct nouveau_gpuobj *pgt,
struct nouveau_mem *mem, u32 pte, u32 cnt, dma_addr_t *list)
{
struct nv04_vmmgr_priv *priv = (void *)vma->vm->vmm;
u32 tmp[4];
int i;
if (pte & 3) {
u32 max = 4 - (pte & 3);
u32 part = (cnt > max) ? max : cnt;
nv44_vm_fill(pgt, priv->null, list, pte, part);
pte += part;
list += part;
cnt -= part;
}
while (cnt >= 4) {
for (i = 0; i < 4; i++)
tmp[i] = *list++ >> 12;
nv_wo32(pgt, pte++ * 4, tmp[0] >> 0 | tmp[1] << 27);
nv_wo32(pgt, pte++ * 4, tmp[1] >> 5 | tmp[2] << 22);
nv_wo32(pgt, pte++ * 4, tmp[2] >> 10 | tmp[3] << 17);
nv_wo32(pgt, pte++ * 4, tmp[3] >> 15 | 0x40000000);
cnt -= 4;
}
if (cnt)
nv44_vm_fill(pgt, priv->null, list, pte, cnt);
}
static void
nv44_vm_unmap(struct nouveau_gpuobj *pgt, u32 pte, u32 cnt)
{
struct nv04_vmmgr_priv *priv = (void *)nouveau_vmmgr(pgt);
if (pte & 3) {
u32 max = 4 - (pte & 3);
u32 part = (cnt > max) ? max : cnt;
nv44_vm_fill(pgt, priv->null, NULL, pte, part);
pte += part;
cnt -= part;
}
while (cnt >= 4) {
nv_wo32(pgt, pte++ * 4, 0x00000000);
nv_wo32(pgt, pte++ * 4, 0x00000000);
nv_wo32(pgt, pte++ * 4, 0x00000000);
nv_wo32(pgt, pte++ * 4, 0x00000000);
cnt -= 4;
}
if (cnt)
nv44_vm_fill(pgt, priv->null, NULL, pte, cnt);
}
static void
nv44_vm_flush(struct nouveau_vm *vm)
{
struct nv04_vmmgr_priv *priv = (void *)vm->vmm;
nv_wr32(priv, 0x100814, priv->base.limit - NV44_GART_PAGE);
nv_wr32(priv, 0x100808, 0x00000020);
if (!nv_wait(priv, 0x100808, 0x00000001, 0x00000001))
nv_error(priv, "timeout: 0x%08x\n", nv_rd32(priv, 0x100808));
nv_wr32(priv, 0x100808, 0x00000000);
}
/*******************************************************************************
* VMMGR subdev
******************************************************************************/
static int
nv44_vmmgr_ctor(struct nouveau_object *parent, struct nouveau_object *engine,
struct nouveau_oclass *oclass, void *data, u32 size,
struct nouveau_object **pobject)
{
struct nouveau_device *device = nv_device(parent);
struct nv04_vmmgr_priv *priv;
int ret;
if (pci_find_capability(device->pdev, PCI_CAP_ID_AGP) ||
!nouveau_boolopt(device->cfgopt, "NvPCIE", true)) {
return nouveau_object_ctor(parent, engine, &nv04_vmmgr_oclass,
data, size, pobject);
}
ret = nouveau_vmmgr_create(parent, engine, oclass, "PCIEGART",
"pciegart", &priv);
*pobject = nv_object(priv);
if (ret)
return ret;
priv->base.create = nv04_vm_create;
priv->base.limit = NV44_GART_SIZE;
priv->base.dma_bits = 39;
priv->base.pgt_bits = 32 - 12;
priv->base.spg_shift = 12;
priv->base.lpg_shift = 12;
priv->base.map_sg = nv44_vm_map_sg;
priv->base.unmap = nv44_vm_unmap;
priv->base.flush = nv44_vm_flush;
priv->nullp = pci_alloc_consistent(device->pdev, 16 * 1024, &priv->null);
if (!priv->nullp) {
nv_error(priv, "unable to allocate dummy pages\n");
return -ENOMEM;
}
ret = nouveau_vm_create(&priv->base, 0, NV44_GART_SIZE, 0, 4096,
&priv->vm);
if (ret)
return ret;
ret = nouveau_gpuobj_new(nv_object(priv), NULL,
(NV44_GART_SIZE / NV44_GART_PAGE) * 4,
512 * 1024, NVOBJ_FLAG_ZERO_ALLOC,
&priv->vm->pgt[0].obj[0]);
priv->vm->pgt[0].refcount[0] = 1;
if (ret)
return ret;
return 0;
}
static int
nv44_vmmgr_init(struct nouveau_object *object)
{
struct nv04_vmmgr_priv *priv = (void *)object;
struct nouveau_gpuobj *gart = priv->vm->pgt[0].obj[0];
u32 addr;
int ret;
ret = nouveau_vmmgr_init(&priv->base);
if (ret)
return ret;
/* calculate vram address of this PRAMIN block, object must be
* allocated on 512KiB alignment, and not exceed a total size
* of 512KiB for this to work correctly
*/
addr = nv_rd32(priv, 0x10020c);
addr -= ((gart->addr >> 19) + 1) << 19;
nv_wr32(priv, 0x100850, 0x80000000);
nv_wr32(priv, 0x100818, priv->null);
nv_wr32(priv, 0x100804, NV44_GART_SIZE);
nv_wr32(priv, 0x100850, 0x00008000);
nv_mask(priv, 0x10008c, 0x00000200, 0x00000200);
nv_wr32(priv, 0x100820, 0x00000000);
nv_wr32(priv, 0x10082c, 0x00000001);
nv_wr32(priv, 0x100800, addr | 0x00000010);
return 0;
}
struct nouveau_oclass
nv44_vmmgr_oclass = {
.handle = NV_SUBDEV(VM, 0x44),
.ofuncs = &(struct nouveau_ofuncs) {
.ctor = nv44_vmmgr_ctor,
.dtor = nv04_vmmgr_dtor,
.init = nv44_vmmgr_init,
.fini = _nouveau_vmmgr_fini,
},
};
| gpl-2.0 |
schqiushui/kernel_sense_a5dug | net/ipv6/anycast.c | 3941 | 11127 | /*
* Anycast support for IPv6
* Linux INET6 implementation
*
* Authors:
* David L Stevens (dlstevens@us.ibm.com)
*
* based heavily on net/ipv6/mcast.c
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/capability.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/random.h>
#include <linux/string.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/in6.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/route.h>
#include <linux/init.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <net/snmp.h>
#include <net/ipv6.h>
#include <net/protocol.h>
#include <net/if_inet6.h>
#include <net/ndisc.h>
#include <net/addrconf.h>
#include <net/ip6_route.h>
#include <net/checksum.h>
static int ipv6_dev_ac_dec(struct net_device *dev, const struct in6_addr *addr);
/* Big ac list lock for all the sockets */
static DEFINE_RWLOCK(ipv6_sk_ac_lock);
/*
* socket join an anycast group
*/
int ipv6_sock_ac_join(struct sock *sk, int ifindex, const struct in6_addr *addr)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct net_device *dev = NULL;
struct inet6_dev *idev;
struct ipv6_ac_socklist *pac;
struct net *net = sock_net(sk);
int ishost = !net->ipv6.devconf_all->forwarding;
int err = 0;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (ipv6_addr_is_multicast(addr))
return -EINVAL;
if (ipv6_chk_addr(net, addr, NULL, 0))
return -EINVAL;
pac = sock_kmalloc(sk, sizeof(struct ipv6_ac_socklist), GFP_KERNEL);
if (pac == NULL)
return -ENOMEM;
pac->acl_next = NULL;
pac->acl_addr = *addr;
rcu_read_lock();
if (ifindex == 0) {
struct rt6_info *rt;
rt = rt6_lookup(net, addr, NULL, 0, 0);
if (rt) {
dev = rt->dst.dev;
dst_release(&rt->dst);
} else if (ishost) {
err = -EADDRNOTAVAIL;
goto error;
} else {
/* router, no matching interface: just pick one */
dev = dev_get_by_flags_rcu(net, IFF_UP,
IFF_UP | IFF_LOOPBACK);
}
} else
dev = dev_get_by_index_rcu(net, ifindex);
if (dev == NULL) {
err = -ENODEV;
goto error;
}
idev = __in6_dev_get(dev);
if (!idev) {
if (ifindex)
err = -ENODEV;
else
err = -EADDRNOTAVAIL;
goto error;
}
/* reset ishost, now that we have a specific device */
ishost = !idev->cnf.forwarding;
pac->acl_ifindex = dev->ifindex;
/* XXX
* For hosts, allow link-local or matching prefix anycasts.
* This obviates the need for propagating anycast routes while
* still allowing some non-router anycast participation.
*/
if (!ipv6_chk_prefix(addr, dev)) {
if (ishost)
err = -EADDRNOTAVAIL;
if (err)
goto error;
}
err = ipv6_dev_ac_inc(dev, addr);
if (!err) {
write_lock_bh(&ipv6_sk_ac_lock);
pac->acl_next = np->ipv6_ac_list;
np->ipv6_ac_list = pac;
write_unlock_bh(&ipv6_sk_ac_lock);
pac = NULL;
}
error:
rcu_read_unlock();
if (pac)
sock_kfree_s(sk, pac, sizeof(*pac));
return err;
}
/*
* socket leave an anycast group
*/
int ipv6_sock_ac_drop(struct sock *sk, int ifindex, const struct in6_addr *addr)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct net_device *dev;
struct ipv6_ac_socklist *pac, *prev_pac;
struct net *net = sock_net(sk);
write_lock_bh(&ipv6_sk_ac_lock);
prev_pac = NULL;
for (pac = np->ipv6_ac_list; pac; pac = pac->acl_next) {
if ((ifindex == 0 || pac->acl_ifindex == ifindex) &&
ipv6_addr_equal(&pac->acl_addr, addr))
break;
prev_pac = pac;
}
if (!pac) {
write_unlock_bh(&ipv6_sk_ac_lock);
return -ENOENT;
}
if (prev_pac)
prev_pac->acl_next = pac->acl_next;
else
np->ipv6_ac_list = pac->acl_next;
write_unlock_bh(&ipv6_sk_ac_lock);
rcu_read_lock();
dev = dev_get_by_index_rcu(net, pac->acl_ifindex);
if (dev)
ipv6_dev_ac_dec(dev, &pac->acl_addr);
rcu_read_unlock();
sock_kfree_s(sk, pac, sizeof(*pac));
return 0;
}
void ipv6_sock_ac_close(struct sock *sk)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct net_device *dev = NULL;
struct ipv6_ac_socklist *pac;
struct net *net = sock_net(sk);
int prev_index;
write_lock_bh(&ipv6_sk_ac_lock);
pac = np->ipv6_ac_list;
np->ipv6_ac_list = NULL;
write_unlock_bh(&ipv6_sk_ac_lock);
prev_index = 0;
rcu_read_lock();
while (pac) {
struct ipv6_ac_socklist *next = pac->acl_next;
if (pac->acl_ifindex != prev_index) {
dev = dev_get_by_index_rcu(net, pac->acl_ifindex);
prev_index = pac->acl_ifindex;
}
if (dev)
ipv6_dev_ac_dec(dev, &pac->acl_addr);
sock_kfree_s(sk, pac, sizeof(*pac));
pac = next;
}
rcu_read_unlock();
}
static void aca_put(struct ifacaddr6 *ac)
{
if (atomic_dec_and_test(&ac->aca_refcnt)) {
in6_dev_put(ac->aca_idev);
dst_release(&ac->aca_rt->dst);
kfree(ac);
}
}
/*
* device anycast group inc (add if not found)
*/
int ipv6_dev_ac_inc(struct net_device *dev, const struct in6_addr *addr)
{
struct ifacaddr6 *aca;
struct inet6_dev *idev;
struct rt6_info *rt;
int err;
idev = in6_dev_get(dev);
if (idev == NULL)
return -EINVAL;
write_lock_bh(&idev->lock);
if (idev->dead) {
err = -ENODEV;
goto out;
}
for (aca = idev->ac_list; aca; aca = aca->aca_next) {
if (ipv6_addr_equal(&aca->aca_addr, addr)) {
aca->aca_users++;
err = 0;
goto out;
}
}
/*
* not found: create a new one.
*/
aca = kzalloc(sizeof(struct ifacaddr6), GFP_ATOMIC);
if (aca == NULL) {
err = -ENOMEM;
goto out;
}
rt = addrconf_dst_alloc(idev, addr, true);
if (IS_ERR(rt)) {
kfree(aca);
err = PTR_ERR(rt);
goto out;
}
aca->aca_addr = *addr;
aca->aca_idev = idev;
aca->aca_rt = rt;
aca->aca_users = 1;
/* aca_tstamp should be updated upon changes */
aca->aca_cstamp = aca->aca_tstamp = jiffies;
atomic_set(&aca->aca_refcnt, 2);
spin_lock_init(&aca->aca_lock);
aca->aca_next = idev->ac_list;
idev->ac_list = aca;
write_unlock_bh(&idev->lock);
ip6_ins_rt(rt);
addrconf_join_solict(dev, &aca->aca_addr);
aca_put(aca);
return 0;
out:
write_unlock_bh(&idev->lock);
in6_dev_put(idev);
return err;
}
/*
* device anycast group decrement
*/
int __ipv6_dev_ac_dec(struct inet6_dev *idev, const struct in6_addr *addr)
{
struct ifacaddr6 *aca, *prev_aca;
write_lock_bh(&idev->lock);
prev_aca = NULL;
for (aca = idev->ac_list; aca; aca = aca->aca_next) {
if (ipv6_addr_equal(&aca->aca_addr, addr))
break;
prev_aca = aca;
}
if (!aca) {
write_unlock_bh(&idev->lock);
return -ENOENT;
}
if (--aca->aca_users > 0) {
write_unlock_bh(&idev->lock);
return 0;
}
if (prev_aca)
prev_aca->aca_next = aca->aca_next;
else
idev->ac_list = aca->aca_next;
write_unlock_bh(&idev->lock);
addrconf_leave_solict(idev, &aca->aca_addr);
dst_hold(&aca->aca_rt->dst);
ip6_del_rt(aca->aca_rt);
aca_put(aca);
return 0;
}
/* called with rcu_read_lock() */
static int ipv6_dev_ac_dec(struct net_device *dev, const struct in6_addr *addr)
{
struct inet6_dev *idev = __in6_dev_get(dev);
if (idev == NULL)
return -ENODEV;
return __ipv6_dev_ac_dec(idev, addr);
}
/*
* check if the interface has this anycast address
* called with rcu_read_lock()
*/
static int ipv6_chk_acast_dev(struct net_device *dev, const struct in6_addr *addr)
{
struct inet6_dev *idev;
struct ifacaddr6 *aca;
idev = __in6_dev_get(dev);
if (idev) {
read_lock_bh(&idev->lock);
for (aca = idev->ac_list; aca; aca = aca->aca_next)
if (ipv6_addr_equal(&aca->aca_addr, addr))
break;
read_unlock_bh(&idev->lock);
return aca != NULL;
}
return 0;
}
/*
* check if given interface (or any, if dev==0) has this anycast address
*/
int ipv6_chk_acast_addr(struct net *net, struct net_device *dev,
const struct in6_addr *addr)
{
int found = 0;
rcu_read_lock();
if (dev)
found = ipv6_chk_acast_dev(dev, addr);
else
for_each_netdev_rcu(net, dev)
if (ipv6_chk_acast_dev(dev, addr)) {
found = 1;
break;
}
rcu_read_unlock();
return found;
}
#ifdef CONFIG_PROC_FS
struct ac6_iter_state {
struct seq_net_private p;
struct net_device *dev;
struct inet6_dev *idev;
};
#define ac6_seq_private(seq) ((struct ac6_iter_state *)(seq)->private)
static inline struct ifacaddr6 *ac6_get_first(struct seq_file *seq)
{
struct ifacaddr6 *im = NULL;
struct ac6_iter_state *state = ac6_seq_private(seq);
struct net *net = seq_file_net(seq);
state->idev = NULL;
for_each_netdev_rcu(net, state->dev) {
struct inet6_dev *idev;
idev = __in6_dev_get(state->dev);
if (!idev)
continue;
read_lock_bh(&idev->lock);
im = idev->ac_list;
if (im) {
state->idev = idev;
break;
}
read_unlock_bh(&idev->lock);
}
return im;
}
static struct ifacaddr6 *ac6_get_next(struct seq_file *seq, struct ifacaddr6 *im)
{
struct ac6_iter_state *state = ac6_seq_private(seq);
im = im->aca_next;
while (!im) {
if (likely(state->idev != NULL))
read_unlock_bh(&state->idev->lock);
state->dev = next_net_device_rcu(state->dev);
if (!state->dev) {
state->idev = NULL;
break;
}
state->idev = __in6_dev_get(state->dev);
if (!state->idev)
continue;
read_lock_bh(&state->idev->lock);
im = state->idev->ac_list;
}
return im;
}
static struct ifacaddr6 *ac6_get_idx(struct seq_file *seq, loff_t pos)
{
struct ifacaddr6 *im = ac6_get_first(seq);
if (im)
while (pos && (im = ac6_get_next(seq, im)) != NULL)
--pos;
return pos ? NULL : im;
}
static void *ac6_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(RCU)
{
rcu_read_lock();
return ac6_get_idx(seq, *pos);
}
static void *ac6_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct ifacaddr6 *im = ac6_get_next(seq, v);
++*pos;
return im;
}
static void ac6_seq_stop(struct seq_file *seq, void *v)
__releases(RCU)
{
struct ac6_iter_state *state = ac6_seq_private(seq);
if (likely(state->idev != NULL)) {
read_unlock_bh(&state->idev->lock);
state->idev = NULL;
}
rcu_read_unlock();
}
static int ac6_seq_show(struct seq_file *seq, void *v)
{
struct ifacaddr6 *im = (struct ifacaddr6 *)v;
struct ac6_iter_state *state = ac6_seq_private(seq);
seq_printf(seq, "%-4d %-15s %pi6 %5d\n",
state->dev->ifindex, state->dev->name,
&im->aca_addr, im->aca_users);
return 0;
}
static const struct seq_operations ac6_seq_ops = {
.start = ac6_seq_start,
.next = ac6_seq_next,
.stop = ac6_seq_stop,
.show = ac6_seq_show,
};
static int ac6_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &ac6_seq_ops,
sizeof(struct ac6_iter_state));
}
static const struct file_operations ac6_seq_fops = {
.owner = THIS_MODULE,
.open = ac6_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
int __net_init ac6_proc_init(struct net *net)
{
if (!proc_net_fops_create(net, "anycast6", S_IRUGO, &ac6_seq_fops))
return -ENOMEM;
return 0;
}
void ac6_proc_exit(struct net *net)
{
proc_net_remove(net, "anycast6");
}
#endif
| gpl-2.0 |
sloanyang/android_kernel_zte_u950 | drivers/staging/wlags49_h2/mmd.c | 4197 | 13378 |
// vim:tw=110:ts=4:
/************************************************************************************************************
*
* FILE : mmd.c
*
* DATE : $Date: 2004/07/23 11:57:45 $ $Revision: 1.4 $
* Original: 2004/05/28 14:05:35 Revision: 1.32 Tag: hcf7_t20040602_01
* Original: 2004/05/13 15:31:45 Revision: 1.30 Tag: hcf7_t7_20040513_01
* Original: 2004/04/15 09:24:42 Revision: 1.25 Tag: hcf7_t7_20040415_01
* Original: 2004/04/08 15:18:17 Revision: 1.24 Tag: t7_20040413_01
* Original: 2004/04/01 15:32:55 Revision: 1.22 Tag: t7_20040401_01
* Original: 2004/03/10 15:39:28 Revision: 1.18 Tag: t20040310_01
* Original: 2004/03/03 14:10:12 Revision: 1.16 Tag: t20040304_01
* Original: 2004/03/02 09:27:12 Revision: 1.14 Tag: t20040302_03
* Original: 2004/02/24 13:00:29 Revision: 1.12 Tag: t20040224_01
* Original: 2004/01/30 09:59:33 Revision: 1.11 Tag: t20040219_01
*
* AUTHOR : Nico Valster
*
* DESC : Common routines for HCF, MSF, UIL as well as USF sources
*
* Note: relative to Asserts, the following can be observed:
* Since the IFB is not known inside the routine, the macro HCFASSERT is replaced with MDDASSERT.
* Also the line number reported in the assert is raised by FILE_NAME_OFFSET (20000) to discriminate the
* MMD Asserts from HCF and DHF asserts.
*
***************************************************************************************************************
*
*
* SOFTWARE LICENSE
*
* This software is provided subject to the following terms and conditions,
* which you should read carefully before using the software. Using this
* software indicates your acceptance of these terms and conditions. If you do
* not agree with these terms and conditions, do not use the software.
*
* COPYRIGHT © 2001 - 2004 by Agere Systems Inc. All Rights Reserved
* All rights reserved.
*
* Redistribution and use in source or binary forms, with or without
* modifications, are permitted provided that the following conditions are met:
*
* . Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following Disclaimer as comments in the code as
* well as in the documentation and/or other materials provided with the
* distribution.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following Disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name of Agere Systems Inc. nor the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* Disclaimer
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY
* USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN
* RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. 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, INCLUDING, BUT NOT LIMITED TO, 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 "hcf.h" // Needed as long as we do not really sort out the mess
#include "hcfdef.h" // get CNV_LITTLE_TO_SHORT
#include "mmd.h" // MoreModularDriver common include file
//to distinguish DHF from HCF asserts by means of line number
#undef FILE_NAME_OFFSET
#define FILE_NAME_OFFSET DHF_FILE_NAME_OFFSET
/*************************************************************************************************************
*
*.MODULE CFG_RANGE_SPEC_STRCT* mmd_check_comp( CFG_RANGES_STRCT *actp, CFG_SUP_RANGE_STRCT *supp )
*.PURPOSE Checks compatibility between an actor and a supplier.
*
*.ARGUMENTS
* actp
* supp
*
*.RETURNS
* NULL incompatible
* <>NULL pointer to matching CFG_RANGE_SPEC_STRCT substructure in actor-structure matching the supplier
*
*.NARRATIVE
*
* Parameters:
* actp address of the actor specification
* supp address of the supplier specification
*
* Description: mmd_check_comp is a support routine to check the compatibility between an actor and a
* supplier. mmd_check_comp is independent of the endianess of the actp and supp structures. This is
* achieved by checking the "bottom" or "role" fields of these structures. Since these fields are restricted
* to a limited range, comparing the contents to a value with a known endian-ess gives a clue to their actual
* endianess.
*
*.DIAGRAM
*1a: The role-field of the actor structure has a known non-zero, not "byte symmetric" value (namely
* COMP_ROLE_ACT or 0x0001), so if and only the contents of this field matches COMP_ROLE_ACT (in Native
* Endian format), the actor structure is Native Endian.
*2a: Since the role-field of the supplier structure is 0x0000, the test as used for the actor does not work
* for a supplier. A supplier has always exactly 1 variant,top,bottom record with (officially, but see the
* note below) each of these 3 values in the range 1 through 99, so one byte of the word value of variant,
* top and bottom words is 0x00 and the other byte is non-zero. Whether the lowest address byte or the
* highest address byte is non-zero depends on the Endianess of the LTV. If and only if the word value of
* bottom is less than 0x0100, the supplier is Native Endian.
* NOTE: the variant field of the supplier structure can not be used for the Endian Detection Algorithm,
* because a a zero-valued variant has been used as Controlled Deployment indication in the past.
* Note: An actor may have multiple sets of variant,top,bottom records, including dummy sets with variant,
* top and bottom fields with a zero-value. As a consequence the endianess of the actor can not be determined
* based on its variant,top,bottom values.
*
* Note: the L and T field of the structures are always in Native Endian format, so you can not draw
* conclusions concerning the Endianess of the structure based on these two fields.
*
*1b/2b
* The only purpose of the CFG_RANGE_SPEC_BYTE_STRCT is to give easy access to the non-zero byte of the word
* value of variant, top and bottom. The variables sup_endian and act_endian are used for the supplier and
* actor structure respectively. These variables must be 0 when the structure has LE format and 1 if the
* structure has BE format. This can be phrased as:
* the variable is false (i.e 0x0000) if either
* (the platform is LE and the LTV is the same as the platform)
* or
* (the platform is BE and the LTV differs from the platform).
* the variable is true (i.e 0x0001) if either
* (the platform is BE and the LTV is the same as the platform)
* or
* (the platform is LE and the LTV differs from the platform).
*
* Alternatively this can be phrased as:
* if the platform is LE
* if the LTV is LE (i.e the same as the platform), then the variable = 0
* else (the LTV is BE (i.e. different from the platform) ), then the variable = 1
* if the platform is BE
* if the LTV is BE (i.e the same as the platform), then the variable = 1
* else (the LTV is LE (i.e. different from the platform) ), then the variable = 0
*
* This is implemented as:
* #if HCF_BIG_ENDIAN == 0 //platform is LE
* sup/act_endian becomes reverse of structure-endianess as determined in 1a/1b
* #endif
*6: Each of the actor variant-bottom-top records is checked against the (single) supplier variant-bottom-top
* range till either an acceptable match is found or all actor records are tried. As explained above, due to
* the limited ranges of these values, checking a byte is acceptable and suitable.
*8: depending on whether a match was found or not (as reflected by the value of the control variable of the
* for loop), the NULL pointer or a pointer to the matching Number/Bottom/Top record of the Actor structure
* is returned.
* As an additional safety, checking the supplier length protects against invalid Supplier structures, which
* may be caused by failing hcf_get_info (in which case the len-field is zero). Note that the contraption
* "supp->len != sizeof(CFG_SUP_RANGE_STRCT)/sizeof(hcf_16) - 1"
* did turn out not to work for a compiler which padded the structure definition.
*
* Note: when consulting references like DesignNotes and Architecture specifications there is a confusing use
* of the notions number and variant. This resulted in an inconsistent use in the HCF nomenclature as well.
* This makes the logic hard to follow and one has to be very much aware of the context when walking through
* the code.
* NOTE: The Endian Detection Algorithm places limitations on future extensions of the fields, i.e. they should
* stay within the currently defined boundaries of 1 through 99 (although 1 through 255) would work as well
* and there should never be used a zero value for the bottom of a valid supplier.
* Note: relative to Asserts, the following can be observed:
* 1: Supplier variant 0x0000 has been used for Controlled Deployment
* 2: An actor may have one or more variant record specifications with a top of zero and a non-zero bottom
* to override the HCF default support of a particular variant by the MSF programmer via hcfcfg.h
* 3: An actor range can be specified as all zeros, e.g. as padding in the automatically generated firmware
* image files.
*.ENDDOC END DOCUMENTATION
*************************************************************************************************************/
CFG_RANGE_SPEC_STRCT*
mmd_check_comp( CFG_RANGES_STRCT *actp, CFG_SUP_RANGE_STRCT *supp )
{
CFG_RANGE_SPEC_BYTE_STRCT *actq = (CFG_RANGE_SPEC_BYTE_STRCT*)actp->var_rec;
CFG_RANGE_SPEC_BYTE_STRCT *supq = (CFG_RANGE_SPEC_BYTE_STRCT*)&(supp->variant);
hcf_16 i;
int act_endian; //actor endian flag
int sup_endian; //supplier endian flag
act_endian = actp->role == COMP_ROLE_ACT; //true if native endian /* 1a */
sup_endian = supp->bottom < 0x0100; //true if native endian /* 2a */
#if HCF_ASSERT
MMDASSERT( supp->len == 6, supp->len )
MMDASSERT( actp->len >= 6 && actp->len%3 == 0, actp->len )
if ( act_endian ) { //native endian
MMDASSERT( actp->role == COMP_ROLE_ACT, actp->role )
MMDASSERT( 1 <= actp->id && actp->id <= 99, actp->id )
} else { //non-native endian
MMDASSERT( actp->role == CNV_END_SHORT(COMP_ROLE_ACT), actp->role )
MMDASSERT( 1 <= CNV_END_SHORT(actp->id) && CNV_END_SHORT(actp->id) <= 99, actp->id )
}
if ( sup_endian ) { //native endian
MMDASSERT( supp->role == COMP_ROLE_SUPL, supp->role )
MMDASSERT( 1 <= supp->id && supp->id <= 99, supp->id )
MMDASSERT( 1 <= supp->variant && supp->variant <= 99, supp->variant )
MMDASSERT( 1 <= supp->bottom && supp->bottom <= 99, supp->bottom )
MMDASSERT( 1 <= supp->top && supp->top <= 99, supp->top )
MMDASSERT( supp->bottom <= supp->top, supp->bottom << 8 | supp->top )
} else { //non-native endian
MMDASSERT( supp->role == CNV_END_SHORT(COMP_ROLE_SUPL), supp->role )
MMDASSERT( 1 <= CNV_END_SHORT(supp->id) && CNV_END_SHORT(supp->id) <= 99, supp->id )
MMDASSERT( 1 <= CNV_END_SHORT(supp->variant) && CNV_END_SHORT(supp->variant) <= 99, supp->variant )
MMDASSERT( 1 <= CNV_END_SHORT(supp->bottom) && CNV_END_SHORT(supp->bottom) <=99, supp->bottom )
MMDASSERT( 1 <= CNV_END_SHORT(supp->top) && CNV_END_SHORT(supp->top) <=99, supp->top )
MMDASSERT( CNV_END_SHORT(supp->bottom) <= CNV_END_SHORT(supp->top), supp->bottom << 8 | supp->top )
}
#endif // HCF_ASSERT
#if HCF_BIG_ENDIAN == 0
act_endian = !act_endian; /* 1b*/
sup_endian = !sup_endian; /* 2b*/
#endif // HCF_BIG_ENDIAN
for ( i = actp->len ; i > 3; actq++, i -= 3 ) { /* 6 */
MMDASSERT( actq->variant[act_endian] <= 99, i<<8 | actq->variant[act_endian] )
MMDASSERT( actq->bottom[act_endian] <= 99 , i<<8 | actq->bottom[act_endian] )
MMDASSERT( actq->top[act_endian] <= 99 , i<<8 | actq->top[act_endian] )
MMDASSERT( actq->bottom[act_endian] <= actq->top[act_endian], i<<8 | actq->bottom[act_endian] )
if ( actq->variant[act_endian] == supq->variant[sup_endian] &&
actq->bottom[act_endian] <= supq->top[sup_endian] &&
actq->top[act_endian] >= supq->bottom[sup_endian]
) break;
}
if ( i <= 3 || supp->len != 6 /*sizeof(CFG_SUP_RANGE_STRCT)/sizeof(hcf_16) - 1 */ ) {
actq = NULL; /* 8 */
}
#if HCF_ASSERT
if ( actq == NULL ) {
for ( i = 0; i <= supp->len; i += 2 ) {
MMDASSERT( DO_ASSERT, MERGE_2( ((hcf_16*)supp)[i], ((hcf_16*)supp)[i+1] ) );
}
for ( i = 0; i <= actp->len; i += 2 ) {
MMDASSERT( DO_ASSERT, MERGE_2( ((hcf_16*)actp)[i], ((hcf_16*)actp)[i+1] ) );
}
}
#endif // HCF_ASSERT
return (CFG_RANGE_SPEC_STRCT*)actq;
} // mmd_check_comp
| gpl-2.0 |
Khaon/android_kernel_samsung_manta | drivers/staging/iio/gyro/adis16080_core.c | 4965 | 4269 | /*
* ADIS16080/100 Yaw Rate Gyroscope with SPI driver
*
* Copyright 2010 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#include <linux/delay.h>
#include <linux/mutex.h>
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/spi/spi.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include <linux/module.h>
#include "../iio.h"
#include "../sysfs.h"
#define ADIS16080_DIN_GYRO (0 << 10) /* Gyroscope output */
#define ADIS16080_DIN_TEMP (1 << 10) /* Temperature output */
#define ADIS16080_DIN_AIN1 (2 << 10)
#define ADIS16080_DIN_AIN2 (3 << 10)
/*
* 1: Write contents on DIN to control register.
* 0: No changes to control register.
*/
#define ADIS16080_DIN_WRITE (1 << 15)
/**
* struct adis16080_state - device instance specific data
* @us: actual spi_device to write data
* @buf: transmit or receive buffer
* @buf_lock: mutex to protect tx and rx
**/
struct adis16080_state {
struct spi_device *us;
struct mutex buf_lock;
u8 buf[2] ____cacheline_aligned;
};
static int adis16080_spi_write(struct iio_dev *indio_dev,
u16 val)
{
int ret;
struct adis16080_state *st = iio_priv(indio_dev);
mutex_lock(&st->buf_lock);
st->buf[0] = val >> 8;
st->buf[1] = val;
ret = spi_write(st->us, st->buf, 2);
mutex_unlock(&st->buf_lock);
return ret;
}
static int adis16080_spi_read(struct iio_dev *indio_dev,
u16 *val)
{
int ret;
struct adis16080_state *st = iio_priv(indio_dev);
mutex_lock(&st->buf_lock);
ret = spi_read(st->us, st->buf, 2);
if (ret == 0)
*val = ((st->buf[0] & 0xF) << 8) | st->buf[1];
mutex_unlock(&st->buf_lock);
return ret;
}
static int adis16080_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int *val,
int *val2,
long mask)
{
int ret = -EINVAL;
u16 ut;
/* Take the iio_dev status lock */
mutex_lock(&indio_dev->mlock);
switch (mask) {
case 0:
ret = adis16080_spi_write(indio_dev,
chan->address |
ADIS16080_DIN_WRITE);
if (ret < 0)
break;
ret = adis16080_spi_read(indio_dev, &ut);
if (ret < 0)
break;
*val = ut;
ret = IIO_VAL_INT;
break;
}
mutex_unlock(&indio_dev->mlock);
return ret;
}
static const struct iio_chan_spec adis16080_channels[] = {
{
.type = IIO_ANGL_VEL,
.modified = 1,
.channel2 = IIO_MOD_Z,
.address = ADIS16080_DIN_GYRO,
}, {
.type = IIO_VOLTAGE,
.indexed = 1,
.channel = 0,
.address = ADIS16080_DIN_AIN1,
}, {
.type = IIO_VOLTAGE,
.indexed = 1,
.channel = 1,
.address = ADIS16080_DIN_AIN2,
}, {
.type = IIO_TEMP,
.indexed = 1,
.channel = 0,
.address = ADIS16080_DIN_TEMP,
}
};
static const struct iio_info adis16080_info = {
.read_raw = &adis16080_read_raw,
.driver_module = THIS_MODULE,
};
static int __devinit adis16080_probe(struct spi_device *spi)
{
int ret;
struct adis16080_state *st;
struct iio_dev *indio_dev;
/* setup the industrialio driver allocated elements */
indio_dev = iio_allocate_device(sizeof(*st));
if (indio_dev == NULL) {
ret = -ENOMEM;
goto error_ret;
}
st = iio_priv(indio_dev);
/* this is only used for removal purposes */
spi_set_drvdata(spi, indio_dev);
/* Allocate the comms buffers */
st->us = spi;
mutex_init(&st->buf_lock);
indio_dev->name = spi->dev.driver->name;
indio_dev->channels = adis16080_channels;
indio_dev->num_channels = ARRAY_SIZE(adis16080_channels);
indio_dev->dev.parent = &spi->dev;
indio_dev->info = &adis16080_info;
indio_dev->modes = INDIO_DIRECT_MODE;
ret = iio_device_register(indio_dev);
if (ret)
goto error_free_dev;
return 0;
error_free_dev:
iio_free_device(indio_dev);
error_ret:
return ret;
}
/* fixme, confirm ordering in this function */
static int adis16080_remove(struct spi_device *spi)
{
iio_device_unregister(spi_get_drvdata(spi));
iio_free_device(spi_get_drvdata(spi));
return 0;
}
static struct spi_driver adis16080_driver = {
.driver = {
.name = "adis16080",
.owner = THIS_MODULE,
},
.probe = adis16080_probe,
.remove = __devexit_p(adis16080_remove),
};
module_spi_driver(adis16080_driver);
MODULE_AUTHOR("Barry Song <21cnbao@gmail.com>");
MODULE_DESCRIPTION("Analog Devices ADIS16080/100 Yaw Rate Gyroscope Driver");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("spi:adis16080");
| gpl-2.0 |
varchild/SebastianFM-kernel | drivers/staging/iio/adc/ad7887_core.c | 4965 | 6431 | /*
* AD7887 SPI ADC driver
*
* Copyright 2010-2011 Analog Devices Inc.
*
* Licensed under the GPL-2.
*/
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include <linux/spi/spi.h>
#include <linux/regulator/consumer.h>
#include <linux/err.h>
#include <linux/module.h>
#include "../iio.h"
#include "../sysfs.h"
#include "../buffer.h"
#include "ad7887.h"
static int ad7887_scan_direct(struct ad7887_state *st, unsigned ch)
{
int ret = spi_sync(st->spi, &st->msg[ch]);
if (ret)
return ret;
return (st->data[(ch * 2)] << 8) | st->data[(ch * 2) + 1];
}
static int ad7887_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int *val,
int *val2,
long m)
{
int ret;
struct ad7887_state *st = iio_priv(indio_dev);
unsigned int scale_uv;
switch (m) {
case 0:
mutex_lock(&indio_dev->mlock);
if (iio_buffer_enabled(indio_dev))
ret = -EBUSY;
else
ret = ad7887_scan_direct(st, chan->address);
mutex_unlock(&indio_dev->mlock);
if (ret < 0)
return ret;
*val = (ret >> st->chip_info->channel[0].scan_type.shift) &
RES_MASK(st->chip_info->channel[0].scan_type.realbits);
return IIO_VAL_INT;
case IIO_CHAN_INFO_SCALE:
scale_uv = (st->int_vref_mv * 1000)
>> st->chip_info->channel[0].scan_type.realbits;
*val = scale_uv/1000;
*val2 = (scale_uv%1000)*1000;
return IIO_VAL_INT_PLUS_MICRO;
}
return -EINVAL;
}
static const struct ad7887_chip_info ad7887_chip_info_tbl[] = {
/*
* More devices added in future
*/
[ID_AD7887] = {
.channel[0] = {
.type = IIO_VOLTAGE,
.indexed = 1,
.channel = 1,
.info_mask = IIO_CHAN_INFO_SCALE_SHARED_BIT,
.address = 1,
.scan_index = 1,
.scan_type = IIO_ST('u', 12, 16, 0),
},
.channel[1] = {
.type = IIO_VOLTAGE,
.indexed = 1,
.channel = 0,
.info_mask = IIO_CHAN_INFO_SCALE_SHARED_BIT,
.address = 0,
.scan_index = 0,
.scan_type = IIO_ST('u', 12, 16, 0),
},
.channel[2] = IIO_CHAN_SOFT_TIMESTAMP(2),
.int_vref_mv = 2500,
},
};
static const struct iio_info ad7887_info = {
.read_raw = &ad7887_read_raw,
.driver_module = THIS_MODULE,
};
static int __devinit ad7887_probe(struct spi_device *spi)
{
struct ad7887_platform_data *pdata = spi->dev.platform_data;
struct ad7887_state *st;
int ret, voltage_uv = 0;
struct iio_dev *indio_dev = iio_allocate_device(sizeof(*st));
if (indio_dev == NULL)
return -ENOMEM;
st = iio_priv(indio_dev);
st->reg = regulator_get(&spi->dev, "vcc");
if (!IS_ERR(st->reg)) {
ret = regulator_enable(st->reg);
if (ret)
goto error_put_reg;
voltage_uv = regulator_get_voltage(st->reg);
}
st->chip_info =
&ad7887_chip_info_tbl[spi_get_device_id(spi)->driver_data];
spi_set_drvdata(spi, indio_dev);
st->spi = spi;
/* Estabilish that the iio_dev is a child of the spi device */
indio_dev->dev.parent = &spi->dev;
indio_dev->name = spi_get_device_id(spi)->name;
indio_dev->info = &ad7887_info;
indio_dev->modes = INDIO_DIRECT_MODE;
/* Setup default message */
st->tx_cmd_buf[0] = AD7887_CH_AIN0 | AD7887_PM_MODE4 |
((pdata && pdata->use_onchip_ref) ?
0 : AD7887_REF_DIS);
st->xfer[0].rx_buf = &st->data[0];
st->xfer[0].tx_buf = &st->tx_cmd_buf[0];
st->xfer[0].len = 2;
spi_message_init(&st->msg[AD7887_CH0]);
spi_message_add_tail(&st->xfer[0], &st->msg[AD7887_CH0]);
if (pdata && pdata->en_dual) {
st->tx_cmd_buf[0] |= AD7887_DUAL | AD7887_REF_DIS;
st->tx_cmd_buf[2] = AD7887_CH_AIN1 | AD7887_DUAL |
AD7887_REF_DIS | AD7887_PM_MODE4;
st->tx_cmd_buf[4] = AD7887_CH_AIN0 | AD7887_DUAL |
AD7887_REF_DIS | AD7887_PM_MODE4;
st->tx_cmd_buf[6] = AD7887_CH_AIN1 | AD7887_DUAL |
AD7887_REF_DIS | AD7887_PM_MODE4;
st->xfer[1].rx_buf = &st->data[0];
st->xfer[1].tx_buf = &st->tx_cmd_buf[2];
st->xfer[1].len = 2;
st->xfer[2].rx_buf = &st->data[2];
st->xfer[2].tx_buf = &st->tx_cmd_buf[4];
st->xfer[2].len = 2;
spi_message_init(&st->msg[AD7887_CH0_CH1]);
spi_message_add_tail(&st->xfer[1], &st->msg[AD7887_CH0_CH1]);
spi_message_add_tail(&st->xfer[2], &st->msg[AD7887_CH0_CH1]);
st->xfer[3].rx_buf = &st->data[0];
st->xfer[3].tx_buf = &st->tx_cmd_buf[6];
st->xfer[3].len = 2;
spi_message_init(&st->msg[AD7887_CH1]);
spi_message_add_tail(&st->xfer[3], &st->msg[AD7887_CH1]);
if (pdata && pdata->vref_mv)
st->int_vref_mv = pdata->vref_mv;
else if (voltage_uv)
st->int_vref_mv = voltage_uv / 1000;
else
dev_warn(&spi->dev, "reference voltage unspecified\n");
indio_dev->channels = st->chip_info->channel;
indio_dev->num_channels = 3;
} else {
if (pdata && pdata->vref_mv)
st->int_vref_mv = pdata->vref_mv;
else if (pdata && pdata->use_onchip_ref)
st->int_vref_mv = st->chip_info->int_vref_mv;
else
dev_warn(&spi->dev, "reference voltage unspecified\n");
indio_dev->channels = &st->chip_info->channel[1];
indio_dev->num_channels = 2;
}
ret = ad7887_register_ring_funcs_and_init(indio_dev);
if (ret)
goto error_disable_reg;
ret = iio_buffer_register(indio_dev,
indio_dev->channels,
indio_dev->num_channels);
if (ret)
goto error_cleanup_ring;
ret = iio_device_register(indio_dev);
if (ret)
goto error_unregister_ring;
return 0;
error_unregister_ring:
iio_buffer_unregister(indio_dev);
error_cleanup_ring:
ad7887_ring_cleanup(indio_dev);
error_disable_reg:
if (!IS_ERR(st->reg))
regulator_disable(st->reg);
error_put_reg:
if (!IS_ERR(st->reg))
regulator_put(st->reg);
iio_free_device(indio_dev);
return ret;
}
static int ad7887_remove(struct spi_device *spi)
{
struct iio_dev *indio_dev = spi_get_drvdata(spi);
struct ad7887_state *st = iio_priv(indio_dev);
iio_device_unregister(indio_dev);
iio_buffer_unregister(indio_dev);
ad7887_ring_cleanup(indio_dev);
if (!IS_ERR(st->reg)) {
regulator_disable(st->reg);
regulator_put(st->reg);
}
iio_free_device(indio_dev);
return 0;
}
static const struct spi_device_id ad7887_id[] = {
{"ad7887", ID_AD7887},
{}
};
MODULE_DEVICE_TABLE(spi, ad7887_id);
static struct spi_driver ad7887_driver = {
.driver = {
.name = "ad7887",
.owner = THIS_MODULE,
},
.probe = ad7887_probe,
.remove = __devexit_p(ad7887_remove),
.id_table = ad7887_id,
};
module_spi_driver(ad7887_driver);
MODULE_AUTHOR("Michael Hennerich <hennerich@blackfin.uclinux.org>");
MODULE_DESCRIPTION("Analog Devices AD7887 ADC");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
AKToronto/Bubba-Zombie | arch/arm/mm/fsr-3level.c | 6501 | 3487 | static struct fsr_info fsr_info[] = {
{ do_bad, SIGBUS, 0, "unknown 0" },
{ do_bad, SIGBUS, 0, "unknown 1" },
{ do_bad, SIGBUS, 0, "unknown 2" },
{ do_bad, SIGBUS, 0, "unknown 3" },
{ do_bad, SIGBUS, 0, "reserved translation fault" },
{ do_translation_fault, SIGSEGV, SEGV_MAPERR, "level 1 translation fault" },
{ do_translation_fault, SIGSEGV, SEGV_MAPERR, "level 2 translation fault" },
{ do_page_fault, SIGSEGV, SEGV_MAPERR, "level 3 translation fault" },
{ do_bad, SIGBUS, 0, "reserved access flag fault" },
{ do_bad, SIGSEGV, SEGV_ACCERR, "level 1 access flag fault" },
{ do_bad, SIGSEGV, SEGV_ACCERR, "level 2 access flag fault" },
{ do_page_fault, SIGSEGV, SEGV_ACCERR, "level 3 access flag fault" },
{ do_bad, SIGBUS, 0, "reserved permission fault" },
{ do_bad, SIGSEGV, SEGV_ACCERR, "level 1 permission fault" },
{ do_sect_fault, SIGSEGV, SEGV_ACCERR, "level 2 permission fault" },
{ do_page_fault, SIGSEGV, SEGV_ACCERR, "level 3 permission fault" },
{ do_bad, SIGBUS, 0, "synchronous external abort" },
{ do_bad, SIGBUS, 0, "asynchronous external abort" },
{ do_bad, SIGBUS, 0, "unknown 18" },
{ do_bad, SIGBUS, 0, "unknown 19" },
{ do_bad, SIGBUS, 0, "synchronous abort (translation table walk)" },
{ do_bad, SIGBUS, 0, "synchronous abort (translation table walk)" },
{ do_bad, SIGBUS, 0, "synchronous abort (translation table walk)" },
{ do_bad, SIGBUS, 0, "synchronous abort (translation table walk)" },
{ do_bad, SIGBUS, 0, "synchronous parity error" },
{ do_bad, SIGBUS, 0, "asynchronous parity error" },
{ do_bad, SIGBUS, 0, "unknown 26" },
{ do_bad, SIGBUS, 0, "unknown 27" },
{ do_bad, SIGBUS, 0, "synchronous parity error (translation table walk" },
{ do_bad, SIGBUS, 0, "synchronous parity error (translation table walk" },
{ do_bad, SIGBUS, 0, "synchronous parity error (translation table walk" },
{ do_bad, SIGBUS, 0, "synchronous parity error (translation table walk" },
{ do_bad, SIGBUS, 0, "unknown 32" },
{ do_bad, SIGBUS, BUS_ADRALN, "alignment fault" },
{ do_bad, SIGBUS, 0, "debug event" },
{ do_bad, SIGBUS, 0, "unknown 35" },
{ do_bad, SIGBUS, 0, "unknown 36" },
{ do_bad, SIGBUS, 0, "unknown 37" },
{ do_bad, SIGBUS, 0, "unknown 38" },
{ do_bad, SIGBUS, 0, "unknown 39" },
{ do_bad, SIGBUS, 0, "unknown 40" },
{ do_bad, SIGBUS, 0, "unknown 41" },
{ do_bad, SIGBUS, 0, "unknown 42" },
{ do_bad, SIGBUS, 0, "unknown 43" },
{ do_bad, SIGBUS, 0, "unknown 44" },
{ do_bad, SIGBUS, 0, "unknown 45" },
{ do_bad, SIGBUS, 0, "unknown 46" },
{ do_bad, SIGBUS, 0, "unknown 47" },
{ do_bad, SIGBUS, 0, "unknown 48" },
{ do_bad, SIGBUS, 0, "unknown 49" },
{ do_bad, SIGBUS, 0, "unknown 50" },
{ do_bad, SIGBUS, 0, "unknown 51" },
{ do_bad, SIGBUS, 0, "implementation fault (lockdown abort)" },
{ do_bad, SIGBUS, 0, "unknown 53" },
{ do_bad, SIGBUS, 0, "unknown 54" },
{ do_bad, SIGBUS, 0, "unknown 55" },
{ do_bad, SIGBUS, 0, "unknown 56" },
{ do_bad, SIGBUS, 0, "unknown 57" },
{ do_bad, SIGBUS, 0, "implementation fault (coprocessor abort)" },
{ do_bad, SIGBUS, 0, "unknown 59" },
{ do_bad, SIGBUS, 0, "unknown 60" },
{ do_bad, SIGBUS, 0, "unknown 61" },
{ do_bad, SIGBUS, 0, "unknown 62" },
{ do_bad, SIGBUS, 0, "unknown 63" },
};
#define ifsr_info fsr_info
| gpl-2.0 |
Jackeagle/kernel_samsung_stock | drivers/misc/sgi-xp/xp_uv.c | 14181 | 3985 | /*
* 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) 2008 Silicon Graphics, Inc. All Rights Reserved.
*/
/*
* Cross Partition (XP) uv-based functions.
*
* Architecture specific implementation of common functions.
*
*/
#include <linux/device.h>
#include <asm/uv/uv_hub.h>
#if defined CONFIG_X86_64
#include <asm/uv/bios.h>
#elif defined CONFIG_IA64_GENERIC || defined CONFIG_IA64_SGI_UV
#include <asm/sn/sn_sal.h>
#endif
#include "../sgi-gru/grukservices.h"
#include "xp.h"
/*
* Convert a virtual memory address to a physical memory address.
*/
static unsigned long
xp_pa_uv(void *addr)
{
return uv_gpa(addr);
}
/*
* Convert a global physical to socket physical address.
*/
static unsigned long
xp_socket_pa_uv(unsigned long gpa)
{
return uv_gpa_to_soc_phys_ram(gpa);
}
static enum xp_retval
xp_remote_mmr_read(unsigned long dst_gpa, const unsigned long src_gpa,
size_t len)
{
int ret;
unsigned long *dst_va = __va(uv_gpa_to_soc_phys_ram(dst_gpa));
BUG_ON(!uv_gpa_in_mmr_space(src_gpa));
BUG_ON(len != 8);
ret = gru_read_gpa(dst_va, src_gpa);
if (ret == 0)
return xpSuccess;
dev_err(xp, "gru_read_gpa() failed, dst_gpa=0x%016lx src_gpa=0x%016lx "
"len=%ld\n", dst_gpa, src_gpa, len);
return xpGruCopyError;
}
static enum xp_retval
xp_remote_memcpy_uv(unsigned long dst_gpa, const unsigned long src_gpa,
size_t len)
{
int ret;
if (uv_gpa_in_mmr_space(src_gpa))
return xp_remote_mmr_read(dst_gpa, src_gpa, len);
ret = gru_copy_gpa(dst_gpa, src_gpa, len);
if (ret == 0)
return xpSuccess;
dev_err(xp, "gru_copy_gpa() failed, dst_gpa=0x%016lx src_gpa=0x%016lx "
"len=%ld\n", dst_gpa, src_gpa, len);
return xpGruCopyError;
}
static int
xp_cpu_to_nasid_uv(int cpuid)
{
/* ??? Is this same as sn2 nasid in mach/part bitmaps set up by SAL? */
return UV_PNODE_TO_NASID(uv_cpu_to_pnode(cpuid));
}
static enum xp_retval
xp_expand_memprotect_uv(unsigned long phys_addr, unsigned long size)
{
int ret;
#if defined CONFIG_X86_64
ret = uv_bios_change_memprotect(phys_addr, size, UV_MEMPROT_ALLOW_RW);
if (ret != BIOS_STATUS_SUCCESS) {
dev_err(xp, "uv_bios_change_memprotect(,, "
"UV_MEMPROT_ALLOW_RW) failed, ret=%d\n", ret);
return xpBiosError;
}
#elif defined CONFIG_IA64_GENERIC || defined CONFIG_IA64_SGI_UV
u64 nasid_array;
ret = sn_change_memprotect(phys_addr, size, SN_MEMPROT_ACCESS_CLASS_1,
&nasid_array);
if (ret != 0) {
dev_err(xp, "sn_change_memprotect(,, "
"SN_MEMPROT_ACCESS_CLASS_1,) failed ret=%d\n", ret);
return xpSalError;
}
#else
#error not a supported configuration
#endif
return xpSuccess;
}
static enum xp_retval
xp_restrict_memprotect_uv(unsigned long phys_addr, unsigned long size)
{
int ret;
#if defined CONFIG_X86_64
ret = uv_bios_change_memprotect(phys_addr, size,
UV_MEMPROT_RESTRICT_ACCESS);
if (ret != BIOS_STATUS_SUCCESS) {
dev_err(xp, "uv_bios_change_memprotect(,, "
"UV_MEMPROT_RESTRICT_ACCESS) failed, ret=%d\n", ret);
return xpBiosError;
}
#elif defined CONFIG_IA64_GENERIC || defined CONFIG_IA64_SGI_UV
u64 nasid_array;
ret = sn_change_memprotect(phys_addr, size, SN_MEMPROT_ACCESS_CLASS_0,
&nasid_array);
if (ret != 0) {
dev_err(xp, "sn_change_memprotect(,, "
"SN_MEMPROT_ACCESS_CLASS_0,) failed ret=%d\n", ret);
return xpSalError;
}
#else
#error not a supported configuration
#endif
return xpSuccess;
}
enum xp_retval
xp_init_uv(void)
{
BUG_ON(!is_uv());
xp_max_npartitions = XP_MAX_NPARTITIONS_UV;
xp_partition_id = sn_partition_id;
xp_region_size = sn_region_size;
xp_pa = xp_pa_uv;
xp_socket_pa = xp_socket_pa_uv;
xp_remote_memcpy = xp_remote_memcpy_uv;
xp_cpu_to_nasid = xp_cpu_to_nasid_uv;
xp_expand_memprotect = xp_expand_memprotect_uv;
xp_restrict_memprotect = xp_restrict_memprotect_uv;
return xpSuccess;
}
void
xp_exit_uv(void)
{
BUG_ON(!is_uv());
}
| gpl-2.0 |
kavishme/kvm | ubuntu/i915/i915_gem_debug.c | 102 | 2209 | /*
* Copyright © 2008 Intel Corporation
*
* 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 (including the next
* paragraph) 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 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.
*
* Authors:
* Keith Packard <keithp@keithp.com>
*
*/
#include <drm/drmP.h>
#include <drm/i915_drm.h>
#include "i915_drv.h"
#if WATCH_LISTS
int
i915_verify_lists(struct drm_device *dev)
{
static int warned;
struct drm_i915_private *dev_priv = to_i915(dev);
struct drm_i915_gem_object *obj;
struct intel_engine_cs *engine;
int err = 0;
if (warned)
return 0;
for_each_engine(engine, dev_priv) {
list_for_each_entry(obj, &engine->active_list,
engine_list[engine->id]) {
if (obj->base.dev != dev ||
!atomic_read(&obj->base.refcount.refcount)) {
DRM_ERROR("%s: freed active obj %p\n",
engine->name, obj);
err++;
break;
} else if (!obj->active ||
obj->last_read_req[engine->id] == NULL) {
DRM_ERROR("%s: invalid active obj %p\n",
engine->name, obj);
err++;
} else if (obj->base.write_domain) {
DRM_ERROR("%s: invalid write obj %p (w %x)\n",
engine->name,
obj, obj->base.write_domain);
err++;
}
}
}
return warned = err;
}
#endif /* WATCH_LIST */
| gpl-2.0 |
Split-Screen/android_kernel_samsung_exynos5410 | fs/sdcardfs/file.c | 102 | 9765 | /*
* fs/sdcardfs/file.c
*
* Copyright (c) 2013 Samsung Electronics Co. Ltd
* Authors: Daeho Jeong, Woojoong Lee, Seunghwan Hyun,
* Sunghwan Yun, Sungjong Seo
*
* This program has been developed as a stackable file system based on
* the WrapFS which written by
*
* Copyright (c) 1998-2011 Erez Zadok
* Copyright (c) 2009 Shrikar Archak
* Copyright (c) 2003-2011 Stony Brook University
* Copyright (c) 2003-2011 The Research Foundation of SUNY
*
* This file is dual licensed. It may be redistributed and/or modified
* under the terms of the Apache 2.0 License OR version 2 of the GNU
* General Public License.
*/
#include "sdcardfs.h"
#ifdef CONFIG_SDCARD_FS_FADV_NOACTIVE
#include <linux/backing-dev.h>
#endif
static ssize_t sdcardfs_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
int err;
struct file *lower_file;
struct dentry *dentry = file->f_path.dentry;
#ifdef CONFIG_SDCARD_FS_FADV_NOACTIVE
struct backing_dev_info *bdi;
#endif
lower_file = sdcardfs_lower_file(file);
#ifdef CONFIG_SDCARD_FS_FADV_NOACTIVE
if (file->f_mode & FMODE_NOACTIVE) {
if (!(lower_file->f_mode & FMODE_NOACTIVE)) {
bdi = lower_file->f_mapping->backing_dev_info;
lower_file->f_ra.ra_pages = bdi->ra_pages * 2;
spin_lock(&lower_file->f_lock);
lower_file->f_mode |= FMODE_NOACTIVE;
spin_unlock(&lower_file->f_lock);
}
}
#endif
err = vfs_read(lower_file, buf, count, ppos);
/* update our inode atime upon a successful lower read */
if (err >= 0)
fsstack_copy_attr_atime(dentry->d_inode,
lower_file->f_path.dentry->d_inode);
return err;
}
static ssize_t sdcardfs_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
int err = 0;
struct file *lower_file;
struct dentry *dentry = file->f_path.dentry;
/* check disk space */
if (!check_min_free_space(dentry, count, 0)) {
printk(KERN_INFO "No minimum free space.\n");
return -ENOSPC;
}
lower_file = sdcardfs_lower_file(file);
err = vfs_write(lower_file, buf, count, ppos);
/* update our inode times+sizes upon a successful lower write */
if (err >= 0) {
fsstack_copy_inode_size(dentry->d_inode,
lower_file->f_path.dentry->d_inode);
fsstack_copy_attr_times(dentry->d_inode,
lower_file->f_path.dentry->d_inode);
}
return err;
}
static int sdcardfs_readdir(struct file *file, void *dirent, filldir_t filldir)
{
int err = 0;
struct file *lower_file = NULL;
struct dentry *dentry = file->f_path.dentry;
lower_file = sdcardfs_lower_file(file);
lower_file->f_pos = file->f_pos;
err = vfs_readdir(lower_file, filldir, dirent);
file->f_pos = lower_file->f_pos;
if (err >= 0) /* copy the atime */
fsstack_copy_attr_atime(dentry->d_inode,
lower_file->f_path.dentry->d_inode);
return err;
}
static long sdcardfs_unlocked_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
long err = -ENOTTY;
struct file *lower_file;
lower_file = sdcardfs_lower_file(file);
/* XXX: use vfs_ioctl if/when VFS exports it */
if (!lower_file || !lower_file->f_op)
goto out;
if (lower_file->f_op->unlocked_ioctl)
err = lower_file->f_op->unlocked_ioctl(lower_file, cmd, arg);
out:
return err;
}
#ifdef CONFIG_COMPAT
static long sdcardfs_compat_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
long err = -ENOTTY;
struct file *lower_file;
lower_file = sdcardfs_lower_file(file);
/* XXX: use vfs_ioctl if/when VFS exports it */
if (!lower_file || !lower_file->f_op)
goto out;
if (lower_file->f_op->compat_ioctl)
err = lower_file->f_op->compat_ioctl(lower_file, cmd, arg);
out:
return err;
}
#endif
static int sdcardfs_mmap(struct file *file, struct vm_area_struct *vma)
{
int err = 0;
bool willwrite;
struct file *lower_file;
const struct vm_operations_struct *saved_vm_ops = NULL;
/* this might be deferred to mmap's writepage */
willwrite = ((vma->vm_flags | VM_SHARED | VM_WRITE) == vma->vm_flags);
/*
* File systems which do not implement ->writepage may use
* generic_file_readonly_mmap as their ->mmap op. If you call
* generic_file_readonly_mmap with VM_WRITE, you'd get an -EINVAL.
* But we cannot call the lower ->mmap op, so we can't tell that
* writeable mappings won't work. Therefore, our only choice is to
* check if the lower file system supports the ->writepage, and if
* not, return EINVAL (the same error that
* generic_file_readonly_mmap returns in that case).
*/
lower_file = sdcardfs_lower_file(file);
if (willwrite && !lower_file->f_mapping->a_ops->writepage) {
err = -EINVAL;
printk(KERN_ERR "sdcardfs: lower file system does not "
"support writeable mmap\n");
goto out;
}
/*
* find and save lower vm_ops.
*
* XXX: the VFS should have a cleaner way of finding the lower vm_ops
*/
if (!SDCARDFS_F(file)->lower_vm_ops) {
err = lower_file->f_op->mmap(lower_file, vma);
if (err) {
printk(KERN_ERR "sdcardfs: lower mmap failed %d\n", err);
goto out;
}
saved_vm_ops = vma->vm_ops; /* save: came from lower ->mmap */
err = do_munmap(current->mm, vma->vm_start,
vma->vm_end - vma->vm_start);
if (err) {
printk(KERN_ERR "sdcardfs: do_munmap failed %d\n", err);
goto out;
}
}
/*
* Next 3 lines are all I need from generic_file_mmap. I definitely
* don't want its test for ->readpage which returns -ENOEXEC.
*/
file_accessed(file);
vma->vm_ops = &sdcardfs_vm_ops;
vma->vm_flags |= VM_CAN_NONLINEAR;
file->f_mapping->a_ops = &sdcardfs_aops; /* set our aops */
if (!SDCARDFS_F(file)->lower_vm_ops) /* save for our ->fault */
SDCARDFS_F(file)->lower_vm_ops = saved_vm_ops;
out:
return err;
}
static int sdcardfs_open(struct inode *inode, struct file *file)
{
int err = 0;
struct file *lower_file = NULL;
struct path lower_path;
struct dentry *dentry = file->f_path.dentry;
struct dentry *parent = dget_parent(dentry);
struct sdcardfs_sb_info *sbi = SDCARDFS_SB(dentry->d_sb);
const struct cred *saved_cred = NULL;
int has_rw;
/* don't open unhashed/deleted files */
if (d_unhashed(dentry)) {
err = -ENOENT;
goto out_err;
}
has_rw = get_caller_has_rw_locked(sbi->pkgl_id, sbi->options.derive);
if(!check_caller_access_to_name(parent->d_inode, dentry->d_name.name,
sbi->options.derive,
open_flags_to_access_mode(file->f_flags), has_rw)) {
printk(KERN_INFO "%s: need to check the caller's gid in packages.list\n"
" dentry: %s, task:%s\n",
__func__, dentry->d_name.name, current->comm);
err = -EACCES;
goto out_err;
}
/* save current_cred and override it */
OVERRIDE_CRED(sbi, saved_cred);
file->private_data =
kzalloc(sizeof(struct sdcardfs_file_info), GFP_KERNEL);
if (!SDCARDFS_F(file)) {
err = -ENOMEM;
goto out_revert_cred;
}
/* open lower object and link sdcardfs's file struct to lower's */
sdcardfs_get_lower_path(file->f_path.dentry, &lower_path);
lower_file = dentry_open(lower_path.dentry, lower_path.mnt,
file->f_flags, current_cred());
if (IS_ERR(lower_file)) {
err = PTR_ERR(lower_file);
lower_file = sdcardfs_lower_file(file);
if (lower_file) {
sdcardfs_set_lower_file(file, NULL);
fput(lower_file); /* fput calls dput for lower_dentry */
}
} else {
sdcardfs_set_lower_file(file, lower_file);
}
if (err)
kfree(SDCARDFS_F(file));
else {
mutex_lock(&inode->i_mutex);
sdcardfs_copy_inode_attr(inode, sdcardfs_lower_inode(inode));
fix_derived_permission(inode);
mutex_unlock(&inode->i_mutex);
}
out_revert_cred:
REVERT_CRED(saved_cred);
out_err:
dput(parent);
return err;
}
static int sdcardfs_flush(struct file *file, fl_owner_t id)
{
int err = 0;
struct file *lower_file = NULL;
lower_file = sdcardfs_lower_file(file);
if (lower_file && lower_file->f_op && lower_file->f_op->flush)
err = lower_file->f_op->flush(lower_file, id);
return err;
}
/* release all lower object references & free the file info structure */
static int sdcardfs_file_release(struct inode *inode, struct file *file)
{
struct file *lower_file;
lower_file = sdcardfs_lower_file(file);
if (lower_file) {
sdcardfs_set_lower_file(file, NULL);
fput(lower_file);
}
kfree(SDCARDFS_F(file));
return 0;
}
static int
sdcardfs_fsync(struct file *file, loff_t start, loff_t end, int datasync)
{
int err;
struct file *lower_file;
struct path lower_path;
struct dentry *dentry = file->f_path.dentry;
lower_file = sdcardfs_lower_file(file);
sdcardfs_get_lower_path(dentry, &lower_path);
err = vfs_fsync_range(lower_file, start, end, datasync);
sdcardfs_put_lower_path(dentry, &lower_path);
return err;
}
static int sdcardfs_fasync(int fd, struct file *file, int flag)
{
int err = 0;
struct file *lower_file = NULL;
lower_file = sdcardfs_lower_file(file);
if (lower_file->f_op && lower_file->f_op->fasync)
err = lower_file->f_op->fasync(fd, lower_file, flag);
return err;
}
const struct file_operations sdcardfs_main_fops = {
.llseek = generic_file_llseek,
.read = sdcardfs_read,
.write = sdcardfs_write,
.unlocked_ioctl = sdcardfs_unlocked_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = sdcardfs_compat_ioctl,
#endif
.mmap = sdcardfs_mmap,
.open = sdcardfs_open,
.flush = sdcardfs_flush,
.release = sdcardfs_file_release,
.fsync = sdcardfs_fsync,
.fasync = sdcardfs_fasync,
};
/* trimmed directory options */
const struct file_operations sdcardfs_dir_fops = {
.llseek = generic_file_llseek,
.read = generic_read_dir,
.readdir = sdcardfs_readdir,
.unlocked_ioctl = sdcardfs_unlocked_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = sdcardfs_compat_ioctl,
#endif
.open = sdcardfs_open,
.release = sdcardfs_file_release,
.flush = sdcardfs_flush,
.fsync = sdcardfs_fsync,
.fasync = sdcardfs_fasync,
};
| gpl-2.0 |
salahuddin118/zswap | drivers/media/media-device.c | 102 | 11591 | /*
* Media device
*
* Copyright (C) 2010 Nokia Corporation
*
* Contacts: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
* Sakari Ailus <sakari.ailus@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/compat.h>
#include <linux/export.h>
#include <linux/ioctl.h>
#include <linux/media.h>
#include <linux/types.h>
#include <media/media-device.h>
#include <media/media-devnode.h>
#include <media/media-entity.h>
/* -----------------------------------------------------------------------------
* Userspace API
*/
static int media_device_open(struct file *filp)
{
return 0;
}
static int media_device_close(struct file *filp)
{
return 0;
}
static int media_device_get_info(struct media_device *dev,
struct media_device_info __user *__info)
{
struct media_device_info info;
memset(&info, 0, sizeof(info));
strlcpy(info.driver, dev->dev->driver->name, sizeof(info.driver));
strlcpy(info.model, dev->model, sizeof(info.model));
strlcpy(info.serial, dev->serial, sizeof(info.serial));
strlcpy(info.bus_info, dev->bus_info, sizeof(info.bus_info));
info.media_version = MEDIA_API_VERSION;
info.hw_revision = dev->hw_revision;
info.driver_version = dev->driver_version;
if (copy_to_user(__info, &info, sizeof(*__info)))
return -EFAULT;
return 0;
}
static struct media_entity *find_entity(struct media_device *mdev, u32 id)
{
struct media_entity *entity;
int next = id & MEDIA_ENT_ID_FLAG_NEXT;
id &= ~MEDIA_ENT_ID_FLAG_NEXT;
spin_lock(&mdev->lock);
media_device_for_each_entity(entity, mdev) {
if ((entity->id == id && !next) ||
(entity->id > id && next)) {
spin_unlock(&mdev->lock);
return entity;
}
}
spin_unlock(&mdev->lock);
return NULL;
}
static long media_device_enum_entities(struct media_device *mdev,
struct media_entity_desc __user *uent)
{
struct media_entity *ent;
struct media_entity_desc u_ent;
memset(&u_ent, 0, sizeof(u_ent));
if (copy_from_user(&u_ent.id, &uent->id, sizeof(u_ent.id)))
return -EFAULT;
ent = find_entity(mdev, u_ent.id);
if (ent == NULL)
return -EINVAL;
u_ent.id = ent->id;
if (ent->name) {
strncpy(u_ent.name, ent->name, sizeof(u_ent.name));
u_ent.name[sizeof(u_ent.name) - 1] = '\0';
} else {
memset(u_ent.name, 0, sizeof(u_ent.name));
}
u_ent.type = ent->type;
u_ent.revision = ent->revision;
u_ent.flags = ent->flags;
u_ent.group_id = ent->group_id;
u_ent.pads = ent->num_pads;
u_ent.links = ent->num_links - ent->num_backlinks;
memcpy(&u_ent.raw, &ent->info, sizeof(ent->info));
if (copy_to_user(uent, &u_ent, sizeof(u_ent)))
return -EFAULT;
return 0;
}
static void media_device_kpad_to_upad(const struct media_pad *kpad,
struct media_pad_desc *upad)
{
upad->entity = kpad->entity->id;
upad->index = kpad->index;
upad->flags = kpad->flags;
}
static long __media_device_enum_links(struct media_device *mdev,
struct media_links_enum *links)
{
struct media_entity *entity;
entity = find_entity(mdev, links->entity);
if (entity == NULL)
return -EINVAL;
if (links->pads) {
unsigned int p;
for (p = 0; p < entity->num_pads; p++) {
struct media_pad_desc pad;
media_device_kpad_to_upad(&entity->pads[p], &pad);
if (copy_to_user(&links->pads[p], &pad, sizeof(pad)))
return -EFAULT;
}
}
if (links->links) {
struct media_link_desc __user *ulink;
unsigned int l;
for (l = 0, ulink = links->links; l < entity->num_links; l++) {
struct media_link_desc link;
/* Ignore backlinks. */
if (entity->links[l].source->entity != entity)
continue;
media_device_kpad_to_upad(entity->links[l].source,
&link.source);
media_device_kpad_to_upad(entity->links[l].sink,
&link.sink);
link.flags = entity->links[l].flags;
if (copy_to_user(ulink, &link, sizeof(*ulink)))
return -EFAULT;
ulink++;
}
}
return 0;
}
static long media_device_enum_links(struct media_device *mdev,
struct media_links_enum __user *ulinks)
{
struct media_links_enum links;
int rval;
if (copy_from_user(&links, ulinks, sizeof(links)))
return -EFAULT;
rval = __media_device_enum_links(mdev, &links);
if (rval < 0)
return rval;
if (copy_to_user(ulinks, &links, sizeof(*ulinks)))
return -EFAULT;
return 0;
}
static long media_device_setup_link(struct media_device *mdev,
struct media_link_desc __user *_ulink)
{
struct media_link *link = NULL;
struct media_link_desc ulink;
struct media_entity *source;
struct media_entity *sink;
int ret;
if (copy_from_user(&ulink, _ulink, sizeof(ulink)))
return -EFAULT;
/* Find the source and sink entities and link.
*/
source = find_entity(mdev, ulink.source.entity);
sink = find_entity(mdev, ulink.sink.entity);
if (source == NULL || sink == NULL)
return -EINVAL;
if (ulink.source.index >= source->num_pads ||
ulink.sink.index >= sink->num_pads)
return -EINVAL;
link = media_entity_find_link(&source->pads[ulink.source.index],
&sink->pads[ulink.sink.index]);
if (link == NULL)
return -EINVAL;
/* Setup the link on both entities. */
ret = __media_entity_setup_link(link, ulink.flags);
if (copy_to_user(_ulink, &ulink, sizeof(ulink)))
return -EFAULT;
return ret;
}
static long media_device_ioctl(struct file *filp, unsigned int cmd,
unsigned long arg)
{
struct media_devnode *devnode = media_devnode_data(filp);
struct media_device *dev = to_media_device(devnode);
long ret;
switch (cmd) {
case MEDIA_IOC_DEVICE_INFO:
ret = media_device_get_info(dev,
(struct media_device_info __user *)arg);
break;
case MEDIA_IOC_ENUM_ENTITIES:
ret = media_device_enum_entities(dev,
(struct media_entity_desc __user *)arg);
break;
case MEDIA_IOC_ENUM_LINKS:
mutex_lock(&dev->graph_mutex);
ret = media_device_enum_links(dev,
(struct media_links_enum __user *)arg);
mutex_unlock(&dev->graph_mutex);
break;
case MEDIA_IOC_SETUP_LINK:
mutex_lock(&dev->graph_mutex);
ret = media_device_setup_link(dev,
(struct media_link_desc __user *)arg);
mutex_unlock(&dev->graph_mutex);
break;
default:
ret = -ENOIOCTLCMD;
}
return ret;
}
#ifdef CONFIG_COMPAT
struct media_links_enum32 {
__u32 entity;
compat_uptr_t pads; /* struct media_pad_desc * */
compat_uptr_t links; /* struct media_link_desc * */
__u32 reserved[4];
};
static long media_device_enum_links32(struct media_device *mdev,
struct media_links_enum32 __user *ulinks)
{
struct media_links_enum links;
compat_uptr_t pads_ptr, links_ptr;
memset(&links, 0, sizeof(links));
if (get_user(links.entity, &ulinks->entity)
|| get_user(pads_ptr, &ulinks->pads)
|| get_user(links_ptr, &ulinks->links))
return -EFAULT;
links.pads = compat_ptr(pads_ptr);
links.links = compat_ptr(links_ptr);
return __media_device_enum_links(mdev, &links);
}
#define MEDIA_IOC_ENUM_LINKS32 _IOWR('|', 0x02, struct media_links_enum32)
static long media_device_compat_ioctl(struct file *filp, unsigned int cmd,
unsigned long arg)
{
struct media_devnode *devnode = media_devnode_data(filp);
struct media_device *dev = to_media_device(devnode);
long ret;
switch (cmd) {
case MEDIA_IOC_DEVICE_INFO:
case MEDIA_IOC_ENUM_ENTITIES:
case MEDIA_IOC_SETUP_LINK:
return media_device_ioctl(filp, cmd, arg);
case MEDIA_IOC_ENUM_LINKS32:
mutex_lock(&dev->graph_mutex);
ret = media_device_enum_links32(dev,
(struct media_links_enum32 __user *)arg);
mutex_unlock(&dev->graph_mutex);
break;
default:
ret = -ENOIOCTLCMD;
}
return ret;
}
#endif /* CONFIG_COMPAT */
static const struct media_file_operations media_device_fops = {
.owner = THIS_MODULE,
.open = media_device_open,
.ioctl = media_device_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = media_device_compat_ioctl,
#endif /* CONFIG_COMPAT */
.release = media_device_close,
};
/* -----------------------------------------------------------------------------
* sysfs
*/
static ssize_t show_model(struct device *cd,
struct device_attribute *attr, char *buf)
{
struct media_device *mdev = to_media_device(to_media_devnode(cd));
return sprintf(buf, "%.*s\n", (int)sizeof(mdev->model), mdev->model);
}
static DEVICE_ATTR(model, S_IRUGO, show_model, NULL);
/* -----------------------------------------------------------------------------
* Registration/unregistration
*/
static void media_device_release(struct media_devnode *mdev)
{
}
/**
* media_device_register - register a media device
* @mdev: The media device
*
* The caller is responsible for initializing the media device before
* registration. The following fields must be set:
*
* - dev must point to the parent device
* - model must be filled with the device model name
*/
int __must_check media_device_register(struct media_device *mdev)
{
int ret;
if (WARN_ON(mdev->dev == NULL || mdev->model[0] == 0))
return -EINVAL;
mdev->entity_id = 1;
INIT_LIST_HEAD(&mdev->entities);
spin_lock_init(&mdev->lock);
mutex_init(&mdev->graph_mutex);
/* Register the device node. */
mdev->devnode.fops = &media_device_fops;
mdev->devnode.parent = mdev->dev;
mdev->devnode.release = media_device_release;
ret = media_devnode_register(&mdev->devnode);
if (ret < 0)
return ret;
ret = device_create_file(&mdev->devnode.dev, &dev_attr_model);
if (ret < 0) {
media_devnode_unregister(&mdev->devnode);
return ret;
}
return 0;
}
EXPORT_SYMBOL_GPL(media_device_register);
/**
* media_device_unregister - unregister a media device
* @mdev: The media device
*
*/
void media_device_unregister(struct media_device *mdev)
{
struct media_entity *entity;
struct media_entity *next;
list_for_each_entry_safe(entity, next, &mdev->entities, list)
media_device_unregister_entity(entity);
device_remove_file(&mdev->devnode.dev, &dev_attr_model);
media_devnode_unregister(&mdev->devnode);
}
EXPORT_SYMBOL_GPL(media_device_unregister);
/**
* media_device_register_entity - Register an entity with a media device
* @mdev: The media device
* @entity: The entity
*/
int __must_check media_device_register_entity(struct media_device *mdev,
struct media_entity *entity)
{
/* Warn if we apparently re-register an entity */
WARN_ON(entity->parent != NULL);
entity->parent = mdev;
spin_lock(&mdev->lock);
if (entity->id == 0)
entity->id = mdev->entity_id++;
else
mdev->entity_id = max(entity->id + 1, mdev->entity_id);
list_add_tail(&entity->list, &mdev->entities);
spin_unlock(&mdev->lock);
return 0;
}
EXPORT_SYMBOL_GPL(media_device_register_entity);
/**
* media_device_unregister_entity - Unregister an entity
* @entity: The entity
*
* If the entity has never been registered this function will return
* immediately.
*/
void media_device_unregister_entity(struct media_entity *entity)
{
struct media_device *mdev = entity->parent;
if (mdev == NULL)
return;
spin_lock(&mdev->lock);
list_del(&entity->list);
spin_unlock(&mdev->lock);
entity->parent = NULL;
}
EXPORT_SYMBOL_GPL(media_device_unregister_entity);
| gpl-2.0 |
lnfamous/Kernel_Stock_Pico | kernel/watchdog.c | 102 | 13924 | /*
* Detect hard and soft lockups on a system
*
* started by Don Zickus, Copyright (C) 2010 Red Hat, Inc.
*
* this code detects hard lockups: incidents in where on a CPU
* the kernel does not respond to anything except NMI.
*
* Note: Most of this code is borrowed heavily from softlockup.c,
* so thanks to Ingo for the initial implementation.
* Some chunks also taken from arch/x86/kernel/apic/nmi.c, thanks
* to those contributors as well.
*/
#include <linux/mm.h>
#include <linux/cpu.h>
#include <linux/nmi.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/freezer.h>
#include <linux/kthread.h>
#include <linux/lockdep.h>
#include <linux/notifier.h>
#include <linux/module.h>
#include <linux/sysctl.h>
#include <asm/irq_regs.h>
#include <linux/perf_event.h>
int watchdog_enabled = 1;
int __read_mostly softlockup_thresh = 60;
static DEFINE_PER_CPU(unsigned long, watchdog_touch_ts);
static DEFINE_PER_CPU(struct task_struct *, softlockup_watchdog);
static DEFINE_PER_CPU(struct hrtimer, watchdog_hrtimer);
static DEFINE_PER_CPU(bool, softlockup_touch_sync);
static DEFINE_PER_CPU(bool, soft_watchdog_warn);
#ifdef CONFIG_HARDLOCKUP_DETECTOR
static DEFINE_PER_CPU(bool, hard_watchdog_warn);
static DEFINE_PER_CPU(bool, watchdog_nmi_touch);
static DEFINE_PER_CPU(unsigned long, hrtimer_interrupts);
static DEFINE_PER_CPU(unsigned long, hrtimer_interrupts_saved);
static DEFINE_PER_CPU(struct perf_event *, watchdog_ev);
#endif
/* boot commands */
/*
* Should we panic when a soft-lockup or hard-lockup occurs:
*/
#ifdef CONFIG_HARDLOCKUP_DETECTOR
static int hardlockup_panic;
static int __init hardlockup_panic_setup(char *str)
{
if (!strncmp(str, "panic", 5))
hardlockup_panic = 1;
else if (!strncmp(str, "0", 1))
watchdog_enabled = 0;
return 1;
}
__setup("nmi_watchdog=", hardlockup_panic_setup);
#endif
unsigned int __read_mostly softlockup_panic =
CONFIG_BOOTPARAM_SOFTLOCKUP_PANIC_VALUE;
static int __init softlockup_panic_setup(char *str)
{
softlockup_panic = simple_strtoul(str, NULL, 0);
return 1;
}
__setup("softlockup_panic=", softlockup_panic_setup);
static int __init nowatchdog_setup(char *str)
{
watchdog_enabled = 0;
return 1;
}
__setup("nowatchdog", nowatchdog_setup);
/* deprecated */
static int __init nosoftlockup_setup(char *str)
{
watchdog_enabled = 0;
return 1;
}
__setup("nosoftlockup", nosoftlockup_setup);
/* */
/*
* Returns seconds, approximately. We don't need nanosecond
* resolution, and we don't need to waste time with a big divide when
* 2^30ns == 1.074s.
*/
static unsigned long get_timestamp(int this_cpu)
{
return cpu_clock(this_cpu) >> 30LL; /* 2^30 ~= 10^9 */
}
static unsigned long get_sample_period(void)
{
/*
* convert softlockup_thresh from seconds to ns
* the divide by 5 is to give hrtimer 5 chances to
* increment before the hardlockup detector generates
* a warning
*/
return softlockup_thresh / 5 * NSEC_PER_SEC;
}
/* Commands for resetting the watchdog */
static void __touch_watchdog(void)
{
int this_cpu = smp_processor_id();
__this_cpu_write(watchdog_touch_ts, get_timestamp(this_cpu));
}
void touch_softlockup_watchdog(void)
{
__this_cpu_write(watchdog_touch_ts, 0);
}
EXPORT_SYMBOL(touch_softlockup_watchdog);
void touch_all_softlockup_watchdogs(void)
{
int cpu;
/*
* this is done lockless
* do we care if a 0 races with a timestamp?
* all it means is the softlock check starts one cycle later
*/
for_each_online_cpu(cpu)
per_cpu(watchdog_touch_ts, cpu) = 0;
}
#ifdef CONFIG_HARDLOCKUP_DETECTOR
void touch_nmi_watchdog(void)
{
if (watchdog_enabled) {
unsigned cpu;
for_each_present_cpu(cpu) {
if (per_cpu(watchdog_nmi_touch, cpu) != true)
per_cpu(watchdog_nmi_touch, cpu) = true;
}
}
touch_softlockup_watchdog();
}
EXPORT_SYMBOL(touch_nmi_watchdog);
#endif
void touch_softlockup_watchdog_sync(void)
{
__raw_get_cpu_var(softlockup_touch_sync) = true;
__raw_get_cpu_var(watchdog_touch_ts) = 0;
}
#ifdef CONFIG_HARDLOCKUP_DETECTOR
/* watchdog detector functions */
static int is_hardlockup(void)
{
unsigned long hrint = __this_cpu_read(hrtimer_interrupts);
if (__this_cpu_read(hrtimer_interrupts_saved) == hrint)
return 1;
__this_cpu_write(hrtimer_interrupts_saved, hrint);
return 0;
}
#endif
static int is_softlockup(unsigned long touch_ts)
{
unsigned long now = get_timestamp(smp_processor_id());
/* Warn about unreasonable delays: */
if (time_after(now, touch_ts + softlockup_thresh))
return now - touch_ts;
return 0;
}
#ifdef CONFIG_HARDLOCKUP_DETECTOR
static struct perf_event_attr wd_hw_attr = {
.type = PERF_TYPE_HARDWARE,
.config = PERF_COUNT_HW_CPU_CYCLES,
.size = sizeof(struct perf_event_attr),
.pinned = 1,
.disabled = 1,
};
/* Callback function for perf event subsystem */
static void watchdog_overflow_callback(struct perf_event *event, int nmi,
struct perf_sample_data *data,
struct pt_regs *regs)
{
/* Ensure the watchdog never gets throttled */
event->hw.interrupts = 0;
if (__this_cpu_read(watchdog_nmi_touch) == true) {
__this_cpu_write(watchdog_nmi_touch, false);
return;
}
/* check for a hardlockup
* This is done by making sure our timer interrupt
* is incrementing. The timer interrupt should have
* fired multiple times before we overflow'd. If it hasn't
* then this is a good indication the cpu is stuck
*/
if (is_hardlockup()) {
int this_cpu = smp_processor_id();
/* only print hardlockups once */
if (__this_cpu_read(hard_watchdog_warn) == true)
return;
if (hardlockup_panic)
panic("Watchdog detected hard LOCKUP on cpu %d", this_cpu);
else
WARN(1, "Watchdog detected hard LOCKUP on cpu %d", this_cpu);
__this_cpu_write(hard_watchdog_warn, true);
return;
}
__this_cpu_write(hard_watchdog_warn, false);
return;
}
static void watchdog_interrupt_count(void)
{
__this_cpu_inc(hrtimer_interrupts);
}
#else
static inline void watchdog_interrupt_count(void) { return; }
#endif /* CONFIG_HARDLOCKUP_DETECTOR */
/* watchdog kicker functions */
static enum hrtimer_restart watchdog_timer_fn(struct hrtimer *hrtimer)
{
unsigned long touch_ts = __this_cpu_read(watchdog_touch_ts);
struct pt_regs *regs = get_irq_regs();
int duration;
/* kick the hardlockup detector */
watchdog_interrupt_count();
/* kick the softlockup detector */
wake_up_process(__this_cpu_read(softlockup_watchdog));
/* .. and repeat */
hrtimer_forward_now(hrtimer, ns_to_ktime(get_sample_period()));
if (touch_ts == 0) {
if (unlikely(__this_cpu_read(softlockup_touch_sync))) {
/*
* If the time stamp was touched atomically
* make sure the scheduler tick is up to date.
*/
__this_cpu_write(softlockup_touch_sync, false);
sched_clock_tick();
}
__touch_watchdog();
return HRTIMER_RESTART;
}
/* check for a softlockup
* This is done by making sure a high priority task is
* being scheduled. The task touches the watchdog to
* indicate it is getting cpu time. If it hasn't then
* this is a good indication some task is hogging the cpu
*/
duration = is_softlockup(touch_ts);
if (unlikely(duration)) {
/* only warn once */
if (__this_cpu_read(soft_watchdog_warn) == true)
return HRTIMER_RESTART;
printk(KERN_ERR "BUG: soft lockup - CPU#%d stuck for %us! [%s:%d]\n",
smp_processor_id(), duration,
current->comm, task_pid_nr(current));
print_modules();
print_irqtrace_events(current);
if (regs)
show_regs(regs);
else
dump_stack();
if (softlockup_panic)
panic("softlockup: hung tasks");
__this_cpu_write(soft_watchdog_warn, true);
} else
__this_cpu_write(soft_watchdog_warn, false);
return HRTIMER_RESTART;
}
/*
* The watchdog thread - touches the timestamp.
*/
static int watchdog(void *unused)
{
static struct sched_param param = { .sched_priority = MAX_RT_PRIO-1 };
struct hrtimer *hrtimer = &__raw_get_cpu_var(watchdog_hrtimer);
sched_setscheduler(current, SCHED_FIFO, ¶m);
/* initialize timestamp */
__touch_watchdog();
/* kick off the timer for the hardlockup detector */
/* done here because hrtimer_start can only pin to smp_processor_id() */
hrtimer_start(hrtimer, ns_to_ktime(get_sample_period()),
HRTIMER_MODE_REL_PINNED);
set_current_state(TASK_INTERRUPTIBLE);
/*
* Run briefly once per second to reset the softlockup timestamp.
* If this gets delayed for more than 60 seconds then the
* debug-printout triggers in watchdog_timer_fn().
*/
while (!kthread_should_stop()) {
__touch_watchdog();
schedule();
if (kthread_should_stop())
break;
set_current_state(TASK_INTERRUPTIBLE);
}
__set_current_state(TASK_RUNNING);
return 0;
}
#ifdef CONFIG_HARDLOCKUP_DETECTOR
static int watchdog_nmi_enable(int cpu)
{
struct perf_event_attr *wd_attr;
struct perf_event *event = per_cpu(watchdog_ev, cpu);
/* is it already setup and enabled? */
if (event && event->state > PERF_EVENT_STATE_OFF)
goto out;
/* it is setup but not enabled */
if (event != NULL)
goto out_enable;
/* Try to register using hardware perf events */
wd_attr = &wd_hw_attr;
wd_attr->sample_period = hw_nmi_get_sample_period();
event = perf_event_create_kernel_counter(wd_attr, cpu, NULL, watchdog_overflow_callback);
if (!IS_ERR(event)) {
printk(KERN_INFO "NMI watchdog enabled, takes one hw-pmu counter.\n");
goto out_save;
}
/* vary the KERN level based on the returned errno */
if (PTR_ERR(event) == -EOPNOTSUPP)
printk(KERN_INFO "NMI watchdog disabled (cpu%i): not supported (no LAPIC?)\n", cpu);
else if (PTR_ERR(event) == -ENOENT)
printk(KERN_WARNING "NMI watchdog disabled (cpu%i): hardware events not enabled\n", cpu);
else
printk(KERN_ERR "NMI watchdog disabled (cpu%i): unable to create perf event: %ld\n", cpu, PTR_ERR(event));
return PTR_ERR(event);
/* success path */
out_save:
per_cpu(watchdog_ev, cpu) = event;
out_enable:
perf_event_enable(per_cpu(watchdog_ev, cpu));
out:
return 0;
}
static void watchdog_nmi_disable(int cpu)
{
struct perf_event *event = per_cpu(watchdog_ev, cpu);
if (event) {
perf_event_disable(event);
per_cpu(watchdog_ev, cpu) = NULL;
/* should be in cleanup, but blocks oprofile */
perf_event_release_kernel(event);
}
return;
}
#else
static int watchdog_nmi_enable(int cpu) { return 0; }
static void watchdog_nmi_disable(int cpu) { return; }
#endif /* CONFIG_HARDLOCKUP_DETECTOR */
/* prepare/enable/disable routines */
static int watchdog_prepare_cpu(int cpu)
{
struct hrtimer *hrtimer = &per_cpu(watchdog_hrtimer, cpu);
WARN_ON(per_cpu(softlockup_watchdog, cpu));
hrtimer_init(hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
hrtimer->function = watchdog_timer_fn;
return 0;
}
static int watchdog_enable(int cpu)
{
struct task_struct *p = per_cpu(softlockup_watchdog, cpu);
int err;
/* enable the perf event */
err = watchdog_nmi_enable(cpu);
if (err)
return err;
/* create the watchdog thread */
if (!p) {
p = kthread_create(watchdog, (void *)(unsigned long)cpu, "watchdog/%d", cpu);
if (IS_ERR(p)) {
printk(KERN_ERR "softlockup watchdog for %i failed\n", cpu);
return PTR_ERR(p);
}
kthread_bind(p, cpu);
per_cpu(watchdog_touch_ts, cpu) = 0;
per_cpu(softlockup_watchdog, cpu) = p;
wake_up_process(p);
}
return 0;
}
static void watchdog_disable(int cpu)
{
struct task_struct *p = per_cpu(softlockup_watchdog, cpu);
struct hrtimer *hrtimer = &per_cpu(watchdog_hrtimer, cpu);
/*
* cancel the timer first to stop incrementing the stats
* and waking up the kthread
*/
hrtimer_cancel(hrtimer);
/* disable the perf event */
watchdog_nmi_disable(cpu);
/* stop the watchdog thread */
if (p) {
per_cpu(softlockup_watchdog, cpu) = NULL;
kthread_stop(p);
}
}
static void watchdog_enable_all_cpus(void)
{
int cpu;
watchdog_enabled = 0;
for_each_online_cpu(cpu)
if (!watchdog_enable(cpu))
/* if any cpu succeeds, watchdog is considered
enabled for the system */
watchdog_enabled = 1;
if (!watchdog_enabled)
printk(KERN_ERR "watchdog: failed to be enabled on some cpus\n");
}
static void watchdog_disable_all_cpus(void)
{
int cpu;
for_each_online_cpu(cpu)
watchdog_disable(cpu);
/* if all watchdogs are disabled, then they are disabled for the system */
watchdog_enabled = 0;
}
/* sysctl functions */
#ifdef CONFIG_SYSCTL
/*
* proc handler for /proc/sys/kernel/nmi_watchdog
*/
int proc_dowatchdog_enabled(struct ctl_table *table, int write,
void __user *buffer, size_t *length, loff_t *ppos)
{
proc_dointvec(table, write, buffer, length, ppos);
if (write) {
if (watchdog_enabled)
watchdog_enable_all_cpus();
else
watchdog_disable_all_cpus();
}
return 0;
}
int proc_dowatchdog_thresh(struct ctl_table *table, int write,
void __user *buffer,
size_t *lenp, loff_t *ppos)
{
return proc_dointvec_minmax(table, write, buffer, lenp, ppos);
}
#endif /* CONFIG_SYSCTL */
/*
* Create/destroy watchdog threads as CPUs come and go:
*/
static int __cpuinit
cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu)
{
int hotcpu = (unsigned long)hcpu;
int err = 0;
switch (action) {
case CPU_UP_PREPARE:
case CPU_UP_PREPARE_FROZEN:
err = watchdog_prepare_cpu(hotcpu);
break;
case CPU_ONLINE:
case CPU_ONLINE_FROZEN:
if (watchdog_enabled)
err = watchdog_enable(hotcpu);
break;
#ifdef CONFIG_HOTPLUG_CPU
case CPU_UP_CANCELED:
case CPU_UP_CANCELED_FROZEN:
watchdog_disable(hotcpu);
break;
case CPU_DEAD:
case CPU_DEAD_FROZEN:
watchdog_disable(hotcpu);
break;
#endif /* CONFIG_HOTPLUG_CPU */
}
return notifier_from_errno(err);
}
static struct notifier_block __cpuinitdata cpu_nfb = {
.notifier_call = cpu_callback
};
void __init lockup_detector_init(void)
{
void *cpu = (void *)(long)smp_processor_id();
int err;
err = cpu_callback(&cpu_nfb, CPU_UP_PREPARE, cpu);
WARN_ON(notifier_to_errno(err));
cpu_callback(&cpu_nfb, CPU_ONLINE, cpu);
register_cpu_notifier(&cpu_nfb);
return;
}
| gpl-2.0 |
qzhuyan/linux | sound/soc/codecs/jz4740.c | 102 | 10628 | /*
* Copyright (C) 2009-2010, Lars-Peter Clausen <lars@metafoo.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.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/io.h>
#include <linux/regmap.h>
#include <linux/delay.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/initval.h>
#include <sound/soc.h>
#include <sound/tlv.h>
#define JZ4740_REG_CODEC_1 0x0
#define JZ4740_REG_CODEC_2 0x4
#define JZ4740_CODEC_1_LINE_ENABLE BIT(29)
#define JZ4740_CODEC_1_MIC_ENABLE BIT(28)
#define JZ4740_CODEC_1_SW1_ENABLE BIT(27)
#define JZ4740_CODEC_1_ADC_ENABLE BIT(26)
#define JZ4740_CODEC_1_SW2_ENABLE BIT(25)
#define JZ4740_CODEC_1_DAC_ENABLE BIT(24)
#define JZ4740_CODEC_1_VREF_DISABLE BIT(20)
#define JZ4740_CODEC_1_VREF_AMP_DISABLE BIT(19)
#define JZ4740_CODEC_1_VREF_PULLDOWN BIT(18)
#define JZ4740_CODEC_1_VREF_LOW_CURRENT BIT(17)
#define JZ4740_CODEC_1_VREF_HIGH_CURRENT BIT(16)
#define JZ4740_CODEC_1_HEADPHONE_DISABLE BIT(14)
#define JZ4740_CODEC_1_HEADPHONE_AMP_CHANGE_ANY BIT(13)
#define JZ4740_CODEC_1_HEADPHONE_CHARGE BIT(12)
#define JZ4740_CODEC_1_HEADPHONE_PULLDOWN (BIT(11) | BIT(10))
#define JZ4740_CODEC_1_HEADPHONE_POWERDOWN_M BIT(9)
#define JZ4740_CODEC_1_HEADPHONE_POWERDOWN BIT(8)
#define JZ4740_CODEC_1_SUSPEND BIT(1)
#define JZ4740_CODEC_1_RESET BIT(0)
#define JZ4740_CODEC_1_LINE_ENABLE_OFFSET 29
#define JZ4740_CODEC_1_MIC_ENABLE_OFFSET 28
#define JZ4740_CODEC_1_SW1_ENABLE_OFFSET 27
#define JZ4740_CODEC_1_ADC_ENABLE_OFFSET 26
#define JZ4740_CODEC_1_SW2_ENABLE_OFFSET 25
#define JZ4740_CODEC_1_DAC_ENABLE_OFFSET 24
#define JZ4740_CODEC_1_HEADPHONE_DISABLE_OFFSET 14
#define JZ4740_CODEC_1_HEADPHONE_POWERDOWN_OFFSET 8
#define JZ4740_CODEC_2_INPUT_VOLUME_MASK 0x1f0000
#define JZ4740_CODEC_2_SAMPLE_RATE_MASK 0x000f00
#define JZ4740_CODEC_2_MIC_BOOST_GAIN_MASK 0x000030
#define JZ4740_CODEC_2_HEADPHONE_VOLUME_MASK 0x000003
#define JZ4740_CODEC_2_INPUT_VOLUME_OFFSET 16
#define JZ4740_CODEC_2_SAMPLE_RATE_OFFSET 8
#define JZ4740_CODEC_2_MIC_BOOST_GAIN_OFFSET 4
#define JZ4740_CODEC_2_HEADPHONE_VOLUME_OFFSET 0
static const struct reg_default jz4740_codec_reg_defaults[] = {
{ JZ4740_REG_CODEC_1, 0x021b2302 },
{ JZ4740_REG_CODEC_2, 0x00170803 },
};
struct jz4740_codec {
struct regmap *regmap;
};
static const DECLARE_TLV_DB_RANGE(jz4740_mic_tlv,
0, 2, TLV_DB_SCALE_ITEM(0, 600, 0),
3, 3, TLV_DB_SCALE_ITEM(2000, 0, 0)
);
static const DECLARE_TLV_DB_SCALE(jz4740_out_tlv, 0, 200, 0);
static const DECLARE_TLV_DB_SCALE(jz4740_in_tlv, -3450, 150, 0);
static const struct snd_kcontrol_new jz4740_codec_controls[] = {
SOC_SINGLE_TLV("Master Playback Volume", JZ4740_REG_CODEC_2,
JZ4740_CODEC_2_HEADPHONE_VOLUME_OFFSET, 3, 0,
jz4740_out_tlv),
SOC_SINGLE_TLV("Master Capture Volume", JZ4740_REG_CODEC_2,
JZ4740_CODEC_2_INPUT_VOLUME_OFFSET, 31, 0,
jz4740_in_tlv),
SOC_SINGLE("Master Playback Switch", JZ4740_REG_CODEC_1,
JZ4740_CODEC_1_HEADPHONE_DISABLE_OFFSET, 1, 1),
SOC_SINGLE_TLV("Mic Capture Volume", JZ4740_REG_CODEC_2,
JZ4740_CODEC_2_MIC_BOOST_GAIN_OFFSET, 3, 0,
jz4740_mic_tlv),
};
static const struct snd_kcontrol_new jz4740_codec_output_controls[] = {
SOC_DAPM_SINGLE("Bypass Switch", JZ4740_REG_CODEC_1,
JZ4740_CODEC_1_SW1_ENABLE_OFFSET, 1, 0),
SOC_DAPM_SINGLE("DAC Switch", JZ4740_REG_CODEC_1,
JZ4740_CODEC_1_SW2_ENABLE_OFFSET, 1, 0),
};
static const struct snd_kcontrol_new jz4740_codec_input_controls[] = {
SOC_DAPM_SINGLE("Line Capture Switch", JZ4740_REG_CODEC_1,
JZ4740_CODEC_1_LINE_ENABLE_OFFSET, 1, 0),
SOC_DAPM_SINGLE("Mic Capture Switch", JZ4740_REG_CODEC_1,
JZ4740_CODEC_1_MIC_ENABLE_OFFSET, 1, 0),
};
static const struct snd_soc_dapm_widget jz4740_codec_dapm_widgets[] = {
SND_SOC_DAPM_ADC("ADC", "Capture", JZ4740_REG_CODEC_1,
JZ4740_CODEC_1_ADC_ENABLE_OFFSET, 0),
SND_SOC_DAPM_DAC("DAC", "Playback", JZ4740_REG_CODEC_1,
JZ4740_CODEC_1_DAC_ENABLE_OFFSET, 0),
SND_SOC_DAPM_MIXER("Output Mixer", JZ4740_REG_CODEC_1,
JZ4740_CODEC_1_HEADPHONE_POWERDOWN_OFFSET, 1,
jz4740_codec_output_controls,
ARRAY_SIZE(jz4740_codec_output_controls)),
SND_SOC_DAPM_MIXER_NAMED_CTL("Input Mixer", SND_SOC_NOPM, 0, 0,
jz4740_codec_input_controls,
ARRAY_SIZE(jz4740_codec_input_controls)),
SND_SOC_DAPM_MIXER("Line Input", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_OUTPUT("LOUT"),
SND_SOC_DAPM_OUTPUT("ROUT"),
SND_SOC_DAPM_INPUT("MIC"),
SND_SOC_DAPM_INPUT("LIN"),
SND_SOC_DAPM_INPUT("RIN"),
};
static const struct snd_soc_dapm_route jz4740_codec_dapm_routes[] = {
{"Line Input", NULL, "LIN"},
{"Line Input", NULL, "RIN"},
{"Input Mixer", "Line Capture Switch", "Line Input"},
{"Input Mixer", "Mic Capture Switch", "MIC"},
{"ADC", NULL, "Input Mixer"},
{"Output Mixer", "Bypass Switch", "Input Mixer"},
{"Output Mixer", "DAC Switch", "DAC"},
{"LOUT", NULL, "Output Mixer"},
{"ROUT", NULL, "Output Mixer"},
};
static int jz4740_codec_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params, struct snd_soc_dai *dai)
{
struct jz4740_codec *jz4740_codec = snd_soc_component_get_drvdata(dai->component);
uint32_t val;
switch (params_rate(params)) {
case 8000:
val = 0;
break;
case 11025:
val = 1;
break;
case 12000:
val = 2;
break;
case 16000:
val = 3;
break;
case 22050:
val = 4;
break;
case 24000:
val = 5;
break;
case 32000:
val = 6;
break;
case 44100:
val = 7;
break;
case 48000:
val = 8;
break;
default:
return -EINVAL;
}
val <<= JZ4740_CODEC_2_SAMPLE_RATE_OFFSET;
regmap_update_bits(jz4740_codec->regmap, JZ4740_REG_CODEC_2,
JZ4740_CODEC_2_SAMPLE_RATE_MASK, val);
return 0;
}
static const struct snd_soc_dai_ops jz4740_codec_dai_ops = {
.hw_params = jz4740_codec_hw_params,
};
static struct snd_soc_dai_driver jz4740_codec_dai = {
.name = "jz4740-hifi",
.playback = {
.stream_name = "Playback",
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S8,
},
.capture = {
.stream_name = "Capture",
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S8,
},
.ops = &jz4740_codec_dai_ops,
.symmetric_rates = 1,
};
static void jz4740_codec_wakeup(struct regmap *regmap)
{
regmap_update_bits(regmap, JZ4740_REG_CODEC_1,
JZ4740_CODEC_1_RESET, JZ4740_CODEC_1_RESET);
udelay(2);
regmap_update_bits(regmap, JZ4740_REG_CODEC_1,
JZ4740_CODEC_1_SUSPEND | JZ4740_CODEC_1_RESET, 0);
regcache_sync(regmap);
}
static int jz4740_codec_set_bias_level(struct snd_soc_component *component,
enum snd_soc_bias_level level)
{
struct jz4740_codec *jz4740_codec = snd_soc_component_get_drvdata(component);
struct regmap *regmap = jz4740_codec->regmap;
unsigned int mask;
unsigned int value;
switch (level) {
case SND_SOC_BIAS_ON:
break;
case SND_SOC_BIAS_PREPARE:
mask = JZ4740_CODEC_1_VREF_DISABLE |
JZ4740_CODEC_1_VREF_AMP_DISABLE |
JZ4740_CODEC_1_HEADPHONE_POWERDOWN_M;
value = 0;
regmap_update_bits(regmap, JZ4740_REG_CODEC_1, mask, value);
break;
case SND_SOC_BIAS_STANDBY:
/* The only way to clear the suspend flag is to reset the codec */
if (snd_soc_component_get_bias_level(component) == SND_SOC_BIAS_OFF)
jz4740_codec_wakeup(regmap);
mask = JZ4740_CODEC_1_VREF_DISABLE |
JZ4740_CODEC_1_VREF_AMP_DISABLE |
JZ4740_CODEC_1_HEADPHONE_POWERDOWN_M;
value = JZ4740_CODEC_1_VREF_DISABLE |
JZ4740_CODEC_1_VREF_AMP_DISABLE |
JZ4740_CODEC_1_HEADPHONE_POWERDOWN_M;
regmap_update_bits(regmap, JZ4740_REG_CODEC_1, mask, value);
break;
case SND_SOC_BIAS_OFF:
mask = JZ4740_CODEC_1_SUSPEND;
value = JZ4740_CODEC_1_SUSPEND;
regmap_update_bits(regmap, JZ4740_REG_CODEC_1, mask, value);
regcache_mark_dirty(regmap);
break;
default:
break;
}
return 0;
}
static int jz4740_codec_dev_probe(struct snd_soc_component *component)
{
struct jz4740_codec *jz4740_codec = snd_soc_component_get_drvdata(component);
regmap_update_bits(jz4740_codec->regmap, JZ4740_REG_CODEC_1,
JZ4740_CODEC_1_SW2_ENABLE, JZ4740_CODEC_1_SW2_ENABLE);
return 0;
}
static const struct snd_soc_component_driver soc_codec_dev_jz4740_codec = {
.probe = jz4740_codec_dev_probe,
.set_bias_level = jz4740_codec_set_bias_level,
.controls = jz4740_codec_controls,
.num_controls = ARRAY_SIZE(jz4740_codec_controls),
.dapm_widgets = jz4740_codec_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(jz4740_codec_dapm_widgets),
.dapm_routes = jz4740_codec_dapm_routes,
.num_dapm_routes = ARRAY_SIZE(jz4740_codec_dapm_routes),
.suspend_bias_off = 1,
.idle_bias_on = 1,
.use_pmdown_time = 1,
.endianness = 1,
.non_legacy_dai_naming = 1,
};
static const struct regmap_config jz4740_codec_regmap_config = {
.reg_bits = 32,
.reg_stride = 4,
.val_bits = 32,
.max_register = JZ4740_REG_CODEC_2,
.reg_defaults = jz4740_codec_reg_defaults,
.num_reg_defaults = ARRAY_SIZE(jz4740_codec_reg_defaults),
.cache_type = REGCACHE_RBTREE,
};
static int jz4740_codec_probe(struct platform_device *pdev)
{
int ret;
struct jz4740_codec *jz4740_codec;
struct resource *mem;
void __iomem *base;
jz4740_codec = devm_kzalloc(&pdev->dev, sizeof(*jz4740_codec),
GFP_KERNEL);
if (!jz4740_codec)
return -ENOMEM;
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
base = devm_ioremap_resource(&pdev->dev, mem);
if (IS_ERR(base))
return PTR_ERR(base);
jz4740_codec->regmap = devm_regmap_init_mmio(&pdev->dev, base,
&jz4740_codec_regmap_config);
if (IS_ERR(jz4740_codec->regmap))
return PTR_ERR(jz4740_codec->regmap);
platform_set_drvdata(pdev, jz4740_codec);
ret = devm_snd_soc_register_component(&pdev->dev,
&soc_codec_dev_jz4740_codec, &jz4740_codec_dai, 1);
if (ret)
dev_err(&pdev->dev, "Failed to register codec\n");
return ret;
}
static struct platform_driver jz4740_codec_driver = {
.probe = jz4740_codec_probe,
.driver = {
.name = "jz4740-codec",
},
};
module_platform_driver(jz4740_codec_driver);
MODULE_DESCRIPTION("JZ4740 SoC internal codec driver");
MODULE_AUTHOR("Lars-Peter Clausen <lars@metafoo.de>");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:jz4740-codec");
| gpl-2.0 |
mdeejay/android_kernel_grouper | drivers/mmc/host/omap_hsmmc.c | 358 | 56865 | /*
* drivers/mmc/host/omap_hsmmc.c
*
* Driver for OMAP2430/3430 MMC controller.
*
* Copyright (C) 2007 Texas Instruments.
*
* Authors:
* Syed Mohammed Khasim <x0khasim@ti.com>
* Madhusudhan <madhu.cr@ti.com>
* Mohit Jalori <mjalori@ti.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/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/platform_device.h>
#include <linux/workqueue.h>
#include <linux/timer.h>
#include <linux/clk.h>
#include <linux/mmc/host.h>
#include <linux/mmc/core.h>
#include <linux/mmc/mmc.h>
#include <linux/io.h>
#include <linux/semaphore.h>
#include <linux/gpio.h>
#include <linux/regulator/consumer.h>
#include <linux/pm_runtime.h>
#include <plat/dma.h>
#include <mach/hardware.h>
#include <plat/board.h>
#include <plat/mmc.h>
#include <plat/cpu.h>
/* OMAP HSMMC Host Controller Registers */
#define OMAP_HSMMC_SYSCONFIG 0x0010
#define OMAP_HSMMC_SYSSTATUS 0x0014
#define OMAP_HSMMC_CON 0x002C
#define OMAP_HSMMC_BLK 0x0104
#define OMAP_HSMMC_ARG 0x0108
#define OMAP_HSMMC_CMD 0x010C
#define OMAP_HSMMC_RSP10 0x0110
#define OMAP_HSMMC_RSP32 0x0114
#define OMAP_HSMMC_RSP54 0x0118
#define OMAP_HSMMC_RSP76 0x011C
#define OMAP_HSMMC_DATA 0x0120
#define OMAP_HSMMC_HCTL 0x0128
#define OMAP_HSMMC_SYSCTL 0x012C
#define OMAP_HSMMC_STAT 0x0130
#define OMAP_HSMMC_IE 0x0134
#define OMAP_HSMMC_ISE 0x0138
#define OMAP_HSMMC_CAPA 0x0140
#define VS18 (1 << 26)
#define VS30 (1 << 25)
#define SDVS18 (0x5 << 9)
#define SDVS30 (0x6 << 9)
#define SDVS33 (0x7 << 9)
#define SDVS_MASK 0x00000E00
#define SDVSCLR 0xFFFFF1FF
#define SDVSDET 0x00000400
#define AUTOIDLE 0x1
#define SDBP (1 << 8)
#define DTO 0xe
#define ICE 0x1
#define ICS 0x2
#define CEN (1 << 2)
#define CLKD_MASK 0x0000FFC0
#define CLKD_SHIFT 6
#define DTO_MASK 0x000F0000
#define DTO_SHIFT 16
#define INT_EN_MASK 0x307F0033
#define BWR_ENABLE (1 << 4)
#define BRR_ENABLE (1 << 5)
#define DTO_ENABLE (1 << 20)
#define INIT_STREAM (1 << 1)
#define DP_SELECT (1 << 21)
#define DDIR (1 << 4)
#define DMA_EN 0x1
#define MSBS (1 << 5)
#define BCE (1 << 1)
#define FOUR_BIT (1 << 1)
#define DW8 (1 << 5)
#define CC 0x1
#define TC 0x02
#define OD 0x1
#define ERR (1 << 15)
#define CMD_TIMEOUT (1 << 16)
#define DATA_TIMEOUT (1 << 20)
#define CMD_CRC (1 << 17)
#define DATA_CRC (1 << 21)
#define CARD_ERR (1 << 28)
#define STAT_CLEAR 0xFFFFFFFF
#define INIT_STREAM_CMD 0x00000000
#define DUAL_VOLT_OCR_BIT 7
#define SRC (1 << 25)
#define SRD (1 << 26)
#define SOFTRESET (1 << 1)
#define RESETDONE (1 << 0)
/*
* FIXME: Most likely all the data using these _DEVID defines should come
* from the platform_data, or implemented in controller and slot specific
* functions.
*/
#define OMAP_MMC1_DEVID 0
#define OMAP_MMC2_DEVID 1
#define OMAP_MMC3_DEVID 2
#define OMAP_MMC4_DEVID 3
#define OMAP_MMC5_DEVID 4
#define MMC_AUTOSUSPEND_DELAY 100
#define MMC_TIMEOUT_MS 20
#define OMAP_MMC_MASTER_CLOCK 96000000
#define OMAP_MMC_MIN_CLOCK 400000
#define OMAP_MMC_MAX_CLOCK 52000000
#define DRIVER_NAME "omap_hsmmc"
/*
* One controller can have multiple slots, like on some omap boards using
* omap.c controller driver. Luckily this is not currently done on any known
* omap_hsmmc.c device.
*/
#define mmc_slot(host) (host->pdata->slots[host->slot_id])
/*
* MMC Host controller read/write API's
*/
#define OMAP_HSMMC_READ(base, reg) \
__raw_readl((base) + OMAP_HSMMC_##reg)
#define OMAP_HSMMC_WRITE(base, reg, val) \
__raw_writel((val), (base) + OMAP_HSMMC_##reg)
struct omap_hsmmc_next {
unsigned int dma_len;
s32 cookie;
};
struct omap_hsmmc_host {
struct device *dev;
struct mmc_host *mmc;
struct mmc_request *mrq;
struct mmc_command *cmd;
struct mmc_data *data;
struct clk *fclk;
struct clk *dbclk;
/*
* vcc == configured supply
* vcc_aux == optional
* - MMC1, supply for DAT4..DAT7
* - MMC2/MMC2, external level shifter voltage supply, for
* chip (SDIO, eMMC, etc) or transceiver (MMC2 only)
*/
struct regulator *vcc;
struct regulator *vcc_aux;
struct work_struct mmc_carddetect_work;
void __iomem *base;
resource_size_t mapbase;
spinlock_t irq_lock; /* Prevent races with irq handler */
unsigned int id;
unsigned int dma_len;
unsigned int dma_sg_idx;
unsigned char bus_mode;
unsigned char power_mode;
u32 *buffer;
u32 bytesleft;
int suspended;
int irq;
int use_dma, dma_ch;
int dma_line_tx, dma_line_rx;
int slot_id;
int got_dbclk;
int response_busy;
int context_loss;
int dpm_state;
int vdd;
int protect_card;
int reqs_blocked;
int use_reg;
int req_in_progress;
struct omap_hsmmc_next next_data;
struct omap_mmc_platform_data *pdata;
};
static int omap_hsmmc_card_detect(struct device *dev, int slot)
{
struct omap_mmc_platform_data *mmc = dev->platform_data;
/* NOTE: assumes card detect signal is active-low */
return !gpio_get_value_cansleep(mmc->slots[0].switch_pin);
}
static int omap_hsmmc_get_wp(struct device *dev, int slot)
{
struct omap_mmc_platform_data *mmc = dev->platform_data;
/* NOTE: assumes write protect signal is active-high */
return gpio_get_value_cansleep(mmc->slots[0].gpio_wp);
}
static int omap_hsmmc_get_cover_state(struct device *dev, int slot)
{
struct omap_mmc_platform_data *mmc = dev->platform_data;
/* NOTE: assumes card detect signal is active-low */
return !gpio_get_value_cansleep(mmc->slots[0].switch_pin);
}
#ifdef CONFIG_PM
static int omap_hsmmc_suspend_cdirq(struct device *dev, int slot)
{
struct omap_mmc_platform_data *mmc = dev->platform_data;
disable_irq(mmc->slots[0].card_detect_irq);
return 0;
}
static int omap_hsmmc_resume_cdirq(struct device *dev, int slot)
{
struct omap_mmc_platform_data *mmc = dev->platform_data;
enable_irq(mmc->slots[0].card_detect_irq);
return 0;
}
#else
#define omap_hsmmc_suspend_cdirq NULL
#define omap_hsmmc_resume_cdirq NULL
#endif
#ifdef CONFIG_REGULATOR
static int omap_hsmmc_1_set_power(struct device *dev, int slot, int power_on,
int vdd)
{
struct omap_hsmmc_host *host =
platform_get_drvdata(to_platform_device(dev));
int ret;
if (mmc_slot(host).before_set_reg)
mmc_slot(host).before_set_reg(dev, slot, power_on, vdd);
if (power_on)
ret = mmc_regulator_set_ocr(host->mmc, host->vcc, vdd);
else
ret = mmc_regulator_set_ocr(host->mmc, host->vcc, 0);
if (mmc_slot(host).after_set_reg)
mmc_slot(host).after_set_reg(dev, slot, power_on, vdd);
return ret;
}
static int omap_hsmmc_235_set_power(struct device *dev, int slot, int power_on,
int vdd)
{
struct omap_hsmmc_host *host =
platform_get_drvdata(to_platform_device(dev));
int ret = 0;
/*
* If we don't see a Vcc regulator, assume it's a fixed
* voltage always-on regulator.
*/
if (!host->vcc)
return 0;
if (mmc_slot(host).before_set_reg)
mmc_slot(host).before_set_reg(dev, slot, power_on, vdd);
/*
* Assume Vcc regulator is used only to power the card ... OMAP
* VDDS is used to power the pins, optionally with a transceiver to
* support cards using voltages other than VDDS (1.8V nominal). When a
* transceiver is used, DAT3..7 are muxed as transceiver control pins.
*
* In some cases this regulator won't support enable/disable;
* e.g. it's a fixed rail for a WLAN chip.
*
* In other cases vcc_aux switches interface power. Example, for
* eMMC cards it represents VccQ. Sometimes transceivers or SDIO
* chips/cards need an interface voltage rail too.
*/
if (power_on) {
ret = mmc_regulator_set_ocr(host->mmc, host->vcc, vdd);
/* Enable interface voltage rail, if needed */
if (ret == 0 && host->vcc_aux) {
ret = regulator_enable(host->vcc_aux);
if (ret < 0)
ret = mmc_regulator_set_ocr(host->mmc,
host->vcc, 0);
}
} else {
/* Shut down the rail */
if (host->vcc_aux)
ret = regulator_disable(host->vcc_aux);
if (!ret) {
/* Then proceed to shut down the local regulator */
ret = mmc_regulator_set_ocr(host->mmc,
host->vcc, 0);
}
}
if (mmc_slot(host).after_set_reg)
mmc_slot(host).after_set_reg(dev, slot, power_on, vdd);
return ret;
}
static int omap_hsmmc_4_set_power(struct device *dev, int slot, int power_on,
int vdd)
{
return 0;
}
static int omap_hsmmc_1_set_sleep(struct device *dev, int slot, int sleep,
int vdd, int cardsleep)
{
struct omap_hsmmc_host *host =
platform_get_drvdata(to_platform_device(dev));
int mode = sleep ? REGULATOR_MODE_STANDBY : REGULATOR_MODE_NORMAL;
return regulator_set_mode(host->vcc, mode);
}
static int omap_hsmmc_235_set_sleep(struct device *dev, int slot, int sleep,
int vdd, int cardsleep)
{
struct omap_hsmmc_host *host =
platform_get_drvdata(to_platform_device(dev));
int err, mode;
/*
* If we don't see a Vcc regulator, assume it's a fixed
* voltage always-on regulator.
*/
if (!host->vcc)
return 0;
mode = sleep ? REGULATOR_MODE_STANDBY : REGULATOR_MODE_NORMAL;
if (!host->vcc_aux)
return regulator_set_mode(host->vcc, mode);
if (cardsleep) {
/* VCC can be turned off if card is asleep */
if (sleep)
err = mmc_regulator_set_ocr(host->mmc, host->vcc, 0);
else
err = mmc_regulator_set_ocr(host->mmc, host->vcc, vdd);
} else
err = regulator_set_mode(host->vcc, mode);
if (err)
return err;
if (!mmc_slot(host).vcc_aux_disable_is_sleep)
return regulator_set_mode(host->vcc_aux, mode);
if (sleep)
return regulator_disable(host->vcc_aux);
else
return regulator_enable(host->vcc_aux);
}
static int omap_hsmmc_4_set_sleep(struct device *dev, int slot, int sleep,
int vdd, int cardsleep)
{
return 0;
}
static int omap_hsmmc_reg_get(struct omap_hsmmc_host *host)
{
struct regulator *reg;
int ret = 0;
int ocr_value = 0;
switch (host->id) {
case OMAP_MMC1_DEVID:
/* On-chip level shifting via PBIAS0/PBIAS1 */
mmc_slot(host).set_power = omap_hsmmc_1_set_power;
mmc_slot(host).set_sleep = omap_hsmmc_1_set_sleep;
break;
case OMAP_MMC2_DEVID:
case OMAP_MMC3_DEVID:
case OMAP_MMC5_DEVID:
/* Off-chip level shifting, or none */
mmc_slot(host).set_power = omap_hsmmc_235_set_power;
mmc_slot(host).set_sleep = omap_hsmmc_235_set_sleep;
break;
case OMAP_MMC4_DEVID:
mmc_slot(host).set_power = omap_hsmmc_4_set_power;
mmc_slot(host).set_sleep = omap_hsmmc_4_set_sleep;
default:
pr_err("MMC%d configuration not supported!\n", host->id);
return -EINVAL;
}
reg = regulator_get(host->dev, "vmmc");
if (IS_ERR(reg)) {
dev_dbg(host->dev, "vmmc regulator missing\n");
/*
* HACK: until fixed.c regulator is usable,
* we don't require a main regulator
* for MMC2 or MMC3
*/
if (host->id == OMAP_MMC1_DEVID) {
ret = PTR_ERR(reg);
goto err;
}
} else {
host->vcc = reg;
ocr_value = mmc_regulator_get_ocrmask(reg);
if (!mmc_slot(host).ocr_mask) {
mmc_slot(host).ocr_mask = ocr_value;
} else {
if (!(mmc_slot(host).ocr_mask & ocr_value)) {
pr_err("MMC%d ocrmask %x is not supported\n",
host->id, mmc_slot(host).ocr_mask);
mmc_slot(host).ocr_mask = 0;
return -EINVAL;
}
}
/* Allow an aux regulator */
reg = regulator_get(host->dev, "vmmc_aux");
host->vcc_aux = IS_ERR(reg) ? NULL : reg;
/* For eMMC do not power off when not in sleep state */
if (mmc_slot(host).no_regulator_off_init)
return 0;
/*
* UGLY HACK: workaround regulator framework bugs.
* When the bootloader leaves a supply active, it's
* initialized with zero usecount ... and we can't
* disable it without first enabling it. Until the
* framework is fixed, we need a workaround like this
* (which is safe for MMC, but not in general).
*/
if (regulator_is_enabled(host->vcc) > 0) {
regulator_enable(host->vcc);
regulator_disable(host->vcc);
}
if (host->vcc_aux) {
if (regulator_is_enabled(reg) > 0) {
regulator_enable(reg);
regulator_disable(reg);
}
}
}
return 0;
err:
mmc_slot(host).set_power = NULL;
mmc_slot(host).set_sleep = NULL;
return ret;
}
static void omap_hsmmc_reg_put(struct omap_hsmmc_host *host)
{
regulator_put(host->vcc);
regulator_put(host->vcc_aux);
mmc_slot(host).set_power = NULL;
mmc_slot(host).set_sleep = NULL;
}
static inline int omap_hsmmc_have_reg(void)
{
return 1;
}
#else
static inline int omap_hsmmc_reg_get(struct omap_hsmmc_host *host)
{
return -EINVAL;
}
static inline void omap_hsmmc_reg_put(struct omap_hsmmc_host *host)
{
}
static inline int omap_hsmmc_have_reg(void)
{
return 0;
}
#endif
static int omap_hsmmc_gpio_init(struct omap_mmc_platform_data *pdata)
{
int ret;
if (gpio_is_valid(pdata->slots[0].switch_pin)) {
if (pdata->slots[0].cover)
pdata->slots[0].get_cover_state =
omap_hsmmc_get_cover_state;
else
pdata->slots[0].card_detect = omap_hsmmc_card_detect;
pdata->slots[0].card_detect_irq =
gpio_to_irq(pdata->slots[0].switch_pin);
ret = gpio_request(pdata->slots[0].switch_pin, "mmc_cd");
if (ret)
return ret;
ret = gpio_direction_input(pdata->slots[0].switch_pin);
if (ret)
goto err_free_sp;
} else
pdata->slots[0].switch_pin = -EINVAL;
if (gpio_is_valid(pdata->slots[0].gpio_wp)) {
pdata->slots[0].get_ro = omap_hsmmc_get_wp;
ret = gpio_request(pdata->slots[0].gpio_wp, "mmc_wp");
if (ret)
goto err_free_cd;
ret = gpio_direction_input(pdata->slots[0].gpio_wp);
if (ret)
goto err_free_wp;
} else
pdata->slots[0].gpio_wp = -EINVAL;
return 0;
err_free_wp:
gpio_free(pdata->slots[0].gpio_wp);
err_free_cd:
if (gpio_is_valid(pdata->slots[0].switch_pin))
err_free_sp:
gpio_free(pdata->slots[0].switch_pin);
return ret;
}
static void omap_hsmmc_gpio_free(struct omap_mmc_platform_data *pdata)
{
if (gpio_is_valid(pdata->slots[0].gpio_wp))
gpio_free(pdata->slots[0].gpio_wp);
if (gpio_is_valid(pdata->slots[0].switch_pin))
gpio_free(pdata->slots[0].switch_pin);
}
/*
* Start clock to the card
*/
static void omap_hsmmc_start_clock(struct omap_hsmmc_host *host)
{
OMAP_HSMMC_WRITE(host->base, SYSCTL,
OMAP_HSMMC_READ(host->base, SYSCTL) | CEN);
}
/*
* Stop clock to the card
*/
static void omap_hsmmc_stop_clock(struct omap_hsmmc_host *host)
{
OMAP_HSMMC_WRITE(host->base, SYSCTL,
OMAP_HSMMC_READ(host->base, SYSCTL) & ~CEN);
if ((OMAP_HSMMC_READ(host->base, SYSCTL) & CEN) != 0x0)
dev_dbg(mmc_dev(host->mmc), "MMC Clock is not stoped\n");
}
static void omap_hsmmc_enable_irq(struct omap_hsmmc_host *host,
struct mmc_command *cmd)
{
unsigned int irq_mask;
if (host->use_dma)
irq_mask = INT_EN_MASK & ~(BRR_ENABLE | BWR_ENABLE);
else
irq_mask = INT_EN_MASK;
/* Disable timeout for erases */
if (cmd->opcode == MMC_ERASE)
irq_mask &= ~DTO_ENABLE;
OMAP_HSMMC_WRITE(host->base, STAT, STAT_CLEAR);
OMAP_HSMMC_WRITE(host->base, ISE, irq_mask);
OMAP_HSMMC_WRITE(host->base, IE, irq_mask);
}
static void omap_hsmmc_disable_irq(struct omap_hsmmc_host *host)
{
OMAP_HSMMC_WRITE(host->base, ISE, 0);
OMAP_HSMMC_WRITE(host->base, IE, 0);
OMAP_HSMMC_WRITE(host->base, STAT, STAT_CLEAR);
}
/* Calculate divisor for the given clock frequency */
static u16 calc_divisor(struct mmc_ios *ios)
{
u16 dsor = 0;
if (ios->clock) {
dsor = DIV_ROUND_UP(OMAP_MMC_MASTER_CLOCK, ios->clock);
if (dsor > 250)
dsor = 250;
}
return dsor;
}
static void omap_hsmmc_set_clock(struct omap_hsmmc_host *host)
{
struct mmc_ios *ios = &host->mmc->ios;
unsigned long regval;
unsigned long timeout;
dev_dbg(mmc_dev(host->mmc), "Set clock to %uHz\n", ios->clock);
omap_hsmmc_stop_clock(host);
regval = OMAP_HSMMC_READ(host->base, SYSCTL);
regval = regval & ~(CLKD_MASK | DTO_MASK);
regval = regval | (calc_divisor(ios) << 6) | (DTO << 16);
OMAP_HSMMC_WRITE(host->base, SYSCTL, regval);
OMAP_HSMMC_WRITE(host->base, SYSCTL,
OMAP_HSMMC_READ(host->base, SYSCTL) | ICE);
/* Wait till the ICS bit is set */
timeout = jiffies + msecs_to_jiffies(MMC_TIMEOUT_MS);
while ((OMAP_HSMMC_READ(host->base, SYSCTL) & ICS) != ICS
&& time_before(jiffies, timeout))
cpu_relax();
omap_hsmmc_start_clock(host);
}
static void omap_hsmmc_set_bus_width(struct omap_hsmmc_host *host)
{
struct mmc_ios *ios = &host->mmc->ios;
u32 con;
con = OMAP_HSMMC_READ(host->base, CON);
switch (ios->bus_width) {
case MMC_BUS_WIDTH_8:
OMAP_HSMMC_WRITE(host->base, CON, con | DW8);
break;
case MMC_BUS_WIDTH_4:
OMAP_HSMMC_WRITE(host->base, CON, con & ~DW8);
OMAP_HSMMC_WRITE(host->base, HCTL,
OMAP_HSMMC_READ(host->base, HCTL) | FOUR_BIT);
break;
case MMC_BUS_WIDTH_1:
OMAP_HSMMC_WRITE(host->base, CON, con & ~DW8);
OMAP_HSMMC_WRITE(host->base, HCTL,
OMAP_HSMMC_READ(host->base, HCTL) & ~FOUR_BIT);
break;
}
}
static void omap_hsmmc_set_bus_mode(struct omap_hsmmc_host *host)
{
struct mmc_ios *ios = &host->mmc->ios;
u32 con;
con = OMAP_HSMMC_READ(host->base, CON);
if (ios->bus_mode == MMC_BUSMODE_OPENDRAIN)
OMAP_HSMMC_WRITE(host->base, CON, con | OD);
else
OMAP_HSMMC_WRITE(host->base, CON, con & ~OD);
}
#ifdef CONFIG_PM
/*
* Restore the MMC host context, if it was lost as result of a
* power state change.
*/
static int omap_hsmmc_context_restore(struct omap_hsmmc_host *host)
{
struct mmc_ios *ios = &host->mmc->ios;
struct omap_mmc_platform_data *pdata = host->pdata;
int context_loss = 0;
u32 hctl, capa;
unsigned long timeout;
if (pdata->get_context_loss_count) {
context_loss = pdata->get_context_loss_count(host->dev);
if (context_loss < 0)
return 1;
}
dev_dbg(mmc_dev(host->mmc), "context was %slost\n",
context_loss == host->context_loss ? "not " : "");
if (host->context_loss == context_loss)
return 1;
/* Wait for hardware reset */
timeout = jiffies + msecs_to_jiffies(MMC_TIMEOUT_MS);
while ((OMAP_HSMMC_READ(host->base, SYSSTATUS) & RESETDONE) != RESETDONE
&& time_before(jiffies, timeout))
;
/* Do software reset */
OMAP_HSMMC_WRITE(host->base, SYSCONFIG, SOFTRESET);
timeout = jiffies + msecs_to_jiffies(MMC_TIMEOUT_MS);
while ((OMAP_HSMMC_READ(host->base, SYSSTATUS) & RESETDONE) != RESETDONE
&& time_before(jiffies, timeout))
;
OMAP_HSMMC_WRITE(host->base, SYSCONFIG,
OMAP_HSMMC_READ(host->base, SYSCONFIG) | AUTOIDLE);
if (host->id == OMAP_MMC1_DEVID) {
if (host->power_mode != MMC_POWER_OFF &&
(1 << ios->vdd) <= MMC_VDD_23_24)
hctl = SDVS18;
else
hctl = SDVS30;
capa = VS30 | VS18;
} else {
hctl = SDVS18;
capa = VS18;
}
OMAP_HSMMC_WRITE(host->base, HCTL,
OMAP_HSMMC_READ(host->base, HCTL) | hctl);
OMAP_HSMMC_WRITE(host->base, CAPA,
OMAP_HSMMC_READ(host->base, CAPA) | capa);
OMAP_HSMMC_WRITE(host->base, HCTL,
OMAP_HSMMC_READ(host->base, HCTL) | SDBP);
timeout = jiffies + msecs_to_jiffies(MMC_TIMEOUT_MS);
while ((OMAP_HSMMC_READ(host->base, HCTL) & SDBP) != SDBP
&& time_before(jiffies, timeout))
;
omap_hsmmc_disable_irq(host);
/* Do not initialize card-specific things if the power is off */
if (host->power_mode == MMC_POWER_OFF)
goto out;
omap_hsmmc_set_bus_width(host);
omap_hsmmc_set_clock(host);
omap_hsmmc_set_bus_mode(host);
out:
host->context_loss = context_loss;
dev_dbg(mmc_dev(host->mmc), "context is restored\n");
return 0;
}
/*
* Save the MMC host context (store the number of power state changes so far).
*/
static void omap_hsmmc_context_save(struct omap_hsmmc_host *host)
{
struct omap_mmc_platform_data *pdata = host->pdata;
int context_loss;
if (pdata->get_context_loss_count) {
context_loss = pdata->get_context_loss_count(host->dev);
if (context_loss < 0)
return;
host->context_loss = context_loss;
}
}
#else
static int omap_hsmmc_context_restore(struct omap_hsmmc_host *host)
{
return 0;
}
static void omap_hsmmc_context_save(struct omap_hsmmc_host *host)
{
}
#endif
/*
* Send init stream sequence to card
* before sending IDLE command
*/
static void send_init_stream(struct omap_hsmmc_host *host)
{
int reg = 0;
unsigned long timeout;
if (host->protect_card)
return;
disable_irq(host->irq);
OMAP_HSMMC_WRITE(host->base, IE, INT_EN_MASK);
OMAP_HSMMC_WRITE(host->base, CON,
OMAP_HSMMC_READ(host->base, CON) | INIT_STREAM);
OMAP_HSMMC_WRITE(host->base, CMD, INIT_STREAM_CMD);
timeout = jiffies + msecs_to_jiffies(MMC_TIMEOUT_MS);
while ((reg != CC) && time_before(jiffies, timeout))
reg = OMAP_HSMMC_READ(host->base, STAT) & CC;
OMAP_HSMMC_WRITE(host->base, CON,
OMAP_HSMMC_READ(host->base, CON) & ~INIT_STREAM);
OMAP_HSMMC_WRITE(host->base, STAT, STAT_CLEAR);
OMAP_HSMMC_READ(host->base, STAT);
enable_irq(host->irq);
}
static inline
int omap_hsmmc_cover_is_closed(struct omap_hsmmc_host *host)
{
int r = 1;
if (mmc_slot(host).get_cover_state)
r = mmc_slot(host).get_cover_state(host->dev, host->slot_id);
return r;
}
static ssize_t
omap_hsmmc_show_cover_switch(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct mmc_host *mmc = container_of(dev, struct mmc_host, class_dev);
struct omap_hsmmc_host *host = mmc_priv(mmc);
return sprintf(buf, "%s\n",
omap_hsmmc_cover_is_closed(host) ? "closed" : "open");
}
static DEVICE_ATTR(cover_switch, S_IRUGO, omap_hsmmc_show_cover_switch, NULL);
static ssize_t
omap_hsmmc_show_slot_name(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct mmc_host *mmc = container_of(dev, struct mmc_host, class_dev);
struct omap_hsmmc_host *host = mmc_priv(mmc);
return sprintf(buf, "%s\n", mmc_slot(host).name);
}
static DEVICE_ATTR(slot_name, S_IRUGO, omap_hsmmc_show_slot_name, NULL);
/*
* Configure the response type and send the cmd.
*/
static void
omap_hsmmc_start_command(struct omap_hsmmc_host *host, struct mmc_command *cmd,
struct mmc_data *data)
{
int cmdreg = 0, resptype = 0, cmdtype = 0;
dev_dbg(mmc_dev(host->mmc), "%s: CMD%d, argument 0x%08x\n",
mmc_hostname(host->mmc), cmd->opcode, cmd->arg);
host->cmd = cmd;
omap_hsmmc_enable_irq(host, cmd);
host->response_busy = 0;
if (cmd->flags & MMC_RSP_PRESENT) {
if (cmd->flags & MMC_RSP_136)
resptype = 1;
else if (cmd->flags & MMC_RSP_BUSY) {
resptype = 3;
host->response_busy = 1;
} else
resptype = 2;
}
/*
* Unlike OMAP1 controller, the cmdtype does not seem to be based on
* ac, bc, adtc, bcr. Only commands ending an open ended transfer need
* a val of 0x3, rest 0x0.
*/
if (cmd == host->mrq->stop)
cmdtype = 0x3;
cmdreg = (cmd->opcode << 24) | (resptype << 16) | (cmdtype << 22);
if (data) {
cmdreg |= DP_SELECT | MSBS | BCE;
if (data->flags & MMC_DATA_READ)
cmdreg |= DDIR;
else
cmdreg &= ~(DDIR);
}
if (host->use_dma)
cmdreg |= DMA_EN;
host->req_in_progress = 1;
OMAP_HSMMC_WRITE(host->base, ARG, cmd->arg);
OMAP_HSMMC_WRITE(host->base, CMD, cmdreg);
}
static int
omap_hsmmc_get_dma_dir(struct omap_hsmmc_host *host, struct mmc_data *data)
{
if (data->flags & MMC_DATA_WRITE)
return DMA_TO_DEVICE;
else
return DMA_FROM_DEVICE;
}
static void omap_hsmmc_request_done(struct omap_hsmmc_host *host, struct mmc_request *mrq)
{
int dma_ch;
spin_lock(&host->irq_lock);
host->req_in_progress = 0;
dma_ch = host->dma_ch;
spin_unlock(&host->irq_lock);
omap_hsmmc_disable_irq(host);
/* Do not complete the request if DMA is still in progress */
if (mrq->data && host->use_dma && dma_ch != -1)
return;
host->mrq = NULL;
mmc_request_done(host->mmc, mrq);
}
/*
* Notify the transfer complete to MMC core
*/
static void
omap_hsmmc_xfer_done(struct omap_hsmmc_host *host, struct mmc_data *data)
{
if (!data) {
struct mmc_request *mrq = host->mrq;
/* TC before CC from CMD6 - don't know why, but it happens */
if (host->cmd && host->cmd->opcode == 6 &&
host->response_busy) {
host->response_busy = 0;
return;
}
omap_hsmmc_request_done(host, mrq);
return;
}
host->data = NULL;
if (!data->error)
data->bytes_xfered += data->blocks * (data->blksz);
else
data->bytes_xfered = 0;
if (!data->stop) {
omap_hsmmc_request_done(host, data->mrq);
return;
}
omap_hsmmc_start_command(host, data->stop, NULL);
}
/*
* Notify the core about command completion
*/
static void
omap_hsmmc_cmd_done(struct omap_hsmmc_host *host, struct mmc_command *cmd)
{
host->cmd = NULL;
if (cmd->flags & MMC_RSP_PRESENT) {
if (cmd->flags & MMC_RSP_136) {
/* response type 2 */
cmd->resp[3] = OMAP_HSMMC_READ(host->base, RSP10);
cmd->resp[2] = OMAP_HSMMC_READ(host->base, RSP32);
cmd->resp[1] = OMAP_HSMMC_READ(host->base, RSP54);
cmd->resp[0] = OMAP_HSMMC_READ(host->base, RSP76);
} else {
/* response types 1, 1b, 3, 4, 5, 6 */
cmd->resp[0] = OMAP_HSMMC_READ(host->base, RSP10);
}
}
if ((host->data == NULL && !host->response_busy) || cmd->error)
omap_hsmmc_request_done(host, cmd->mrq);
}
/*
* DMA clean up for command errors
*/
static void omap_hsmmc_dma_cleanup(struct omap_hsmmc_host *host, int errno)
{
int dma_ch;
host->data->error = errno;
spin_lock(&host->irq_lock);
dma_ch = host->dma_ch;
host->dma_ch = -1;
spin_unlock(&host->irq_lock);
if (host->use_dma && dma_ch != -1) {
dma_unmap_sg(mmc_dev(host->mmc), host->data->sg,
host->data->sg_len,
omap_hsmmc_get_dma_dir(host, host->data));
omap_free_dma(dma_ch);
}
host->data = NULL;
}
/*
* Readable error output
*/
#ifdef CONFIG_MMC_DEBUG
static void omap_hsmmc_dbg_report_irq(struct omap_hsmmc_host *host, u32 status)
{
/* --- means reserved bit without definition at documentation */
static const char *omap_hsmmc_status_bits[] = {
"CC" , "TC" , "BGE", "---", "BWR" , "BRR" , "---" , "---" ,
"CIRQ", "OBI" , "---", "---", "---" , "---" , "---" , "ERRI",
"CTO" , "CCRC", "CEB", "CIE", "DTO" , "DCRC", "DEB" , "---" ,
"ACE" , "---" , "---", "---", "CERR", "BADA", "---" , "---"
};
char res[256];
char *buf = res;
int len, i;
len = sprintf(buf, "MMC IRQ 0x%x :", status);
buf += len;
for (i = 0; i < ARRAY_SIZE(omap_hsmmc_status_bits); i++)
if (status & (1 << i)) {
len = sprintf(buf, " %s", omap_hsmmc_status_bits[i]);
buf += len;
}
dev_dbg(mmc_dev(host->mmc), "%s\n", res);
}
#else
static inline void omap_hsmmc_dbg_report_irq(struct omap_hsmmc_host *host,
u32 status)
{
}
#endif /* CONFIG_MMC_DEBUG */
/*
* MMC controller internal state machines reset
*
* Used to reset command or data internal state machines, using respectively
* SRC or SRD bit of SYSCTL register
* Can be called from interrupt context
*/
static inline void omap_hsmmc_reset_controller_fsm(struct omap_hsmmc_host *host,
unsigned long bit)
{
unsigned long i = 0;
unsigned long limit = (loops_per_jiffy *
msecs_to_jiffies(MMC_TIMEOUT_MS));
OMAP_HSMMC_WRITE(host->base, SYSCTL,
OMAP_HSMMC_READ(host->base, SYSCTL) | bit);
/*
* OMAP4 ES2 and greater has an updated reset logic.
* Monitor a 0->1 transition first
*/
if (mmc_slot(host).features & HSMMC_HAS_UPDATED_RESET) {
while ((!(OMAP_HSMMC_READ(host->base, SYSCTL) & bit))
&& (i++ < limit))
cpu_relax();
}
i = 0;
while ((OMAP_HSMMC_READ(host->base, SYSCTL) & bit) &&
(i++ < limit))
cpu_relax();
if (OMAP_HSMMC_READ(host->base, SYSCTL) & bit)
dev_err(mmc_dev(host->mmc),
"Timeout waiting on controller reset in %s\n",
__func__);
}
static void omap_hsmmc_do_irq(struct omap_hsmmc_host *host, int status)
{
struct mmc_data *data;
int end_cmd = 0, end_trans = 0;
if (!host->req_in_progress) {
do {
OMAP_HSMMC_WRITE(host->base, STAT, status);
/* Flush posted write */
status = OMAP_HSMMC_READ(host->base, STAT);
} while (status & INT_EN_MASK);
return;
}
data = host->data;
dev_dbg(mmc_dev(host->mmc), "IRQ Status is %x\n", status);
if (status & ERR) {
omap_hsmmc_dbg_report_irq(host, status);
if ((status & CMD_TIMEOUT) ||
(status & CMD_CRC)) {
if (host->cmd) {
if (status & CMD_TIMEOUT) {
omap_hsmmc_reset_controller_fsm(host,
SRC);
host->cmd->error = -ETIMEDOUT;
} else {
host->cmd->error = -EILSEQ;
}
end_cmd = 1;
}
if (host->data || host->response_busy) {
if (host->data)
omap_hsmmc_dma_cleanup(host,
-ETIMEDOUT);
host->response_busy = 0;
omap_hsmmc_reset_controller_fsm(host, SRD);
}
}
if ((status & DATA_TIMEOUT) ||
(status & DATA_CRC)) {
if (host->data || host->response_busy) {
int err = (status & DATA_TIMEOUT) ?
-ETIMEDOUT : -EILSEQ;
if (host->data)
omap_hsmmc_dma_cleanup(host, err);
else
host->mrq->cmd->error = err;
host->response_busy = 0;
omap_hsmmc_reset_controller_fsm(host, SRD);
end_trans = 1;
}
}
if (status & CARD_ERR) {
dev_dbg(mmc_dev(host->mmc),
"Ignoring card err CMD%d\n", host->cmd->opcode);
if (host->cmd)
end_cmd = 1;
if (host->data)
end_trans = 1;
}
}
OMAP_HSMMC_WRITE(host->base, STAT, status);
if (end_cmd || ((status & CC) && host->cmd))
omap_hsmmc_cmd_done(host, host->cmd);
if ((end_trans || (status & TC)) && host->mrq)
omap_hsmmc_xfer_done(host, data);
}
/*
* MMC controller IRQ handler
*/
static irqreturn_t omap_hsmmc_irq(int irq, void *dev_id)
{
struct omap_hsmmc_host *host = dev_id;
int status;
status = OMAP_HSMMC_READ(host->base, STAT);
do {
omap_hsmmc_do_irq(host, status);
/* Flush posted write */
status = OMAP_HSMMC_READ(host->base, STAT);
} while (status & INT_EN_MASK);
return IRQ_HANDLED;
}
static void set_sd_bus_power(struct omap_hsmmc_host *host)
{
unsigned long i;
OMAP_HSMMC_WRITE(host->base, HCTL,
OMAP_HSMMC_READ(host->base, HCTL) | SDBP);
for (i = 0; i < loops_per_jiffy; i++) {
if (OMAP_HSMMC_READ(host->base, HCTL) & SDBP)
break;
cpu_relax();
}
}
/*
* Switch MMC interface voltage ... only relevant for MMC1.
*
* MMC2 and MMC3 use fixed 1.8V levels, and maybe a transceiver.
* The MMC2 transceiver controls are used instead of DAT4..DAT7.
* Some chips, like eMMC ones, use internal transceivers.
*/
static int omap_hsmmc_switch_opcond(struct omap_hsmmc_host *host, int vdd)
{
u32 reg_val = 0;
int ret;
/* Disable the clocks */
pm_runtime_put_sync(host->dev);
if (host->got_dbclk)
clk_disable(host->dbclk);
/* Turn the power off */
ret = mmc_slot(host).set_power(host->dev, host->slot_id, 0, 0);
/* Turn the power ON with given VDD 1.8 or 3.0v */
if (!ret)
ret = mmc_slot(host).set_power(host->dev, host->slot_id, 1,
vdd);
pm_runtime_get_sync(host->dev);
if (host->got_dbclk)
clk_enable(host->dbclk);
if (ret != 0)
goto err;
OMAP_HSMMC_WRITE(host->base, HCTL,
OMAP_HSMMC_READ(host->base, HCTL) & SDVSCLR);
reg_val = OMAP_HSMMC_READ(host->base, HCTL);
/*
* If a MMC dual voltage card is detected, the set_ios fn calls
* this fn with VDD bit set for 1.8V. Upon card removal from the
* slot, omap_hsmmc_set_ios sets the VDD back to 3V on MMC_POWER_OFF.
*
* Cope with a bit of slop in the range ... per data sheets:
* - "1.8V" for vdds_mmc1/vdds_mmc1a can be up to 2.45V max,
* but recommended values are 1.71V to 1.89V
* - "3.0V" for vdds_mmc1/vdds_mmc1a can be up to 3.5V max,
* but recommended values are 2.7V to 3.3V
*
* Board setup code shouldn't permit anything very out-of-range.
* TWL4030-family VMMC1 and VSIM regulators are fine (avoiding the
* middle range) but VSIM can't power DAT4..DAT7 at more than 3V.
*/
if ((1 << vdd) <= MMC_VDD_23_24)
reg_val |= SDVS18;
else
reg_val |= SDVS30;
OMAP_HSMMC_WRITE(host->base, HCTL, reg_val);
set_sd_bus_power(host);
return 0;
err:
dev_dbg(mmc_dev(host->mmc), "Unable to switch operating voltage\n");
return ret;
}
/* Protect the card while the cover is open */
static void omap_hsmmc_protect_card(struct omap_hsmmc_host *host)
{
if (!mmc_slot(host).get_cover_state)
return;
host->reqs_blocked = 0;
if (mmc_slot(host).get_cover_state(host->dev, host->slot_id)) {
if (host->protect_card) {
printk(KERN_INFO "%s: cover is closed, "
"card is now accessible\n",
mmc_hostname(host->mmc));
host->protect_card = 0;
}
} else {
if (!host->protect_card) {
printk(KERN_INFO "%s: cover is open, "
"card is now inaccessible\n",
mmc_hostname(host->mmc));
host->protect_card = 1;
}
}
}
/*
* Work Item to notify the core about card insertion/removal
*/
static void omap_hsmmc_detect(struct work_struct *work)
{
struct omap_hsmmc_host *host =
container_of(work, struct omap_hsmmc_host, mmc_carddetect_work);
struct omap_mmc_slot_data *slot = &mmc_slot(host);
int carddetect;
if (host->suspended)
return;
sysfs_notify(&host->mmc->class_dev.kobj, NULL, "cover_switch");
if (slot->card_detect)
carddetect = slot->card_detect(host->dev, host->slot_id);
else {
omap_hsmmc_protect_card(host);
carddetect = -ENOSYS;
}
if (carddetect)
mmc_detect_change(host->mmc, (HZ * 200) / 1000);
else
mmc_detect_change(host->mmc, (HZ * 50) / 1000);
}
/*
* ISR for handling card insertion and removal
*/
static irqreturn_t omap_hsmmc_cd_handler(int irq, void *dev_id)
{
struct omap_hsmmc_host *host = (struct omap_hsmmc_host *)dev_id;
if (host->suspended)
return IRQ_HANDLED;
schedule_work(&host->mmc_carddetect_work);
return IRQ_HANDLED;
}
static int omap_hsmmc_get_dma_sync_dev(struct omap_hsmmc_host *host,
struct mmc_data *data)
{
int sync_dev;
if (data->flags & MMC_DATA_WRITE)
sync_dev = host->dma_line_tx;
else
sync_dev = host->dma_line_rx;
return sync_dev;
}
static void omap_hsmmc_config_dma_params(struct omap_hsmmc_host *host,
struct mmc_data *data,
struct scatterlist *sgl)
{
int blksz, nblk, dma_ch;
dma_ch = host->dma_ch;
if (data->flags & MMC_DATA_WRITE) {
omap_set_dma_dest_params(dma_ch, 0, OMAP_DMA_AMODE_CONSTANT,
(host->mapbase + OMAP_HSMMC_DATA), 0, 0);
omap_set_dma_src_params(dma_ch, 0, OMAP_DMA_AMODE_POST_INC,
sg_dma_address(sgl), 0, 0);
} else {
omap_set_dma_src_params(dma_ch, 0, OMAP_DMA_AMODE_CONSTANT,
(host->mapbase + OMAP_HSMMC_DATA), 0, 0);
omap_set_dma_dest_params(dma_ch, 0, OMAP_DMA_AMODE_POST_INC,
sg_dma_address(sgl), 0, 0);
}
blksz = host->data->blksz;
nblk = sg_dma_len(sgl) / blksz;
omap_set_dma_transfer_params(dma_ch, OMAP_DMA_DATA_TYPE_S32,
blksz / 4, nblk, OMAP_DMA_SYNC_FRAME,
omap_hsmmc_get_dma_sync_dev(host, data),
!(data->flags & MMC_DATA_WRITE));
omap_start_dma(dma_ch);
}
/*
* DMA call back function
*/
static void omap_hsmmc_dma_cb(int lch, u16 ch_status, void *cb_data)
{
struct omap_hsmmc_host *host = cb_data;
struct mmc_data *data;
int dma_ch, req_in_progress;
if (!(ch_status & OMAP_DMA_BLOCK_IRQ)) {
dev_warn(mmc_dev(host->mmc), "unexpected dma status %x\n",
ch_status);
return;
}
spin_lock(&host->irq_lock);
if (host->dma_ch < 0) {
spin_unlock(&host->irq_lock);
return;
}
data = host->mrq->data;
host->dma_sg_idx++;
if (host->dma_sg_idx < host->dma_len) {
/* Fire up the next transfer. */
omap_hsmmc_config_dma_params(host, data,
data->sg + host->dma_sg_idx);
spin_unlock(&host->irq_lock);
return;
}
if (!data->host_cookie)
dma_unmap_sg(mmc_dev(host->mmc), data->sg, data->sg_len,
omap_hsmmc_get_dma_dir(host, data));
req_in_progress = host->req_in_progress;
dma_ch = host->dma_ch;
host->dma_ch = -1;
spin_unlock(&host->irq_lock);
omap_free_dma(dma_ch);
/* If DMA has finished after TC, complete the request */
if (!req_in_progress) {
struct mmc_request *mrq = host->mrq;
host->mrq = NULL;
mmc_request_done(host->mmc, mrq);
}
}
static int omap_hsmmc_pre_dma_transfer(struct omap_hsmmc_host *host,
struct mmc_data *data,
struct omap_hsmmc_next *next)
{
int dma_len;
if (!next && data->host_cookie &&
data->host_cookie != host->next_data.cookie) {
printk(KERN_WARNING "[%s] invalid cookie: data->host_cookie %d"
" host->next_data.cookie %d\n",
__func__, data->host_cookie, host->next_data.cookie);
data->host_cookie = 0;
}
/* Check if next job is already prepared */
if (next ||
(!next && data->host_cookie != host->next_data.cookie)) {
dma_len = dma_map_sg(mmc_dev(host->mmc), data->sg,
data->sg_len,
omap_hsmmc_get_dma_dir(host, data));
} else {
dma_len = host->next_data.dma_len;
host->next_data.dma_len = 0;
}
if (dma_len == 0)
return -EINVAL;
if (next) {
next->dma_len = dma_len;
data->host_cookie = ++next->cookie < 0 ? 1 : next->cookie;
} else
host->dma_len = dma_len;
return 0;
}
/*
* Routine to configure and start DMA for the MMC card
*/
static int omap_hsmmc_start_dma_transfer(struct omap_hsmmc_host *host,
struct mmc_request *req)
{
int dma_ch = 0, ret = 0, i;
struct mmc_data *data = req->data;
/* Sanity check: all the SG entries must be aligned by block size. */
for (i = 0; i < data->sg_len; i++) {
struct scatterlist *sgl;
sgl = data->sg + i;
if (sgl->length % data->blksz)
return -EINVAL;
}
if ((data->blksz % 4) != 0)
/* REVISIT: The MMC buffer increments only when MSB is written.
* Return error for blksz which is non multiple of four.
*/
return -EINVAL;
BUG_ON(host->dma_ch != -1);
ret = omap_request_dma(omap_hsmmc_get_dma_sync_dev(host, data),
"MMC/SD", omap_hsmmc_dma_cb, host, &dma_ch);
if (ret != 0) {
dev_err(mmc_dev(host->mmc),
"%s: omap_request_dma() failed with %d\n",
mmc_hostname(host->mmc), ret);
return ret;
}
ret = omap_hsmmc_pre_dma_transfer(host, data, NULL);
if (ret)
return ret;
host->dma_ch = dma_ch;
host->dma_sg_idx = 0;
omap_hsmmc_config_dma_params(host, data, data->sg);
return 0;
}
static void set_data_timeout(struct omap_hsmmc_host *host,
unsigned int timeout_ns,
unsigned int timeout_clks)
{
unsigned int timeout, cycle_ns;
uint32_t reg, clkd, dto = 0;
reg = OMAP_HSMMC_READ(host->base, SYSCTL);
clkd = (reg & CLKD_MASK) >> CLKD_SHIFT;
if (clkd == 0)
clkd = 1;
cycle_ns = 1000000000 / (clk_get_rate(host->fclk) / clkd);
timeout = timeout_ns / cycle_ns;
timeout += timeout_clks;
if (timeout) {
while ((timeout & 0x80000000) == 0) {
dto += 1;
timeout <<= 1;
}
dto = 31 - dto;
timeout <<= 1;
if (timeout && dto)
dto += 1;
if (dto >= 13)
dto -= 13;
else
dto = 0;
if (dto > 14)
dto = 14;
}
reg &= ~DTO_MASK;
reg |= dto << DTO_SHIFT;
OMAP_HSMMC_WRITE(host->base, SYSCTL, reg);
}
/*
* Configure block length for MMC/SD cards and initiate the transfer.
*/
static int
omap_hsmmc_prepare_data(struct omap_hsmmc_host *host, struct mmc_request *req)
{
int ret;
host->data = req->data;
if (req->data == NULL) {
OMAP_HSMMC_WRITE(host->base, BLK, 0);
/*
* Set an arbitrary 100ms data timeout for commands with
* busy signal.
*/
if (req->cmd->flags & MMC_RSP_BUSY)
set_data_timeout(host, 100000000U, 0);
return 0;
}
OMAP_HSMMC_WRITE(host->base, BLK, (req->data->blksz)
| (req->data->blocks << 16));
set_data_timeout(host, req->data->timeout_ns, req->data->timeout_clks);
if (host->use_dma) {
ret = omap_hsmmc_start_dma_transfer(host, req);
if (ret != 0) {
dev_dbg(mmc_dev(host->mmc), "MMC start dma failure\n");
return ret;
}
}
return 0;
}
static void omap_hsmmc_post_req(struct mmc_host *mmc, struct mmc_request *mrq,
int err)
{
struct omap_hsmmc_host *host = mmc_priv(mmc);
struct mmc_data *data = mrq->data;
if (host->use_dma) {
dma_unmap_sg(mmc_dev(host->mmc), data->sg, data->sg_len,
omap_hsmmc_get_dma_dir(host, data));
data->host_cookie = 0;
}
}
static void omap_hsmmc_pre_req(struct mmc_host *mmc, struct mmc_request *mrq,
bool is_first_req)
{
struct omap_hsmmc_host *host = mmc_priv(mmc);
if (mrq->data->host_cookie) {
mrq->data->host_cookie = 0;
return ;
}
if (host->use_dma)
if (omap_hsmmc_pre_dma_transfer(host, mrq->data,
&host->next_data))
mrq->data->host_cookie = 0;
}
/*
* Request function. for read/write operation
*/
static void omap_hsmmc_request(struct mmc_host *mmc, struct mmc_request *req)
{
struct omap_hsmmc_host *host = mmc_priv(mmc);
int err;
BUG_ON(host->req_in_progress);
BUG_ON(host->dma_ch != -1);
if (host->protect_card) {
if (host->reqs_blocked < 3) {
/*
* Ensure the controller is left in a consistent
* state by resetting the command and data state
* machines.
*/
omap_hsmmc_reset_controller_fsm(host, SRD);
omap_hsmmc_reset_controller_fsm(host, SRC);
host->reqs_blocked += 1;
}
req->cmd->error = -EBADF;
if (req->data)
req->data->error = -EBADF;
req->cmd->retries = 0;
mmc_request_done(mmc, req);
return;
} else if (host->reqs_blocked)
host->reqs_blocked = 0;
WARN_ON(host->mrq != NULL);
host->mrq = req;
err = omap_hsmmc_prepare_data(host, req);
if (err) {
req->cmd->error = err;
if (req->data)
req->data->error = err;
host->mrq = NULL;
mmc_request_done(mmc, req);
return;
}
omap_hsmmc_start_command(host, req->cmd, req->data);
}
/* Routine to configure clock values. Exposed API to core */
static void omap_hsmmc_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
{
struct omap_hsmmc_host *host = mmc_priv(mmc);
int do_send_init_stream = 0;
pm_runtime_get_sync(host->dev);
if (ios->power_mode != host->power_mode) {
switch (ios->power_mode) {
case MMC_POWER_OFF:
mmc_slot(host).set_power(host->dev, host->slot_id,
0, 0);
host->vdd = 0;
break;
case MMC_POWER_UP:
mmc_slot(host).set_power(host->dev, host->slot_id,
1, ios->vdd);
host->vdd = ios->vdd;
break;
case MMC_POWER_ON:
do_send_init_stream = 1;
break;
}
host->power_mode = ios->power_mode;
}
/* FIXME: set registers based only on changes to ios */
omap_hsmmc_set_bus_width(host);
if (host->pdata->controller_flags & OMAP_HSMMC_SUPPORTS_DUAL_VOLT) {
/* Only MMC1 can interface at 3V without some flavor
* of external transceiver; but they all handle 1.8V.
*/
if ((OMAP_HSMMC_READ(host->base, HCTL) & SDVSDET) &&
(ios->vdd == DUAL_VOLT_OCR_BIT)) {
/*
* The mmc_select_voltage fn of the core does
* not seem to set the power_mode to
* MMC_POWER_UP upon recalculating the voltage.
* vdd 1.8v.
*/
if (omap_hsmmc_switch_opcond(host, ios->vdd) != 0)
dev_dbg(mmc_dev(host->mmc),
"Switch operation failed\n");
}
}
omap_hsmmc_set_clock(host);
if (do_send_init_stream)
send_init_stream(host);
omap_hsmmc_set_bus_mode(host);
pm_runtime_put_autosuspend(host->dev);
}
static int omap_hsmmc_get_cd(struct mmc_host *mmc)
{
struct omap_hsmmc_host *host = mmc_priv(mmc);
if (!mmc_slot(host).card_detect)
return -ENOSYS;
return mmc_slot(host).card_detect(host->dev, host->slot_id);
}
static int omap_hsmmc_get_ro(struct mmc_host *mmc)
{
struct omap_hsmmc_host *host = mmc_priv(mmc);
if (!mmc_slot(host).get_ro)
return -ENOSYS;
return mmc_slot(host).get_ro(host->dev, 0);
}
static void omap_hsmmc_init_card(struct mmc_host *mmc, struct mmc_card *card)
{
struct omap_hsmmc_host *host = mmc_priv(mmc);
if (mmc_slot(host).init_card)
mmc_slot(host).init_card(card);
}
static void omap_hsmmc_conf_bus_power(struct omap_hsmmc_host *host)
{
u32 hctl, capa, value;
/* Only MMC1 supports 3.0V */
if (host->pdata->controller_flags & OMAP_HSMMC_SUPPORTS_DUAL_VOLT) {
hctl = SDVS30;
capa = VS30 | VS18;
} else {
hctl = SDVS18;
capa = VS18;
}
value = OMAP_HSMMC_READ(host->base, HCTL) & ~SDVS_MASK;
OMAP_HSMMC_WRITE(host->base, HCTL, value | hctl);
value = OMAP_HSMMC_READ(host->base, CAPA);
OMAP_HSMMC_WRITE(host->base, CAPA, value | capa);
/* Set the controller to AUTO IDLE mode */
value = OMAP_HSMMC_READ(host->base, SYSCONFIG);
OMAP_HSMMC_WRITE(host->base, SYSCONFIG, value | AUTOIDLE);
/* Set SD bus power bit */
set_sd_bus_power(host);
}
static int omap_hsmmc_enable_fclk(struct mmc_host *mmc)
{
struct omap_hsmmc_host *host = mmc_priv(mmc);
pm_runtime_get_sync(host->dev);
return 0;
}
static int omap_hsmmc_disable_fclk(struct mmc_host *mmc, int lazy)
{
struct omap_hsmmc_host *host = mmc_priv(mmc);
pm_runtime_mark_last_busy(host->dev);
pm_runtime_put_autosuspend(host->dev);
return 0;
}
static const struct mmc_host_ops omap_hsmmc_ops = {
.enable = omap_hsmmc_enable_fclk,
.disable = omap_hsmmc_disable_fclk,
.post_req = omap_hsmmc_post_req,
.pre_req = omap_hsmmc_pre_req,
.request = omap_hsmmc_request,
.set_ios = omap_hsmmc_set_ios,
.get_cd = omap_hsmmc_get_cd,
.get_ro = omap_hsmmc_get_ro,
.init_card = omap_hsmmc_init_card,
/* NYET -- enable_sdio_irq */
};
#ifdef CONFIG_DEBUG_FS
static int omap_hsmmc_regs_show(struct seq_file *s, void *data)
{
struct mmc_host *mmc = s->private;
struct omap_hsmmc_host *host = mmc_priv(mmc);
int context_loss = 0;
if (host->pdata->get_context_loss_count)
context_loss = host->pdata->get_context_loss_count(host->dev);
seq_printf(s, "mmc%d:\n"
" enabled:\t%d\n"
" dpm_state:\t%d\n"
" nesting_cnt:\t%d\n"
" ctx_loss:\t%d:%d\n"
"\nregs:\n",
mmc->index, mmc->enabled ? 1 : 0,
host->dpm_state, mmc->nesting_cnt,
host->context_loss, context_loss);
if (host->suspended) {
seq_printf(s, "host suspended, can't read registers\n");
return 0;
}
pm_runtime_get_sync(host->dev);
seq_printf(s, "SYSCONFIG:\t0x%08x\n",
OMAP_HSMMC_READ(host->base, SYSCONFIG));
seq_printf(s, "CON:\t\t0x%08x\n",
OMAP_HSMMC_READ(host->base, CON));
seq_printf(s, "HCTL:\t\t0x%08x\n",
OMAP_HSMMC_READ(host->base, HCTL));
seq_printf(s, "SYSCTL:\t\t0x%08x\n",
OMAP_HSMMC_READ(host->base, SYSCTL));
seq_printf(s, "IE:\t\t0x%08x\n",
OMAP_HSMMC_READ(host->base, IE));
seq_printf(s, "ISE:\t\t0x%08x\n",
OMAP_HSMMC_READ(host->base, ISE));
seq_printf(s, "CAPA:\t\t0x%08x\n",
OMAP_HSMMC_READ(host->base, CAPA));
pm_runtime_mark_last_busy(host->dev);
pm_runtime_put_autosuspend(host->dev);
return 0;
}
static int omap_hsmmc_regs_open(struct inode *inode, struct file *file)
{
return single_open(file, omap_hsmmc_regs_show, inode->i_private);
}
static const struct file_operations mmc_regs_fops = {
.open = omap_hsmmc_regs_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static void omap_hsmmc_debugfs(struct mmc_host *mmc)
{
if (mmc->debugfs_root)
debugfs_create_file("regs", S_IRUSR, mmc->debugfs_root,
mmc, &mmc_regs_fops);
}
#else
static void omap_hsmmc_debugfs(struct mmc_host *mmc)
{
}
#endif
static int __init omap_hsmmc_probe(struct platform_device *pdev)
{
struct omap_mmc_platform_data *pdata = pdev->dev.platform_data;
struct mmc_host *mmc;
struct omap_hsmmc_host *host = NULL;
struct resource *res;
int ret, irq;
if (pdata == NULL) {
dev_err(&pdev->dev, "Platform Data is missing\n");
return -ENXIO;
}
if (pdata->nr_slots == 0) {
dev_err(&pdev->dev, "No Slots\n");
return -ENXIO;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
irq = platform_get_irq(pdev, 0);
if (res == NULL || irq < 0)
return -ENXIO;
res->start += pdata->reg_offset;
res->end += pdata->reg_offset;
res = request_mem_region(res->start, resource_size(res), pdev->name);
if (res == NULL)
return -EBUSY;
ret = omap_hsmmc_gpio_init(pdata);
if (ret)
goto err;
mmc = mmc_alloc_host(sizeof(struct omap_hsmmc_host), &pdev->dev);
if (!mmc) {
ret = -ENOMEM;
goto err_alloc;
}
host = mmc_priv(mmc);
host->mmc = mmc;
host->pdata = pdata;
host->dev = &pdev->dev;
host->use_dma = 1;
host->dev->dma_mask = &pdata->dma_mask;
host->dma_ch = -1;
host->irq = irq;
host->id = pdev->id;
host->slot_id = 0;
host->mapbase = res->start;
host->base = ioremap(host->mapbase, SZ_4K);
host->power_mode = MMC_POWER_OFF;
host->next_data.cookie = 1;
platform_set_drvdata(pdev, host);
INIT_WORK(&host->mmc_carddetect_work, omap_hsmmc_detect);
mmc->ops = &omap_hsmmc_ops;
/*
* If regulator_disable can only put vcc_aux to sleep then there is
* no off state.
*/
if (mmc_slot(host).vcc_aux_disable_is_sleep)
mmc_slot(host).no_off = 1;
mmc->f_min = OMAP_MMC_MIN_CLOCK;
mmc->f_max = OMAP_MMC_MAX_CLOCK;
spin_lock_init(&host->irq_lock);
host->fclk = clk_get(&pdev->dev, "fck");
if (IS_ERR(host->fclk)) {
ret = PTR_ERR(host->fclk);
host->fclk = NULL;
goto err1;
}
omap_hsmmc_context_save(host);
mmc->caps |= MMC_CAP_DISABLE;
pm_runtime_enable(host->dev);
pm_runtime_get_sync(host->dev);
pm_runtime_set_autosuspend_delay(host->dev, MMC_AUTOSUSPEND_DELAY);
pm_runtime_use_autosuspend(host->dev);
if (cpu_is_omap2430()) {
host->dbclk = clk_get(&pdev->dev, "mmchsdb_fck");
/*
* MMC can still work without debounce clock.
*/
if (IS_ERR(host->dbclk))
dev_warn(mmc_dev(host->mmc),
"Failed to get debounce clock\n");
else
host->got_dbclk = 1;
if (host->got_dbclk)
if (clk_enable(host->dbclk) != 0)
dev_dbg(mmc_dev(host->mmc), "Enabling debounce"
" clk failed\n");
}
/* Since we do only SG emulation, we can have as many segs
* as we want. */
mmc->max_segs = 1024;
mmc->max_blk_size = 512; /* Block Length at max can be 1024 */
mmc->max_blk_count = 0xFFFF; /* No. of Blocks is 16 bits */
mmc->max_req_size = mmc->max_blk_size * mmc->max_blk_count;
mmc->max_seg_size = mmc->max_req_size;
mmc->caps |= MMC_CAP_MMC_HIGHSPEED | MMC_CAP_SD_HIGHSPEED |
MMC_CAP_WAIT_WHILE_BUSY | MMC_CAP_ERASE;
mmc->caps |= mmc_slot(host).caps;
if (mmc->caps & MMC_CAP_8_BIT_DATA)
mmc->caps |= MMC_CAP_4_BIT_DATA;
if (mmc_slot(host).nonremovable)
mmc->caps |= MMC_CAP_NONREMOVABLE;
omap_hsmmc_conf_bus_power(host);
/* Select DMA lines */
switch (host->id) {
case OMAP_MMC1_DEVID:
host->dma_line_tx = OMAP24XX_DMA_MMC1_TX;
host->dma_line_rx = OMAP24XX_DMA_MMC1_RX;
break;
case OMAP_MMC2_DEVID:
host->dma_line_tx = OMAP24XX_DMA_MMC2_TX;
host->dma_line_rx = OMAP24XX_DMA_MMC2_RX;
break;
case OMAP_MMC3_DEVID:
host->dma_line_tx = OMAP34XX_DMA_MMC3_TX;
host->dma_line_rx = OMAP34XX_DMA_MMC3_RX;
break;
case OMAP_MMC4_DEVID:
host->dma_line_tx = OMAP44XX_DMA_MMC4_TX;
host->dma_line_rx = OMAP44XX_DMA_MMC4_RX;
break;
case OMAP_MMC5_DEVID:
host->dma_line_tx = OMAP44XX_DMA_MMC5_TX;
host->dma_line_rx = OMAP44XX_DMA_MMC5_RX;
break;
default:
dev_err(mmc_dev(host->mmc), "Invalid MMC id\n");
goto err_irq;
}
/* Request IRQ for MMC operations */
ret = request_irq(host->irq, omap_hsmmc_irq, IRQF_DISABLED,
mmc_hostname(mmc), host);
if (ret) {
dev_dbg(mmc_dev(host->mmc), "Unable to grab HSMMC IRQ\n");
goto err_irq;
}
if (pdata->init != NULL) {
if (pdata->init(&pdev->dev) != 0) {
dev_dbg(mmc_dev(host->mmc),
"Unable to configure MMC IRQs\n");
goto err_irq_cd_init;
}
}
if (omap_hsmmc_have_reg() && !mmc_slot(host).set_power) {
ret = omap_hsmmc_reg_get(host);
if (ret)
goto err_reg;
host->use_reg = 1;
}
mmc->ocr_avail = mmc_slot(host).ocr_mask;
/* Request IRQ for card detect */
if ((mmc_slot(host).card_detect_irq)) {
ret = request_irq(mmc_slot(host).card_detect_irq,
omap_hsmmc_cd_handler,
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING
| IRQF_DISABLED,
mmc_hostname(mmc), host);
if (ret) {
dev_dbg(mmc_dev(host->mmc),
"Unable to grab MMC CD IRQ\n");
goto err_irq_cd;
}
pdata->suspend = omap_hsmmc_suspend_cdirq;
pdata->resume = omap_hsmmc_resume_cdirq;
}
omap_hsmmc_disable_irq(host);
omap_hsmmc_protect_card(host);
mmc_add_host(mmc);
if (mmc_slot(host).name != NULL) {
ret = device_create_file(&mmc->class_dev, &dev_attr_slot_name);
if (ret < 0)
goto err_slot_name;
}
if (mmc_slot(host).card_detect_irq && mmc_slot(host).get_cover_state) {
ret = device_create_file(&mmc->class_dev,
&dev_attr_cover_switch);
if (ret < 0)
goto err_slot_name;
}
omap_hsmmc_debugfs(mmc);
pm_runtime_mark_last_busy(host->dev);
pm_runtime_put_autosuspend(host->dev);
return 0;
err_slot_name:
mmc_remove_host(mmc);
free_irq(mmc_slot(host).card_detect_irq, host);
err_irq_cd:
if (host->use_reg)
omap_hsmmc_reg_put(host);
err_reg:
if (host->pdata->cleanup)
host->pdata->cleanup(&pdev->dev);
err_irq_cd_init:
free_irq(host->irq, host);
err_irq:
pm_runtime_mark_last_busy(host->dev);
pm_runtime_put_autosuspend(host->dev);
clk_put(host->fclk);
if (host->got_dbclk) {
clk_disable(host->dbclk);
clk_put(host->dbclk);
}
err1:
iounmap(host->base);
platform_set_drvdata(pdev, NULL);
mmc_free_host(mmc);
err_alloc:
omap_hsmmc_gpio_free(pdata);
err:
release_mem_region(res->start, resource_size(res));
return ret;
}
static int omap_hsmmc_remove(struct platform_device *pdev)
{
struct omap_hsmmc_host *host = platform_get_drvdata(pdev);
struct resource *res;
if (host) {
pm_runtime_get_sync(host->dev);
mmc_remove_host(host->mmc);
if (host->use_reg)
omap_hsmmc_reg_put(host);
if (host->pdata->cleanup)
host->pdata->cleanup(&pdev->dev);
free_irq(host->irq, host);
if (mmc_slot(host).card_detect_irq)
free_irq(mmc_slot(host).card_detect_irq, host);
flush_work_sync(&host->mmc_carddetect_work);
pm_runtime_put_sync(host->dev);
pm_runtime_disable(host->dev);
clk_put(host->fclk);
if (host->got_dbclk) {
clk_disable(host->dbclk);
clk_put(host->dbclk);
}
mmc_free_host(host->mmc);
iounmap(host->base);
omap_hsmmc_gpio_free(pdev->dev.platform_data);
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res)
release_mem_region(res->start, resource_size(res));
platform_set_drvdata(pdev, NULL);
return 0;
}
#ifdef CONFIG_PM
static int omap_hsmmc_suspend(struct device *dev)
{
int ret = 0;
struct platform_device *pdev = to_platform_device(dev);
struct omap_hsmmc_host *host = platform_get_drvdata(pdev);
if (host && host->suspended)
return 0;
if (host) {
pm_runtime_get_sync(host->dev);
host->suspended = 1;
if (host->pdata->suspend) {
ret = host->pdata->suspend(&pdev->dev,
host->slot_id);
if (ret) {
dev_dbg(mmc_dev(host->mmc),
"Unable to handle MMC board"
" level suspend\n");
host->suspended = 0;
return ret;
}
}
cancel_work_sync(&host->mmc_carddetect_work);
ret = mmc_suspend_host(host->mmc);
if (ret == 0) {
omap_hsmmc_disable_irq(host);
OMAP_HSMMC_WRITE(host->base, HCTL,
OMAP_HSMMC_READ(host->base, HCTL) & ~SDBP);
if (host->got_dbclk)
clk_disable(host->dbclk);
} else {
host->suspended = 0;
if (host->pdata->resume) {
ret = host->pdata->resume(&pdev->dev,
host->slot_id);
if (ret)
dev_dbg(mmc_dev(host->mmc),
"Unmask interrupt failed\n");
}
}
pm_runtime_put_sync(host->dev);
}
return ret;
}
/* Routine to resume the MMC device */
static int omap_hsmmc_resume(struct device *dev)
{
int ret = 0;
struct platform_device *pdev = to_platform_device(dev);
struct omap_hsmmc_host *host = platform_get_drvdata(pdev);
if (host && !host->suspended)
return 0;
if (host) {
pm_runtime_get_sync(host->dev);
if (host->got_dbclk)
clk_enable(host->dbclk);
omap_hsmmc_conf_bus_power(host);
if (host->pdata->resume) {
ret = host->pdata->resume(&pdev->dev, host->slot_id);
if (ret)
dev_dbg(mmc_dev(host->mmc),
"Unmask interrupt failed\n");
}
omap_hsmmc_protect_card(host);
/* Notify the core to resume the host */
ret = mmc_resume_host(host->mmc);
if (ret == 0)
host->suspended = 0;
pm_runtime_mark_last_busy(host->dev);
pm_runtime_put_autosuspend(host->dev);
}
return ret;
}
#else
#define omap_hsmmc_suspend NULL
#define omap_hsmmc_resume NULL
#endif
static int omap_hsmmc_runtime_suspend(struct device *dev)
{
struct omap_hsmmc_host *host;
host = platform_get_drvdata(to_platform_device(dev));
omap_hsmmc_context_save(host);
dev_dbg(mmc_dev(host->mmc), "disabled\n");
return 0;
}
static int omap_hsmmc_runtime_resume(struct device *dev)
{
struct omap_hsmmc_host *host;
host = platform_get_drvdata(to_platform_device(dev));
omap_hsmmc_context_restore(host);
dev_dbg(mmc_dev(host->mmc), "enabled\n");
return 0;
}
static struct dev_pm_ops omap_hsmmc_dev_pm_ops = {
.suspend = omap_hsmmc_suspend,
.resume = omap_hsmmc_resume,
.runtime_suspend = omap_hsmmc_runtime_suspend,
.runtime_resume = omap_hsmmc_runtime_resume,
};
static struct platform_driver omap_hsmmc_driver = {
.remove = omap_hsmmc_remove,
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
.pm = &omap_hsmmc_dev_pm_ops,
},
};
static int __init omap_hsmmc_init(void)
{
/* Register the MMC driver */
return platform_driver_probe(&omap_hsmmc_driver, omap_hsmmc_probe);
}
static void __exit omap_hsmmc_cleanup(void)
{
/* Unregister MMC driver */
platform_driver_unregister(&omap_hsmmc_driver);
}
module_init(omap_hsmmc_init);
module_exit(omap_hsmmc_cleanup);
MODULE_DESCRIPTION("OMAP High Speed Multimedia Card driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" DRIVER_NAME);
MODULE_AUTHOR("Texas Instruments Inc");
| gpl-2.0 |
Dm47021/Linux-kernel_4.1.15-rt17_MusicOS | drivers/scsi/pm8001/pm8001_hwi.c | 614 | 166256 | /*
* PMC-Sierra SPC 8001 SAS/SATA based host adapters driver
*
* Copyright (c) 2008-2009 USI Co., Ltd.
* 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 <linux/slab.h>
#include "pm8001_sas.h"
#include "pm8001_hwi.h"
#include "pm8001_chips.h"
#include "pm8001_ctl.h"
/**
* read_main_config_table - read the configure table and save it.
* @pm8001_ha: our hba card information
*/
static void read_main_config_table(struct pm8001_hba_info *pm8001_ha)
{
void __iomem *address = pm8001_ha->main_cfg_tbl_addr;
pm8001_ha->main_cfg_tbl.pm8001_tbl.signature =
pm8001_mr32(address, 0x00);
pm8001_ha->main_cfg_tbl.pm8001_tbl.interface_rev =
pm8001_mr32(address, 0x04);
pm8001_ha->main_cfg_tbl.pm8001_tbl.firmware_rev =
pm8001_mr32(address, 0x08);
pm8001_ha->main_cfg_tbl.pm8001_tbl.max_out_io =
pm8001_mr32(address, 0x0C);
pm8001_ha->main_cfg_tbl.pm8001_tbl.max_sgl =
pm8001_mr32(address, 0x10);
pm8001_ha->main_cfg_tbl.pm8001_tbl.ctrl_cap_flag =
pm8001_mr32(address, 0x14);
pm8001_ha->main_cfg_tbl.pm8001_tbl.gst_offset =
pm8001_mr32(address, 0x18);
pm8001_ha->main_cfg_tbl.pm8001_tbl.inbound_queue_offset =
pm8001_mr32(address, MAIN_IBQ_OFFSET);
pm8001_ha->main_cfg_tbl.pm8001_tbl.outbound_queue_offset =
pm8001_mr32(address, MAIN_OBQ_OFFSET);
pm8001_ha->main_cfg_tbl.pm8001_tbl.hda_mode_flag =
pm8001_mr32(address, MAIN_HDA_FLAGS_OFFSET);
/* read analog Setting offset from the configuration table */
pm8001_ha->main_cfg_tbl.pm8001_tbl.anolog_setup_table_offset =
pm8001_mr32(address, MAIN_ANALOG_SETUP_OFFSET);
/* read Error Dump Offset and Length */
pm8001_ha->main_cfg_tbl.pm8001_tbl.fatal_err_dump_offset0 =
pm8001_mr32(address, MAIN_FATAL_ERROR_RDUMP0_OFFSET);
pm8001_ha->main_cfg_tbl.pm8001_tbl.fatal_err_dump_length0 =
pm8001_mr32(address, MAIN_FATAL_ERROR_RDUMP0_LENGTH);
pm8001_ha->main_cfg_tbl.pm8001_tbl.fatal_err_dump_offset1 =
pm8001_mr32(address, MAIN_FATAL_ERROR_RDUMP1_OFFSET);
pm8001_ha->main_cfg_tbl.pm8001_tbl.fatal_err_dump_length1 =
pm8001_mr32(address, MAIN_FATAL_ERROR_RDUMP1_LENGTH);
}
/**
* read_general_status_table - read the general status table and save it.
* @pm8001_ha: our hba card information
*/
static void read_general_status_table(struct pm8001_hba_info *pm8001_ha)
{
void __iomem *address = pm8001_ha->general_stat_tbl_addr;
pm8001_ha->gs_tbl.pm8001_tbl.gst_len_mpistate =
pm8001_mr32(address, 0x00);
pm8001_ha->gs_tbl.pm8001_tbl.iq_freeze_state0 =
pm8001_mr32(address, 0x04);
pm8001_ha->gs_tbl.pm8001_tbl.iq_freeze_state1 =
pm8001_mr32(address, 0x08);
pm8001_ha->gs_tbl.pm8001_tbl.msgu_tcnt =
pm8001_mr32(address, 0x0C);
pm8001_ha->gs_tbl.pm8001_tbl.iop_tcnt =
pm8001_mr32(address, 0x10);
pm8001_ha->gs_tbl.pm8001_tbl.rsvd =
pm8001_mr32(address, 0x14);
pm8001_ha->gs_tbl.pm8001_tbl.phy_state[0] =
pm8001_mr32(address, 0x18);
pm8001_ha->gs_tbl.pm8001_tbl.phy_state[1] =
pm8001_mr32(address, 0x1C);
pm8001_ha->gs_tbl.pm8001_tbl.phy_state[2] =
pm8001_mr32(address, 0x20);
pm8001_ha->gs_tbl.pm8001_tbl.phy_state[3] =
pm8001_mr32(address, 0x24);
pm8001_ha->gs_tbl.pm8001_tbl.phy_state[4] =
pm8001_mr32(address, 0x28);
pm8001_ha->gs_tbl.pm8001_tbl.phy_state[5] =
pm8001_mr32(address, 0x2C);
pm8001_ha->gs_tbl.pm8001_tbl.phy_state[6] =
pm8001_mr32(address, 0x30);
pm8001_ha->gs_tbl.pm8001_tbl.phy_state[7] =
pm8001_mr32(address, 0x34);
pm8001_ha->gs_tbl.pm8001_tbl.gpio_input_val =
pm8001_mr32(address, 0x38);
pm8001_ha->gs_tbl.pm8001_tbl.rsvd1[0] =
pm8001_mr32(address, 0x3C);
pm8001_ha->gs_tbl.pm8001_tbl.rsvd1[1] =
pm8001_mr32(address, 0x40);
pm8001_ha->gs_tbl.pm8001_tbl.recover_err_info[0] =
pm8001_mr32(address, 0x44);
pm8001_ha->gs_tbl.pm8001_tbl.recover_err_info[1] =
pm8001_mr32(address, 0x48);
pm8001_ha->gs_tbl.pm8001_tbl.recover_err_info[2] =
pm8001_mr32(address, 0x4C);
pm8001_ha->gs_tbl.pm8001_tbl.recover_err_info[3] =
pm8001_mr32(address, 0x50);
pm8001_ha->gs_tbl.pm8001_tbl.recover_err_info[4] =
pm8001_mr32(address, 0x54);
pm8001_ha->gs_tbl.pm8001_tbl.recover_err_info[5] =
pm8001_mr32(address, 0x58);
pm8001_ha->gs_tbl.pm8001_tbl.recover_err_info[6] =
pm8001_mr32(address, 0x5C);
pm8001_ha->gs_tbl.pm8001_tbl.recover_err_info[7] =
pm8001_mr32(address, 0x60);
}
/**
* read_inbnd_queue_table - read the inbound queue table and save it.
* @pm8001_ha: our hba card information
*/
static void read_inbnd_queue_table(struct pm8001_hba_info *pm8001_ha)
{
int i;
void __iomem *address = pm8001_ha->inbnd_q_tbl_addr;
for (i = 0; i < PM8001_MAX_INB_NUM; i++) {
u32 offset = i * 0x20;
pm8001_ha->inbnd_q_tbl[i].pi_pci_bar =
get_pci_bar_index(pm8001_mr32(address, (offset + 0x14)));
pm8001_ha->inbnd_q_tbl[i].pi_offset =
pm8001_mr32(address, (offset + 0x18));
}
}
/**
* read_outbnd_queue_table - read the outbound queue table and save it.
* @pm8001_ha: our hba card information
*/
static void read_outbnd_queue_table(struct pm8001_hba_info *pm8001_ha)
{
int i;
void __iomem *address = pm8001_ha->outbnd_q_tbl_addr;
for (i = 0; i < PM8001_MAX_OUTB_NUM; i++) {
u32 offset = i * 0x24;
pm8001_ha->outbnd_q_tbl[i].ci_pci_bar =
get_pci_bar_index(pm8001_mr32(address, (offset + 0x14)));
pm8001_ha->outbnd_q_tbl[i].ci_offset =
pm8001_mr32(address, (offset + 0x18));
}
}
/**
* init_default_table_values - init the default table.
* @pm8001_ha: our hba card information
*/
static void init_default_table_values(struct pm8001_hba_info *pm8001_ha)
{
int i;
u32 offsetib, offsetob;
void __iomem *addressib = pm8001_ha->inbnd_q_tbl_addr;
void __iomem *addressob = pm8001_ha->outbnd_q_tbl_addr;
pm8001_ha->main_cfg_tbl.pm8001_tbl.inbound_q_nppd_hppd = 0;
pm8001_ha->main_cfg_tbl.pm8001_tbl.outbound_hw_event_pid0_3 = 0;
pm8001_ha->main_cfg_tbl.pm8001_tbl.outbound_hw_event_pid4_7 = 0;
pm8001_ha->main_cfg_tbl.pm8001_tbl.outbound_ncq_event_pid0_3 = 0;
pm8001_ha->main_cfg_tbl.pm8001_tbl.outbound_ncq_event_pid4_7 = 0;
pm8001_ha->main_cfg_tbl.pm8001_tbl.outbound_tgt_ITNexus_event_pid0_3 =
0;
pm8001_ha->main_cfg_tbl.pm8001_tbl.outbound_tgt_ITNexus_event_pid4_7 =
0;
pm8001_ha->main_cfg_tbl.pm8001_tbl.outbound_tgt_ssp_event_pid0_3 = 0;
pm8001_ha->main_cfg_tbl.pm8001_tbl.outbound_tgt_ssp_event_pid4_7 = 0;
pm8001_ha->main_cfg_tbl.pm8001_tbl.outbound_tgt_smp_event_pid0_3 = 0;
pm8001_ha->main_cfg_tbl.pm8001_tbl.outbound_tgt_smp_event_pid4_7 = 0;
pm8001_ha->main_cfg_tbl.pm8001_tbl.upper_event_log_addr =
pm8001_ha->memoryMap.region[AAP1].phys_addr_hi;
pm8001_ha->main_cfg_tbl.pm8001_tbl.lower_event_log_addr =
pm8001_ha->memoryMap.region[AAP1].phys_addr_lo;
pm8001_ha->main_cfg_tbl.pm8001_tbl.event_log_size =
PM8001_EVENT_LOG_SIZE;
pm8001_ha->main_cfg_tbl.pm8001_tbl.event_log_option = 0x01;
pm8001_ha->main_cfg_tbl.pm8001_tbl.upper_iop_event_log_addr =
pm8001_ha->memoryMap.region[IOP].phys_addr_hi;
pm8001_ha->main_cfg_tbl.pm8001_tbl.lower_iop_event_log_addr =
pm8001_ha->memoryMap.region[IOP].phys_addr_lo;
pm8001_ha->main_cfg_tbl.pm8001_tbl.iop_event_log_size =
PM8001_EVENT_LOG_SIZE;
pm8001_ha->main_cfg_tbl.pm8001_tbl.iop_event_log_option = 0x01;
pm8001_ha->main_cfg_tbl.pm8001_tbl.fatal_err_interrupt = 0x01;
for (i = 0; i < PM8001_MAX_INB_NUM; i++) {
pm8001_ha->inbnd_q_tbl[i].element_pri_size_cnt =
PM8001_MPI_QUEUE | (pm8001_ha->iomb_size << 16) | (0x00<<30);
pm8001_ha->inbnd_q_tbl[i].upper_base_addr =
pm8001_ha->memoryMap.region[IB + i].phys_addr_hi;
pm8001_ha->inbnd_q_tbl[i].lower_base_addr =
pm8001_ha->memoryMap.region[IB + i].phys_addr_lo;
pm8001_ha->inbnd_q_tbl[i].base_virt =
(u8 *)pm8001_ha->memoryMap.region[IB + i].virt_ptr;
pm8001_ha->inbnd_q_tbl[i].total_length =
pm8001_ha->memoryMap.region[IB + i].total_len;
pm8001_ha->inbnd_q_tbl[i].ci_upper_base_addr =
pm8001_ha->memoryMap.region[CI + i].phys_addr_hi;
pm8001_ha->inbnd_q_tbl[i].ci_lower_base_addr =
pm8001_ha->memoryMap.region[CI + i].phys_addr_lo;
pm8001_ha->inbnd_q_tbl[i].ci_virt =
pm8001_ha->memoryMap.region[CI + i].virt_ptr;
offsetib = i * 0x20;
pm8001_ha->inbnd_q_tbl[i].pi_pci_bar =
get_pci_bar_index(pm8001_mr32(addressib,
(offsetib + 0x14)));
pm8001_ha->inbnd_q_tbl[i].pi_offset =
pm8001_mr32(addressib, (offsetib + 0x18));
pm8001_ha->inbnd_q_tbl[i].producer_idx = 0;
pm8001_ha->inbnd_q_tbl[i].consumer_index = 0;
}
for (i = 0; i < PM8001_MAX_OUTB_NUM; i++) {
pm8001_ha->outbnd_q_tbl[i].element_size_cnt =
PM8001_MPI_QUEUE | (pm8001_ha->iomb_size << 16) | (0x01<<30);
pm8001_ha->outbnd_q_tbl[i].upper_base_addr =
pm8001_ha->memoryMap.region[OB + i].phys_addr_hi;
pm8001_ha->outbnd_q_tbl[i].lower_base_addr =
pm8001_ha->memoryMap.region[OB + i].phys_addr_lo;
pm8001_ha->outbnd_q_tbl[i].base_virt =
(u8 *)pm8001_ha->memoryMap.region[OB + i].virt_ptr;
pm8001_ha->outbnd_q_tbl[i].total_length =
pm8001_ha->memoryMap.region[OB + i].total_len;
pm8001_ha->outbnd_q_tbl[i].pi_upper_base_addr =
pm8001_ha->memoryMap.region[PI + i].phys_addr_hi;
pm8001_ha->outbnd_q_tbl[i].pi_lower_base_addr =
pm8001_ha->memoryMap.region[PI + i].phys_addr_lo;
pm8001_ha->outbnd_q_tbl[i].interrup_vec_cnt_delay =
0 | (10 << 16) | (i << 24);
pm8001_ha->outbnd_q_tbl[i].pi_virt =
pm8001_ha->memoryMap.region[PI + i].virt_ptr;
offsetob = i * 0x24;
pm8001_ha->outbnd_q_tbl[i].ci_pci_bar =
get_pci_bar_index(pm8001_mr32(addressob,
offsetob + 0x14));
pm8001_ha->outbnd_q_tbl[i].ci_offset =
pm8001_mr32(addressob, (offsetob + 0x18));
pm8001_ha->outbnd_q_tbl[i].consumer_idx = 0;
pm8001_ha->outbnd_q_tbl[i].producer_index = 0;
}
}
/**
* update_main_config_table - update the main default table to the HBA.
* @pm8001_ha: our hba card information
*/
static void update_main_config_table(struct pm8001_hba_info *pm8001_ha)
{
void __iomem *address = pm8001_ha->main_cfg_tbl_addr;
pm8001_mw32(address, 0x24,
pm8001_ha->main_cfg_tbl.pm8001_tbl.inbound_q_nppd_hppd);
pm8001_mw32(address, 0x28,
pm8001_ha->main_cfg_tbl.pm8001_tbl.outbound_hw_event_pid0_3);
pm8001_mw32(address, 0x2C,
pm8001_ha->main_cfg_tbl.pm8001_tbl.outbound_hw_event_pid4_7);
pm8001_mw32(address, 0x30,
pm8001_ha->main_cfg_tbl.pm8001_tbl.outbound_ncq_event_pid0_3);
pm8001_mw32(address, 0x34,
pm8001_ha->main_cfg_tbl.pm8001_tbl.outbound_ncq_event_pid4_7);
pm8001_mw32(address, 0x38,
pm8001_ha->main_cfg_tbl.pm8001_tbl.
outbound_tgt_ITNexus_event_pid0_3);
pm8001_mw32(address, 0x3C,
pm8001_ha->main_cfg_tbl.pm8001_tbl.
outbound_tgt_ITNexus_event_pid4_7);
pm8001_mw32(address, 0x40,
pm8001_ha->main_cfg_tbl.pm8001_tbl.
outbound_tgt_ssp_event_pid0_3);
pm8001_mw32(address, 0x44,
pm8001_ha->main_cfg_tbl.pm8001_tbl.
outbound_tgt_ssp_event_pid4_7);
pm8001_mw32(address, 0x48,
pm8001_ha->main_cfg_tbl.pm8001_tbl.
outbound_tgt_smp_event_pid0_3);
pm8001_mw32(address, 0x4C,
pm8001_ha->main_cfg_tbl.pm8001_tbl.
outbound_tgt_smp_event_pid4_7);
pm8001_mw32(address, 0x50,
pm8001_ha->main_cfg_tbl.pm8001_tbl.upper_event_log_addr);
pm8001_mw32(address, 0x54,
pm8001_ha->main_cfg_tbl.pm8001_tbl.lower_event_log_addr);
pm8001_mw32(address, 0x58,
pm8001_ha->main_cfg_tbl.pm8001_tbl.event_log_size);
pm8001_mw32(address, 0x5C,
pm8001_ha->main_cfg_tbl.pm8001_tbl.event_log_option);
pm8001_mw32(address, 0x60,
pm8001_ha->main_cfg_tbl.pm8001_tbl.upper_iop_event_log_addr);
pm8001_mw32(address, 0x64,
pm8001_ha->main_cfg_tbl.pm8001_tbl.lower_iop_event_log_addr);
pm8001_mw32(address, 0x68,
pm8001_ha->main_cfg_tbl.pm8001_tbl.iop_event_log_size);
pm8001_mw32(address, 0x6C,
pm8001_ha->main_cfg_tbl.pm8001_tbl.iop_event_log_option);
pm8001_mw32(address, 0x70,
pm8001_ha->main_cfg_tbl.pm8001_tbl.fatal_err_interrupt);
}
/**
* update_inbnd_queue_table - update the inbound queue table to the HBA.
* @pm8001_ha: our hba card information
*/
static void update_inbnd_queue_table(struct pm8001_hba_info *pm8001_ha,
int number)
{
void __iomem *address = pm8001_ha->inbnd_q_tbl_addr;
u16 offset = number * 0x20;
pm8001_mw32(address, offset + 0x00,
pm8001_ha->inbnd_q_tbl[number].element_pri_size_cnt);
pm8001_mw32(address, offset + 0x04,
pm8001_ha->inbnd_q_tbl[number].upper_base_addr);
pm8001_mw32(address, offset + 0x08,
pm8001_ha->inbnd_q_tbl[number].lower_base_addr);
pm8001_mw32(address, offset + 0x0C,
pm8001_ha->inbnd_q_tbl[number].ci_upper_base_addr);
pm8001_mw32(address, offset + 0x10,
pm8001_ha->inbnd_q_tbl[number].ci_lower_base_addr);
}
/**
* update_outbnd_queue_table - update the outbound queue table to the HBA.
* @pm8001_ha: our hba card information
*/
static void update_outbnd_queue_table(struct pm8001_hba_info *pm8001_ha,
int number)
{
void __iomem *address = pm8001_ha->outbnd_q_tbl_addr;
u16 offset = number * 0x24;
pm8001_mw32(address, offset + 0x00,
pm8001_ha->outbnd_q_tbl[number].element_size_cnt);
pm8001_mw32(address, offset + 0x04,
pm8001_ha->outbnd_q_tbl[number].upper_base_addr);
pm8001_mw32(address, offset + 0x08,
pm8001_ha->outbnd_q_tbl[number].lower_base_addr);
pm8001_mw32(address, offset + 0x0C,
pm8001_ha->outbnd_q_tbl[number].pi_upper_base_addr);
pm8001_mw32(address, offset + 0x10,
pm8001_ha->outbnd_q_tbl[number].pi_lower_base_addr);
pm8001_mw32(address, offset + 0x1C,
pm8001_ha->outbnd_q_tbl[number].interrup_vec_cnt_delay);
}
/**
* pm8001_bar4_shift - function is called to shift BAR base address
* @pm8001_ha : our hba card infomation
* @shiftValue : shifting value in memory bar.
*/
int pm8001_bar4_shift(struct pm8001_hba_info *pm8001_ha, u32 shiftValue)
{
u32 regVal;
unsigned long start;
/* program the inbound AXI translation Lower Address */
pm8001_cw32(pm8001_ha, 1, SPC_IBW_AXI_TRANSLATION_LOW, shiftValue);
/* confirm the setting is written */
start = jiffies + HZ; /* 1 sec */
do {
regVal = pm8001_cr32(pm8001_ha, 1, SPC_IBW_AXI_TRANSLATION_LOW);
} while ((regVal != shiftValue) && time_before(jiffies, start));
if (regVal != shiftValue) {
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("TIMEOUT:SPC_IBW_AXI_TRANSLATION_LOW"
" = 0x%x\n", regVal));
return -1;
}
return 0;
}
/**
* mpi_set_phys_g3_with_ssc
* @pm8001_ha: our hba card information
* @SSCbit: set SSCbit to 0 to disable all phys ssc; 1 to enable all phys ssc.
*/
static void mpi_set_phys_g3_with_ssc(struct pm8001_hba_info *pm8001_ha,
u32 SSCbit)
{
u32 value, offset, i;
unsigned long flags;
#define SAS2_SETTINGS_LOCAL_PHY_0_3_SHIFT_ADDR 0x00030000
#define SAS2_SETTINGS_LOCAL_PHY_4_7_SHIFT_ADDR 0x00040000
#define SAS2_SETTINGS_LOCAL_PHY_0_3_OFFSET 0x1074
#define SAS2_SETTINGS_LOCAL_PHY_4_7_OFFSET 0x1074
#define PHY_G3_WITHOUT_SSC_BIT_SHIFT 12
#define PHY_G3_WITH_SSC_BIT_SHIFT 13
#define SNW3_PHY_CAPABILITIES_PARITY 31
/*
* Using shifted destination address 0x3_0000:0x1074 + 0x4000*N (N=0:3)
* Using shifted destination address 0x4_0000:0x1074 + 0x4000*(N-4) (N=4:7)
*/
spin_lock_irqsave(&pm8001_ha->lock, flags);
if (-1 == pm8001_bar4_shift(pm8001_ha,
SAS2_SETTINGS_LOCAL_PHY_0_3_SHIFT_ADDR)) {
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
return;
}
for (i = 0; i < 4; i++) {
offset = SAS2_SETTINGS_LOCAL_PHY_0_3_OFFSET + 0x4000 * i;
pm8001_cw32(pm8001_ha, 2, offset, 0x80001501);
}
/* shift membase 3 for SAS2_SETTINGS_LOCAL_PHY 4 - 7 */
if (-1 == pm8001_bar4_shift(pm8001_ha,
SAS2_SETTINGS_LOCAL_PHY_4_7_SHIFT_ADDR)) {
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
return;
}
for (i = 4; i < 8; i++) {
offset = SAS2_SETTINGS_LOCAL_PHY_4_7_OFFSET + 0x4000 * (i-4);
pm8001_cw32(pm8001_ha, 2, offset, 0x80001501);
}
/*************************************************************
Change the SSC upspreading value to 0x0 so that upspreading is disabled.
Device MABC SMOD0 Controls
Address: (via MEMBASE-III):
Using shifted destination address 0x0_0000: with Offset 0xD8
31:28 R/W Reserved Do not change
27:24 R/W SAS_SMOD_SPRDUP 0000
23:20 R/W SAS_SMOD_SPRDDN 0000
19:0 R/W Reserved Do not change
Upon power-up this register will read as 0x8990c016,
and I would like you to change the SAS_SMOD_SPRDUP bits to 0b0000
so that the written value will be 0x8090c016.
This will ensure only down-spreading SSC is enabled on the SPC.
*************************************************************/
value = pm8001_cr32(pm8001_ha, 2, 0xd8);
pm8001_cw32(pm8001_ha, 2, 0xd8, 0x8000C016);
/*set the shifted destination address to 0x0 to avoid error operation */
pm8001_bar4_shift(pm8001_ha, 0x0);
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
return;
}
/**
* mpi_set_open_retry_interval_reg
* @pm8001_ha: our hba card information
* @interval - interval time for each OPEN_REJECT (RETRY). The units are in 1us.
*/
static void mpi_set_open_retry_interval_reg(struct pm8001_hba_info *pm8001_ha,
u32 interval)
{
u32 offset;
u32 value;
u32 i;
unsigned long flags;
#define OPEN_RETRY_INTERVAL_PHY_0_3_SHIFT_ADDR 0x00030000
#define OPEN_RETRY_INTERVAL_PHY_4_7_SHIFT_ADDR 0x00040000
#define OPEN_RETRY_INTERVAL_PHY_0_3_OFFSET 0x30B4
#define OPEN_RETRY_INTERVAL_PHY_4_7_OFFSET 0x30B4
#define OPEN_RETRY_INTERVAL_REG_MASK 0x0000FFFF
value = interval & OPEN_RETRY_INTERVAL_REG_MASK;
spin_lock_irqsave(&pm8001_ha->lock, flags);
/* shift bar and set the OPEN_REJECT(RETRY) interval time of PHY 0 -3.*/
if (-1 == pm8001_bar4_shift(pm8001_ha,
OPEN_RETRY_INTERVAL_PHY_0_3_SHIFT_ADDR)) {
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
return;
}
for (i = 0; i < 4; i++) {
offset = OPEN_RETRY_INTERVAL_PHY_0_3_OFFSET + 0x4000 * i;
pm8001_cw32(pm8001_ha, 2, offset, value);
}
if (-1 == pm8001_bar4_shift(pm8001_ha,
OPEN_RETRY_INTERVAL_PHY_4_7_SHIFT_ADDR)) {
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
return;
}
for (i = 4; i < 8; i++) {
offset = OPEN_RETRY_INTERVAL_PHY_4_7_OFFSET + 0x4000 * (i-4);
pm8001_cw32(pm8001_ha, 2, offset, value);
}
/*set the shifted destination address to 0x0 to avoid error operation */
pm8001_bar4_shift(pm8001_ha, 0x0);
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
return;
}
/**
* mpi_init_check - check firmware initialization status.
* @pm8001_ha: our hba card information
*/
static int mpi_init_check(struct pm8001_hba_info *pm8001_ha)
{
u32 max_wait_count;
u32 value;
u32 gst_len_mpistate;
/* Write bit0=1 to Inbound DoorBell Register to tell the SPC FW the
table is updated */
pm8001_cw32(pm8001_ha, 0, MSGU_IBDB_SET, SPC_MSGU_CFG_TABLE_UPDATE);
/* wait until Inbound DoorBell Clear Register toggled */
max_wait_count = 1 * 1000 * 1000;/* 1 sec */
do {
udelay(1);
value = pm8001_cr32(pm8001_ha, 0, MSGU_IBDB_SET);
value &= SPC_MSGU_CFG_TABLE_UPDATE;
} while ((value != 0) && (--max_wait_count));
if (!max_wait_count)
return -1;
/* check the MPI-State for initialization */
gst_len_mpistate =
pm8001_mr32(pm8001_ha->general_stat_tbl_addr,
GST_GSTLEN_MPIS_OFFSET);
if (GST_MPI_STATE_INIT != (gst_len_mpistate & GST_MPI_STATE_MASK))
return -1;
/* check MPI Initialization error */
gst_len_mpistate = gst_len_mpistate >> 16;
if (0x0000 != gst_len_mpistate)
return -1;
return 0;
}
/**
* check_fw_ready - The LLDD check if the FW is ready, if not, return error.
* @pm8001_ha: our hba card information
*/
static int check_fw_ready(struct pm8001_hba_info *pm8001_ha)
{
u32 value, value1;
u32 max_wait_count;
/* check error state */
value = pm8001_cr32(pm8001_ha, 0, MSGU_SCRATCH_PAD_1);
value1 = pm8001_cr32(pm8001_ha, 0, MSGU_SCRATCH_PAD_2);
/* check AAP error */
if (SCRATCH_PAD1_ERR == (value & SCRATCH_PAD_STATE_MASK)) {
/* error state */
value = pm8001_cr32(pm8001_ha, 0, MSGU_SCRATCH_PAD_0);
return -1;
}
/* check IOP error */
if (SCRATCH_PAD2_ERR == (value1 & SCRATCH_PAD_STATE_MASK)) {
/* error state */
value1 = pm8001_cr32(pm8001_ha, 0, MSGU_SCRATCH_PAD_3);
return -1;
}
/* bit 4-31 of scratch pad1 should be zeros if it is not
in error state*/
if (value & SCRATCH_PAD1_STATE_MASK) {
/* error case */
pm8001_cr32(pm8001_ha, 0, MSGU_SCRATCH_PAD_0);
return -1;
}
/* bit 2, 4-31 of scratch pad2 should be zeros if it is not
in error state */
if (value1 & SCRATCH_PAD2_STATE_MASK) {
/* error case */
return -1;
}
max_wait_count = 1 * 1000 * 1000;/* 1 sec timeout */
/* wait until scratch pad 1 and 2 registers in ready state */
do {
udelay(1);
value = pm8001_cr32(pm8001_ha, 0, MSGU_SCRATCH_PAD_1)
& SCRATCH_PAD1_RDY;
value1 = pm8001_cr32(pm8001_ha, 0, MSGU_SCRATCH_PAD_2)
& SCRATCH_PAD2_RDY;
if ((--max_wait_count) == 0)
return -1;
} while ((value != SCRATCH_PAD1_RDY) || (value1 != SCRATCH_PAD2_RDY));
return 0;
}
static void init_pci_device_addresses(struct pm8001_hba_info *pm8001_ha)
{
void __iomem *base_addr;
u32 value;
u32 offset;
u32 pcibar;
u32 pcilogic;
value = pm8001_cr32(pm8001_ha, 0, 0x44);
offset = value & 0x03FFFFFF;
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("Scratchpad 0 Offset: %x\n", offset));
pcilogic = (value & 0xFC000000) >> 26;
pcibar = get_pci_bar_index(pcilogic);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("Scratchpad 0 PCI BAR: %d\n", pcibar));
pm8001_ha->main_cfg_tbl_addr = base_addr =
pm8001_ha->io_mem[pcibar].memvirtaddr + offset;
pm8001_ha->general_stat_tbl_addr =
base_addr + pm8001_cr32(pm8001_ha, pcibar, offset + 0x18);
pm8001_ha->inbnd_q_tbl_addr =
base_addr + pm8001_cr32(pm8001_ha, pcibar, offset + 0x1C);
pm8001_ha->outbnd_q_tbl_addr =
base_addr + pm8001_cr32(pm8001_ha, pcibar, offset + 0x20);
}
/**
* pm8001_chip_init - the main init function that initialize whole PM8001 chip.
* @pm8001_ha: our hba card information
*/
static int pm8001_chip_init(struct pm8001_hba_info *pm8001_ha)
{
u8 i = 0;
u16 deviceid;
pci_read_config_word(pm8001_ha->pdev, PCI_DEVICE_ID, &deviceid);
/* 8081 controllers need BAR shift to access MPI space
* as this is shared with BIOS data */
if (deviceid == 0x8081 || deviceid == 0x0042) {
if (-1 == pm8001_bar4_shift(pm8001_ha, GSM_SM_BASE)) {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("Shift Bar4 to 0x%x failed\n",
GSM_SM_BASE));
return -1;
}
}
/* check the firmware status */
if (-1 == check_fw_ready(pm8001_ha)) {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("Firmware is not ready!\n"));
return -EBUSY;
}
/* Initialize pci space address eg: mpi offset */
init_pci_device_addresses(pm8001_ha);
init_default_table_values(pm8001_ha);
read_main_config_table(pm8001_ha);
read_general_status_table(pm8001_ha);
read_inbnd_queue_table(pm8001_ha);
read_outbnd_queue_table(pm8001_ha);
/* update main config table ,inbound table and outbound table */
update_main_config_table(pm8001_ha);
for (i = 0; i < PM8001_MAX_INB_NUM; i++)
update_inbnd_queue_table(pm8001_ha, i);
for (i = 0; i < PM8001_MAX_OUTB_NUM; i++)
update_outbnd_queue_table(pm8001_ha, i);
/* 8081 controller donot require these operations */
if (deviceid != 0x8081 && deviceid != 0x0042) {
mpi_set_phys_g3_with_ssc(pm8001_ha, 0);
/* 7->130ms, 34->500ms, 119->1.5s */
mpi_set_open_retry_interval_reg(pm8001_ha, 119);
}
/* notify firmware update finished and check initialization status */
if (0 == mpi_init_check(pm8001_ha)) {
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("MPI initialize successful!\n"));
} else
return -EBUSY;
/*This register is a 16-bit timer with a resolution of 1us. This is the
timer used for interrupt delay/coalescing in the PCIe Application Layer.
Zero is not a valid value. A value of 1 in the register will cause the
interrupts to be normal. A value greater than 1 will cause coalescing
delays.*/
pm8001_cw32(pm8001_ha, 1, 0x0033c0, 0x1);
pm8001_cw32(pm8001_ha, 1, 0x0033c4, 0x0);
return 0;
}
static int mpi_uninit_check(struct pm8001_hba_info *pm8001_ha)
{
u32 max_wait_count;
u32 value;
u32 gst_len_mpistate;
u16 deviceid;
pci_read_config_word(pm8001_ha->pdev, PCI_DEVICE_ID, &deviceid);
if (deviceid == 0x8081 || deviceid == 0x0042) {
if (-1 == pm8001_bar4_shift(pm8001_ha, GSM_SM_BASE)) {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("Shift Bar4 to 0x%x failed\n",
GSM_SM_BASE));
return -1;
}
}
init_pci_device_addresses(pm8001_ha);
/* Write bit1=1 to Inbound DoorBell Register to tell the SPC FW the
table is stop */
pm8001_cw32(pm8001_ha, 0, MSGU_IBDB_SET, SPC_MSGU_CFG_TABLE_RESET);
/* wait until Inbound DoorBell Clear Register toggled */
max_wait_count = 1 * 1000 * 1000;/* 1 sec */
do {
udelay(1);
value = pm8001_cr32(pm8001_ha, 0, MSGU_IBDB_SET);
value &= SPC_MSGU_CFG_TABLE_RESET;
} while ((value != 0) && (--max_wait_count));
if (!max_wait_count) {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("TIMEOUT:IBDB value/=0x%x\n", value));
return -1;
}
/* check the MPI-State for termination in progress */
/* wait until Inbound DoorBell Clear Register toggled */
max_wait_count = 1 * 1000 * 1000; /* 1 sec */
do {
udelay(1);
gst_len_mpistate =
pm8001_mr32(pm8001_ha->general_stat_tbl_addr,
GST_GSTLEN_MPIS_OFFSET);
if (GST_MPI_STATE_UNINIT ==
(gst_len_mpistate & GST_MPI_STATE_MASK))
break;
} while (--max_wait_count);
if (!max_wait_count) {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk(" TIME OUT MPI State = 0x%x\n",
gst_len_mpistate & GST_MPI_STATE_MASK));
return -1;
}
return 0;
}
/**
* soft_reset_ready_check - Function to check FW is ready for soft reset.
* @pm8001_ha: our hba card information
*/
static u32 soft_reset_ready_check(struct pm8001_hba_info *pm8001_ha)
{
u32 regVal, regVal1, regVal2;
if (mpi_uninit_check(pm8001_ha) != 0) {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("MPI state is not ready\n"));
return -1;
}
/* read the scratch pad 2 register bit 2 */
regVal = pm8001_cr32(pm8001_ha, 0, MSGU_SCRATCH_PAD_2)
& SCRATCH_PAD2_FWRDY_RST;
if (regVal == SCRATCH_PAD2_FWRDY_RST) {
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("Firmware is ready for reset .\n"));
} else {
unsigned long flags;
/* Trigger NMI twice via RB6 */
spin_lock_irqsave(&pm8001_ha->lock, flags);
if (-1 == pm8001_bar4_shift(pm8001_ha, RB6_ACCESS_REG)) {
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("Shift Bar4 to 0x%x failed\n",
RB6_ACCESS_REG));
return -1;
}
pm8001_cw32(pm8001_ha, 2, SPC_RB6_OFFSET,
RB6_MAGIC_NUMBER_RST);
pm8001_cw32(pm8001_ha, 2, SPC_RB6_OFFSET, RB6_MAGIC_NUMBER_RST);
/* wait for 100 ms */
mdelay(100);
regVal = pm8001_cr32(pm8001_ha, 0, MSGU_SCRATCH_PAD_2) &
SCRATCH_PAD2_FWRDY_RST;
if (regVal != SCRATCH_PAD2_FWRDY_RST) {
regVal1 = pm8001_cr32(pm8001_ha, 0, MSGU_SCRATCH_PAD_1);
regVal2 = pm8001_cr32(pm8001_ha, 0, MSGU_SCRATCH_PAD_2);
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("TIMEOUT:MSGU_SCRATCH_PAD1"
"=0x%x, MSGU_SCRATCH_PAD2=0x%x\n",
regVal1, regVal2));
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("SCRATCH_PAD0 value = 0x%x\n",
pm8001_cr32(pm8001_ha, 0, MSGU_SCRATCH_PAD_0)));
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("SCRATCH_PAD3 value = 0x%x\n",
pm8001_cr32(pm8001_ha, 0, MSGU_SCRATCH_PAD_3)));
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
return -1;
}
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
}
return 0;
}
/**
* pm8001_chip_soft_rst - soft reset the PM8001 chip, so that the clear all
* the FW register status to the originated status.
* @pm8001_ha: our hba card information
*/
static int
pm8001_chip_soft_rst(struct pm8001_hba_info *pm8001_ha)
{
u32 regVal, toggleVal;
u32 max_wait_count;
u32 regVal1, regVal2, regVal3;
u32 signature = 0x252acbcd; /* for host scratch pad0 */
unsigned long flags;
/* step1: Check FW is ready for soft reset */
if (soft_reset_ready_check(pm8001_ha) != 0) {
PM8001_FAIL_DBG(pm8001_ha, pm8001_printk("FW is not ready\n"));
return -1;
}
/* step 2: clear NMI status register on AAP1 and IOP, write the same
value to clear */
/* map 0x60000 to BAR4(0x20), BAR2(win) */
spin_lock_irqsave(&pm8001_ha->lock, flags);
if (-1 == pm8001_bar4_shift(pm8001_ha, MBIC_AAP1_ADDR_BASE)) {
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("Shift Bar4 to 0x%x failed\n",
MBIC_AAP1_ADDR_BASE));
return -1;
}
regVal = pm8001_cr32(pm8001_ha, 2, MBIC_NMI_ENABLE_VPE0_IOP);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("MBIC - NMI Enable VPE0 (IOP)= 0x%x\n", regVal));
pm8001_cw32(pm8001_ha, 2, MBIC_NMI_ENABLE_VPE0_IOP, 0x0);
/* map 0x70000 to BAR4(0x20), BAR2(win) */
if (-1 == pm8001_bar4_shift(pm8001_ha, MBIC_IOP_ADDR_BASE)) {
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("Shift Bar4 to 0x%x failed\n",
MBIC_IOP_ADDR_BASE));
return -1;
}
regVal = pm8001_cr32(pm8001_ha, 2, MBIC_NMI_ENABLE_VPE0_AAP1);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("MBIC - NMI Enable VPE0 (AAP1)= 0x%x\n", regVal));
pm8001_cw32(pm8001_ha, 2, MBIC_NMI_ENABLE_VPE0_AAP1, 0x0);
regVal = pm8001_cr32(pm8001_ha, 1, PCIE_EVENT_INTERRUPT_ENABLE);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("PCIE -Event Interrupt Enable = 0x%x\n", regVal));
pm8001_cw32(pm8001_ha, 1, PCIE_EVENT_INTERRUPT_ENABLE, 0x0);
regVal = pm8001_cr32(pm8001_ha, 1, PCIE_EVENT_INTERRUPT);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("PCIE - Event Interrupt = 0x%x\n", regVal));
pm8001_cw32(pm8001_ha, 1, PCIE_EVENT_INTERRUPT, regVal);
regVal = pm8001_cr32(pm8001_ha, 1, PCIE_ERROR_INTERRUPT_ENABLE);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("PCIE -Error Interrupt Enable = 0x%x\n", regVal));
pm8001_cw32(pm8001_ha, 1, PCIE_ERROR_INTERRUPT_ENABLE, 0x0);
regVal = pm8001_cr32(pm8001_ha, 1, PCIE_ERROR_INTERRUPT);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("PCIE - Error Interrupt = 0x%x\n", regVal));
pm8001_cw32(pm8001_ha, 1, PCIE_ERROR_INTERRUPT, regVal);
/* read the scratch pad 1 register bit 2 */
regVal = pm8001_cr32(pm8001_ha, 0, MSGU_SCRATCH_PAD_1)
& SCRATCH_PAD1_RST;
toggleVal = regVal ^ SCRATCH_PAD1_RST;
/* set signature in host scratch pad0 register to tell SPC that the
host performs the soft reset */
pm8001_cw32(pm8001_ha, 0, MSGU_HOST_SCRATCH_PAD_0, signature);
/* read required registers for confirmming */
/* map 0x0700000 to BAR4(0x20), BAR2(win) */
if (-1 == pm8001_bar4_shift(pm8001_ha, GSM_ADDR_BASE)) {
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("Shift Bar4 to 0x%x failed\n",
GSM_ADDR_BASE));
return -1;
}
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("GSM 0x0(0x00007b88)-GSM Configuration and"
" Reset = 0x%x\n",
pm8001_cr32(pm8001_ha, 2, GSM_CONFIG_RESET)));
/* step 3: host read GSM Configuration and Reset register */
regVal = pm8001_cr32(pm8001_ha, 2, GSM_CONFIG_RESET);
/* Put those bits to low */
/* GSM XCBI offset = 0x70 0000
0x00 Bit 13 COM_SLV_SW_RSTB 1
0x00 Bit 12 QSSP_SW_RSTB 1
0x00 Bit 11 RAAE_SW_RSTB 1
0x00 Bit 9 RB_1_SW_RSTB 1
0x00 Bit 8 SM_SW_RSTB 1
*/
regVal &= ~(0x00003b00);
/* host write GSM Configuration and Reset register */
pm8001_cw32(pm8001_ha, 2, GSM_CONFIG_RESET, regVal);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("GSM 0x0 (0x00007b88 ==> 0x00004088) - GSM "
"Configuration and Reset is set to = 0x%x\n",
pm8001_cr32(pm8001_ha, 2, GSM_CONFIG_RESET)));
/* step 4: */
/* disable GSM - Read Address Parity Check */
regVal1 = pm8001_cr32(pm8001_ha, 2, GSM_READ_ADDR_PARITY_CHECK);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("GSM 0x700038 - Read Address Parity Check "
"Enable = 0x%x\n", regVal1));
pm8001_cw32(pm8001_ha, 2, GSM_READ_ADDR_PARITY_CHECK, 0x0);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("GSM 0x700038 - Read Address Parity Check Enable"
"is set to = 0x%x\n",
pm8001_cr32(pm8001_ha, 2, GSM_READ_ADDR_PARITY_CHECK)));
/* disable GSM - Write Address Parity Check */
regVal2 = pm8001_cr32(pm8001_ha, 2, GSM_WRITE_ADDR_PARITY_CHECK);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("GSM 0x700040 - Write Address Parity Check"
" Enable = 0x%x\n", regVal2));
pm8001_cw32(pm8001_ha, 2, GSM_WRITE_ADDR_PARITY_CHECK, 0x0);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("GSM 0x700040 - Write Address Parity Check "
"Enable is set to = 0x%x\n",
pm8001_cr32(pm8001_ha, 2, GSM_WRITE_ADDR_PARITY_CHECK)));
/* disable GSM - Write Data Parity Check */
regVal3 = pm8001_cr32(pm8001_ha, 2, GSM_WRITE_DATA_PARITY_CHECK);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("GSM 0x300048 - Write Data Parity Check"
" Enable = 0x%x\n", regVal3));
pm8001_cw32(pm8001_ha, 2, GSM_WRITE_DATA_PARITY_CHECK, 0x0);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("GSM 0x300048 - Write Data Parity Check Enable"
"is set to = 0x%x\n",
pm8001_cr32(pm8001_ha, 2, GSM_WRITE_DATA_PARITY_CHECK)));
/* step 5: delay 10 usec */
udelay(10);
/* step 5-b: set GPIO-0 output control to tristate anyway */
if (-1 == pm8001_bar4_shift(pm8001_ha, GPIO_ADDR_BASE)) {
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("Shift Bar4 to 0x%x failed\n",
GPIO_ADDR_BASE));
return -1;
}
regVal = pm8001_cr32(pm8001_ha, 2, GPIO_GPIO_0_0UTPUT_CTL_OFFSET);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("GPIO Output Control Register:"
" = 0x%x\n", regVal));
/* set GPIO-0 output control to tri-state */
regVal &= 0xFFFFFFFC;
pm8001_cw32(pm8001_ha, 2, GPIO_GPIO_0_0UTPUT_CTL_OFFSET, regVal);
/* Step 6: Reset the IOP and AAP1 */
/* map 0x00000 to BAR4(0x20), BAR2(win) */
if (-1 == pm8001_bar4_shift(pm8001_ha, SPC_TOP_LEVEL_ADDR_BASE)) {
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("SPC Shift Bar4 to 0x%x failed\n",
SPC_TOP_LEVEL_ADDR_BASE));
return -1;
}
regVal = pm8001_cr32(pm8001_ha, 2, SPC_REG_RESET);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("Top Register before resetting IOP/AAP1"
":= 0x%x\n", regVal));
regVal &= ~(SPC_REG_RESET_PCS_IOP_SS | SPC_REG_RESET_PCS_AAP1_SS);
pm8001_cw32(pm8001_ha, 2, SPC_REG_RESET, regVal);
/* step 7: Reset the BDMA/OSSP */
regVal = pm8001_cr32(pm8001_ha, 2, SPC_REG_RESET);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("Top Register before resetting BDMA/OSSP"
": = 0x%x\n", regVal));
regVal &= ~(SPC_REG_RESET_BDMA_CORE | SPC_REG_RESET_OSSP);
pm8001_cw32(pm8001_ha, 2, SPC_REG_RESET, regVal);
/* step 8: delay 10 usec */
udelay(10);
/* step 9: bring the BDMA and OSSP out of reset */
regVal = pm8001_cr32(pm8001_ha, 2, SPC_REG_RESET);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("Top Register before bringing up BDMA/OSSP"
":= 0x%x\n", regVal));
regVal |= (SPC_REG_RESET_BDMA_CORE | SPC_REG_RESET_OSSP);
pm8001_cw32(pm8001_ha, 2, SPC_REG_RESET, regVal);
/* step 10: delay 10 usec */
udelay(10);
/* step 11: reads and sets the GSM Configuration and Reset Register */
/* map 0x0700000 to BAR4(0x20), BAR2(win) */
if (-1 == pm8001_bar4_shift(pm8001_ha, GSM_ADDR_BASE)) {
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("SPC Shift Bar4 to 0x%x failed\n",
GSM_ADDR_BASE));
return -1;
}
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("GSM 0x0 (0x00007b88)-GSM Configuration and "
"Reset = 0x%x\n", pm8001_cr32(pm8001_ha, 2, GSM_CONFIG_RESET)));
regVal = pm8001_cr32(pm8001_ha, 2, GSM_CONFIG_RESET);
/* Put those bits to high */
/* GSM XCBI offset = 0x70 0000
0x00 Bit 13 COM_SLV_SW_RSTB 1
0x00 Bit 12 QSSP_SW_RSTB 1
0x00 Bit 11 RAAE_SW_RSTB 1
0x00 Bit 9 RB_1_SW_RSTB 1
0x00 Bit 8 SM_SW_RSTB 1
*/
regVal |= (GSM_CONFIG_RESET_VALUE);
pm8001_cw32(pm8001_ha, 2, GSM_CONFIG_RESET, regVal);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("GSM (0x00004088 ==> 0x00007b88) - GSM"
" Configuration and Reset is set to = 0x%x\n",
pm8001_cr32(pm8001_ha, 2, GSM_CONFIG_RESET)));
/* step 12: Restore GSM - Read Address Parity Check */
regVal = pm8001_cr32(pm8001_ha, 2, GSM_READ_ADDR_PARITY_CHECK);
/* just for debugging */
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("GSM 0x700038 - Read Address Parity Check Enable"
" = 0x%x\n", regVal));
pm8001_cw32(pm8001_ha, 2, GSM_READ_ADDR_PARITY_CHECK, regVal1);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("GSM 0x700038 - Read Address Parity"
" Check Enable is set to = 0x%x\n",
pm8001_cr32(pm8001_ha, 2, GSM_READ_ADDR_PARITY_CHECK)));
/* Restore GSM - Write Address Parity Check */
regVal = pm8001_cr32(pm8001_ha, 2, GSM_WRITE_ADDR_PARITY_CHECK);
pm8001_cw32(pm8001_ha, 2, GSM_WRITE_ADDR_PARITY_CHECK, regVal2);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("GSM 0x700040 - Write Address Parity Check"
" Enable is set to = 0x%x\n",
pm8001_cr32(pm8001_ha, 2, GSM_WRITE_ADDR_PARITY_CHECK)));
/* Restore GSM - Write Data Parity Check */
regVal = pm8001_cr32(pm8001_ha, 2, GSM_WRITE_DATA_PARITY_CHECK);
pm8001_cw32(pm8001_ha, 2, GSM_WRITE_DATA_PARITY_CHECK, regVal3);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("GSM 0x700048 - Write Data Parity Check Enable"
"is set to = 0x%x\n",
pm8001_cr32(pm8001_ha, 2, GSM_WRITE_DATA_PARITY_CHECK)));
/* step 13: bring the IOP and AAP1 out of reset */
/* map 0x00000 to BAR4(0x20), BAR2(win) */
if (-1 == pm8001_bar4_shift(pm8001_ha, SPC_TOP_LEVEL_ADDR_BASE)) {
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("Shift Bar4 to 0x%x failed\n",
SPC_TOP_LEVEL_ADDR_BASE));
return -1;
}
regVal = pm8001_cr32(pm8001_ha, 2, SPC_REG_RESET);
regVal |= (SPC_REG_RESET_PCS_IOP_SS | SPC_REG_RESET_PCS_AAP1_SS);
pm8001_cw32(pm8001_ha, 2, SPC_REG_RESET, regVal);
/* step 14: delay 10 usec - Normal Mode */
udelay(10);
/* check Soft Reset Normal mode or Soft Reset HDA mode */
if (signature == SPC_SOFT_RESET_SIGNATURE) {
/* step 15 (Normal Mode): wait until scratch pad1 register
bit 2 toggled */
max_wait_count = 2 * 1000 * 1000;/* 2 sec */
do {
udelay(1);
regVal = pm8001_cr32(pm8001_ha, 0, MSGU_SCRATCH_PAD_1) &
SCRATCH_PAD1_RST;
} while ((regVal != toggleVal) && (--max_wait_count));
if (!max_wait_count) {
regVal = pm8001_cr32(pm8001_ha, 0,
MSGU_SCRATCH_PAD_1);
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("TIMEOUT : ToggleVal 0x%x,"
"MSGU_SCRATCH_PAD1 = 0x%x\n",
toggleVal, regVal));
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("SCRATCH_PAD0 value = 0x%x\n",
pm8001_cr32(pm8001_ha, 0,
MSGU_SCRATCH_PAD_0)));
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("SCRATCH_PAD2 value = 0x%x\n",
pm8001_cr32(pm8001_ha, 0,
MSGU_SCRATCH_PAD_2)));
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("SCRATCH_PAD3 value = 0x%x\n",
pm8001_cr32(pm8001_ha, 0,
MSGU_SCRATCH_PAD_3)));
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
return -1;
}
/* step 16 (Normal) - Clear ODMR and ODCR */
pm8001_cw32(pm8001_ha, 0, MSGU_ODCR, ODCR_CLEAR_ALL);
pm8001_cw32(pm8001_ha, 0, MSGU_ODMR, ODMR_CLEAR_ALL);
/* step 17 (Normal Mode): wait for the FW and IOP to get
ready - 1 sec timeout */
/* Wait for the SPC Configuration Table to be ready */
if (check_fw_ready(pm8001_ha) == -1) {
regVal = pm8001_cr32(pm8001_ha, 0, MSGU_SCRATCH_PAD_1);
/* return error if MPI Configuration Table not ready */
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("FW not ready SCRATCH_PAD1"
" = 0x%x\n", regVal));
regVal = pm8001_cr32(pm8001_ha, 0, MSGU_SCRATCH_PAD_2);
/* return error if MPI Configuration Table not ready */
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("FW not ready SCRATCH_PAD2"
" = 0x%x\n", regVal));
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("SCRATCH_PAD0 value = 0x%x\n",
pm8001_cr32(pm8001_ha, 0,
MSGU_SCRATCH_PAD_0)));
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("SCRATCH_PAD3 value = 0x%x\n",
pm8001_cr32(pm8001_ha, 0,
MSGU_SCRATCH_PAD_3)));
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
return -1;
}
}
pm8001_bar4_shift(pm8001_ha, 0);
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("SPC soft reset Complete\n"));
return 0;
}
static void pm8001_hw_chip_rst(struct pm8001_hba_info *pm8001_ha)
{
u32 i;
u32 regVal;
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("chip reset start\n"));
/* do SPC chip reset. */
regVal = pm8001_cr32(pm8001_ha, 1, SPC_REG_RESET);
regVal &= ~(SPC_REG_RESET_DEVICE);
pm8001_cw32(pm8001_ha, 1, SPC_REG_RESET, regVal);
/* delay 10 usec */
udelay(10);
/* bring chip reset out of reset */
regVal = pm8001_cr32(pm8001_ha, 1, SPC_REG_RESET);
regVal |= SPC_REG_RESET_DEVICE;
pm8001_cw32(pm8001_ha, 1, SPC_REG_RESET, regVal);
/* delay 10 usec */
udelay(10);
/* wait for 20 msec until the firmware gets reloaded */
i = 20;
do {
mdelay(1);
} while ((--i) != 0);
PM8001_INIT_DBG(pm8001_ha,
pm8001_printk("chip reset finished\n"));
}
/**
* pm8001_chip_iounmap - which maped when initialized.
* @pm8001_ha: our hba card information
*/
void pm8001_chip_iounmap(struct pm8001_hba_info *pm8001_ha)
{
s8 bar, logical = 0;
for (bar = 0; bar < 6; bar++) {
/*
** logical BARs for SPC:
** bar 0 and 1 - logical BAR0
** bar 2 and 3 - logical BAR1
** bar4 - logical BAR2
** bar5 - logical BAR3
** Skip the appropriate assignments:
*/
if ((bar == 1) || (bar == 3))
continue;
if (pm8001_ha->io_mem[logical].memvirtaddr) {
iounmap(pm8001_ha->io_mem[logical].memvirtaddr);
logical++;
}
}
}
/**
* pm8001_chip_interrupt_enable - enable PM8001 chip interrupt
* @pm8001_ha: our hba card information
*/
static void
pm8001_chip_intx_interrupt_enable(struct pm8001_hba_info *pm8001_ha)
{
pm8001_cw32(pm8001_ha, 0, MSGU_ODMR, ODMR_CLEAR_ALL);
pm8001_cw32(pm8001_ha, 0, MSGU_ODCR, ODCR_CLEAR_ALL);
}
/**
* pm8001_chip_intx_interrupt_disable- disable PM8001 chip interrupt
* @pm8001_ha: our hba card information
*/
static void
pm8001_chip_intx_interrupt_disable(struct pm8001_hba_info *pm8001_ha)
{
pm8001_cw32(pm8001_ha, 0, MSGU_ODMR, ODMR_MASK_ALL);
}
/**
* pm8001_chip_msix_interrupt_enable - enable PM8001 chip interrupt
* @pm8001_ha: our hba card information
*/
static void
pm8001_chip_msix_interrupt_enable(struct pm8001_hba_info *pm8001_ha,
u32 int_vec_idx)
{
u32 msi_index;
u32 value;
msi_index = int_vec_idx * MSIX_TABLE_ELEMENT_SIZE;
msi_index += MSIX_TABLE_BASE;
pm8001_cw32(pm8001_ha, 0, msi_index, MSIX_INTERRUPT_ENABLE);
value = (1 << int_vec_idx);
pm8001_cw32(pm8001_ha, 0, MSGU_ODCR, value);
}
/**
* pm8001_chip_msix_interrupt_disable - disable PM8001 chip interrupt
* @pm8001_ha: our hba card information
*/
static void
pm8001_chip_msix_interrupt_disable(struct pm8001_hba_info *pm8001_ha,
u32 int_vec_idx)
{
u32 msi_index;
msi_index = int_vec_idx * MSIX_TABLE_ELEMENT_SIZE;
msi_index += MSIX_TABLE_BASE;
pm8001_cw32(pm8001_ha, 0, msi_index, MSIX_INTERRUPT_DISABLE);
}
/**
* pm8001_chip_interrupt_enable - enable PM8001 chip interrupt
* @pm8001_ha: our hba card information
*/
static void
pm8001_chip_interrupt_enable(struct pm8001_hba_info *pm8001_ha, u8 vec)
{
#ifdef PM8001_USE_MSIX
pm8001_chip_msix_interrupt_enable(pm8001_ha, 0);
return;
#endif
pm8001_chip_intx_interrupt_enable(pm8001_ha);
}
/**
* pm8001_chip_intx_interrupt_disable- disable PM8001 chip interrupt
* @pm8001_ha: our hba card information
*/
static void
pm8001_chip_interrupt_disable(struct pm8001_hba_info *pm8001_ha, u8 vec)
{
#ifdef PM8001_USE_MSIX
pm8001_chip_msix_interrupt_disable(pm8001_ha, 0);
return;
#endif
pm8001_chip_intx_interrupt_disable(pm8001_ha);
}
/**
* pm8001_mpi_msg_free_get - get the free message buffer for transfer
* inbound queue.
* @circularQ: the inbound queue we want to transfer to HBA.
* @messageSize: the message size of this transfer, normally it is 64 bytes
* @messagePtr: the pointer to message.
*/
int pm8001_mpi_msg_free_get(struct inbound_queue_table *circularQ,
u16 messageSize, void **messagePtr)
{
u32 offset, consumer_index;
struct mpi_msg_hdr *msgHeader;
u8 bcCount = 1; /* only support single buffer */
/* Checks is the requested message size can be allocated in this queue*/
if (messageSize > IOMB_SIZE_SPCV) {
*messagePtr = NULL;
return -1;
}
/* Stores the new consumer index */
consumer_index = pm8001_read_32(circularQ->ci_virt);
circularQ->consumer_index = cpu_to_le32(consumer_index);
if (((circularQ->producer_idx + bcCount) % PM8001_MPI_QUEUE) ==
le32_to_cpu(circularQ->consumer_index)) {
*messagePtr = NULL;
return -1;
}
/* get memory IOMB buffer address */
offset = circularQ->producer_idx * messageSize;
/* increment to next bcCount element */
circularQ->producer_idx = (circularQ->producer_idx + bcCount)
% PM8001_MPI_QUEUE;
/* Adds that distance to the base of the region virtual address plus
the message header size*/
msgHeader = (struct mpi_msg_hdr *)(circularQ->base_virt + offset);
*messagePtr = ((void *)msgHeader) + sizeof(struct mpi_msg_hdr);
return 0;
}
/**
* pm8001_mpi_build_cmd- build the message queue for transfer, update the PI to
* FW to tell the fw to get this message from IOMB.
* @pm8001_ha: our hba card information
* @circularQ: the inbound queue we want to transfer to HBA.
* @opCode: the operation code represents commands which LLDD and fw recognized.
* @payload: the command payload of each operation command.
*/
int pm8001_mpi_build_cmd(struct pm8001_hba_info *pm8001_ha,
struct inbound_queue_table *circularQ,
u32 opCode, void *payload, u32 responseQueue)
{
u32 Header = 0, hpriority = 0, bc = 1, category = 0x02;
void *pMessage;
if (pm8001_mpi_msg_free_get(circularQ, pm8001_ha->iomb_size,
&pMessage) < 0) {
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("No free mpi buffer\n"));
return -ENOMEM;
}
BUG_ON(!payload);
/*Copy to the payload*/
memcpy(pMessage, payload, (pm8001_ha->iomb_size -
sizeof(struct mpi_msg_hdr)));
/*Build the header*/
Header = ((1 << 31) | (hpriority << 30) | ((bc & 0x1f) << 24)
| ((responseQueue & 0x3F) << 16)
| ((category & 0xF) << 12) | (opCode & 0xFFF));
pm8001_write_32((pMessage - 4), 0, cpu_to_le32(Header));
/*Update the PI to the firmware*/
pm8001_cw32(pm8001_ha, circularQ->pi_pci_bar,
circularQ->pi_offset, circularQ->producer_idx);
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("INB Q %x OPCODE:%x , UPDATED PI=%d CI=%d\n",
responseQueue, opCode, circularQ->producer_idx,
circularQ->consumer_index));
return 0;
}
u32 pm8001_mpi_msg_free_set(struct pm8001_hba_info *pm8001_ha, void *pMsg,
struct outbound_queue_table *circularQ, u8 bc)
{
u32 producer_index;
struct mpi_msg_hdr *msgHeader;
struct mpi_msg_hdr *pOutBoundMsgHeader;
msgHeader = (struct mpi_msg_hdr *)(pMsg - sizeof(struct mpi_msg_hdr));
pOutBoundMsgHeader = (struct mpi_msg_hdr *)(circularQ->base_virt +
circularQ->consumer_idx * pm8001_ha->iomb_size);
if (pOutBoundMsgHeader != msgHeader) {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("consumer_idx = %d msgHeader = %p\n",
circularQ->consumer_idx, msgHeader));
/* Update the producer index from SPC */
producer_index = pm8001_read_32(circularQ->pi_virt);
circularQ->producer_index = cpu_to_le32(producer_index);
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("consumer_idx = %d producer_index = %d"
"msgHeader = %p\n", circularQ->consumer_idx,
circularQ->producer_index, msgHeader));
return 0;
}
/* free the circular queue buffer elements associated with the message*/
circularQ->consumer_idx = (circularQ->consumer_idx + bc)
% PM8001_MPI_QUEUE;
/* update the CI of outbound queue */
pm8001_cw32(pm8001_ha, circularQ->ci_pci_bar, circularQ->ci_offset,
circularQ->consumer_idx);
/* Update the producer index from SPC*/
producer_index = pm8001_read_32(circularQ->pi_virt);
circularQ->producer_index = cpu_to_le32(producer_index);
PM8001_IO_DBG(pm8001_ha,
pm8001_printk(" CI=%d PI=%d\n", circularQ->consumer_idx,
circularQ->producer_index));
return 0;
}
/**
* pm8001_mpi_msg_consume- get the MPI message from outbound queue
* message table.
* @pm8001_ha: our hba card information
* @circularQ: the outbound queue table.
* @messagePtr1: the message contents of this outbound message.
* @pBC: the message size.
*/
u32 pm8001_mpi_msg_consume(struct pm8001_hba_info *pm8001_ha,
struct outbound_queue_table *circularQ,
void **messagePtr1, u8 *pBC)
{
struct mpi_msg_hdr *msgHeader;
__le32 msgHeader_tmp;
u32 header_tmp;
do {
/* If there are not-yet-delivered messages ... */
if (le32_to_cpu(circularQ->producer_index)
!= circularQ->consumer_idx) {
/*Get the pointer to the circular queue buffer element*/
msgHeader = (struct mpi_msg_hdr *)
(circularQ->base_virt +
circularQ->consumer_idx * pm8001_ha->iomb_size);
/* read header */
header_tmp = pm8001_read_32(msgHeader);
msgHeader_tmp = cpu_to_le32(header_tmp);
if (0 != (le32_to_cpu(msgHeader_tmp) & 0x80000000)) {
if (OPC_OUB_SKIP_ENTRY !=
(le32_to_cpu(msgHeader_tmp) & 0xfff)) {
*messagePtr1 =
((u8 *)msgHeader) +
sizeof(struct mpi_msg_hdr);
*pBC = (u8)((le32_to_cpu(msgHeader_tmp)
>> 24) & 0x1f);
PM8001_IO_DBG(pm8001_ha,
pm8001_printk(": CI=%d PI=%d "
"msgHeader=%x\n",
circularQ->consumer_idx,
circularQ->producer_index,
msgHeader_tmp));
return MPI_IO_STATUS_SUCCESS;
} else {
circularQ->consumer_idx =
(circularQ->consumer_idx +
((le32_to_cpu(msgHeader_tmp)
>> 24) & 0x1f))
% PM8001_MPI_QUEUE;
msgHeader_tmp = 0;
pm8001_write_32(msgHeader, 0, 0);
/* update the CI of outbound queue */
pm8001_cw32(pm8001_ha,
circularQ->ci_pci_bar,
circularQ->ci_offset,
circularQ->consumer_idx);
}
} else {
circularQ->consumer_idx =
(circularQ->consumer_idx +
((le32_to_cpu(msgHeader_tmp) >> 24) &
0x1f)) % PM8001_MPI_QUEUE;
msgHeader_tmp = 0;
pm8001_write_32(msgHeader, 0, 0);
/* update the CI of outbound queue */
pm8001_cw32(pm8001_ha, circularQ->ci_pci_bar,
circularQ->ci_offset,
circularQ->consumer_idx);
return MPI_IO_STATUS_FAIL;
}
} else {
u32 producer_index;
void *pi_virt = circularQ->pi_virt;
/* Update the producer index from SPC */
producer_index = pm8001_read_32(pi_virt);
circularQ->producer_index = cpu_to_le32(producer_index);
}
} while (le32_to_cpu(circularQ->producer_index) !=
circularQ->consumer_idx);
/* while we don't have any more not-yet-delivered message */
/* report empty */
return MPI_IO_STATUS_BUSY;
}
void pm8001_work_fn(struct work_struct *work)
{
struct pm8001_work *pw = container_of(work, struct pm8001_work, work);
struct pm8001_device *pm8001_dev;
struct domain_device *dev;
/*
* So far, all users of this stash an associated structure here.
* If we get here, and this pointer is null, then the action
* was cancelled. This nullification happens when the device
* goes away.
*/
pm8001_dev = pw->data; /* Most stash device structure */
if ((pm8001_dev == NULL)
|| ((pw->handler != IO_XFER_ERROR_BREAK)
&& (pm8001_dev->dev_type == SAS_PHY_UNUSED))) {
kfree(pw);
return;
}
switch (pw->handler) {
case IO_XFER_ERROR_BREAK:
{ /* This one stashes the sas_task instead */
struct sas_task *t = (struct sas_task *)pm8001_dev;
u32 tag;
struct pm8001_ccb_info *ccb;
struct pm8001_hba_info *pm8001_ha = pw->pm8001_ha;
unsigned long flags, flags1;
struct task_status_struct *ts;
int i;
if (pm8001_query_task(t) == TMF_RESP_FUNC_SUCC)
break; /* Task still on lu */
spin_lock_irqsave(&pm8001_ha->lock, flags);
spin_lock_irqsave(&t->task_state_lock, flags1);
if (unlikely((t->task_state_flags & SAS_TASK_STATE_DONE))) {
spin_unlock_irqrestore(&t->task_state_lock, flags1);
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
break; /* Task got completed by another */
}
spin_unlock_irqrestore(&t->task_state_lock, flags1);
/* Search for a possible ccb that matches the task */
for (i = 0; ccb = NULL, i < PM8001_MAX_CCB; i++) {
ccb = &pm8001_ha->ccb_info[i];
tag = ccb->ccb_tag;
if ((tag != 0xFFFFFFFF) && (ccb->task == t))
break;
}
if (!ccb) {
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
break; /* Task got freed by another */
}
ts = &t->task_status;
ts->resp = SAS_TASK_COMPLETE;
/* Force the midlayer to retry */
ts->stat = SAS_QUEUE_FULL;
pm8001_dev = ccb->device;
if (pm8001_dev)
pm8001_dev->running_req--;
spin_lock_irqsave(&t->task_state_lock, flags1);
t->task_state_flags &= ~SAS_TASK_STATE_PENDING;
t->task_state_flags &= ~SAS_TASK_AT_INITIATOR;
t->task_state_flags |= SAS_TASK_STATE_DONE;
if (unlikely((t->task_state_flags & SAS_TASK_STATE_ABORTED))) {
spin_unlock_irqrestore(&t->task_state_lock, flags1);
PM8001_FAIL_DBG(pm8001_ha, pm8001_printk("task 0x%p"
" done with event 0x%x resp 0x%x stat 0x%x but"
" aborted by upper layer!\n",
t, pw->handler, ts->resp, ts->stat));
pm8001_ccb_task_free(pm8001_ha, t, ccb, tag);
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
} else {
spin_unlock_irqrestore(&t->task_state_lock, flags1);
pm8001_ccb_task_free(pm8001_ha, t, ccb, tag);
mb();/* in order to force CPU ordering */
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
t->task_done(t);
}
} break;
case IO_XFER_OPEN_RETRY_TIMEOUT:
{ /* This one stashes the sas_task instead */
struct sas_task *t = (struct sas_task *)pm8001_dev;
u32 tag;
struct pm8001_ccb_info *ccb;
struct pm8001_hba_info *pm8001_ha = pw->pm8001_ha;
unsigned long flags, flags1;
int i, ret = 0;
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_OPEN_RETRY_TIMEOUT\n"));
ret = pm8001_query_task(t);
PM8001_IO_DBG(pm8001_ha,
switch (ret) {
case TMF_RESP_FUNC_SUCC:
pm8001_printk("...Task on lu\n");
break;
case TMF_RESP_FUNC_COMPLETE:
pm8001_printk("...Task NOT on lu\n");
break;
default:
pm8001_printk("...query task failed!!!\n");
break;
});
spin_lock_irqsave(&pm8001_ha->lock, flags);
spin_lock_irqsave(&t->task_state_lock, flags1);
if (unlikely((t->task_state_flags & SAS_TASK_STATE_DONE))) {
spin_unlock_irqrestore(&t->task_state_lock, flags1);
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
if (ret == TMF_RESP_FUNC_SUCC) /* task on lu */
(void)pm8001_abort_task(t);
break; /* Task got completed by another */
}
spin_unlock_irqrestore(&t->task_state_lock, flags1);
/* Search for a possible ccb that matches the task */
for (i = 0; ccb = NULL, i < PM8001_MAX_CCB; i++) {
ccb = &pm8001_ha->ccb_info[i];
tag = ccb->ccb_tag;
if ((tag != 0xFFFFFFFF) && (ccb->task == t))
break;
}
if (!ccb) {
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
if (ret == TMF_RESP_FUNC_SUCC) /* task on lu */
(void)pm8001_abort_task(t);
break; /* Task got freed by another */
}
pm8001_dev = ccb->device;
dev = pm8001_dev->sas_device;
switch (ret) {
case TMF_RESP_FUNC_SUCC: /* task on lu */
ccb->open_retry = 1; /* Snub completion */
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
ret = pm8001_abort_task(t);
ccb->open_retry = 0;
switch (ret) {
case TMF_RESP_FUNC_SUCC:
case TMF_RESP_FUNC_COMPLETE:
break;
default: /* device misbehavior */
ret = TMF_RESP_FUNC_FAILED;
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("...Reset phy\n"));
pm8001_I_T_nexus_reset(dev);
break;
}
break;
case TMF_RESP_FUNC_COMPLETE: /* task not on lu */
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
/* Do we need to abort the task locally? */
break;
default: /* device misbehavior */
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
ret = TMF_RESP_FUNC_FAILED;
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("...Reset phy\n"));
pm8001_I_T_nexus_reset(dev);
}
if (ret == TMF_RESP_FUNC_FAILED)
t = NULL;
pm8001_open_reject_retry(pm8001_ha, t, pm8001_dev);
PM8001_IO_DBG(pm8001_ha, pm8001_printk("...Complete\n"));
} break;
case IO_OPEN_CNX_ERROR_IT_NEXUS_LOSS:
dev = pm8001_dev->sas_device;
pm8001_I_T_nexus_event_handler(dev);
break;
case IO_OPEN_CNX_ERROR_STP_RESOURCES_BUSY:
dev = pm8001_dev->sas_device;
pm8001_I_T_nexus_reset(dev);
break;
case IO_DS_IN_ERROR:
dev = pm8001_dev->sas_device;
pm8001_I_T_nexus_reset(dev);
break;
case IO_DS_NON_OPERATIONAL:
dev = pm8001_dev->sas_device;
pm8001_I_T_nexus_reset(dev);
break;
}
kfree(pw);
}
int pm8001_handle_event(struct pm8001_hba_info *pm8001_ha, void *data,
int handler)
{
struct pm8001_work *pw;
int ret = 0;
pw = kmalloc(sizeof(struct pm8001_work), GFP_ATOMIC);
if (pw) {
pw->pm8001_ha = pm8001_ha;
pw->data = data;
pw->handler = handler;
INIT_WORK(&pw->work, pm8001_work_fn);
queue_work(pm8001_wq, &pw->work);
} else
ret = -ENOMEM;
return ret;
}
static void pm8001_send_abort_all(struct pm8001_hba_info *pm8001_ha,
struct pm8001_device *pm8001_ha_dev)
{
int res;
u32 ccb_tag;
struct pm8001_ccb_info *ccb;
struct sas_task *task = NULL;
struct task_abort_req task_abort;
struct inbound_queue_table *circularQ;
u32 opc = OPC_INB_SATA_ABORT;
int ret;
if (!pm8001_ha_dev) {
PM8001_FAIL_DBG(pm8001_ha, pm8001_printk("dev is null\n"));
return;
}
task = sas_alloc_slow_task(GFP_ATOMIC);
if (!task) {
PM8001_FAIL_DBG(pm8001_ha, pm8001_printk("cannot "
"allocate task\n"));
return;
}
task->task_done = pm8001_task_done;
res = pm8001_tag_alloc(pm8001_ha, &ccb_tag);
if (res)
return;
ccb = &pm8001_ha->ccb_info[ccb_tag];
ccb->device = pm8001_ha_dev;
ccb->ccb_tag = ccb_tag;
ccb->task = task;
circularQ = &pm8001_ha->inbnd_q_tbl[0];
memset(&task_abort, 0, sizeof(task_abort));
task_abort.abort_all = cpu_to_le32(1);
task_abort.device_id = cpu_to_le32(pm8001_ha_dev->device_id);
task_abort.tag = cpu_to_le32(ccb_tag);
ret = pm8001_mpi_build_cmd(pm8001_ha, circularQ, opc, &task_abort, 0);
if (ret)
pm8001_tag_free(pm8001_ha, ccb_tag);
}
static void pm8001_send_read_log(struct pm8001_hba_info *pm8001_ha,
struct pm8001_device *pm8001_ha_dev)
{
struct sata_start_req sata_cmd;
int res;
u32 ccb_tag;
struct pm8001_ccb_info *ccb;
struct sas_task *task = NULL;
struct host_to_dev_fis fis;
struct domain_device *dev;
struct inbound_queue_table *circularQ;
u32 opc = OPC_INB_SATA_HOST_OPSTART;
task = sas_alloc_slow_task(GFP_ATOMIC);
if (!task) {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("cannot allocate task !!!\n"));
return;
}
task->task_done = pm8001_task_done;
res = pm8001_tag_alloc(pm8001_ha, &ccb_tag);
if (res) {
sas_free_task(task);
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("cannot allocate tag !!!\n"));
return;
}
/* allocate domain device by ourselves as libsas
* is not going to provide any
*/
dev = kzalloc(sizeof(struct domain_device), GFP_ATOMIC);
if (!dev) {
sas_free_task(task);
pm8001_tag_free(pm8001_ha, ccb_tag);
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("Domain device cannot be allocated\n"));
return;
}
task->dev = dev;
task->dev->lldd_dev = pm8001_ha_dev;
ccb = &pm8001_ha->ccb_info[ccb_tag];
ccb->device = pm8001_ha_dev;
ccb->ccb_tag = ccb_tag;
ccb->task = task;
pm8001_ha_dev->id |= NCQ_READ_LOG_FLAG;
pm8001_ha_dev->id |= NCQ_2ND_RLE_FLAG;
memset(&sata_cmd, 0, sizeof(sata_cmd));
circularQ = &pm8001_ha->inbnd_q_tbl[0];
/* construct read log FIS */
memset(&fis, 0, sizeof(struct host_to_dev_fis));
fis.fis_type = 0x27;
fis.flags = 0x80;
fis.command = ATA_CMD_READ_LOG_EXT;
fis.lbal = 0x10;
fis.sector_count = 0x1;
sata_cmd.tag = cpu_to_le32(ccb_tag);
sata_cmd.device_id = cpu_to_le32(pm8001_ha_dev->device_id);
sata_cmd.ncqtag_atap_dir_m |= ((0x1 << 7) | (0x5 << 9));
memcpy(&sata_cmd.sata_fis, &fis, sizeof(struct host_to_dev_fis));
res = pm8001_mpi_build_cmd(pm8001_ha, circularQ, opc, &sata_cmd, 0);
if (res) {
sas_free_task(task);
pm8001_tag_free(pm8001_ha, ccb_tag);
kfree(dev);
}
}
/**
* mpi_ssp_completion- process the event that FW response to the SSP request.
* @pm8001_ha: our hba card information
* @piomb: the message contents of this outbound message.
*
* When FW has completed a ssp request for example a IO request, after it has
* filled the SG data with the data, it will trigger this event represent
* that he has finished the job,please check the coresponding buffer.
* So we will tell the caller who maybe waiting the result to tell upper layer
* that the task has been finished.
*/
static void
mpi_ssp_completion(struct pm8001_hba_info *pm8001_ha , void *piomb)
{
struct sas_task *t;
struct pm8001_ccb_info *ccb;
unsigned long flags;
u32 status;
u32 param;
u32 tag;
struct ssp_completion_resp *psspPayload;
struct task_status_struct *ts;
struct ssp_response_iu *iu;
struct pm8001_device *pm8001_dev;
psspPayload = (struct ssp_completion_resp *)(piomb + 4);
status = le32_to_cpu(psspPayload->status);
tag = le32_to_cpu(psspPayload->tag);
ccb = &pm8001_ha->ccb_info[tag];
if ((status == IO_ABORTED) && ccb->open_retry) {
/* Being completed by another */
ccb->open_retry = 0;
return;
}
pm8001_dev = ccb->device;
param = le32_to_cpu(psspPayload->param);
t = ccb->task;
if (status && status != IO_UNDERFLOW)
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("sas IO status 0x%x\n", status));
if (unlikely(!t || !t->lldd_task || !t->dev))
return;
ts = &t->task_status;
/* Print sas address of IO failed device */
if ((status != IO_SUCCESS) && (status != IO_OVERFLOW) &&
(status != IO_UNDERFLOW))
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("SAS Address of IO Failure Drive:"
"%016llx", SAS_ADDR(t->dev->sas_addr)));
switch (status) {
case IO_SUCCESS:
PM8001_IO_DBG(pm8001_ha, pm8001_printk("IO_SUCCESS"
",param = %d\n", param));
if (param == 0) {
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAM_STAT_GOOD;
} else {
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_PROTO_RESPONSE;
ts->residual = param;
iu = &psspPayload->ssp_resp_iu;
sas_ssp_task_response(pm8001_ha->dev, t, iu);
}
if (pm8001_dev)
pm8001_dev->running_req--;
break;
case IO_ABORTED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_ABORTED IOMB Tag\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_ABORTED_TASK;
break;
case IO_UNDERFLOW:
/* SSP Completion with error */
PM8001_IO_DBG(pm8001_ha, pm8001_printk("IO_UNDERFLOW"
",param = %d\n", param));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DATA_UNDERRUN;
ts->residual = param;
if (pm8001_dev)
pm8001_dev->running_req--;
break;
case IO_NO_DEVICE:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_NO_DEVICE\n"));
ts->resp = SAS_TASK_UNDELIVERED;
ts->stat = SAS_PHY_DOWN;
break;
case IO_XFER_ERROR_BREAK:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_BREAK\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
/* Force the midlayer to retry */
ts->open_rej_reason = SAS_OREJ_RSVD_RETRY;
break;
case IO_XFER_ERROR_PHY_NOT_READY:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_PHY_NOT_READY\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_RETRY;
break;
case IO_OPEN_CNX_ERROR_PROTOCOL_NOT_SUPPORTED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_PROTOCOL_NOT_SUPPORTED\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_EPROTO;
break;
case IO_OPEN_CNX_ERROR_ZONE_VIOLATION:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_ZONE_VIOLATION\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_UNKNOWN;
break;
case IO_OPEN_CNX_ERROR_BREAK:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_BREAK\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_RETRY;
break;
case IO_OPEN_CNX_ERROR_IT_NEXUS_LOSS:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_IT_NEXUS_LOSS\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_UNKNOWN;
if (!t->uldd_task)
pm8001_handle_event(pm8001_ha,
pm8001_dev,
IO_OPEN_CNX_ERROR_IT_NEXUS_LOSS);
break;
case IO_OPEN_CNX_ERROR_BAD_DESTINATION:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_BAD_DESTINATION\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_BAD_DEST;
break;
case IO_OPEN_CNX_ERROR_CONNECTION_RATE_NOT_SUPPORTED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_CONNECTION_RATE_"
"NOT_SUPPORTED\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_CONN_RATE;
break;
case IO_OPEN_CNX_ERROR_WRONG_DESTINATION:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_WRONG_DESTINATION\n"));
ts->resp = SAS_TASK_UNDELIVERED;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_WRONG_DEST;
break;
case IO_XFER_ERROR_NAK_RECEIVED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_NAK_RECEIVED\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_RETRY;
break;
case IO_XFER_ERROR_ACK_NAK_TIMEOUT:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_ACK_NAK_TIMEOUT\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_NAK_R_ERR;
break;
case IO_XFER_ERROR_DMA:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_DMA\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
break;
case IO_XFER_OPEN_RETRY_TIMEOUT:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_OPEN_RETRY_TIMEOUT\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_RETRY;
break;
case IO_XFER_ERROR_OFFSET_MISMATCH:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_OFFSET_MISMATCH\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
break;
case IO_PORT_IN_RESET:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_PORT_IN_RESET\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
break;
case IO_DS_NON_OPERATIONAL:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_DS_NON_OPERATIONAL\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
if (!t->uldd_task)
pm8001_handle_event(pm8001_ha,
pm8001_dev,
IO_DS_NON_OPERATIONAL);
break;
case IO_DS_IN_RECOVERY:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_DS_IN_RECOVERY\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
break;
case IO_TM_TAG_NOT_FOUND:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_TM_TAG_NOT_FOUND\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
break;
case IO_SSP_EXT_IU_ZERO_LEN_ERROR:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_SSP_EXT_IU_ZERO_LEN_ERROR\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
break;
case IO_OPEN_CNX_ERROR_HW_RESOURCE_BUSY:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_HW_RESOURCE_BUSY\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_RETRY;
break;
default:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("Unknown status 0x%x\n", status));
/* not allowed case. Therefore, return failed status */
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
break;
}
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("scsi_status = %x\n ",
psspPayload->ssp_resp_iu.status));
spin_lock_irqsave(&t->task_state_lock, flags);
t->task_state_flags &= ~SAS_TASK_STATE_PENDING;
t->task_state_flags &= ~SAS_TASK_AT_INITIATOR;
t->task_state_flags |= SAS_TASK_STATE_DONE;
if (unlikely((t->task_state_flags & SAS_TASK_STATE_ABORTED))) {
spin_unlock_irqrestore(&t->task_state_lock, flags);
PM8001_FAIL_DBG(pm8001_ha, pm8001_printk("task 0x%p done with"
" io_status 0x%x resp 0x%x "
"stat 0x%x but aborted by upper layer!\n",
t, status, ts->resp, ts->stat));
pm8001_ccb_task_free(pm8001_ha, t, ccb, tag);
} else {
spin_unlock_irqrestore(&t->task_state_lock, flags);
pm8001_ccb_task_free(pm8001_ha, t, ccb, tag);
mb();/* in order to force CPU ordering */
t->task_done(t);
}
}
/*See the comments for mpi_ssp_completion */
static void mpi_ssp_event(struct pm8001_hba_info *pm8001_ha , void *piomb)
{
struct sas_task *t;
unsigned long flags;
struct task_status_struct *ts;
struct pm8001_ccb_info *ccb;
struct pm8001_device *pm8001_dev;
struct ssp_event_resp *psspPayload =
(struct ssp_event_resp *)(piomb + 4);
u32 event = le32_to_cpu(psspPayload->event);
u32 tag = le32_to_cpu(psspPayload->tag);
u32 port_id = le32_to_cpu(psspPayload->port_id);
u32 dev_id = le32_to_cpu(psspPayload->device_id);
ccb = &pm8001_ha->ccb_info[tag];
t = ccb->task;
pm8001_dev = ccb->device;
if (event)
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("sas IO status 0x%x\n", event));
if (unlikely(!t || !t->lldd_task || !t->dev))
return;
ts = &t->task_status;
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("port_id = %x,device_id = %x\n",
port_id, dev_id));
switch (event) {
case IO_OVERFLOW:
PM8001_IO_DBG(pm8001_ha, pm8001_printk("IO_UNDERFLOW\n");)
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DATA_OVERRUN;
ts->residual = 0;
if (pm8001_dev)
pm8001_dev->running_req--;
break;
case IO_XFER_ERROR_BREAK:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_BREAK\n"));
pm8001_handle_event(pm8001_ha, t, IO_XFER_ERROR_BREAK);
return;
case IO_XFER_ERROR_PHY_NOT_READY:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_PHY_NOT_READY\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_RETRY;
break;
case IO_OPEN_CNX_ERROR_PROTOCOL_NOT_SUPPORTED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_PROTOCOL_NOT"
"_SUPPORTED\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_EPROTO;
break;
case IO_OPEN_CNX_ERROR_ZONE_VIOLATION:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_ZONE_VIOLATION\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_UNKNOWN;
break;
case IO_OPEN_CNX_ERROR_BREAK:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_BREAK\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_RETRY;
break;
case IO_OPEN_CNX_ERROR_IT_NEXUS_LOSS:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_IT_NEXUS_LOSS\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_UNKNOWN;
if (!t->uldd_task)
pm8001_handle_event(pm8001_ha,
pm8001_dev,
IO_OPEN_CNX_ERROR_IT_NEXUS_LOSS);
break;
case IO_OPEN_CNX_ERROR_BAD_DESTINATION:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_BAD_DESTINATION\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_BAD_DEST;
break;
case IO_OPEN_CNX_ERROR_CONNECTION_RATE_NOT_SUPPORTED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_CONNECTION_RATE_"
"NOT_SUPPORTED\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_CONN_RATE;
break;
case IO_OPEN_CNX_ERROR_WRONG_DESTINATION:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_WRONG_DESTINATION\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_WRONG_DEST;
break;
case IO_XFER_ERROR_NAK_RECEIVED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_NAK_RECEIVED\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_RETRY;
break;
case IO_XFER_ERROR_ACK_NAK_TIMEOUT:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_ACK_NAK_TIMEOUT\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_NAK_R_ERR;
break;
case IO_XFER_OPEN_RETRY_TIMEOUT:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_OPEN_RETRY_TIMEOUT\n"));
pm8001_handle_event(pm8001_ha, t, IO_XFER_OPEN_RETRY_TIMEOUT);
return;
case IO_XFER_ERROR_UNEXPECTED_PHASE:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_UNEXPECTED_PHASE\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DATA_OVERRUN;
break;
case IO_XFER_ERROR_XFER_RDY_OVERRUN:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_XFER_RDY_OVERRUN\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DATA_OVERRUN;
break;
case IO_XFER_ERROR_XFER_RDY_NOT_EXPECTED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_XFER_RDY_NOT_EXPECTED\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DATA_OVERRUN;
break;
case IO_XFER_ERROR_CMD_ISSUE_ACK_NAK_TIMEOUT:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_CMD_ISSUE_ACK_NAK_TIMEOUT\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DATA_OVERRUN;
break;
case IO_XFER_ERROR_OFFSET_MISMATCH:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_OFFSET_MISMATCH\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DATA_OVERRUN;
break;
case IO_XFER_ERROR_XFER_ZERO_DATA_LEN:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_XFER_ZERO_DATA_LEN\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DATA_OVERRUN;
break;
case IO_XFER_CMD_FRAME_ISSUED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk(" IO_XFER_CMD_FRAME_ISSUED\n"));
return;
default:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("Unknown status 0x%x\n", event));
/* not allowed case. Therefore, return failed status */
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DATA_OVERRUN;
break;
}
spin_lock_irqsave(&t->task_state_lock, flags);
t->task_state_flags &= ~SAS_TASK_STATE_PENDING;
t->task_state_flags &= ~SAS_TASK_AT_INITIATOR;
t->task_state_flags |= SAS_TASK_STATE_DONE;
if (unlikely((t->task_state_flags & SAS_TASK_STATE_ABORTED))) {
spin_unlock_irqrestore(&t->task_state_lock, flags);
PM8001_FAIL_DBG(pm8001_ha, pm8001_printk("task 0x%p done with"
" event 0x%x resp 0x%x "
"stat 0x%x but aborted by upper layer!\n",
t, event, ts->resp, ts->stat));
pm8001_ccb_task_free(pm8001_ha, t, ccb, tag);
} else {
spin_unlock_irqrestore(&t->task_state_lock, flags);
pm8001_ccb_task_free(pm8001_ha, t, ccb, tag);
mb();/* in order to force CPU ordering */
t->task_done(t);
}
}
/*See the comments for mpi_ssp_completion */
static void
mpi_sata_completion(struct pm8001_hba_info *pm8001_ha, void *piomb)
{
struct sas_task *t;
struct pm8001_ccb_info *ccb;
u32 param;
u32 status;
u32 tag;
int i, j;
u8 sata_addr_low[4];
u32 temp_sata_addr_low;
u8 sata_addr_hi[4];
u32 temp_sata_addr_hi;
struct sata_completion_resp *psataPayload;
struct task_status_struct *ts;
struct ata_task_resp *resp ;
u32 *sata_resp;
struct pm8001_device *pm8001_dev;
unsigned long flags;
psataPayload = (struct sata_completion_resp *)(piomb + 4);
status = le32_to_cpu(psataPayload->status);
tag = le32_to_cpu(psataPayload->tag);
if (!tag) {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("tag null\n"));
return;
}
ccb = &pm8001_ha->ccb_info[tag];
param = le32_to_cpu(psataPayload->param);
if (ccb) {
t = ccb->task;
pm8001_dev = ccb->device;
} else {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("ccb null\n"));
return;
}
if (t) {
if (t->dev && (t->dev->lldd_dev))
pm8001_dev = t->dev->lldd_dev;
} else {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("task null\n"));
return;
}
if ((pm8001_dev && !(pm8001_dev->id & NCQ_READ_LOG_FLAG))
&& unlikely(!t || !t->lldd_task || !t->dev)) {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("task or dev null\n"));
return;
}
ts = &t->task_status;
if (!ts) {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("ts null\n"));
return;
}
/* Print sas address of IO failed device */
if ((status != IO_SUCCESS) && (status != IO_OVERFLOW) &&
(status != IO_UNDERFLOW)) {
if (!((t->dev->parent) &&
(DEV_IS_EXPANDER(t->dev->parent->dev_type)))) {
for (i = 0 , j = 4; j <= 7 && i <= 3; i++ , j++)
sata_addr_low[i] = pm8001_ha->sas_addr[j];
for (i = 0 , j = 0; j <= 3 && i <= 3; i++ , j++)
sata_addr_hi[i] = pm8001_ha->sas_addr[j];
memcpy(&temp_sata_addr_low, sata_addr_low,
sizeof(sata_addr_low));
memcpy(&temp_sata_addr_hi, sata_addr_hi,
sizeof(sata_addr_hi));
temp_sata_addr_hi = (((temp_sata_addr_hi >> 24) & 0xff)
|((temp_sata_addr_hi << 8) &
0xff0000) |
((temp_sata_addr_hi >> 8)
& 0xff00) |
((temp_sata_addr_hi << 24) &
0xff000000));
temp_sata_addr_low = ((((temp_sata_addr_low >> 24)
& 0xff) |
((temp_sata_addr_low << 8)
& 0xff0000) |
((temp_sata_addr_low >> 8)
& 0xff00) |
((temp_sata_addr_low << 24)
& 0xff000000)) +
pm8001_dev->attached_phy +
0x10);
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("SAS Address of IO Failure Drive:"
"%08x%08x", temp_sata_addr_hi,
temp_sata_addr_low));
} else {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("SAS Address of IO Failure Drive:"
"%016llx", SAS_ADDR(t->dev->sas_addr)));
}
}
switch (status) {
case IO_SUCCESS:
PM8001_IO_DBG(pm8001_ha, pm8001_printk("IO_SUCCESS\n"));
if (param == 0) {
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAM_STAT_GOOD;
/* check if response is for SEND READ LOG */
if (pm8001_dev &&
(pm8001_dev->id & NCQ_READ_LOG_FLAG)) {
/* set new bit for abort_all */
pm8001_dev->id |= NCQ_ABORT_ALL_FLAG;
/* clear bit for read log */
pm8001_dev->id = pm8001_dev->id & 0x7FFFFFFF;
pm8001_send_abort_all(pm8001_ha, pm8001_dev);
/* Free the tag */
pm8001_tag_free(pm8001_ha, tag);
sas_free_task(t);
return;
}
} else {
u8 len;
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_PROTO_RESPONSE;
ts->residual = param;
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("SAS_PROTO_RESPONSE len = %d\n",
param));
sata_resp = &psataPayload->sata_resp[0];
resp = (struct ata_task_resp *)ts->buf;
if (t->ata_task.dma_xfer == 0 &&
t->data_dir == PCI_DMA_FROMDEVICE) {
len = sizeof(struct pio_setup_fis);
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("PIO read len = %d\n", len));
} else if (t->ata_task.use_ncq) {
len = sizeof(struct set_dev_bits_fis);
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("FPDMA len = %d\n", len));
} else {
len = sizeof(struct dev_to_host_fis);
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("other len = %d\n", len));
}
if (SAS_STATUS_BUF_SIZE >= sizeof(*resp)) {
resp->frame_len = len;
memcpy(&resp->ending_fis[0], sata_resp, len);
ts->buf_valid_size = sizeof(*resp);
} else
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("response to large\n"));
}
if (pm8001_dev)
pm8001_dev->running_req--;
break;
case IO_ABORTED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_ABORTED IOMB Tag\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_ABORTED_TASK;
if (pm8001_dev)
pm8001_dev->running_req--;
break;
/* following cases are to do cases */
case IO_UNDERFLOW:
/* SATA Completion with error */
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_UNDERFLOW param = %d\n", param));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DATA_UNDERRUN;
ts->residual = param;
if (pm8001_dev)
pm8001_dev->running_req--;
break;
case IO_NO_DEVICE:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_NO_DEVICE\n"));
ts->resp = SAS_TASK_UNDELIVERED;
ts->stat = SAS_PHY_DOWN;
break;
case IO_XFER_ERROR_BREAK:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_BREAK\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_INTERRUPTED;
break;
case IO_XFER_ERROR_PHY_NOT_READY:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_PHY_NOT_READY\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_RETRY;
break;
case IO_OPEN_CNX_ERROR_PROTOCOL_NOT_SUPPORTED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_PROTOCOL_NOT"
"_SUPPORTED\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_EPROTO;
break;
case IO_OPEN_CNX_ERROR_ZONE_VIOLATION:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_ZONE_VIOLATION\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_UNKNOWN;
break;
case IO_OPEN_CNX_ERROR_BREAK:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_BREAK\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_CONT0;
break;
case IO_OPEN_CNX_ERROR_IT_NEXUS_LOSS:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_IT_NEXUS_LOSS\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DEV_NO_RESPONSE;
if (!t->uldd_task) {
pm8001_handle_event(pm8001_ha,
pm8001_dev,
IO_OPEN_CNX_ERROR_IT_NEXUS_LOSS);
ts->resp = SAS_TASK_UNDELIVERED;
ts->stat = SAS_QUEUE_FULL;
pm8001_ccb_task_free_done(pm8001_ha, t, ccb, tag);
return;
}
break;
case IO_OPEN_CNX_ERROR_BAD_DESTINATION:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_BAD_DESTINATION\n"));
ts->resp = SAS_TASK_UNDELIVERED;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_BAD_DEST;
if (!t->uldd_task) {
pm8001_handle_event(pm8001_ha,
pm8001_dev,
IO_OPEN_CNX_ERROR_IT_NEXUS_LOSS);
ts->resp = SAS_TASK_UNDELIVERED;
ts->stat = SAS_QUEUE_FULL;
pm8001_ccb_task_free_done(pm8001_ha, t, ccb, tag);
return;
}
break;
case IO_OPEN_CNX_ERROR_CONNECTION_RATE_NOT_SUPPORTED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_CONNECTION_RATE_"
"NOT_SUPPORTED\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_CONN_RATE;
break;
case IO_OPEN_CNX_ERROR_STP_RESOURCES_BUSY:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_STP_RESOURCES"
"_BUSY\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DEV_NO_RESPONSE;
if (!t->uldd_task) {
pm8001_handle_event(pm8001_ha,
pm8001_dev,
IO_OPEN_CNX_ERROR_STP_RESOURCES_BUSY);
ts->resp = SAS_TASK_UNDELIVERED;
ts->stat = SAS_QUEUE_FULL;
pm8001_ccb_task_free_done(pm8001_ha, t, ccb, tag);
return;
}
break;
case IO_OPEN_CNX_ERROR_WRONG_DESTINATION:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_WRONG_DESTINATION\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_WRONG_DEST;
break;
case IO_XFER_ERROR_NAK_RECEIVED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_NAK_RECEIVED\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_NAK_R_ERR;
break;
case IO_XFER_ERROR_ACK_NAK_TIMEOUT:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_ACK_NAK_TIMEOUT\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_NAK_R_ERR;
break;
case IO_XFER_ERROR_DMA:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_DMA\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_ABORTED_TASK;
break;
case IO_XFER_ERROR_SATA_LINK_TIMEOUT:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_SATA_LINK_TIMEOUT\n"));
ts->resp = SAS_TASK_UNDELIVERED;
ts->stat = SAS_DEV_NO_RESPONSE;
break;
case IO_XFER_ERROR_REJECTED_NCQ_MODE:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_REJECTED_NCQ_MODE\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DATA_UNDERRUN;
break;
case IO_XFER_OPEN_RETRY_TIMEOUT:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_OPEN_RETRY_TIMEOUT\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_TO;
break;
case IO_PORT_IN_RESET:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_PORT_IN_RESET\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DEV_NO_RESPONSE;
break;
case IO_DS_NON_OPERATIONAL:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_DS_NON_OPERATIONAL\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DEV_NO_RESPONSE;
if (!t->uldd_task) {
pm8001_handle_event(pm8001_ha, pm8001_dev,
IO_DS_NON_OPERATIONAL);
ts->resp = SAS_TASK_UNDELIVERED;
ts->stat = SAS_QUEUE_FULL;
pm8001_ccb_task_free_done(pm8001_ha, t, ccb, tag);
return;
}
break;
case IO_DS_IN_RECOVERY:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk(" IO_DS_IN_RECOVERY\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DEV_NO_RESPONSE;
break;
case IO_DS_IN_ERROR:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_DS_IN_ERROR\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DEV_NO_RESPONSE;
if (!t->uldd_task) {
pm8001_handle_event(pm8001_ha, pm8001_dev,
IO_DS_IN_ERROR);
ts->resp = SAS_TASK_UNDELIVERED;
ts->stat = SAS_QUEUE_FULL;
pm8001_ccb_task_free_done(pm8001_ha, t, ccb, tag);
return;
}
break;
case IO_OPEN_CNX_ERROR_HW_RESOURCE_BUSY:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_HW_RESOURCE_BUSY\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_RETRY;
default:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("Unknown status 0x%x\n", status));
/* not allowed case. Therefore, return failed status */
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DEV_NO_RESPONSE;
break;
}
spin_lock_irqsave(&t->task_state_lock, flags);
t->task_state_flags &= ~SAS_TASK_STATE_PENDING;
t->task_state_flags &= ~SAS_TASK_AT_INITIATOR;
t->task_state_flags |= SAS_TASK_STATE_DONE;
if (unlikely((t->task_state_flags & SAS_TASK_STATE_ABORTED))) {
spin_unlock_irqrestore(&t->task_state_lock, flags);
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("task 0x%p done with io_status 0x%x"
" resp 0x%x stat 0x%x but aborted by upper layer!\n",
t, status, ts->resp, ts->stat));
pm8001_ccb_task_free(pm8001_ha, t, ccb, tag);
} else {
spin_unlock_irqrestore(&t->task_state_lock, flags);
pm8001_ccb_task_free_done(pm8001_ha, t, ccb, tag);
}
}
/*See the comments for mpi_ssp_completion */
static void mpi_sata_event(struct pm8001_hba_info *pm8001_ha , void *piomb)
{
struct sas_task *t;
struct task_status_struct *ts;
struct pm8001_ccb_info *ccb;
struct pm8001_device *pm8001_dev;
struct sata_event_resp *psataPayload =
(struct sata_event_resp *)(piomb + 4);
u32 event = le32_to_cpu(psataPayload->event);
u32 tag = le32_to_cpu(psataPayload->tag);
u32 port_id = le32_to_cpu(psataPayload->port_id);
u32 dev_id = le32_to_cpu(psataPayload->device_id);
unsigned long flags;
ccb = &pm8001_ha->ccb_info[tag];
if (ccb) {
t = ccb->task;
pm8001_dev = ccb->device;
} else {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("No CCB !!!. returning\n"));
}
if (event)
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("SATA EVENT 0x%x\n", event));
/* Check if this is NCQ error */
if (event == IO_XFER_ERROR_ABORTED_NCQ_MODE) {
/* find device using device id */
pm8001_dev = pm8001_find_dev(pm8001_ha, dev_id);
/* send read log extension */
if (pm8001_dev)
pm8001_send_read_log(pm8001_ha, pm8001_dev);
return;
}
ccb = &pm8001_ha->ccb_info[tag];
t = ccb->task;
pm8001_dev = ccb->device;
if (event)
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("sata IO status 0x%x\n", event));
if (unlikely(!t || !t->lldd_task || !t->dev))
return;
ts = &t->task_status;
PM8001_IO_DBG(pm8001_ha, pm8001_printk(
"port_id:0x%x, device_id:0x%x, tag:0x%x, event:0x%x\n",
port_id, dev_id, tag, event));
switch (event) {
case IO_OVERFLOW:
PM8001_IO_DBG(pm8001_ha, pm8001_printk("IO_UNDERFLOW\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DATA_OVERRUN;
ts->residual = 0;
if (pm8001_dev)
pm8001_dev->running_req--;
break;
case IO_XFER_ERROR_BREAK:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_BREAK\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_INTERRUPTED;
break;
case IO_XFER_ERROR_PHY_NOT_READY:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_PHY_NOT_READY\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_RETRY;
break;
case IO_OPEN_CNX_ERROR_PROTOCOL_NOT_SUPPORTED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_PROTOCOL_NOT"
"_SUPPORTED\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_EPROTO;
break;
case IO_OPEN_CNX_ERROR_ZONE_VIOLATION:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_ZONE_VIOLATION\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_UNKNOWN;
break;
case IO_OPEN_CNX_ERROR_BREAK:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_BREAK\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_CONT0;
break;
case IO_OPEN_CNX_ERROR_IT_NEXUS_LOSS:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_IT_NEXUS_LOSS\n"));
ts->resp = SAS_TASK_UNDELIVERED;
ts->stat = SAS_DEV_NO_RESPONSE;
if (!t->uldd_task) {
pm8001_handle_event(pm8001_ha,
pm8001_dev,
IO_OPEN_CNX_ERROR_IT_NEXUS_LOSS);
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_QUEUE_FULL;
pm8001_ccb_task_free_done(pm8001_ha, t, ccb, tag);
return;
}
break;
case IO_OPEN_CNX_ERROR_BAD_DESTINATION:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_BAD_DESTINATION\n"));
ts->resp = SAS_TASK_UNDELIVERED;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_BAD_DEST;
break;
case IO_OPEN_CNX_ERROR_CONNECTION_RATE_NOT_SUPPORTED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_CONNECTION_RATE_"
"NOT_SUPPORTED\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_CONN_RATE;
break;
case IO_OPEN_CNX_ERROR_WRONG_DESTINATION:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_WRONG_DESTINATION\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_WRONG_DEST;
break;
case IO_XFER_ERROR_NAK_RECEIVED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_NAK_RECEIVED\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_NAK_R_ERR;
break;
case IO_XFER_ERROR_PEER_ABORTED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_PEER_ABORTED\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_NAK_R_ERR;
break;
case IO_XFER_ERROR_REJECTED_NCQ_MODE:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_REJECTED_NCQ_MODE\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DATA_UNDERRUN;
break;
case IO_XFER_OPEN_RETRY_TIMEOUT:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_OPEN_RETRY_TIMEOUT\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_TO;
break;
case IO_XFER_ERROR_UNEXPECTED_PHASE:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_UNEXPECTED_PHASE\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_TO;
break;
case IO_XFER_ERROR_XFER_RDY_OVERRUN:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_XFER_RDY_OVERRUN\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_TO;
break;
case IO_XFER_ERROR_XFER_RDY_NOT_EXPECTED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_XFER_RDY_NOT_EXPECTED\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_TO;
break;
case IO_XFER_ERROR_OFFSET_MISMATCH:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_OFFSET_MISMATCH\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_TO;
break;
case IO_XFER_ERROR_XFER_ZERO_DATA_LEN:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_XFER_ZERO_DATA_LEN\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_TO;
break;
case IO_XFER_CMD_FRAME_ISSUED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_CMD_FRAME_ISSUED\n"));
break;
case IO_XFER_PIO_SETUP_ERROR:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_PIO_SETUP_ERROR\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_TO;
break;
default:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("Unknown status 0x%x\n", event));
/* not allowed case. Therefore, return failed status */
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_TO;
break;
}
spin_lock_irqsave(&t->task_state_lock, flags);
t->task_state_flags &= ~SAS_TASK_STATE_PENDING;
t->task_state_flags &= ~SAS_TASK_AT_INITIATOR;
t->task_state_flags |= SAS_TASK_STATE_DONE;
if (unlikely((t->task_state_flags & SAS_TASK_STATE_ABORTED))) {
spin_unlock_irqrestore(&t->task_state_lock, flags);
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("task 0x%p done with io_status 0x%x"
" resp 0x%x stat 0x%x but aborted by upper layer!\n",
t, event, ts->resp, ts->stat));
pm8001_ccb_task_free(pm8001_ha, t, ccb, tag);
} else {
spin_unlock_irqrestore(&t->task_state_lock, flags);
pm8001_ccb_task_free_done(pm8001_ha, t, ccb, tag);
}
}
/*See the comments for mpi_ssp_completion */
static void
mpi_smp_completion(struct pm8001_hba_info *pm8001_ha, void *piomb)
{
u32 param;
struct sas_task *t;
struct pm8001_ccb_info *ccb;
unsigned long flags;
u32 status;
u32 tag;
struct smp_completion_resp *psmpPayload;
struct task_status_struct *ts;
struct pm8001_device *pm8001_dev;
psmpPayload = (struct smp_completion_resp *)(piomb + 4);
status = le32_to_cpu(psmpPayload->status);
tag = le32_to_cpu(psmpPayload->tag);
ccb = &pm8001_ha->ccb_info[tag];
param = le32_to_cpu(psmpPayload->param);
t = ccb->task;
ts = &t->task_status;
pm8001_dev = ccb->device;
if (status)
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("smp IO status 0x%x\n", status));
if (unlikely(!t || !t->lldd_task || !t->dev))
return;
switch (status) {
case IO_SUCCESS:
PM8001_IO_DBG(pm8001_ha, pm8001_printk("IO_SUCCESS\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAM_STAT_GOOD;
if (pm8001_dev)
pm8001_dev->running_req--;
break;
case IO_ABORTED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_ABORTED IOMB\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_ABORTED_TASK;
if (pm8001_dev)
pm8001_dev->running_req--;
break;
case IO_OVERFLOW:
PM8001_IO_DBG(pm8001_ha, pm8001_printk("IO_UNDERFLOW\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DATA_OVERRUN;
ts->residual = 0;
if (pm8001_dev)
pm8001_dev->running_req--;
break;
case IO_NO_DEVICE:
PM8001_IO_DBG(pm8001_ha, pm8001_printk("IO_NO_DEVICE\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_PHY_DOWN;
break;
case IO_ERROR_HW_TIMEOUT:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_ERROR_HW_TIMEOUT\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAM_STAT_BUSY;
break;
case IO_XFER_ERROR_BREAK:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_BREAK\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAM_STAT_BUSY;
break;
case IO_XFER_ERROR_PHY_NOT_READY:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_PHY_NOT_READY\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAM_STAT_BUSY;
break;
case IO_OPEN_CNX_ERROR_PROTOCOL_NOT_SUPPORTED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_PROTOCOL_NOT_SUPPORTED\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_UNKNOWN;
break;
case IO_OPEN_CNX_ERROR_ZONE_VIOLATION:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_ZONE_VIOLATION\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_UNKNOWN;
break;
case IO_OPEN_CNX_ERROR_BREAK:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_BREAK\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_CONT0;
break;
case IO_OPEN_CNX_ERROR_IT_NEXUS_LOSS:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_IT_NEXUS_LOSS\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_UNKNOWN;
pm8001_handle_event(pm8001_ha,
pm8001_dev,
IO_OPEN_CNX_ERROR_IT_NEXUS_LOSS);
break;
case IO_OPEN_CNX_ERROR_BAD_DESTINATION:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_BAD_DESTINATION\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_BAD_DEST;
break;
case IO_OPEN_CNX_ERROR_CONNECTION_RATE_NOT_SUPPORTED:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_CONNECTION_RATE_"
"NOT_SUPPORTED\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_CONN_RATE;
break;
case IO_OPEN_CNX_ERROR_WRONG_DESTINATION:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_WRONG_DESTINATION\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_WRONG_DEST;
break;
case IO_XFER_ERROR_RX_FRAME:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_ERROR_RX_FRAME\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DEV_NO_RESPONSE;
break;
case IO_XFER_OPEN_RETRY_TIMEOUT:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_XFER_OPEN_RETRY_TIMEOUT\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_RETRY;
break;
case IO_ERROR_INTERNAL_SMP_RESOURCE:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_ERROR_INTERNAL_SMP_RESOURCE\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_QUEUE_FULL;
break;
case IO_PORT_IN_RESET:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_PORT_IN_RESET\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_RETRY;
break;
case IO_DS_NON_OPERATIONAL:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_DS_NON_OPERATIONAL\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DEV_NO_RESPONSE;
break;
case IO_DS_IN_RECOVERY:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_DS_IN_RECOVERY\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_RETRY;
break;
case IO_OPEN_CNX_ERROR_HW_RESOURCE_BUSY:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("IO_OPEN_CNX_ERROR_HW_RESOURCE_BUSY\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_OPEN_REJECT;
ts->open_rej_reason = SAS_OREJ_RSVD_RETRY;
break;
default:
PM8001_IO_DBG(pm8001_ha,
pm8001_printk("Unknown status 0x%x\n", status));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAS_DEV_NO_RESPONSE;
/* not allowed case. Therefore, return failed status */
break;
}
spin_lock_irqsave(&t->task_state_lock, flags);
t->task_state_flags &= ~SAS_TASK_STATE_PENDING;
t->task_state_flags &= ~SAS_TASK_AT_INITIATOR;
t->task_state_flags |= SAS_TASK_STATE_DONE;
if (unlikely((t->task_state_flags & SAS_TASK_STATE_ABORTED))) {
spin_unlock_irqrestore(&t->task_state_lock, flags);
PM8001_FAIL_DBG(pm8001_ha, pm8001_printk("task 0x%p done with"
" io_status 0x%x resp 0x%x "
"stat 0x%x but aborted by upper layer!\n",
t, status, ts->resp, ts->stat));
pm8001_ccb_task_free(pm8001_ha, t, ccb, tag);
} else {
spin_unlock_irqrestore(&t->task_state_lock, flags);
pm8001_ccb_task_free(pm8001_ha, t, ccb, tag);
mb();/* in order to force CPU ordering */
t->task_done(t);
}
}
void pm8001_mpi_set_dev_state_resp(struct pm8001_hba_info *pm8001_ha,
void *piomb)
{
struct set_dev_state_resp *pPayload =
(struct set_dev_state_resp *)(piomb + 4);
u32 tag = le32_to_cpu(pPayload->tag);
struct pm8001_ccb_info *ccb = &pm8001_ha->ccb_info[tag];
struct pm8001_device *pm8001_dev = ccb->device;
u32 status = le32_to_cpu(pPayload->status);
u32 device_id = le32_to_cpu(pPayload->device_id);
u8 pds = le32_to_cpu(pPayload->pds_nds) & PDS_BITS;
u8 nds = le32_to_cpu(pPayload->pds_nds) & NDS_BITS;
PM8001_MSG_DBG(pm8001_ha, pm8001_printk("Set device id = 0x%x state "
"from 0x%x to 0x%x status = 0x%x!\n",
device_id, pds, nds, status));
complete(pm8001_dev->setds_completion);
ccb->task = NULL;
ccb->ccb_tag = 0xFFFFFFFF;
pm8001_tag_free(pm8001_ha, tag);
}
void pm8001_mpi_set_nvmd_resp(struct pm8001_hba_info *pm8001_ha, void *piomb)
{
struct get_nvm_data_resp *pPayload =
(struct get_nvm_data_resp *)(piomb + 4);
u32 tag = le32_to_cpu(pPayload->tag);
struct pm8001_ccb_info *ccb = &pm8001_ha->ccb_info[tag];
u32 dlen_status = le32_to_cpu(pPayload->dlen_status);
complete(pm8001_ha->nvmd_completion);
PM8001_MSG_DBG(pm8001_ha, pm8001_printk("Set nvm data complete!\n"));
if ((dlen_status & NVMD_STAT) != 0) {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("Set nvm data error!\n"));
return;
}
ccb->task = NULL;
ccb->ccb_tag = 0xFFFFFFFF;
pm8001_tag_free(pm8001_ha, tag);
}
void
pm8001_mpi_get_nvmd_resp(struct pm8001_hba_info *pm8001_ha, void *piomb)
{
struct fw_control_ex *fw_control_context;
struct get_nvm_data_resp *pPayload =
(struct get_nvm_data_resp *)(piomb + 4);
u32 tag = le32_to_cpu(pPayload->tag);
struct pm8001_ccb_info *ccb = &pm8001_ha->ccb_info[tag];
u32 dlen_status = le32_to_cpu(pPayload->dlen_status);
u32 ir_tds_bn_dps_das_nvm =
le32_to_cpu(pPayload->ir_tda_bn_dps_das_nvm);
void *virt_addr = pm8001_ha->memoryMap.region[NVMD].virt_ptr;
fw_control_context = ccb->fw_control_context;
PM8001_MSG_DBG(pm8001_ha, pm8001_printk("Get nvm data complete!\n"));
if ((dlen_status & NVMD_STAT) != 0) {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("Get nvm data error!\n"));
complete(pm8001_ha->nvmd_completion);
return;
}
if (ir_tds_bn_dps_das_nvm & IPMode) {
/* indirect mode - IR bit set */
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("Get NVMD success, IR=1\n"));
if ((ir_tds_bn_dps_das_nvm & NVMD_TYPE) == TWI_DEVICE) {
if (ir_tds_bn_dps_das_nvm == 0x80a80200) {
memcpy(pm8001_ha->sas_addr,
((u8 *)virt_addr + 4),
SAS_ADDR_SIZE);
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("Get SAS address"
" from VPD successfully!\n"));
}
} else if (((ir_tds_bn_dps_das_nvm & NVMD_TYPE) == C_SEEPROM)
|| ((ir_tds_bn_dps_das_nvm & NVMD_TYPE) == VPD_FLASH) ||
((ir_tds_bn_dps_das_nvm & NVMD_TYPE) == EXPAN_ROM)) {
;
} else if (((ir_tds_bn_dps_das_nvm & NVMD_TYPE) == AAP1_RDUMP)
|| ((ir_tds_bn_dps_das_nvm & NVMD_TYPE) == IOP_RDUMP)) {
;
} else {
/* Should not be happened*/
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("(IR=1)Wrong Device type 0x%x\n",
ir_tds_bn_dps_das_nvm));
}
} else /* direct mode */{
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("Get NVMD success, IR=0, dataLen=%d\n",
(dlen_status & NVMD_LEN) >> 24));
}
/* Though fw_control_context is freed below, usrAddr still needs
* to be updated as this holds the response to the request function
*/
memcpy(fw_control_context->usrAddr,
pm8001_ha->memoryMap.region[NVMD].virt_ptr,
fw_control_context->len);
kfree(ccb->fw_control_context);
ccb->task = NULL;
ccb->ccb_tag = 0xFFFFFFFF;
pm8001_tag_free(pm8001_ha, tag);
complete(pm8001_ha->nvmd_completion);
}
int pm8001_mpi_local_phy_ctl(struct pm8001_hba_info *pm8001_ha, void *piomb)
{
struct local_phy_ctl_resp *pPayload =
(struct local_phy_ctl_resp *)(piomb + 4);
u32 status = le32_to_cpu(pPayload->status);
u32 phy_id = le32_to_cpu(pPayload->phyop_phyid) & ID_BITS;
u32 phy_op = le32_to_cpu(pPayload->phyop_phyid) & OP_BITS;
if (status != 0) {
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("%x phy execute %x phy op failed!\n",
phy_id, phy_op));
} else
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("%x phy execute %x phy op success!\n",
phy_id, phy_op));
return 0;
}
/**
* pm8001_bytes_dmaed - one of the interface function communication with libsas
* @pm8001_ha: our hba card information
* @i: which phy that received the event.
*
* when HBA driver received the identify done event or initiate FIS received
* event(for SATA), it will invoke this function to notify the sas layer that
* the sas toplogy has formed, please discover the the whole sas domain,
* while receive a broadcast(change) primitive just tell the sas
* layer to discover the changed domain rather than the whole domain.
*/
void pm8001_bytes_dmaed(struct pm8001_hba_info *pm8001_ha, int i)
{
struct pm8001_phy *phy = &pm8001_ha->phy[i];
struct asd_sas_phy *sas_phy = &phy->sas_phy;
struct sas_ha_struct *sas_ha;
if (!phy->phy_attached)
return;
sas_ha = pm8001_ha->sas;
if (sas_phy->phy) {
struct sas_phy *sphy = sas_phy->phy;
sphy->negotiated_linkrate = sas_phy->linkrate;
sphy->minimum_linkrate = phy->minimum_linkrate;
sphy->minimum_linkrate_hw = SAS_LINK_RATE_1_5_GBPS;
sphy->maximum_linkrate = phy->maximum_linkrate;
sphy->maximum_linkrate_hw = phy->maximum_linkrate;
}
if (phy->phy_type & PORT_TYPE_SAS) {
struct sas_identify_frame *id;
id = (struct sas_identify_frame *)phy->frame_rcvd;
id->dev_type = phy->identify.device_type;
id->initiator_bits = SAS_PROTOCOL_ALL;
id->target_bits = phy->identify.target_port_protocols;
} else if (phy->phy_type & PORT_TYPE_SATA) {
/*Nothing*/
}
PM8001_MSG_DBG(pm8001_ha, pm8001_printk("phy %d byte dmaded.\n", i));
sas_phy->frame_rcvd_size = phy->frame_rcvd_size;
pm8001_ha->sas->notify_port_event(sas_phy, PORTE_BYTES_DMAED);
}
/* Get the link rate speed */
void pm8001_get_lrate_mode(struct pm8001_phy *phy, u8 link_rate)
{
struct sas_phy *sas_phy = phy->sas_phy.phy;
switch (link_rate) {
case PHY_SPEED_60:
phy->sas_phy.linkrate = SAS_LINK_RATE_6_0_GBPS;
phy->sas_phy.phy->negotiated_linkrate = SAS_LINK_RATE_6_0_GBPS;
break;
case PHY_SPEED_30:
phy->sas_phy.linkrate = SAS_LINK_RATE_3_0_GBPS;
phy->sas_phy.phy->negotiated_linkrate = SAS_LINK_RATE_3_0_GBPS;
break;
case PHY_SPEED_15:
phy->sas_phy.linkrate = SAS_LINK_RATE_1_5_GBPS;
phy->sas_phy.phy->negotiated_linkrate = SAS_LINK_RATE_1_5_GBPS;
break;
}
sas_phy->negotiated_linkrate = phy->sas_phy.linkrate;
sas_phy->maximum_linkrate_hw = SAS_LINK_RATE_6_0_GBPS;
sas_phy->minimum_linkrate_hw = SAS_LINK_RATE_1_5_GBPS;
sas_phy->maximum_linkrate = SAS_LINK_RATE_6_0_GBPS;
sas_phy->minimum_linkrate = SAS_LINK_RATE_1_5_GBPS;
}
/**
* asd_get_attached_sas_addr -- extract/generate attached SAS address
* @phy: pointer to asd_phy
* @sas_addr: pointer to buffer where the SAS address is to be written
*
* This function extracts the SAS address from an IDENTIFY frame
* received. If OOB is SATA, then a SAS address is generated from the
* HA tables.
*
* LOCKING: the frame_rcvd_lock needs to be held since this parses the frame
* buffer.
*/
void pm8001_get_attached_sas_addr(struct pm8001_phy *phy,
u8 *sas_addr)
{
if (phy->sas_phy.frame_rcvd[0] == 0x34
&& phy->sas_phy.oob_mode == SATA_OOB_MODE) {
struct pm8001_hba_info *pm8001_ha = phy->sas_phy.ha->lldd_ha;
/* FIS device-to-host */
u64 addr = be64_to_cpu(*(__be64 *)pm8001_ha->sas_addr);
addr += phy->sas_phy.id;
*(__be64 *)sas_addr = cpu_to_be64(addr);
} else {
struct sas_identify_frame *idframe =
(void *) phy->sas_phy.frame_rcvd;
memcpy(sas_addr, idframe->sas_addr, SAS_ADDR_SIZE);
}
}
/**
* pm8001_hw_event_ack_req- For PM8001,some events need to acknowage to FW.
* @pm8001_ha: our hba card information
* @Qnum: the outbound queue message number.
* @SEA: source of event to ack
* @port_id: port id.
* @phyId: phy id.
* @param0: parameter 0.
* @param1: parameter 1.
*/
static void pm8001_hw_event_ack_req(struct pm8001_hba_info *pm8001_ha,
u32 Qnum, u32 SEA, u32 port_id, u32 phyId, u32 param0, u32 param1)
{
struct hw_event_ack_req payload;
u32 opc = OPC_INB_SAS_HW_EVENT_ACK;
struct inbound_queue_table *circularQ;
memset((u8 *)&payload, 0, sizeof(payload));
circularQ = &pm8001_ha->inbnd_q_tbl[Qnum];
payload.tag = cpu_to_le32(1);
payload.sea_phyid_portid = cpu_to_le32(((SEA & 0xFFFF) << 8) |
((phyId & 0x0F) << 4) | (port_id & 0x0F));
payload.param0 = cpu_to_le32(param0);
payload.param1 = cpu_to_le32(param1);
pm8001_mpi_build_cmd(pm8001_ha, circularQ, opc, &payload, 0);
}
static int pm8001_chip_phy_ctl_req(struct pm8001_hba_info *pm8001_ha,
u32 phyId, u32 phy_op);
/**
* hw_event_sas_phy_up -FW tells me a SAS phy up event.
* @pm8001_ha: our hba card information
* @piomb: IO message buffer
*/
static void
hw_event_sas_phy_up(struct pm8001_hba_info *pm8001_ha, void *piomb)
{
struct hw_event_resp *pPayload =
(struct hw_event_resp *)(piomb + 4);
u32 lr_evt_status_phyid_portid =
le32_to_cpu(pPayload->lr_evt_status_phyid_portid);
u8 link_rate =
(u8)((lr_evt_status_phyid_portid & 0xF0000000) >> 28);
u8 port_id = (u8)(lr_evt_status_phyid_portid & 0x0000000F);
u8 phy_id =
(u8)((lr_evt_status_phyid_portid & 0x000000F0) >> 4);
u32 npip_portstate = le32_to_cpu(pPayload->npip_portstate);
u8 portstate = (u8)(npip_portstate & 0x0000000F);
struct pm8001_port *port = &pm8001_ha->port[port_id];
struct sas_ha_struct *sas_ha = pm8001_ha->sas;
struct pm8001_phy *phy = &pm8001_ha->phy[phy_id];
unsigned long flags;
u8 deviceType = pPayload->sas_identify.dev_type;
port->port_state = portstate;
phy->phy_state = PHY_STATE_LINK_UP_SPC;
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_SAS_PHY_UP port id = %d, phy id = %d\n",
port_id, phy_id));
switch (deviceType) {
case SAS_PHY_UNUSED:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("device type no device.\n"));
break;
case SAS_END_DEVICE:
PM8001_MSG_DBG(pm8001_ha, pm8001_printk("end device.\n"));
pm8001_chip_phy_ctl_req(pm8001_ha, phy_id,
PHY_NOTIFY_ENABLE_SPINUP);
port->port_attached = 1;
pm8001_get_lrate_mode(phy, link_rate);
break;
case SAS_EDGE_EXPANDER_DEVICE:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("expander device.\n"));
port->port_attached = 1;
pm8001_get_lrate_mode(phy, link_rate);
break;
case SAS_FANOUT_EXPANDER_DEVICE:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("fanout expander device.\n"));
port->port_attached = 1;
pm8001_get_lrate_mode(phy, link_rate);
break;
default:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("unknown device type(%x)\n", deviceType));
break;
}
phy->phy_type |= PORT_TYPE_SAS;
phy->identify.device_type = deviceType;
phy->phy_attached = 1;
if (phy->identify.device_type == SAS_END_DEVICE)
phy->identify.target_port_protocols = SAS_PROTOCOL_SSP;
else if (phy->identify.device_type != SAS_PHY_UNUSED)
phy->identify.target_port_protocols = SAS_PROTOCOL_SMP;
phy->sas_phy.oob_mode = SAS_OOB_MODE;
sas_ha->notify_phy_event(&phy->sas_phy, PHYE_OOB_DONE);
spin_lock_irqsave(&phy->sas_phy.frame_rcvd_lock, flags);
memcpy(phy->frame_rcvd, &pPayload->sas_identify,
sizeof(struct sas_identify_frame)-4);
phy->frame_rcvd_size = sizeof(struct sas_identify_frame) - 4;
pm8001_get_attached_sas_addr(phy, phy->sas_phy.attached_sas_addr);
spin_unlock_irqrestore(&phy->sas_phy.frame_rcvd_lock, flags);
if (pm8001_ha->flags == PM8001F_RUN_TIME)
mdelay(200);/*delay a moment to wait disk to spinup*/
pm8001_bytes_dmaed(pm8001_ha, phy_id);
}
/**
* hw_event_sata_phy_up -FW tells me a SATA phy up event.
* @pm8001_ha: our hba card information
* @piomb: IO message buffer
*/
static void
hw_event_sata_phy_up(struct pm8001_hba_info *pm8001_ha, void *piomb)
{
struct hw_event_resp *pPayload =
(struct hw_event_resp *)(piomb + 4);
u32 lr_evt_status_phyid_portid =
le32_to_cpu(pPayload->lr_evt_status_phyid_portid);
u8 link_rate =
(u8)((lr_evt_status_phyid_portid & 0xF0000000) >> 28);
u8 port_id = (u8)(lr_evt_status_phyid_portid & 0x0000000F);
u8 phy_id =
(u8)((lr_evt_status_phyid_portid & 0x000000F0) >> 4);
u32 npip_portstate = le32_to_cpu(pPayload->npip_portstate);
u8 portstate = (u8)(npip_portstate & 0x0000000F);
struct pm8001_port *port = &pm8001_ha->port[port_id];
struct sas_ha_struct *sas_ha = pm8001_ha->sas;
struct pm8001_phy *phy = &pm8001_ha->phy[phy_id];
unsigned long flags;
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_SATA_PHY_UP port id = %d,"
" phy id = %d\n", port_id, phy_id));
port->port_state = portstate;
phy->phy_state = PHY_STATE_LINK_UP_SPC;
port->port_attached = 1;
pm8001_get_lrate_mode(phy, link_rate);
phy->phy_type |= PORT_TYPE_SATA;
phy->phy_attached = 1;
phy->sas_phy.oob_mode = SATA_OOB_MODE;
sas_ha->notify_phy_event(&phy->sas_phy, PHYE_OOB_DONE);
spin_lock_irqsave(&phy->sas_phy.frame_rcvd_lock, flags);
memcpy(phy->frame_rcvd, ((u8 *)&pPayload->sata_fis - 4),
sizeof(struct dev_to_host_fis));
phy->frame_rcvd_size = sizeof(struct dev_to_host_fis);
phy->identify.target_port_protocols = SAS_PROTOCOL_SATA;
phy->identify.device_type = SAS_SATA_DEV;
pm8001_get_attached_sas_addr(phy, phy->sas_phy.attached_sas_addr);
spin_unlock_irqrestore(&phy->sas_phy.frame_rcvd_lock, flags);
pm8001_bytes_dmaed(pm8001_ha, phy_id);
}
/**
* hw_event_phy_down -we should notify the libsas the phy is down.
* @pm8001_ha: our hba card information
* @piomb: IO message buffer
*/
static void
hw_event_phy_down(struct pm8001_hba_info *pm8001_ha, void *piomb)
{
struct hw_event_resp *pPayload =
(struct hw_event_resp *)(piomb + 4);
u32 lr_evt_status_phyid_portid =
le32_to_cpu(pPayload->lr_evt_status_phyid_portid);
u8 port_id = (u8)(lr_evt_status_phyid_portid & 0x0000000F);
u8 phy_id =
(u8)((lr_evt_status_phyid_portid & 0x000000F0) >> 4);
u32 npip_portstate = le32_to_cpu(pPayload->npip_portstate);
u8 portstate = (u8)(npip_portstate & 0x0000000F);
struct pm8001_port *port = &pm8001_ha->port[port_id];
struct pm8001_phy *phy = &pm8001_ha->phy[phy_id];
port->port_state = portstate;
phy->phy_type = 0;
phy->identify.device_type = 0;
phy->phy_attached = 0;
memset(&phy->dev_sas_addr, 0, SAS_ADDR_SIZE);
switch (portstate) {
case PORT_VALID:
break;
case PORT_INVALID:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(" PortInvalid portID %d\n", port_id));
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(" Last phy Down and port invalid\n"));
port->port_attached = 0;
pm8001_hw_event_ack_req(pm8001_ha, 0, HW_EVENT_PHY_DOWN,
port_id, phy_id, 0, 0);
break;
case PORT_IN_RESET:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(" Port In Reset portID %d\n", port_id));
break;
case PORT_NOT_ESTABLISHED:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(" phy Down and PORT_NOT_ESTABLISHED\n"));
port->port_attached = 0;
break;
case PORT_LOSTCOMM:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(" phy Down and PORT_LOSTCOMM\n"));
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(" Last phy Down and port invalid\n"));
port->port_attached = 0;
pm8001_hw_event_ack_req(pm8001_ha, 0, HW_EVENT_PHY_DOWN,
port_id, phy_id, 0, 0);
break;
default:
port->port_attached = 0;
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(" phy Down and(default) = %x\n",
portstate));
break;
}
}
/**
* pm8001_mpi_reg_resp -process register device ID response.
* @pm8001_ha: our hba card information
* @piomb: IO message buffer
*
* when sas layer find a device it will notify LLDD, then the driver register
* the domain device to FW, this event is the return device ID which the FW
* has assigned, from now,inter-communication with FW is no longer using the
* SAS address, use device ID which FW assigned.
*/
int pm8001_mpi_reg_resp(struct pm8001_hba_info *pm8001_ha, void *piomb)
{
u32 status;
u32 device_id;
u32 htag;
struct pm8001_ccb_info *ccb;
struct pm8001_device *pm8001_dev;
struct dev_reg_resp *registerRespPayload =
(struct dev_reg_resp *)(piomb + 4);
htag = le32_to_cpu(registerRespPayload->tag);
ccb = &pm8001_ha->ccb_info[htag];
pm8001_dev = ccb->device;
status = le32_to_cpu(registerRespPayload->status);
device_id = le32_to_cpu(registerRespPayload->device_id);
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(" register device is status = %d\n", status));
switch (status) {
case DEVREG_SUCCESS:
PM8001_MSG_DBG(pm8001_ha, pm8001_printk("DEVREG_SUCCESS\n"));
pm8001_dev->device_id = device_id;
break;
case DEVREG_FAILURE_OUT_OF_RESOURCE:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("DEVREG_FAILURE_OUT_OF_RESOURCE\n"));
break;
case DEVREG_FAILURE_DEVICE_ALREADY_REGISTERED:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("DEVREG_FAILURE_DEVICE_ALREADY_REGISTERED\n"));
break;
case DEVREG_FAILURE_INVALID_PHY_ID:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("DEVREG_FAILURE_INVALID_PHY_ID\n"));
break;
case DEVREG_FAILURE_PHY_ID_ALREADY_REGISTERED:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("DEVREG_FAILURE_PHY_ID_ALREADY_REGISTERED\n"));
break;
case DEVREG_FAILURE_PORT_ID_OUT_OF_RANGE:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("DEVREG_FAILURE_PORT_ID_OUT_OF_RANGE\n"));
break;
case DEVREG_FAILURE_PORT_NOT_VALID_STATE:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("DEVREG_FAILURE_PORT_NOT_VALID_STATE\n"));
break;
case DEVREG_FAILURE_DEVICE_TYPE_NOT_VALID:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("DEVREG_FAILURE_DEVICE_TYPE_NOT_VALID\n"));
break;
default:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("DEVREG_FAILURE_DEVICE_TYPE_NOT_UNSORPORTED\n"));
break;
}
complete(pm8001_dev->dcompletion);
ccb->task = NULL;
ccb->ccb_tag = 0xFFFFFFFF;
pm8001_tag_free(pm8001_ha, htag);
return 0;
}
int pm8001_mpi_dereg_resp(struct pm8001_hba_info *pm8001_ha, void *piomb)
{
u32 status;
u32 device_id;
struct dev_reg_resp *registerRespPayload =
(struct dev_reg_resp *)(piomb + 4);
status = le32_to_cpu(registerRespPayload->status);
device_id = le32_to_cpu(registerRespPayload->device_id);
if (status != 0)
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(" deregister device failed ,status = %x"
", device_id = %x\n", status, device_id));
return 0;
}
/**
* fw_flash_update_resp - Response from FW for flash update command.
* @pm8001_ha: our hba card information
* @piomb: IO message buffer
*/
int pm8001_mpi_fw_flash_update_resp(struct pm8001_hba_info *pm8001_ha,
void *piomb)
{
u32 status;
struct fw_flash_Update_resp *ppayload =
(struct fw_flash_Update_resp *)(piomb + 4);
u32 tag = le32_to_cpu(ppayload->tag);
struct pm8001_ccb_info *ccb = &pm8001_ha->ccb_info[tag];
status = le32_to_cpu(ppayload->status);
switch (status) {
case FLASH_UPDATE_COMPLETE_PENDING_REBOOT:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(": FLASH_UPDATE_COMPLETE_PENDING_REBOOT\n"));
break;
case FLASH_UPDATE_IN_PROGRESS:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(": FLASH_UPDATE_IN_PROGRESS\n"));
break;
case FLASH_UPDATE_HDR_ERR:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(": FLASH_UPDATE_HDR_ERR\n"));
break;
case FLASH_UPDATE_OFFSET_ERR:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(": FLASH_UPDATE_OFFSET_ERR\n"));
break;
case FLASH_UPDATE_CRC_ERR:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(": FLASH_UPDATE_CRC_ERR\n"));
break;
case FLASH_UPDATE_LENGTH_ERR:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(": FLASH_UPDATE_LENGTH_ERR\n"));
break;
case FLASH_UPDATE_HW_ERR:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(": FLASH_UPDATE_HW_ERR\n"));
break;
case FLASH_UPDATE_DNLD_NOT_SUPPORTED:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(": FLASH_UPDATE_DNLD_NOT_SUPPORTED\n"));
break;
case FLASH_UPDATE_DISABLED:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(": FLASH_UPDATE_DISABLED\n"));
break;
default:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("No matched status = %d\n", status));
break;
}
kfree(ccb->fw_control_context);
ccb->task = NULL;
ccb->ccb_tag = 0xFFFFFFFF;
pm8001_tag_free(pm8001_ha, tag);
complete(pm8001_ha->nvmd_completion);
return 0;
}
int pm8001_mpi_general_event(struct pm8001_hba_info *pm8001_ha , void *piomb)
{
u32 status;
int i;
struct general_event_resp *pPayload =
(struct general_event_resp *)(piomb + 4);
status = le32_to_cpu(pPayload->status);
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk(" status = 0x%x\n", status));
for (i = 0; i < GENERAL_EVENT_PAYLOAD; i++)
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("inb_IOMB_payload[0x%x] 0x%x,\n", i,
pPayload->inb_IOMB_payload[i]));
return 0;
}
int pm8001_mpi_task_abort_resp(struct pm8001_hba_info *pm8001_ha, void *piomb)
{
struct sas_task *t;
struct pm8001_ccb_info *ccb;
unsigned long flags;
u32 status ;
u32 tag, scp;
struct task_status_struct *ts;
struct pm8001_device *pm8001_dev;
struct task_abort_resp *pPayload =
(struct task_abort_resp *)(piomb + 4);
status = le32_to_cpu(pPayload->status);
tag = le32_to_cpu(pPayload->tag);
if (!tag) {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk(" TAG NULL. RETURNING !!!"));
return -1;
}
scp = le32_to_cpu(pPayload->scp);
ccb = &pm8001_ha->ccb_info[tag];
t = ccb->task;
pm8001_dev = ccb->device; /* retrieve device */
if (!t) {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk(" TASK NULL. RETURNING !!!"));
return -1;
}
ts = &t->task_status;
if (status != 0)
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("task abort failed status 0x%x ,"
"tag = 0x%x, scp= 0x%x\n", status, tag, scp));
switch (status) {
case IO_SUCCESS:
PM8001_EH_DBG(pm8001_ha, pm8001_printk("IO_SUCCESS\n"));
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAM_STAT_GOOD;
break;
case IO_NOT_VALID:
PM8001_EH_DBG(pm8001_ha, pm8001_printk("IO_NOT_VALID\n"));
ts->resp = TMF_RESP_FUNC_FAILED;
break;
}
spin_lock_irqsave(&t->task_state_lock, flags);
t->task_state_flags &= ~SAS_TASK_STATE_PENDING;
t->task_state_flags &= ~SAS_TASK_AT_INITIATOR;
t->task_state_flags |= SAS_TASK_STATE_DONE;
spin_unlock_irqrestore(&t->task_state_lock, flags);
pm8001_ccb_task_free(pm8001_ha, t, ccb, tag);
mb();
if (pm8001_dev->id & NCQ_ABORT_ALL_FLAG) {
pm8001_tag_free(pm8001_ha, tag);
sas_free_task(t);
/* clear the flag */
pm8001_dev->id &= 0xBFFFFFFF;
} else
t->task_done(t);
return 0;
}
/**
* mpi_hw_event -The hw event has come.
* @pm8001_ha: our hba card information
* @piomb: IO message buffer
*/
static int mpi_hw_event(struct pm8001_hba_info *pm8001_ha, void* piomb)
{
unsigned long flags;
struct hw_event_resp *pPayload =
(struct hw_event_resp *)(piomb + 4);
u32 lr_evt_status_phyid_portid =
le32_to_cpu(pPayload->lr_evt_status_phyid_portid);
u8 port_id = (u8)(lr_evt_status_phyid_portid & 0x0000000F);
u8 phy_id =
(u8)((lr_evt_status_phyid_portid & 0x000000F0) >> 4);
u16 eventType =
(u16)((lr_evt_status_phyid_portid & 0x00FFFF00) >> 8);
u8 status =
(u8)((lr_evt_status_phyid_portid & 0x0F000000) >> 24);
struct sas_ha_struct *sas_ha = pm8001_ha->sas;
struct pm8001_phy *phy = &pm8001_ha->phy[phy_id];
struct asd_sas_phy *sas_phy = sas_ha->sas_phy[phy_id];
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("outbound queue HW event & event type : "));
switch (eventType) {
case HW_EVENT_PHY_START_STATUS:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_PHY_START_STATUS"
" status = %x\n", status));
if (status == 0) {
phy->phy_state = 1;
if (pm8001_ha->flags == PM8001F_RUN_TIME)
complete(phy->enable_completion);
}
break;
case HW_EVENT_SAS_PHY_UP:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_PHY_START_STATUS\n"));
hw_event_sas_phy_up(pm8001_ha, piomb);
break;
case HW_EVENT_SATA_PHY_UP:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_SATA_PHY_UP\n"));
hw_event_sata_phy_up(pm8001_ha, piomb);
break;
case HW_EVENT_PHY_STOP_STATUS:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_PHY_STOP_STATUS "
"status = %x\n", status));
if (status == 0)
phy->phy_state = 0;
break;
case HW_EVENT_SATA_SPINUP_HOLD:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_SATA_SPINUP_HOLD\n"));
sas_ha->notify_phy_event(&phy->sas_phy, PHYE_SPINUP_HOLD);
break;
case HW_EVENT_PHY_DOWN:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_PHY_DOWN\n"));
sas_ha->notify_phy_event(&phy->sas_phy, PHYE_LOSS_OF_SIGNAL);
phy->phy_attached = 0;
phy->phy_state = 0;
hw_event_phy_down(pm8001_ha, piomb);
break;
case HW_EVENT_PORT_INVALID:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_PORT_INVALID\n"));
sas_phy_disconnected(sas_phy);
phy->phy_attached = 0;
sas_ha->notify_port_event(sas_phy, PORTE_LINK_RESET_ERR);
break;
/* the broadcast change primitive received, tell the LIBSAS this event
to revalidate the sas domain*/
case HW_EVENT_BROADCAST_CHANGE:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_BROADCAST_CHANGE\n"));
pm8001_hw_event_ack_req(pm8001_ha, 0, HW_EVENT_BROADCAST_CHANGE,
port_id, phy_id, 1, 0);
spin_lock_irqsave(&sas_phy->sas_prim_lock, flags);
sas_phy->sas_prim = HW_EVENT_BROADCAST_CHANGE;
spin_unlock_irqrestore(&sas_phy->sas_prim_lock, flags);
sas_ha->notify_port_event(sas_phy, PORTE_BROADCAST_RCVD);
break;
case HW_EVENT_PHY_ERROR:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_PHY_ERROR\n"));
sas_phy_disconnected(&phy->sas_phy);
phy->phy_attached = 0;
sas_ha->notify_phy_event(&phy->sas_phy, PHYE_OOB_ERROR);
break;
case HW_EVENT_BROADCAST_EXP:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_BROADCAST_EXP\n"));
spin_lock_irqsave(&sas_phy->sas_prim_lock, flags);
sas_phy->sas_prim = HW_EVENT_BROADCAST_EXP;
spin_unlock_irqrestore(&sas_phy->sas_prim_lock, flags);
sas_ha->notify_port_event(sas_phy, PORTE_BROADCAST_RCVD);
break;
case HW_EVENT_LINK_ERR_INVALID_DWORD:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_LINK_ERR_INVALID_DWORD\n"));
pm8001_hw_event_ack_req(pm8001_ha, 0,
HW_EVENT_LINK_ERR_INVALID_DWORD, port_id, phy_id, 0, 0);
sas_phy_disconnected(sas_phy);
phy->phy_attached = 0;
sas_ha->notify_port_event(sas_phy, PORTE_LINK_RESET_ERR);
break;
case HW_EVENT_LINK_ERR_DISPARITY_ERROR:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_LINK_ERR_DISPARITY_ERROR\n"));
pm8001_hw_event_ack_req(pm8001_ha, 0,
HW_EVENT_LINK_ERR_DISPARITY_ERROR,
port_id, phy_id, 0, 0);
sas_phy_disconnected(sas_phy);
phy->phy_attached = 0;
sas_ha->notify_port_event(sas_phy, PORTE_LINK_RESET_ERR);
break;
case HW_EVENT_LINK_ERR_CODE_VIOLATION:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_LINK_ERR_CODE_VIOLATION\n"));
pm8001_hw_event_ack_req(pm8001_ha, 0,
HW_EVENT_LINK_ERR_CODE_VIOLATION,
port_id, phy_id, 0, 0);
sas_phy_disconnected(sas_phy);
phy->phy_attached = 0;
sas_ha->notify_port_event(sas_phy, PORTE_LINK_RESET_ERR);
break;
case HW_EVENT_LINK_ERR_LOSS_OF_DWORD_SYNCH:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_LINK_ERR_LOSS_OF_DWORD_SYNCH\n"));
pm8001_hw_event_ack_req(pm8001_ha, 0,
HW_EVENT_LINK_ERR_LOSS_OF_DWORD_SYNCH,
port_id, phy_id, 0, 0);
sas_phy_disconnected(sas_phy);
phy->phy_attached = 0;
sas_ha->notify_port_event(sas_phy, PORTE_LINK_RESET_ERR);
break;
case HW_EVENT_MALFUNCTION:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_MALFUNCTION\n"));
break;
case HW_EVENT_BROADCAST_SES:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_BROADCAST_SES\n"));
spin_lock_irqsave(&sas_phy->sas_prim_lock, flags);
sas_phy->sas_prim = HW_EVENT_BROADCAST_SES;
spin_unlock_irqrestore(&sas_phy->sas_prim_lock, flags);
sas_ha->notify_port_event(sas_phy, PORTE_BROADCAST_RCVD);
break;
case HW_EVENT_INBOUND_CRC_ERROR:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_INBOUND_CRC_ERROR\n"));
pm8001_hw_event_ack_req(pm8001_ha, 0,
HW_EVENT_INBOUND_CRC_ERROR,
port_id, phy_id, 0, 0);
break;
case HW_EVENT_HARD_RESET_RECEIVED:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_HARD_RESET_RECEIVED\n"));
sas_ha->notify_port_event(sas_phy, PORTE_HARD_RESET);
break;
case HW_EVENT_ID_FRAME_TIMEOUT:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_ID_FRAME_TIMEOUT\n"));
sas_phy_disconnected(sas_phy);
phy->phy_attached = 0;
sas_ha->notify_port_event(sas_phy, PORTE_LINK_RESET_ERR);
break;
case HW_EVENT_LINK_ERR_PHY_RESET_FAILED:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_LINK_ERR_PHY_RESET_FAILED\n"));
pm8001_hw_event_ack_req(pm8001_ha, 0,
HW_EVENT_LINK_ERR_PHY_RESET_FAILED,
port_id, phy_id, 0, 0);
sas_phy_disconnected(sas_phy);
phy->phy_attached = 0;
sas_ha->notify_port_event(sas_phy, PORTE_LINK_RESET_ERR);
break;
case HW_EVENT_PORT_RESET_TIMER_TMO:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_PORT_RESET_TIMER_TMO\n"));
sas_phy_disconnected(sas_phy);
phy->phy_attached = 0;
sas_ha->notify_port_event(sas_phy, PORTE_LINK_RESET_ERR);
break;
case HW_EVENT_PORT_RECOVERY_TIMER_TMO:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_PORT_RECOVERY_TIMER_TMO\n"));
sas_phy_disconnected(sas_phy);
phy->phy_attached = 0;
sas_ha->notify_port_event(sas_phy, PORTE_LINK_RESET_ERR);
break;
case HW_EVENT_PORT_RECOVER:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_PORT_RECOVER\n"));
break;
case HW_EVENT_PORT_RESET_COMPLETE:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("HW_EVENT_PORT_RESET_COMPLETE\n"));
break;
case EVENT_BROADCAST_ASYNCH_EVENT:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("EVENT_BROADCAST_ASYNCH_EVENT\n"));
break;
default:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("Unknown event type = %x\n", eventType));
break;
}
return 0;
}
/**
* process_one_iomb - process one outbound Queue memory block
* @pm8001_ha: our hba card information
* @piomb: IO message buffer
*/
static void process_one_iomb(struct pm8001_hba_info *pm8001_ha, void *piomb)
{
__le32 pHeader = *(__le32 *)piomb;
u8 opc = (u8)((le32_to_cpu(pHeader)) & 0xFFF);
PM8001_MSG_DBG(pm8001_ha, pm8001_printk("process_one_iomb:"));
switch (opc) {
case OPC_OUB_ECHO:
PM8001_MSG_DBG(pm8001_ha, pm8001_printk("OPC_OUB_ECHO\n"));
break;
case OPC_OUB_HW_EVENT:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_HW_EVENT\n"));
mpi_hw_event(pm8001_ha, piomb);
break;
case OPC_OUB_SSP_COMP:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_SSP_COMP\n"));
mpi_ssp_completion(pm8001_ha, piomb);
break;
case OPC_OUB_SMP_COMP:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_SMP_COMP\n"));
mpi_smp_completion(pm8001_ha, piomb);
break;
case OPC_OUB_LOCAL_PHY_CNTRL:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_LOCAL_PHY_CNTRL\n"));
pm8001_mpi_local_phy_ctl(pm8001_ha, piomb);
break;
case OPC_OUB_DEV_REGIST:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_DEV_REGIST\n"));
pm8001_mpi_reg_resp(pm8001_ha, piomb);
break;
case OPC_OUB_DEREG_DEV:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("unregister the device\n"));
pm8001_mpi_dereg_resp(pm8001_ha, piomb);
break;
case OPC_OUB_GET_DEV_HANDLE:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_GET_DEV_HANDLE\n"));
break;
case OPC_OUB_SATA_COMP:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_SATA_COMP\n"));
mpi_sata_completion(pm8001_ha, piomb);
break;
case OPC_OUB_SATA_EVENT:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_SATA_EVENT\n"));
mpi_sata_event(pm8001_ha, piomb);
break;
case OPC_OUB_SSP_EVENT:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_SSP_EVENT\n"));
mpi_ssp_event(pm8001_ha, piomb);
break;
case OPC_OUB_DEV_HANDLE_ARRIV:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_DEV_HANDLE_ARRIV\n"));
/*This is for target*/
break;
case OPC_OUB_SSP_RECV_EVENT:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_SSP_RECV_EVENT\n"));
/*This is for target*/
break;
case OPC_OUB_DEV_INFO:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_DEV_INFO\n"));
break;
case OPC_OUB_FW_FLASH_UPDATE:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_FW_FLASH_UPDATE\n"));
pm8001_mpi_fw_flash_update_resp(pm8001_ha, piomb);
break;
case OPC_OUB_GPIO_RESPONSE:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_GPIO_RESPONSE\n"));
break;
case OPC_OUB_GPIO_EVENT:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_GPIO_EVENT\n"));
break;
case OPC_OUB_GENERAL_EVENT:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_GENERAL_EVENT\n"));
pm8001_mpi_general_event(pm8001_ha, piomb);
break;
case OPC_OUB_SSP_ABORT_RSP:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_SSP_ABORT_RSP\n"));
pm8001_mpi_task_abort_resp(pm8001_ha, piomb);
break;
case OPC_OUB_SATA_ABORT_RSP:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_SATA_ABORT_RSP\n"));
pm8001_mpi_task_abort_resp(pm8001_ha, piomb);
break;
case OPC_OUB_SAS_DIAG_MODE_START_END:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_SAS_DIAG_MODE_START_END\n"));
break;
case OPC_OUB_SAS_DIAG_EXECUTE:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_SAS_DIAG_EXECUTE\n"));
break;
case OPC_OUB_GET_TIME_STAMP:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_GET_TIME_STAMP\n"));
break;
case OPC_OUB_SAS_HW_EVENT_ACK:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_SAS_HW_EVENT_ACK\n"));
break;
case OPC_OUB_PORT_CONTROL:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_PORT_CONTROL\n"));
break;
case OPC_OUB_SMP_ABORT_RSP:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_SMP_ABORT_RSP\n"));
pm8001_mpi_task_abort_resp(pm8001_ha, piomb);
break;
case OPC_OUB_GET_NVMD_DATA:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_GET_NVMD_DATA\n"));
pm8001_mpi_get_nvmd_resp(pm8001_ha, piomb);
break;
case OPC_OUB_SET_NVMD_DATA:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_SET_NVMD_DATA\n"));
pm8001_mpi_set_nvmd_resp(pm8001_ha, piomb);
break;
case OPC_OUB_DEVICE_HANDLE_REMOVAL:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_DEVICE_HANDLE_REMOVAL\n"));
break;
case OPC_OUB_SET_DEVICE_STATE:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_SET_DEVICE_STATE\n"));
pm8001_mpi_set_dev_state_resp(pm8001_ha, piomb);
break;
case OPC_OUB_GET_DEVICE_STATE:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_GET_DEVICE_STATE\n"));
break;
case OPC_OUB_SET_DEV_INFO:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_SET_DEV_INFO\n"));
break;
case OPC_OUB_SAS_RE_INITIALIZE:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("OPC_OUB_SAS_RE_INITIALIZE\n"));
break;
default:
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("Unknown outbound Queue IOMB OPC = %x\n",
opc));
break;
}
}
static int process_oq(struct pm8001_hba_info *pm8001_ha, u8 vec)
{
struct outbound_queue_table *circularQ;
void *pMsg1 = NULL;
u8 uninitialized_var(bc);
u32 ret = MPI_IO_STATUS_FAIL;
unsigned long flags;
spin_lock_irqsave(&pm8001_ha->lock, flags);
circularQ = &pm8001_ha->outbnd_q_tbl[vec];
do {
ret = pm8001_mpi_msg_consume(pm8001_ha, circularQ, &pMsg1, &bc);
if (MPI_IO_STATUS_SUCCESS == ret) {
/* process the outbound message */
process_one_iomb(pm8001_ha, (void *)(pMsg1 - 4));
/* free the message from the outbound circular buffer */
pm8001_mpi_msg_free_set(pm8001_ha, pMsg1,
circularQ, bc);
}
if (MPI_IO_STATUS_BUSY == ret) {
/* Update the producer index from SPC */
circularQ->producer_index =
cpu_to_le32(pm8001_read_32(circularQ->pi_virt));
if (le32_to_cpu(circularQ->producer_index) ==
circularQ->consumer_idx)
/* OQ is empty */
break;
}
} while (1);
spin_unlock_irqrestore(&pm8001_ha->lock, flags);
return ret;
}
/* PCI_DMA_... to our direction translation. */
static const u8 data_dir_flags[] = {
[PCI_DMA_BIDIRECTIONAL] = DATA_DIR_BYRECIPIENT,/* UNSPECIFIED */
[PCI_DMA_TODEVICE] = DATA_DIR_OUT,/* OUTBOUND */
[PCI_DMA_FROMDEVICE] = DATA_DIR_IN,/* INBOUND */
[PCI_DMA_NONE] = DATA_DIR_NONE,/* NO TRANSFER */
};
void
pm8001_chip_make_sg(struct scatterlist *scatter, int nr, void *prd)
{
int i;
struct scatterlist *sg;
struct pm8001_prd *buf_prd = prd;
for_each_sg(scatter, sg, nr, i) {
buf_prd->addr = cpu_to_le64(sg_dma_address(sg));
buf_prd->im_len.len = cpu_to_le32(sg_dma_len(sg));
buf_prd->im_len.e = 0;
buf_prd++;
}
}
static void build_smp_cmd(u32 deviceID, __le32 hTag, struct smp_req *psmp_cmd)
{
psmp_cmd->tag = hTag;
psmp_cmd->device_id = cpu_to_le32(deviceID);
psmp_cmd->len_ip_ir = cpu_to_le32(1|(1 << 1));
}
/**
* pm8001_chip_smp_req - send a SMP task to FW
* @pm8001_ha: our hba card information.
* @ccb: the ccb information this request used.
*/
static int pm8001_chip_smp_req(struct pm8001_hba_info *pm8001_ha,
struct pm8001_ccb_info *ccb)
{
int elem, rc;
struct sas_task *task = ccb->task;
struct domain_device *dev = task->dev;
struct pm8001_device *pm8001_dev = dev->lldd_dev;
struct scatterlist *sg_req, *sg_resp;
u32 req_len, resp_len;
struct smp_req smp_cmd;
u32 opc;
struct inbound_queue_table *circularQ;
memset(&smp_cmd, 0, sizeof(smp_cmd));
/*
* DMA-map SMP request, response buffers
*/
sg_req = &task->smp_task.smp_req;
elem = dma_map_sg(pm8001_ha->dev, sg_req, 1, PCI_DMA_TODEVICE);
if (!elem)
return -ENOMEM;
req_len = sg_dma_len(sg_req);
sg_resp = &task->smp_task.smp_resp;
elem = dma_map_sg(pm8001_ha->dev, sg_resp, 1, PCI_DMA_FROMDEVICE);
if (!elem) {
rc = -ENOMEM;
goto err_out;
}
resp_len = sg_dma_len(sg_resp);
/* must be in dwords */
if ((req_len & 0x3) || (resp_len & 0x3)) {
rc = -EINVAL;
goto err_out_2;
}
opc = OPC_INB_SMP_REQUEST;
circularQ = &pm8001_ha->inbnd_q_tbl[0];
smp_cmd.tag = cpu_to_le32(ccb->ccb_tag);
smp_cmd.long_smp_req.long_req_addr =
cpu_to_le64((u64)sg_dma_address(&task->smp_task.smp_req));
smp_cmd.long_smp_req.long_req_size =
cpu_to_le32((u32)sg_dma_len(&task->smp_task.smp_req)-4);
smp_cmd.long_smp_req.long_resp_addr =
cpu_to_le64((u64)sg_dma_address(&task->smp_task.smp_resp));
smp_cmd.long_smp_req.long_resp_size =
cpu_to_le32((u32)sg_dma_len(&task->smp_task.smp_resp)-4);
build_smp_cmd(pm8001_dev->device_id, smp_cmd.tag, &smp_cmd);
rc = pm8001_mpi_build_cmd(pm8001_ha, circularQ, opc,
(u32 *)&smp_cmd, 0);
if (rc)
goto err_out_2;
return 0;
err_out_2:
dma_unmap_sg(pm8001_ha->dev, &ccb->task->smp_task.smp_resp, 1,
PCI_DMA_FROMDEVICE);
err_out:
dma_unmap_sg(pm8001_ha->dev, &ccb->task->smp_task.smp_req, 1,
PCI_DMA_TODEVICE);
return rc;
}
/**
* pm8001_chip_ssp_io_req - send a SSP task to FW
* @pm8001_ha: our hba card information.
* @ccb: the ccb information this request used.
*/
static int pm8001_chip_ssp_io_req(struct pm8001_hba_info *pm8001_ha,
struct pm8001_ccb_info *ccb)
{
struct sas_task *task = ccb->task;
struct domain_device *dev = task->dev;
struct pm8001_device *pm8001_dev = dev->lldd_dev;
struct ssp_ini_io_start_req ssp_cmd;
u32 tag = ccb->ccb_tag;
int ret;
u64 phys_addr;
struct inbound_queue_table *circularQ;
u32 opc = OPC_INB_SSPINIIOSTART;
memset(&ssp_cmd, 0, sizeof(ssp_cmd));
memcpy(ssp_cmd.ssp_iu.lun, task->ssp_task.LUN, 8);
ssp_cmd.dir_m_tlr =
cpu_to_le32(data_dir_flags[task->data_dir] << 8 | 0x0);/*0 for
SAS 1.1 compatible TLR*/
ssp_cmd.data_len = cpu_to_le32(task->total_xfer_len);
ssp_cmd.device_id = cpu_to_le32(pm8001_dev->device_id);
ssp_cmd.tag = cpu_to_le32(tag);
if (task->ssp_task.enable_first_burst)
ssp_cmd.ssp_iu.efb_prio_attr |= 0x80;
ssp_cmd.ssp_iu.efb_prio_attr |= (task->ssp_task.task_prio << 3);
ssp_cmd.ssp_iu.efb_prio_attr |= (task->ssp_task.task_attr & 7);
memcpy(ssp_cmd.ssp_iu.cdb, task->ssp_task.cmd->cmnd,
task->ssp_task.cmd->cmd_len);
circularQ = &pm8001_ha->inbnd_q_tbl[0];
/* fill in PRD (scatter/gather) table, if any */
if (task->num_scatter > 1) {
pm8001_chip_make_sg(task->scatter, ccb->n_elem, ccb->buf_prd);
phys_addr = ccb->ccb_dma_handle +
offsetof(struct pm8001_ccb_info, buf_prd[0]);
ssp_cmd.addr_low = cpu_to_le32(lower_32_bits(phys_addr));
ssp_cmd.addr_high = cpu_to_le32(upper_32_bits(phys_addr));
ssp_cmd.esgl = cpu_to_le32(1<<31);
} else if (task->num_scatter == 1) {
u64 dma_addr = sg_dma_address(task->scatter);
ssp_cmd.addr_low = cpu_to_le32(lower_32_bits(dma_addr));
ssp_cmd.addr_high = cpu_to_le32(upper_32_bits(dma_addr));
ssp_cmd.len = cpu_to_le32(task->total_xfer_len);
ssp_cmd.esgl = 0;
} else if (task->num_scatter == 0) {
ssp_cmd.addr_low = 0;
ssp_cmd.addr_high = 0;
ssp_cmd.len = cpu_to_le32(task->total_xfer_len);
ssp_cmd.esgl = 0;
}
ret = pm8001_mpi_build_cmd(pm8001_ha, circularQ, opc, &ssp_cmd, 0);
return ret;
}
static int pm8001_chip_sata_req(struct pm8001_hba_info *pm8001_ha,
struct pm8001_ccb_info *ccb)
{
struct sas_task *task = ccb->task;
struct domain_device *dev = task->dev;
struct pm8001_device *pm8001_ha_dev = dev->lldd_dev;
u32 tag = ccb->ccb_tag;
int ret;
struct sata_start_req sata_cmd;
u32 hdr_tag, ncg_tag = 0;
u64 phys_addr;
u32 ATAP = 0x0;
u32 dir;
struct inbound_queue_table *circularQ;
unsigned long flags;
u32 opc = OPC_INB_SATA_HOST_OPSTART;
memset(&sata_cmd, 0, sizeof(sata_cmd));
circularQ = &pm8001_ha->inbnd_q_tbl[0];
if (task->data_dir == PCI_DMA_NONE) {
ATAP = 0x04; /* no data*/
PM8001_IO_DBG(pm8001_ha, pm8001_printk("no data\n"));
} else if (likely(!task->ata_task.device_control_reg_update)) {
if (task->ata_task.dma_xfer) {
ATAP = 0x06; /* DMA */
PM8001_IO_DBG(pm8001_ha, pm8001_printk("DMA\n"));
} else {
ATAP = 0x05; /* PIO*/
PM8001_IO_DBG(pm8001_ha, pm8001_printk("PIO\n"));
}
if (task->ata_task.use_ncq &&
dev->sata_dev.class != ATA_DEV_ATAPI) {
ATAP = 0x07; /* FPDMA */
PM8001_IO_DBG(pm8001_ha, pm8001_printk("FPDMA\n"));
}
}
if (task->ata_task.use_ncq && pm8001_get_ncq_tag(task, &hdr_tag)) {
task->ata_task.fis.sector_count |= (u8) (hdr_tag << 3);
ncg_tag = hdr_tag;
}
dir = data_dir_flags[task->data_dir] << 8;
sata_cmd.tag = cpu_to_le32(tag);
sata_cmd.device_id = cpu_to_le32(pm8001_ha_dev->device_id);
sata_cmd.data_len = cpu_to_le32(task->total_xfer_len);
sata_cmd.ncqtag_atap_dir_m =
cpu_to_le32(((ncg_tag & 0xff)<<16)|((ATAP & 0x3f) << 10) | dir);
sata_cmd.sata_fis = task->ata_task.fis;
if (likely(!task->ata_task.device_control_reg_update))
sata_cmd.sata_fis.flags |= 0x80;/* C=1: update ATA cmd reg */
sata_cmd.sata_fis.flags &= 0xF0;/* PM_PORT field shall be 0 */
/* fill in PRD (scatter/gather) table, if any */
if (task->num_scatter > 1) {
pm8001_chip_make_sg(task->scatter, ccb->n_elem, ccb->buf_prd);
phys_addr = ccb->ccb_dma_handle +
offsetof(struct pm8001_ccb_info, buf_prd[0]);
sata_cmd.addr_low = lower_32_bits(phys_addr);
sata_cmd.addr_high = upper_32_bits(phys_addr);
sata_cmd.esgl = cpu_to_le32(1 << 31);
} else if (task->num_scatter == 1) {
u64 dma_addr = sg_dma_address(task->scatter);
sata_cmd.addr_low = lower_32_bits(dma_addr);
sata_cmd.addr_high = upper_32_bits(dma_addr);
sata_cmd.len = cpu_to_le32(task->total_xfer_len);
sata_cmd.esgl = 0;
} else if (task->num_scatter == 0) {
sata_cmd.addr_low = 0;
sata_cmd.addr_high = 0;
sata_cmd.len = cpu_to_le32(task->total_xfer_len);
sata_cmd.esgl = 0;
}
/* Check for read log for failed drive and return */
if (sata_cmd.sata_fis.command == 0x2f) {
if (((pm8001_ha_dev->id & NCQ_READ_LOG_FLAG) ||
(pm8001_ha_dev->id & NCQ_ABORT_ALL_FLAG) ||
(pm8001_ha_dev->id & NCQ_2ND_RLE_FLAG))) {
struct task_status_struct *ts;
pm8001_ha_dev->id &= 0xDFFFFFFF;
ts = &task->task_status;
spin_lock_irqsave(&task->task_state_lock, flags);
ts->resp = SAS_TASK_COMPLETE;
ts->stat = SAM_STAT_GOOD;
task->task_state_flags &= ~SAS_TASK_STATE_PENDING;
task->task_state_flags &= ~SAS_TASK_AT_INITIATOR;
task->task_state_flags |= SAS_TASK_STATE_DONE;
if (unlikely((task->task_state_flags &
SAS_TASK_STATE_ABORTED))) {
spin_unlock_irqrestore(&task->task_state_lock,
flags);
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("task 0x%p resp 0x%x "
" stat 0x%x but aborted by upper layer "
"\n", task, ts->resp, ts->stat));
pm8001_ccb_task_free(pm8001_ha, task, ccb, tag);
} else {
spin_unlock_irqrestore(&task->task_state_lock,
flags);
pm8001_ccb_task_free_done(pm8001_ha, task,
ccb, tag);
return 0;
}
}
}
ret = pm8001_mpi_build_cmd(pm8001_ha, circularQ, opc, &sata_cmd, 0);
return ret;
}
/**
* pm8001_chip_phy_start_req - start phy via PHY_START COMMAND
* @pm8001_ha: our hba card information.
* @num: the inbound queue number
* @phy_id: the phy id which we wanted to start up.
*/
static int
pm8001_chip_phy_start_req(struct pm8001_hba_info *pm8001_ha, u8 phy_id)
{
struct phy_start_req payload;
struct inbound_queue_table *circularQ;
int ret;
u32 tag = 0x01;
u32 opcode = OPC_INB_PHYSTART;
circularQ = &pm8001_ha->inbnd_q_tbl[0];
memset(&payload, 0, sizeof(payload));
payload.tag = cpu_to_le32(tag);
/*
** [0:7] PHY Identifier
** [8:11] link rate 1.5G, 3G, 6G
** [12:13] link mode 01b SAS mode; 10b SATA mode; 11b both
** [14] 0b disable spin up hold; 1b enable spin up hold
*/
payload.ase_sh_lm_slr_phyid = cpu_to_le32(SPINHOLD_DISABLE |
LINKMODE_AUTO | LINKRATE_15 |
LINKRATE_30 | LINKRATE_60 | phy_id);
payload.sas_identify.dev_type = SAS_END_DEVICE;
payload.sas_identify.initiator_bits = SAS_PROTOCOL_ALL;
memcpy(payload.sas_identify.sas_addr,
pm8001_ha->sas_addr, SAS_ADDR_SIZE);
payload.sas_identify.phy_id = phy_id;
ret = pm8001_mpi_build_cmd(pm8001_ha, circularQ, opcode, &payload, 0);
return ret;
}
/**
* pm8001_chip_phy_stop_req - start phy via PHY_STOP COMMAND
* @pm8001_ha: our hba card information.
* @num: the inbound queue number
* @phy_id: the phy id which we wanted to start up.
*/
int pm8001_chip_phy_stop_req(struct pm8001_hba_info *pm8001_ha,
u8 phy_id)
{
struct phy_stop_req payload;
struct inbound_queue_table *circularQ;
int ret;
u32 tag = 0x01;
u32 opcode = OPC_INB_PHYSTOP;
circularQ = &pm8001_ha->inbnd_q_tbl[0];
memset(&payload, 0, sizeof(payload));
payload.tag = cpu_to_le32(tag);
payload.phy_id = cpu_to_le32(phy_id);
ret = pm8001_mpi_build_cmd(pm8001_ha, circularQ, opcode, &payload, 0);
return ret;
}
/**
* see comments on pm8001_mpi_reg_resp.
*/
static int pm8001_chip_reg_dev_req(struct pm8001_hba_info *pm8001_ha,
struct pm8001_device *pm8001_dev, u32 flag)
{
struct reg_dev_req payload;
u32 opc;
u32 stp_sspsmp_sata = 0x4;
struct inbound_queue_table *circularQ;
u32 linkrate, phy_id;
int rc, tag = 0xdeadbeef;
struct pm8001_ccb_info *ccb;
u8 retryFlag = 0x1;
u16 firstBurstSize = 0;
u16 ITNT = 2000;
struct domain_device *dev = pm8001_dev->sas_device;
struct domain_device *parent_dev = dev->parent;
circularQ = &pm8001_ha->inbnd_q_tbl[0];
memset(&payload, 0, sizeof(payload));
rc = pm8001_tag_alloc(pm8001_ha, &tag);
if (rc)
return rc;
ccb = &pm8001_ha->ccb_info[tag];
ccb->device = pm8001_dev;
ccb->ccb_tag = tag;
payload.tag = cpu_to_le32(tag);
if (flag == 1)
stp_sspsmp_sata = 0x02; /*direct attached sata */
else {
if (pm8001_dev->dev_type == SAS_SATA_DEV)
stp_sspsmp_sata = 0x00; /* stp*/
else if (pm8001_dev->dev_type == SAS_END_DEVICE ||
pm8001_dev->dev_type == SAS_EDGE_EXPANDER_DEVICE ||
pm8001_dev->dev_type == SAS_FANOUT_EXPANDER_DEVICE)
stp_sspsmp_sata = 0x01; /*ssp or smp*/
}
if (parent_dev && DEV_IS_EXPANDER(parent_dev->dev_type))
phy_id = parent_dev->ex_dev.ex_phy->phy_id;
else
phy_id = pm8001_dev->attached_phy;
opc = OPC_INB_REG_DEV;
linkrate = (pm8001_dev->sas_device->linkrate < dev->port->linkrate) ?
pm8001_dev->sas_device->linkrate : dev->port->linkrate;
payload.phyid_portid =
cpu_to_le32(((pm8001_dev->sas_device->port->id) & 0x0F) |
((phy_id & 0x0F) << 4));
payload.dtype_dlr_retry = cpu_to_le32((retryFlag & 0x01) |
((linkrate & 0x0F) * 0x1000000) |
((stp_sspsmp_sata & 0x03) * 0x10000000));
payload.firstburstsize_ITNexustimeout =
cpu_to_le32(ITNT | (firstBurstSize * 0x10000));
memcpy(payload.sas_addr, pm8001_dev->sas_device->sas_addr,
SAS_ADDR_SIZE);
rc = pm8001_mpi_build_cmd(pm8001_ha, circularQ, opc, &payload, 0);
return rc;
}
/**
* see comments on pm8001_mpi_reg_resp.
*/
int pm8001_chip_dereg_dev_req(struct pm8001_hba_info *pm8001_ha,
u32 device_id)
{
struct dereg_dev_req payload;
u32 opc = OPC_INB_DEREG_DEV_HANDLE;
int ret;
struct inbound_queue_table *circularQ;
circularQ = &pm8001_ha->inbnd_q_tbl[0];
memset(&payload, 0, sizeof(payload));
payload.tag = cpu_to_le32(1);
payload.device_id = cpu_to_le32(device_id);
PM8001_MSG_DBG(pm8001_ha,
pm8001_printk("unregister device device_id = %d\n", device_id));
ret = pm8001_mpi_build_cmd(pm8001_ha, circularQ, opc, &payload, 0);
return ret;
}
/**
* pm8001_chip_phy_ctl_req - support the local phy operation
* @pm8001_ha: our hba card information.
* @num: the inbound queue number
* @phy_id: the phy id which we wanted to operate
* @phy_op:
*/
static int pm8001_chip_phy_ctl_req(struct pm8001_hba_info *pm8001_ha,
u32 phyId, u32 phy_op)
{
struct local_phy_ctl_req payload;
struct inbound_queue_table *circularQ;
int ret;
u32 opc = OPC_INB_LOCAL_PHY_CONTROL;
memset(&payload, 0, sizeof(payload));
circularQ = &pm8001_ha->inbnd_q_tbl[0];
payload.tag = cpu_to_le32(1);
payload.phyop_phyid =
cpu_to_le32(((phy_op & 0xff) << 8) | (phyId & 0x0F));
ret = pm8001_mpi_build_cmd(pm8001_ha, circularQ, opc, &payload, 0);
return ret;
}
static u32 pm8001_chip_is_our_interupt(struct pm8001_hba_info *pm8001_ha)
{
u32 value;
#ifdef PM8001_USE_MSIX
return 1;
#endif
value = pm8001_cr32(pm8001_ha, 0, MSGU_ODR);
if (value)
return 1;
return 0;
}
/**
* pm8001_chip_isr - PM8001 isr handler.
* @pm8001_ha: our hba card information.
* @irq: irq number.
* @stat: stat.
*/
static irqreturn_t
pm8001_chip_isr(struct pm8001_hba_info *pm8001_ha, u8 vec)
{
pm8001_chip_interrupt_disable(pm8001_ha, vec);
process_oq(pm8001_ha, vec);
pm8001_chip_interrupt_enable(pm8001_ha, vec);
return IRQ_HANDLED;
}
static int send_task_abort(struct pm8001_hba_info *pm8001_ha, u32 opc,
u32 dev_id, u8 flag, u32 task_tag, u32 cmd_tag)
{
struct task_abort_req task_abort;
struct inbound_queue_table *circularQ;
int ret;
circularQ = &pm8001_ha->inbnd_q_tbl[0];
memset(&task_abort, 0, sizeof(task_abort));
if (ABORT_SINGLE == (flag & ABORT_MASK)) {
task_abort.abort_all = 0;
task_abort.device_id = cpu_to_le32(dev_id);
task_abort.tag_to_abort = cpu_to_le32(task_tag);
task_abort.tag = cpu_to_le32(cmd_tag);
} else if (ABORT_ALL == (flag & ABORT_MASK)) {
task_abort.abort_all = cpu_to_le32(1);
task_abort.device_id = cpu_to_le32(dev_id);
task_abort.tag = cpu_to_le32(cmd_tag);
}
ret = pm8001_mpi_build_cmd(pm8001_ha, circularQ, opc, &task_abort, 0);
return ret;
}
/**
* pm8001_chip_abort_task - SAS abort task when error or exception happened.
* @task: the task we wanted to aborted.
* @flag: the abort flag.
*/
int pm8001_chip_abort_task(struct pm8001_hba_info *pm8001_ha,
struct pm8001_device *pm8001_dev, u8 flag, u32 task_tag, u32 cmd_tag)
{
u32 opc, device_id;
int rc = TMF_RESP_FUNC_FAILED;
PM8001_EH_DBG(pm8001_ha,
pm8001_printk("cmd_tag = %x, abort task tag = 0x%x",
cmd_tag, task_tag));
if (pm8001_dev->dev_type == SAS_END_DEVICE)
opc = OPC_INB_SSP_ABORT;
else if (pm8001_dev->dev_type == SAS_SATA_DEV)
opc = OPC_INB_SATA_ABORT;
else
opc = OPC_INB_SMP_ABORT;/* SMP */
device_id = pm8001_dev->device_id;
rc = send_task_abort(pm8001_ha, opc, device_id, flag,
task_tag, cmd_tag);
if (rc != TMF_RESP_FUNC_COMPLETE)
PM8001_EH_DBG(pm8001_ha, pm8001_printk("rc= %d\n", rc));
return rc;
}
/**
* pm8001_chip_ssp_tm_req - built the task management command.
* @pm8001_ha: our hba card information.
* @ccb: the ccb information.
* @tmf: task management function.
*/
int pm8001_chip_ssp_tm_req(struct pm8001_hba_info *pm8001_ha,
struct pm8001_ccb_info *ccb, struct pm8001_tmf_task *tmf)
{
struct sas_task *task = ccb->task;
struct domain_device *dev = task->dev;
struct pm8001_device *pm8001_dev = dev->lldd_dev;
u32 opc = OPC_INB_SSPINITMSTART;
struct inbound_queue_table *circularQ;
struct ssp_ini_tm_start_req sspTMCmd;
int ret;
memset(&sspTMCmd, 0, sizeof(sspTMCmd));
sspTMCmd.device_id = cpu_to_le32(pm8001_dev->device_id);
sspTMCmd.relate_tag = cpu_to_le32(tmf->tag_of_task_to_be_managed);
sspTMCmd.tmf = cpu_to_le32(tmf->tmf);
memcpy(sspTMCmd.lun, task->ssp_task.LUN, 8);
sspTMCmd.tag = cpu_to_le32(ccb->ccb_tag);
if (pm8001_ha->chip_id != chip_8001)
sspTMCmd.ds_ads_m = 0x08;
circularQ = &pm8001_ha->inbnd_q_tbl[0];
ret = pm8001_mpi_build_cmd(pm8001_ha, circularQ, opc, &sspTMCmd, 0);
return ret;
}
int pm8001_chip_get_nvmd_req(struct pm8001_hba_info *pm8001_ha,
void *payload)
{
u32 opc = OPC_INB_GET_NVMD_DATA;
u32 nvmd_type;
int rc;
u32 tag;
struct pm8001_ccb_info *ccb;
struct inbound_queue_table *circularQ;
struct get_nvm_data_req nvmd_req;
struct fw_control_ex *fw_control_context;
struct pm8001_ioctl_payload *ioctl_payload = payload;
nvmd_type = ioctl_payload->minor_function;
fw_control_context = kzalloc(sizeof(struct fw_control_ex), GFP_KERNEL);
if (!fw_control_context)
return -ENOMEM;
fw_control_context->usrAddr = (u8 *)ioctl_payload->func_specific;
fw_control_context->len = ioctl_payload->length;
circularQ = &pm8001_ha->inbnd_q_tbl[0];
memset(&nvmd_req, 0, sizeof(nvmd_req));
rc = pm8001_tag_alloc(pm8001_ha, &tag);
if (rc) {
kfree(fw_control_context);
return rc;
}
ccb = &pm8001_ha->ccb_info[tag];
ccb->ccb_tag = tag;
ccb->fw_control_context = fw_control_context;
nvmd_req.tag = cpu_to_le32(tag);
switch (nvmd_type) {
case TWI_DEVICE: {
u32 twi_addr, twi_page_size;
twi_addr = 0xa8;
twi_page_size = 2;
nvmd_req.len_ir_vpdd = cpu_to_le32(IPMode | twi_addr << 16 |
twi_page_size << 8 | TWI_DEVICE);
nvmd_req.resp_len = cpu_to_le32(ioctl_payload->length);
nvmd_req.resp_addr_hi =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_hi);
nvmd_req.resp_addr_lo =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_lo);
break;
}
case C_SEEPROM: {
nvmd_req.len_ir_vpdd = cpu_to_le32(IPMode | C_SEEPROM);
nvmd_req.resp_len = cpu_to_le32(ioctl_payload->length);
nvmd_req.resp_addr_hi =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_hi);
nvmd_req.resp_addr_lo =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_lo);
break;
}
case VPD_FLASH: {
nvmd_req.len_ir_vpdd = cpu_to_le32(IPMode | VPD_FLASH);
nvmd_req.resp_len = cpu_to_le32(ioctl_payload->length);
nvmd_req.resp_addr_hi =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_hi);
nvmd_req.resp_addr_lo =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_lo);
break;
}
case EXPAN_ROM: {
nvmd_req.len_ir_vpdd = cpu_to_le32(IPMode | EXPAN_ROM);
nvmd_req.resp_len = cpu_to_le32(ioctl_payload->length);
nvmd_req.resp_addr_hi =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_hi);
nvmd_req.resp_addr_lo =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_lo);
break;
}
case IOP_RDUMP: {
nvmd_req.len_ir_vpdd = cpu_to_le32(IPMode | IOP_RDUMP);
nvmd_req.resp_len = cpu_to_le32(ioctl_payload->length);
nvmd_req.vpd_offset = cpu_to_le32(ioctl_payload->offset);
nvmd_req.resp_addr_hi =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_hi);
nvmd_req.resp_addr_lo =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_lo);
break;
}
default:
break;
}
rc = pm8001_mpi_build_cmd(pm8001_ha, circularQ, opc, &nvmd_req, 0);
if (rc) {
kfree(fw_control_context);
pm8001_tag_free(pm8001_ha, tag);
}
return rc;
}
int pm8001_chip_set_nvmd_req(struct pm8001_hba_info *pm8001_ha,
void *payload)
{
u32 opc = OPC_INB_SET_NVMD_DATA;
u32 nvmd_type;
int rc;
u32 tag;
struct pm8001_ccb_info *ccb;
struct inbound_queue_table *circularQ;
struct set_nvm_data_req nvmd_req;
struct fw_control_ex *fw_control_context;
struct pm8001_ioctl_payload *ioctl_payload = payload;
nvmd_type = ioctl_payload->minor_function;
fw_control_context = kzalloc(sizeof(struct fw_control_ex), GFP_KERNEL);
if (!fw_control_context)
return -ENOMEM;
circularQ = &pm8001_ha->inbnd_q_tbl[0];
memcpy(pm8001_ha->memoryMap.region[NVMD].virt_ptr,
&ioctl_payload->func_specific,
ioctl_payload->length);
memset(&nvmd_req, 0, sizeof(nvmd_req));
rc = pm8001_tag_alloc(pm8001_ha, &tag);
if (rc) {
kfree(fw_control_context);
return -EBUSY;
}
ccb = &pm8001_ha->ccb_info[tag];
ccb->fw_control_context = fw_control_context;
ccb->ccb_tag = tag;
nvmd_req.tag = cpu_to_le32(tag);
switch (nvmd_type) {
case TWI_DEVICE: {
u32 twi_addr, twi_page_size;
twi_addr = 0xa8;
twi_page_size = 2;
nvmd_req.reserved[0] = cpu_to_le32(0xFEDCBA98);
nvmd_req.len_ir_vpdd = cpu_to_le32(IPMode | twi_addr << 16 |
twi_page_size << 8 | TWI_DEVICE);
nvmd_req.resp_len = cpu_to_le32(ioctl_payload->length);
nvmd_req.resp_addr_hi =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_hi);
nvmd_req.resp_addr_lo =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_lo);
break;
}
case C_SEEPROM:
nvmd_req.len_ir_vpdd = cpu_to_le32(IPMode | C_SEEPROM);
nvmd_req.resp_len = cpu_to_le32(ioctl_payload->length);
nvmd_req.reserved[0] = cpu_to_le32(0xFEDCBA98);
nvmd_req.resp_addr_hi =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_hi);
nvmd_req.resp_addr_lo =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_lo);
break;
case VPD_FLASH:
nvmd_req.len_ir_vpdd = cpu_to_le32(IPMode | VPD_FLASH);
nvmd_req.resp_len = cpu_to_le32(ioctl_payload->length);
nvmd_req.reserved[0] = cpu_to_le32(0xFEDCBA98);
nvmd_req.resp_addr_hi =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_hi);
nvmd_req.resp_addr_lo =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_lo);
break;
case EXPAN_ROM:
nvmd_req.len_ir_vpdd = cpu_to_le32(IPMode | EXPAN_ROM);
nvmd_req.resp_len = cpu_to_le32(ioctl_payload->length);
nvmd_req.reserved[0] = cpu_to_le32(0xFEDCBA98);
nvmd_req.resp_addr_hi =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_hi);
nvmd_req.resp_addr_lo =
cpu_to_le32(pm8001_ha->memoryMap.region[NVMD].phys_addr_lo);
break;
default:
break;
}
rc = pm8001_mpi_build_cmd(pm8001_ha, circularQ, opc, &nvmd_req, 0);
if (rc) {
kfree(fw_control_context);
pm8001_tag_free(pm8001_ha, tag);
}
return rc;
}
/**
* pm8001_chip_fw_flash_update_build - support the firmware update operation
* @pm8001_ha: our hba card information.
* @fw_flash_updata_info: firmware flash update param
*/
int
pm8001_chip_fw_flash_update_build(struct pm8001_hba_info *pm8001_ha,
void *fw_flash_updata_info, u32 tag)
{
struct fw_flash_Update_req payload;
struct fw_flash_updata_info *info;
struct inbound_queue_table *circularQ;
int ret;
u32 opc = OPC_INB_FW_FLASH_UPDATE;
memset(&payload, 0, sizeof(struct fw_flash_Update_req));
circularQ = &pm8001_ha->inbnd_q_tbl[0];
info = fw_flash_updata_info;
payload.tag = cpu_to_le32(tag);
payload.cur_image_len = cpu_to_le32(info->cur_image_len);
payload.cur_image_offset = cpu_to_le32(info->cur_image_offset);
payload.total_image_len = cpu_to_le32(info->total_image_len);
payload.len = info->sgl.im_len.len ;
payload.sgl_addr_lo =
cpu_to_le32(lower_32_bits(le64_to_cpu(info->sgl.addr)));
payload.sgl_addr_hi =
cpu_to_le32(upper_32_bits(le64_to_cpu(info->sgl.addr)));
ret = pm8001_mpi_build_cmd(pm8001_ha, circularQ, opc, &payload, 0);
return ret;
}
int
pm8001_chip_fw_flash_update_req(struct pm8001_hba_info *pm8001_ha,
void *payload)
{
struct fw_flash_updata_info flash_update_info;
struct fw_control_info *fw_control;
struct fw_control_ex *fw_control_context;
int rc;
u32 tag;
struct pm8001_ccb_info *ccb;
void *buffer = pm8001_ha->memoryMap.region[FW_FLASH].virt_ptr;
dma_addr_t phys_addr = pm8001_ha->memoryMap.region[FW_FLASH].phys_addr;
struct pm8001_ioctl_payload *ioctl_payload = payload;
fw_control_context = kzalloc(sizeof(struct fw_control_ex), GFP_KERNEL);
if (!fw_control_context)
return -ENOMEM;
fw_control = (struct fw_control_info *)&ioctl_payload->func_specific;
memcpy(buffer, fw_control->buffer, fw_control->len);
flash_update_info.sgl.addr = cpu_to_le64(phys_addr);
flash_update_info.sgl.im_len.len = cpu_to_le32(fw_control->len);
flash_update_info.sgl.im_len.e = 0;
flash_update_info.cur_image_offset = fw_control->offset;
flash_update_info.cur_image_len = fw_control->len;
flash_update_info.total_image_len = fw_control->size;
fw_control_context->fw_control = fw_control;
fw_control_context->virtAddr = buffer;
fw_control_context->phys_addr = phys_addr;
fw_control_context->len = fw_control->len;
rc = pm8001_tag_alloc(pm8001_ha, &tag);
if (rc) {
kfree(fw_control_context);
return -EBUSY;
}
ccb = &pm8001_ha->ccb_info[tag];
ccb->fw_control_context = fw_control_context;
ccb->ccb_tag = tag;
rc = pm8001_chip_fw_flash_update_build(pm8001_ha, &flash_update_info,
tag);
return rc;
}
ssize_t
pm8001_get_gsm_dump(struct device *cdev, u32 length, char *buf)
{
u32 value, rem, offset = 0, bar = 0;
u32 index, work_offset, dw_length;
u32 shift_value, gsm_base, gsm_dump_offset;
char *direct_data;
struct Scsi_Host *shost = class_to_shost(cdev);
struct sas_ha_struct *sha = SHOST_TO_SAS_HA(shost);
struct pm8001_hba_info *pm8001_ha = sha->lldd_ha;
direct_data = buf;
gsm_dump_offset = pm8001_ha->fatal_forensic_shift_offset;
/* check max is 1 Mbytes */
if ((length > 0x100000) || (gsm_dump_offset & 3) ||
((gsm_dump_offset + length) > 0x1000000))
return -EINVAL;
if (pm8001_ha->chip_id == chip_8001)
bar = 2;
else
bar = 1;
work_offset = gsm_dump_offset & 0xFFFF0000;
offset = gsm_dump_offset & 0x0000FFFF;
gsm_dump_offset = work_offset;
/* adjust length to dword boundary */
rem = length & 3;
dw_length = length >> 2;
for (index = 0; index < dw_length; index++) {
if ((work_offset + offset) & 0xFFFF0000) {
if (pm8001_ha->chip_id == chip_8001)
shift_value = ((gsm_dump_offset + offset) &
SHIFT_REG_64K_MASK);
else
shift_value = (((gsm_dump_offset + offset) &
SHIFT_REG_64K_MASK) >>
SHIFT_REG_BIT_SHIFT);
if (pm8001_ha->chip_id == chip_8001) {
gsm_base = GSM_BASE;
if (-1 == pm8001_bar4_shift(pm8001_ha,
(gsm_base + shift_value)))
return -EIO;
} else {
gsm_base = 0;
if (-1 == pm80xx_bar4_shift(pm8001_ha,
(gsm_base + shift_value)))
return -EIO;
}
gsm_dump_offset = (gsm_dump_offset + offset) &
0xFFFF0000;
work_offset = 0;
offset = offset & 0x0000FFFF;
}
value = pm8001_cr32(pm8001_ha, bar, (work_offset + offset) &
0x0000FFFF);
direct_data += sprintf(direct_data, "%08x ", value);
offset += 4;
}
if (rem != 0) {
value = pm8001_cr32(pm8001_ha, bar, (work_offset + offset) &
0x0000FFFF);
/* xfr for non_dw */
direct_data += sprintf(direct_data, "%08x ", value);
}
/* Shift back to BAR4 original address */
if (-1 == pm8001_bar4_shift(pm8001_ha, 0))
return -EIO;
pm8001_ha->fatal_forensic_shift_offset += 1024;
if (pm8001_ha->fatal_forensic_shift_offset >= 0x100000)
pm8001_ha->fatal_forensic_shift_offset = 0;
return direct_data - buf;
}
int
pm8001_chip_set_dev_state_req(struct pm8001_hba_info *pm8001_ha,
struct pm8001_device *pm8001_dev, u32 state)
{
struct set_dev_state_req payload;
struct inbound_queue_table *circularQ;
struct pm8001_ccb_info *ccb;
int rc;
u32 tag;
u32 opc = OPC_INB_SET_DEVICE_STATE;
memset(&payload, 0, sizeof(payload));
rc = pm8001_tag_alloc(pm8001_ha, &tag);
if (rc)
return -1;
ccb = &pm8001_ha->ccb_info[tag];
ccb->ccb_tag = tag;
ccb->device = pm8001_dev;
circularQ = &pm8001_ha->inbnd_q_tbl[0];
payload.tag = cpu_to_le32(tag);
payload.device_id = cpu_to_le32(pm8001_dev->device_id);
payload.nds = cpu_to_le32(state);
rc = pm8001_mpi_build_cmd(pm8001_ha, circularQ, opc, &payload, 0);
return rc;
}
static int
pm8001_chip_sas_re_initialization(struct pm8001_hba_info *pm8001_ha)
{
struct sas_re_initialization_req payload;
struct inbound_queue_table *circularQ;
struct pm8001_ccb_info *ccb;
int rc;
u32 tag;
u32 opc = OPC_INB_SAS_RE_INITIALIZE;
memset(&payload, 0, sizeof(payload));
rc = pm8001_tag_alloc(pm8001_ha, &tag);
if (rc)
return -ENOMEM;
ccb = &pm8001_ha->ccb_info[tag];
ccb->ccb_tag = tag;
circularQ = &pm8001_ha->inbnd_q_tbl[0];
payload.tag = cpu_to_le32(tag);
payload.SSAHOLT = cpu_to_le32(0xd << 25);
payload.sata_hol_tmo = cpu_to_le32(80);
payload.open_reject_cmdretries_data_retries = cpu_to_le32(0xff00ff);
rc = pm8001_mpi_build_cmd(pm8001_ha, circularQ, opc, &payload, 0);
if (rc)
pm8001_tag_free(pm8001_ha, tag);
return rc;
}
const struct pm8001_dispatch pm8001_8001_dispatch = {
.name = "pmc8001",
.chip_init = pm8001_chip_init,
.chip_soft_rst = pm8001_chip_soft_rst,
.chip_rst = pm8001_hw_chip_rst,
.chip_iounmap = pm8001_chip_iounmap,
.isr = pm8001_chip_isr,
.is_our_interupt = pm8001_chip_is_our_interupt,
.isr_process_oq = process_oq,
.interrupt_enable = pm8001_chip_interrupt_enable,
.interrupt_disable = pm8001_chip_interrupt_disable,
.make_prd = pm8001_chip_make_sg,
.smp_req = pm8001_chip_smp_req,
.ssp_io_req = pm8001_chip_ssp_io_req,
.sata_req = pm8001_chip_sata_req,
.phy_start_req = pm8001_chip_phy_start_req,
.phy_stop_req = pm8001_chip_phy_stop_req,
.reg_dev_req = pm8001_chip_reg_dev_req,
.dereg_dev_req = pm8001_chip_dereg_dev_req,
.phy_ctl_req = pm8001_chip_phy_ctl_req,
.task_abort = pm8001_chip_abort_task,
.ssp_tm_req = pm8001_chip_ssp_tm_req,
.get_nvmd_req = pm8001_chip_get_nvmd_req,
.set_nvmd_req = pm8001_chip_set_nvmd_req,
.fw_flash_update_req = pm8001_chip_fw_flash_update_req,
.set_dev_state_req = pm8001_chip_set_dev_state_req,
.sas_re_init_req = pm8001_chip_sas_re_initialization,
};
| gpl-2.0 |
jrfastab/rocker-net-next | net/rxrpc/ar-key.c | 1126 | 29786 | /* RxRPC key management
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@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.
*
* RxRPC keys should have a description of describing their purpose:
* "afs@CAMBRIDGE.REDHAT.COM>
*/
#include <linux/module.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <linux/key-type.h>
#include <linux/crypto.h>
#include <linux/ctype.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <net/af_rxrpc.h>
#include <keys/rxrpc-type.h>
#include <keys/user-type.h>
#include "ar-internal.h"
static int rxrpc_vet_description_s(const char *);
static int rxrpc_preparse(struct key_preparsed_payload *);
static int rxrpc_preparse_s(struct key_preparsed_payload *);
static void rxrpc_free_preparse(struct key_preparsed_payload *);
static void rxrpc_free_preparse_s(struct key_preparsed_payload *);
static void rxrpc_destroy(struct key *);
static void rxrpc_destroy_s(struct key *);
static void rxrpc_describe(const struct key *, struct seq_file *);
static long rxrpc_read(const struct key *, char __user *, size_t);
/*
* rxrpc defined keys take an arbitrary string as the description and an
* arbitrary blob of data as the payload
*/
struct key_type key_type_rxrpc = {
.name = "rxrpc",
.preparse = rxrpc_preparse,
.free_preparse = rxrpc_free_preparse,
.instantiate = generic_key_instantiate,
.destroy = rxrpc_destroy,
.describe = rxrpc_describe,
.read = rxrpc_read,
};
EXPORT_SYMBOL(key_type_rxrpc);
/*
* rxrpc server defined keys take "<serviceId>:<securityIndex>" as the
* description and an 8-byte decryption key as the payload
*/
struct key_type key_type_rxrpc_s = {
.name = "rxrpc_s",
.vet_description = rxrpc_vet_description_s,
.preparse = rxrpc_preparse_s,
.free_preparse = rxrpc_free_preparse_s,
.instantiate = generic_key_instantiate,
.destroy = rxrpc_destroy_s,
.describe = rxrpc_describe,
};
/*
* Vet the description for an RxRPC server key
*/
static int rxrpc_vet_description_s(const char *desc)
{
unsigned long num;
char *p;
num = simple_strtoul(desc, &p, 10);
if (*p != ':' || num > 65535)
return -EINVAL;
num = simple_strtoul(p + 1, &p, 10);
if (*p || num < 1 || num > 255)
return -EINVAL;
return 0;
}
/*
* parse an RxKAD type XDR format token
* - the caller guarantees we have at least 4 words
*/
static int rxrpc_preparse_xdr_rxkad(struct key_preparsed_payload *prep,
size_t datalen,
const __be32 *xdr, unsigned int toklen)
{
struct rxrpc_key_token *token, **pptoken;
size_t plen;
u32 tktlen;
_enter(",{%x,%x,%x,%x},%u",
ntohl(xdr[0]), ntohl(xdr[1]), ntohl(xdr[2]), ntohl(xdr[3]),
toklen);
if (toklen <= 8 * 4)
return -EKEYREJECTED;
tktlen = ntohl(xdr[7]);
_debug("tktlen: %x", tktlen);
if (tktlen > AFSTOKEN_RK_TIX_MAX)
return -EKEYREJECTED;
if (toklen < 8 * 4 + tktlen)
return -EKEYREJECTED;
plen = sizeof(*token) + sizeof(*token->kad) + tktlen;
prep->quotalen = datalen + plen;
plen -= sizeof(*token);
token = kzalloc(sizeof(*token), GFP_KERNEL);
if (!token)
return -ENOMEM;
token->kad = kzalloc(plen, GFP_KERNEL);
if (!token->kad) {
kfree(token);
return -ENOMEM;
}
token->security_index = RXRPC_SECURITY_RXKAD;
token->kad->ticket_len = tktlen;
token->kad->vice_id = ntohl(xdr[0]);
token->kad->kvno = ntohl(xdr[1]);
token->kad->start = ntohl(xdr[4]);
token->kad->expiry = ntohl(xdr[5]);
token->kad->primary_flag = ntohl(xdr[6]);
memcpy(&token->kad->session_key, &xdr[2], 8);
memcpy(&token->kad->ticket, &xdr[8], tktlen);
_debug("SCIX: %u", token->security_index);
_debug("TLEN: %u", token->kad->ticket_len);
_debug("EXPY: %x", token->kad->expiry);
_debug("KVNO: %u", token->kad->kvno);
_debug("PRIM: %u", token->kad->primary_flag);
_debug("SKEY: %02x%02x%02x%02x%02x%02x%02x%02x",
token->kad->session_key[0], token->kad->session_key[1],
token->kad->session_key[2], token->kad->session_key[3],
token->kad->session_key[4], token->kad->session_key[5],
token->kad->session_key[6], token->kad->session_key[7]);
if (token->kad->ticket_len >= 8)
_debug("TCKT: %02x%02x%02x%02x%02x%02x%02x%02x",
token->kad->ticket[0], token->kad->ticket[1],
token->kad->ticket[2], token->kad->ticket[3],
token->kad->ticket[4], token->kad->ticket[5],
token->kad->ticket[6], token->kad->ticket[7]);
/* count the number of tokens attached */
prep->type_data[0] = (void *)((unsigned long)prep->type_data[0] + 1);
/* attach the data */
for (pptoken = (struct rxrpc_key_token **)&prep->payload[0];
*pptoken;
pptoken = &(*pptoken)->next)
continue;
*pptoken = token;
if (token->kad->expiry < prep->expiry)
prep->expiry = token->kad->expiry;
_leave(" = 0");
return 0;
}
static void rxrpc_free_krb5_principal(struct krb5_principal *princ)
{
int loop;
if (princ->name_parts) {
for (loop = princ->n_name_parts - 1; loop >= 0; loop--)
kfree(princ->name_parts[loop]);
kfree(princ->name_parts);
}
kfree(princ->realm);
}
static void rxrpc_free_krb5_tagged(struct krb5_tagged_data *td)
{
kfree(td->data);
}
/*
* free up an RxK5 token
*/
static void rxrpc_rxk5_free(struct rxk5_key *rxk5)
{
int loop;
rxrpc_free_krb5_principal(&rxk5->client);
rxrpc_free_krb5_principal(&rxk5->server);
rxrpc_free_krb5_tagged(&rxk5->session);
if (rxk5->addresses) {
for (loop = rxk5->n_addresses - 1; loop >= 0; loop--)
rxrpc_free_krb5_tagged(&rxk5->addresses[loop]);
kfree(rxk5->addresses);
}
if (rxk5->authdata) {
for (loop = rxk5->n_authdata - 1; loop >= 0; loop--)
rxrpc_free_krb5_tagged(&rxk5->authdata[loop]);
kfree(rxk5->authdata);
}
kfree(rxk5->ticket);
kfree(rxk5->ticket2);
kfree(rxk5);
}
/*
* extract a krb5 principal
*/
static int rxrpc_krb5_decode_principal(struct krb5_principal *princ,
const __be32 **_xdr,
unsigned int *_toklen)
{
const __be32 *xdr = *_xdr;
unsigned int toklen = *_toklen, n_parts, loop, tmp;
/* there must be at least one name, and at least #names+1 length
* words */
if (toklen <= 12)
return -EINVAL;
_enter(",{%x,%x,%x},%u",
ntohl(xdr[0]), ntohl(xdr[1]), ntohl(xdr[2]), toklen);
n_parts = ntohl(*xdr++);
toklen -= 4;
if (n_parts <= 0 || n_parts > AFSTOKEN_K5_COMPONENTS_MAX)
return -EINVAL;
princ->n_name_parts = n_parts;
if (toklen <= (n_parts + 1) * 4)
return -EINVAL;
princ->name_parts = kcalloc(n_parts, sizeof(char *), GFP_KERNEL);
if (!princ->name_parts)
return -ENOMEM;
for (loop = 0; loop < n_parts; loop++) {
if (toklen < 4)
return -EINVAL;
tmp = ntohl(*xdr++);
toklen -= 4;
if (tmp <= 0 || tmp > AFSTOKEN_STRING_MAX)
return -EINVAL;
if (tmp > toklen)
return -EINVAL;
princ->name_parts[loop] = kmalloc(tmp + 1, GFP_KERNEL);
if (!princ->name_parts[loop])
return -ENOMEM;
memcpy(princ->name_parts[loop], xdr, tmp);
princ->name_parts[loop][tmp] = 0;
tmp = (tmp + 3) & ~3;
toklen -= tmp;
xdr += tmp >> 2;
}
if (toklen < 4)
return -EINVAL;
tmp = ntohl(*xdr++);
toklen -= 4;
if (tmp <= 0 || tmp > AFSTOKEN_K5_REALM_MAX)
return -EINVAL;
if (tmp > toklen)
return -EINVAL;
princ->realm = kmalloc(tmp + 1, GFP_KERNEL);
if (!princ->realm)
return -ENOMEM;
memcpy(princ->realm, xdr, tmp);
princ->realm[tmp] = 0;
tmp = (tmp + 3) & ~3;
toklen -= tmp;
xdr += tmp >> 2;
_debug("%s/...@%s", princ->name_parts[0], princ->realm);
*_xdr = xdr;
*_toklen = toklen;
_leave(" = 0 [toklen=%u]", toklen);
return 0;
}
/*
* extract a piece of krb5 tagged data
*/
static int rxrpc_krb5_decode_tagged_data(struct krb5_tagged_data *td,
size_t max_data_size,
const __be32 **_xdr,
unsigned int *_toklen)
{
const __be32 *xdr = *_xdr;
unsigned int toklen = *_toklen, len;
/* there must be at least one tag and one length word */
if (toklen <= 8)
return -EINVAL;
_enter(",%zu,{%x,%x},%u",
max_data_size, ntohl(xdr[0]), ntohl(xdr[1]), toklen);
td->tag = ntohl(*xdr++);
len = ntohl(*xdr++);
toklen -= 8;
if (len > max_data_size)
return -EINVAL;
td->data_len = len;
if (len > 0) {
td->data = kmemdup(xdr, len, GFP_KERNEL);
if (!td->data)
return -ENOMEM;
len = (len + 3) & ~3;
toklen -= len;
xdr += len >> 2;
}
_debug("tag %x len %x", td->tag, td->data_len);
*_xdr = xdr;
*_toklen = toklen;
_leave(" = 0 [toklen=%u]", toklen);
return 0;
}
/*
* extract an array of tagged data
*/
static int rxrpc_krb5_decode_tagged_array(struct krb5_tagged_data **_td,
u8 *_n_elem,
u8 max_n_elem,
size_t max_elem_size,
const __be32 **_xdr,
unsigned int *_toklen)
{
struct krb5_tagged_data *td;
const __be32 *xdr = *_xdr;
unsigned int toklen = *_toklen, n_elem, loop;
int ret;
/* there must be at least one count */
if (toklen < 4)
return -EINVAL;
_enter(",,%u,%zu,{%x},%u",
max_n_elem, max_elem_size, ntohl(xdr[0]), toklen);
n_elem = ntohl(*xdr++);
toklen -= 4;
if (n_elem > max_n_elem)
return -EINVAL;
*_n_elem = n_elem;
if (n_elem > 0) {
if (toklen <= (n_elem + 1) * 4)
return -EINVAL;
_debug("n_elem %d", n_elem);
td = kcalloc(n_elem, sizeof(struct krb5_tagged_data),
GFP_KERNEL);
if (!td)
return -ENOMEM;
*_td = td;
for (loop = 0; loop < n_elem; loop++) {
ret = rxrpc_krb5_decode_tagged_data(&td[loop],
max_elem_size,
&xdr, &toklen);
if (ret < 0)
return ret;
}
}
*_xdr = xdr;
*_toklen = toklen;
_leave(" = 0 [toklen=%u]", toklen);
return 0;
}
/*
* extract a krb5 ticket
*/
static int rxrpc_krb5_decode_ticket(u8 **_ticket, u16 *_tktlen,
const __be32 **_xdr, unsigned int *_toklen)
{
const __be32 *xdr = *_xdr;
unsigned int toklen = *_toklen, len;
/* there must be at least one length word */
if (toklen <= 4)
return -EINVAL;
_enter(",{%x},%u", ntohl(xdr[0]), toklen);
len = ntohl(*xdr++);
toklen -= 4;
if (len > AFSTOKEN_K5_TIX_MAX)
return -EINVAL;
*_tktlen = len;
_debug("ticket len %u", len);
if (len > 0) {
*_ticket = kmemdup(xdr, len, GFP_KERNEL);
if (!*_ticket)
return -ENOMEM;
len = (len + 3) & ~3;
toklen -= len;
xdr += len >> 2;
}
*_xdr = xdr;
*_toklen = toklen;
_leave(" = 0 [toklen=%u]", toklen);
return 0;
}
/*
* parse an RxK5 type XDR format token
* - the caller guarantees we have at least 4 words
*/
static int rxrpc_preparse_xdr_rxk5(struct key_preparsed_payload *prep,
size_t datalen,
const __be32 *xdr, unsigned int toklen)
{
struct rxrpc_key_token *token, **pptoken;
struct rxk5_key *rxk5;
const __be32 *end_xdr = xdr + (toklen >> 2);
int ret;
_enter(",{%x,%x,%x,%x},%u",
ntohl(xdr[0]), ntohl(xdr[1]), ntohl(xdr[2]), ntohl(xdr[3]),
toklen);
/* reserve some payload space for this subkey - the length of the token
* is a reasonable approximation */
prep->quotalen = datalen + toklen;
token = kzalloc(sizeof(*token), GFP_KERNEL);
if (!token)
return -ENOMEM;
rxk5 = kzalloc(sizeof(*rxk5), GFP_KERNEL);
if (!rxk5) {
kfree(token);
return -ENOMEM;
}
token->security_index = RXRPC_SECURITY_RXK5;
token->k5 = rxk5;
/* extract the principals */
ret = rxrpc_krb5_decode_principal(&rxk5->client, &xdr, &toklen);
if (ret < 0)
goto error;
ret = rxrpc_krb5_decode_principal(&rxk5->server, &xdr, &toklen);
if (ret < 0)
goto error;
/* extract the session key and the encoding type (the tag field ->
* ENCTYPE_xxx) */
ret = rxrpc_krb5_decode_tagged_data(&rxk5->session, AFSTOKEN_DATA_MAX,
&xdr, &toklen);
if (ret < 0)
goto error;
if (toklen < 4 * 8 + 2 * 4)
goto inval;
rxk5->authtime = be64_to_cpup((const __be64 *) xdr);
xdr += 2;
rxk5->starttime = be64_to_cpup((const __be64 *) xdr);
xdr += 2;
rxk5->endtime = be64_to_cpup((const __be64 *) xdr);
xdr += 2;
rxk5->renew_till = be64_to_cpup((const __be64 *) xdr);
xdr += 2;
rxk5->is_skey = ntohl(*xdr++);
rxk5->flags = ntohl(*xdr++);
toklen -= 4 * 8 + 2 * 4;
_debug("times: a=%llx s=%llx e=%llx rt=%llx",
rxk5->authtime, rxk5->starttime, rxk5->endtime,
rxk5->renew_till);
_debug("is_skey=%x flags=%x", rxk5->is_skey, rxk5->flags);
/* extract the permitted client addresses */
ret = rxrpc_krb5_decode_tagged_array(&rxk5->addresses,
&rxk5->n_addresses,
AFSTOKEN_K5_ADDRESSES_MAX,
AFSTOKEN_DATA_MAX,
&xdr, &toklen);
if (ret < 0)
goto error;
ASSERTCMP((end_xdr - xdr) << 2, ==, toklen);
/* extract the tickets */
ret = rxrpc_krb5_decode_ticket(&rxk5->ticket, &rxk5->ticket_len,
&xdr, &toklen);
if (ret < 0)
goto error;
ret = rxrpc_krb5_decode_ticket(&rxk5->ticket2, &rxk5->ticket2_len,
&xdr, &toklen);
if (ret < 0)
goto error;
ASSERTCMP((end_xdr - xdr) << 2, ==, toklen);
/* extract the typed auth data */
ret = rxrpc_krb5_decode_tagged_array(&rxk5->authdata,
&rxk5->n_authdata,
AFSTOKEN_K5_AUTHDATA_MAX,
AFSTOKEN_BDATALN_MAX,
&xdr, &toklen);
if (ret < 0)
goto error;
ASSERTCMP((end_xdr - xdr) << 2, ==, toklen);
if (toklen != 0)
goto inval;
/* attach the payload */
for (pptoken = (struct rxrpc_key_token **)&prep->payload[0];
*pptoken;
pptoken = &(*pptoken)->next)
continue;
*pptoken = token;
if (token->kad->expiry < prep->expiry)
prep->expiry = token->kad->expiry;
_leave(" = 0");
return 0;
inval:
ret = -EINVAL;
error:
rxrpc_rxk5_free(rxk5);
kfree(token);
_leave(" = %d", ret);
return ret;
}
/*
* attempt to parse the data as the XDR format
* - the caller guarantees we have more than 7 words
*/
static int rxrpc_preparse_xdr(struct key_preparsed_payload *prep)
{
const __be32 *xdr = prep->data, *token;
const char *cp;
unsigned int len, tmp, loop, ntoken, toklen, sec_ix;
size_t datalen = prep->datalen;
int ret;
_enter(",{%x,%x,%x,%x},%zu",
ntohl(xdr[0]), ntohl(xdr[1]), ntohl(xdr[2]), ntohl(xdr[3]),
prep->datalen);
if (datalen > AFSTOKEN_LENGTH_MAX)
goto not_xdr;
/* XDR is an array of __be32's */
if (datalen & 3)
goto not_xdr;
/* the flags should be 0 (the setpag bit must be handled by
* userspace) */
if (ntohl(*xdr++) != 0)
goto not_xdr;
datalen -= 4;
/* check the cell name */
len = ntohl(*xdr++);
if (len < 1 || len > AFSTOKEN_CELL_MAX)
goto not_xdr;
datalen -= 4;
tmp = (len + 3) & ~3;
if (tmp > datalen)
goto not_xdr;
cp = (const char *) xdr;
for (loop = 0; loop < len; loop++)
if (!isprint(cp[loop]))
goto not_xdr;
if (len < tmp)
for (; loop < tmp; loop++)
if (cp[loop])
goto not_xdr;
_debug("cellname: [%u/%u] '%*.*s'",
len, tmp, len, len, (const char *) xdr);
datalen -= tmp;
xdr += tmp >> 2;
/* get the token count */
if (datalen < 12)
goto not_xdr;
ntoken = ntohl(*xdr++);
datalen -= 4;
_debug("ntoken: %x", ntoken);
if (ntoken < 1 || ntoken > AFSTOKEN_MAX)
goto not_xdr;
/* check each token wrapper */
token = xdr;
loop = ntoken;
do {
if (datalen < 8)
goto not_xdr;
toklen = ntohl(*xdr++);
sec_ix = ntohl(*xdr);
datalen -= 4;
_debug("token: [%x/%zx] %x", toklen, datalen, sec_ix);
if (toklen < 20 || toklen > datalen)
goto not_xdr;
datalen -= (toklen + 3) & ~3;
xdr += (toklen + 3) >> 2;
} while (--loop > 0);
_debug("remainder: %zu", datalen);
if (datalen != 0)
goto not_xdr;
/* okay: we're going to assume it's valid XDR format
* - we ignore the cellname, relying on the key to be correctly named
*/
do {
xdr = token;
toklen = ntohl(*xdr++);
token = xdr + ((toklen + 3) >> 2);
sec_ix = ntohl(*xdr++);
toklen -= 4;
_debug("TOKEN type=%u [%p-%p]", sec_ix, xdr, token);
switch (sec_ix) {
case RXRPC_SECURITY_RXKAD:
ret = rxrpc_preparse_xdr_rxkad(prep, datalen, xdr, toklen);
if (ret != 0)
goto error;
break;
case RXRPC_SECURITY_RXK5:
ret = rxrpc_preparse_xdr_rxk5(prep, datalen, xdr, toklen);
if (ret != 0)
goto error;
break;
default:
ret = -EPROTONOSUPPORT;
goto error;
}
} while (--ntoken > 0);
_leave(" = 0");
return 0;
not_xdr:
_leave(" = -EPROTO");
return -EPROTO;
error:
_leave(" = %d", ret);
return ret;
}
/*
* Preparse an rxrpc defined key.
*
* Data should be of the form:
* OFFSET LEN CONTENT
* 0 4 key interface version number
* 4 2 security index (type)
* 6 2 ticket length
* 8 4 key expiry time (time_t)
* 12 4 kvno
* 16 8 session key
* 24 [len] ticket
*
* if no data is provided, then a no-security key is made
*/
static int rxrpc_preparse(struct key_preparsed_payload *prep)
{
const struct rxrpc_key_data_v1 *v1;
struct rxrpc_key_token *token, **pp;
size_t plen;
u32 kver;
int ret;
_enter("%zu", prep->datalen);
/* handle a no-security key */
if (!prep->data && prep->datalen == 0)
return 0;
/* determine if the XDR payload format is being used */
if (prep->datalen > 7 * 4) {
ret = rxrpc_preparse_xdr(prep);
if (ret != -EPROTO)
return ret;
}
/* get the key interface version number */
ret = -EINVAL;
if (prep->datalen <= 4 || !prep->data)
goto error;
memcpy(&kver, prep->data, sizeof(kver));
prep->data += sizeof(kver);
prep->datalen -= sizeof(kver);
_debug("KEY I/F VERSION: %u", kver);
ret = -EKEYREJECTED;
if (kver != 1)
goto error;
/* deal with a version 1 key */
ret = -EINVAL;
if (prep->datalen < sizeof(*v1))
goto error;
v1 = prep->data;
if (prep->datalen != sizeof(*v1) + v1->ticket_length)
goto error;
_debug("SCIX: %u", v1->security_index);
_debug("TLEN: %u", v1->ticket_length);
_debug("EXPY: %x", v1->expiry);
_debug("KVNO: %u", v1->kvno);
_debug("SKEY: %02x%02x%02x%02x%02x%02x%02x%02x",
v1->session_key[0], v1->session_key[1],
v1->session_key[2], v1->session_key[3],
v1->session_key[4], v1->session_key[5],
v1->session_key[6], v1->session_key[7]);
if (v1->ticket_length >= 8)
_debug("TCKT: %02x%02x%02x%02x%02x%02x%02x%02x",
v1->ticket[0], v1->ticket[1],
v1->ticket[2], v1->ticket[3],
v1->ticket[4], v1->ticket[5],
v1->ticket[6], v1->ticket[7]);
ret = -EPROTONOSUPPORT;
if (v1->security_index != RXRPC_SECURITY_RXKAD)
goto error;
plen = sizeof(*token->kad) + v1->ticket_length;
prep->quotalen = plen + sizeof(*token);
ret = -ENOMEM;
token = kzalloc(sizeof(*token), GFP_KERNEL);
if (!token)
goto error;
token->kad = kzalloc(plen, GFP_KERNEL);
if (!token->kad)
goto error_free;
token->security_index = RXRPC_SECURITY_RXKAD;
token->kad->ticket_len = v1->ticket_length;
token->kad->expiry = v1->expiry;
token->kad->kvno = v1->kvno;
memcpy(&token->kad->session_key, &v1->session_key, 8);
memcpy(&token->kad->ticket, v1->ticket, v1->ticket_length);
/* count the number of tokens attached */
prep->type_data[0] = (void *)((unsigned long)prep->type_data[0] + 1);
/* attach the data */
pp = (struct rxrpc_key_token **)&prep->payload[0];
while (*pp)
pp = &(*pp)->next;
*pp = token;
if (token->kad->expiry < prep->expiry)
prep->expiry = token->kad->expiry;
token = NULL;
ret = 0;
error_free:
kfree(token);
error:
return ret;
}
/*
* Free token list.
*/
static void rxrpc_free_token_list(struct rxrpc_key_token *token)
{
struct rxrpc_key_token *next;
for (; token; token = next) {
next = token->next;
switch (token->security_index) {
case RXRPC_SECURITY_RXKAD:
kfree(token->kad);
break;
case RXRPC_SECURITY_RXK5:
if (token->k5)
rxrpc_rxk5_free(token->k5);
break;
default:
printk(KERN_ERR "Unknown token type %x on rxrpc key\n",
token->security_index);
BUG();
}
kfree(token);
}
}
/*
* Clean up preparse data.
*/
static void rxrpc_free_preparse(struct key_preparsed_payload *prep)
{
rxrpc_free_token_list(prep->payload[0]);
}
/*
* Preparse a server secret key.
*
* The data should be the 8-byte secret key.
*/
static int rxrpc_preparse_s(struct key_preparsed_payload *prep)
{
struct crypto_blkcipher *ci;
_enter("%zu", prep->datalen);
if (prep->datalen != 8)
return -EINVAL;
memcpy(&prep->type_data, prep->data, 8);
ci = crypto_alloc_blkcipher("pcbc(des)", 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(ci)) {
_leave(" = %ld", PTR_ERR(ci));
return PTR_ERR(ci);
}
if (crypto_blkcipher_setkey(ci, prep->data, 8) < 0)
BUG();
prep->payload[0] = ci;
_leave(" = 0");
return 0;
}
/*
* Clean up preparse data.
*/
static void rxrpc_free_preparse_s(struct key_preparsed_payload *prep)
{
if (prep->payload[0])
crypto_free_blkcipher(prep->payload[0]);
}
/*
* dispose of the data dangling from the corpse of a rxrpc key
*/
static void rxrpc_destroy(struct key *key)
{
rxrpc_free_token_list(key->payload.data);
}
/*
* dispose of the data dangling from the corpse of a rxrpc key
*/
static void rxrpc_destroy_s(struct key *key)
{
if (key->payload.data) {
crypto_free_blkcipher(key->payload.data);
key->payload.data = NULL;
}
}
/*
* describe the rxrpc key
*/
static void rxrpc_describe(const struct key *key, struct seq_file *m)
{
seq_puts(m, key->description);
}
/*
* grab the security key for a socket
*/
int rxrpc_request_key(struct rxrpc_sock *rx, char __user *optval, int optlen)
{
struct key *key;
char *description;
_enter("");
if (optlen <= 0 || optlen > PAGE_SIZE - 1)
return -EINVAL;
description = kmalloc(optlen + 1, GFP_KERNEL);
if (!description)
return -ENOMEM;
if (copy_from_user(description, optval, optlen)) {
kfree(description);
return -EFAULT;
}
description[optlen] = 0;
key = request_key(&key_type_rxrpc, description, NULL);
if (IS_ERR(key)) {
kfree(description);
_leave(" = %ld", PTR_ERR(key));
return PTR_ERR(key);
}
rx->key = key;
kfree(description);
_leave(" = 0 [key %x]", key->serial);
return 0;
}
/*
* grab the security keyring for a server socket
*/
int rxrpc_server_keyring(struct rxrpc_sock *rx, char __user *optval,
int optlen)
{
struct key *key;
char *description;
_enter("");
if (optlen <= 0 || optlen > PAGE_SIZE - 1)
return -EINVAL;
description = kmalloc(optlen + 1, GFP_KERNEL);
if (!description)
return -ENOMEM;
if (copy_from_user(description, optval, optlen)) {
kfree(description);
return -EFAULT;
}
description[optlen] = 0;
key = request_key(&key_type_keyring, description, NULL);
if (IS_ERR(key)) {
kfree(description);
_leave(" = %ld", PTR_ERR(key));
return PTR_ERR(key);
}
rx->securities = key;
kfree(description);
_leave(" = 0 [key %x]", key->serial);
return 0;
}
/*
* generate a server data key
*/
int rxrpc_get_server_data_key(struct rxrpc_connection *conn,
const void *session_key,
time_t expiry,
u32 kvno)
{
const struct cred *cred = current_cred();
struct key *key;
int ret;
struct {
u32 kver;
struct rxrpc_key_data_v1 v1;
} data;
_enter("");
key = key_alloc(&key_type_rxrpc, "x",
GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred, 0,
KEY_ALLOC_NOT_IN_QUOTA);
if (IS_ERR(key)) {
_leave(" = -ENOMEM [alloc %ld]", PTR_ERR(key));
return -ENOMEM;
}
_debug("key %d", key_serial(key));
data.kver = 1;
data.v1.security_index = RXRPC_SECURITY_RXKAD;
data.v1.ticket_length = 0;
data.v1.expiry = expiry;
data.v1.kvno = 0;
memcpy(&data.v1.session_key, session_key, sizeof(data.v1.session_key));
ret = key_instantiate_and_link(key, &data, sizeof(data), NULL, NULL);
if (ret < 0)
goto error;
conn->key = key;
_leave(" = 0 [%d]", key_serial(key));
return 0;
error:
key_revoke(key);
key_put(key);
_leave(" = -ENOMEM [ins %d]", ret);
return -ENOMEM;
}
EXPORT_SYMBOL(rxrpc_get_server_data_key);
/**
* rxrpc_get_null_key - Generate a null RxRPC key
* @keyname: The name to give the key.
*
* Generate a null RxRPC key that can be used to indicate anonymous security is
* required for a particular domain.
*/
struct key *rxrpc_get_null_key(const char *keyname)
{
const struct cred *cred = current_cred();
struct key *key;
int ret;
key = key_alloc(&key_type_rxrpc, keyname,
GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred,
KEY_POS_SEARCH, KEY_ALLOC_NOT_IN_QUOTA);
if (IS_ERR(key))
return key;
ret = key_instantiate_and_link(key, NULL, 0, NULL, NULL);
if (ret < 0) {
key_revoke(key);
key_put(key);
return ERR_PTR(ret);
}
return key;
}
EXPORT_SYMBOL(rxrpc_get_null_key);
/*
* read the contents of an rxrpc key
* - this returns the result in XDR form
*/
static long rxrpc_read(const struct key *key,
char __user *buffer, size_t buflen)
{
const struct rxrpc_key_token *token;
const struct krb5_principal *princ;
size_t size;
__be32 __user *xdr, *oldxdr;
u32 cnlen, toksize, ntoks, tok, zero;
u16 toksizes[AFSTOKEN_MAX];
int loop;
_enter("");
/* we don't know what form we should return non-AFS keys in */
if (memcmp(key->description, "afs@", 4) != 0)
return -EOPNOTSUPP;
cnlen = strlen(key->description + 4);
#define RND(X) (((X) + 3) & ~3)
/* AFS keys we return in XDR form, so we need to work out the size of
* the XDR */
size = 2 * 4; /* flags, cellname len */
size += RND(cnlen); /* cellname */
size += 1 * 4; /* token count */
ntoks = 0;
for (token = key->payload.data; token; token = token->next) {
toksize = 4; /* sec index */
switch (token->security_index) {
case RXRPC_SECURITY_RXKAD:
toksize += 8 * 4; /* viceid, kvno, key*2, begin,
* end, primary, tktlen */
toksize += RND(token->kad->ticket_len);
break;
case RXRPC_SECURITY_RXK5:
princ = &token->k5->client;
toksize += 4 + princ->n_name_parts * 4;
for (loop = 0; loop < princ->n_name_parts; loop++)
toksize += RND(strlen(princ->name_parts[loop]));
toksize += 4 + RND(strlen(princ->realm));
princ = &token->k5->server;
toksize += 4 + princ->n_name_parts * 4;
for (loop = 0; loop < princ->n_name_parts; loop++)
toksize += RND(strlen(princ->name_parts[loop]));
toksize += 4 + RND(strlen(princ->realm));
toksize += 8 + RND(token->k5->session.data_len);
toksize += 4 * 8 + 2 * 4;
toksize += 4 + token->k5->n_addresses * 8;
for (loop = 0; loop < token->k5->n_addresses; loop++)
toksize += RND(token->k5->addresses[loop].data_len);
toksize += 4 + RND(token->k5->ticket_len);
toksize += 4 + RND(token->k5->ticket2_len);
toksize += 4 + token->k5->n_authdata * 8;
for (loop = 0; loop < token->k5->n_authdata; loop++)
toksize += RND(token->k5->authdata[loop].data_len);
break;
default: /* we have a ticket we can't encode */
BUG();
continue;
}
_debug("token[%u]: toksize=%u", ntoks, toksize);
ASSERTCMP(toksize, <=, AFSTOKEN_LENGTH_MAX);
toksizes[ntoks++] = toksize;
size += toksize + 4; /* each token has a length word */
}
#undef RND
if (!buffer || buflen < size)
return size;
xdr = (__be32 __user *) buffer;
zero = 0;
#define ENCODE(x) \
do { \
__be32 y = htonl(x); \
if (put_user(y, xdr++) < 0) \
goto fault; \
} while(0)
#define ENCODE_DATA(l, s) \
do { \
u32 _l = (l); \
ENCODE(l); \
if (copy_to_user(xdr, (s), _l) != 0) \
goto fault; \
if (_l & 3 && \
copy_to_user((u8 __user *)xdr + _l, &zero, 4 - (_l & 3)) != 0) \
goto fault; \
xdr += (_l + 3) >> 2; \
} while(0)
#define ENCODE64(x) \
do { \
__be64 y = cpu_to_be64(x); \
if (copy_to_user(xdr, &y, 8) != 0) \
goto fault; \
xdr += 8 >> 2; \
} while(0)
#define ENCODE_STR(s) \
do { \
const char *_s = (s); \
ENCODE_DATA(strlen(_s), _s); \
} while(0)
ENCODE(0); /* flags */
ENCODE_DATA(cnlen, key->description + 4); /* cellname */
ENCODE(ntoks);
tok = 0;
for (token = key->payload.data; token; token = token->next) {
toksize = toksizes[tok++];
ENCODE(toksize);
oldxdr = xdr;
ENCODE(token->security_index);
switch (token->security_index) {
case RXRPC_SECURITY_RXKAD:
ENCODE(token->kad->vice_id);
ENCODE(token->kad->kvno);
ENCODE_DATA(8, token->kad->session_key);
ENCODE(token->kad->start);
ENCODE(token->kad->expiry);
ENCODE(token->kad->primary_flag);
ENCODE_DATA(token->kad->ticket_len, token->kad->ticket);
break;
case RXRPC_SECURITY_RXK5:
princ = &token->k5->client;
ENCODE(princ->n_name_parts);
for (loop = 0; loop < princ->n_name_parts; loop++)
ENCODE_STR(princ->name_parts[loop]);
ENCODE_STR(princ->realm);
princ = &token->k5->server;
ENCODE(princ->n_name_parts);
for (loop = 0; loop < princ->n_name_parts; loop++)
ENCODE_STR(princ->name_parts[loop]);
ENCODE_STR(princ->realm);
ENCODE(token->k5->session.tag);
ENCODE_DATA(token->k5->session.data_len,
token->k5->session.data);
ENCODE64(token->k5->authtime);
ENCODE64(token->k5->starttime);
ENCODE64(token->k5->endtime);
ENCODE64(token->k5->renew_till);
ENCODE(token->k5->is_skey);
ENCODE(token->k5->flags);
ENCODE(token->k5->n_addresses);
for (loop = 0; loop < token->k5->n_addresses; loop++) {
ENCODE(token->k5->addresses[loop].tag);
ENCODE_DATA(token->k5->addresses[loop].data_len,
token->k5->addresses[loop].data);
}
ENCODE_DATA(token->k5->ticket_len, token->k5->ticket);
ENCODE_DATA(token->k5->ticket2_len, token->k5->ticket2);
ENCODE(token->k5->n_authdata);
for (loop = 0; loop < token->k5->n_authdata; loop++) {
ENCODE(token->k5->authdata[loop].tag);
ENCODE_DATA(token->k5->authdata[loop].data_len,
token->k5->authdata[loop].data);
}
break;
default:
BUG();
break;
}
ASSERTCMP((unsigned long)xdr - (unsigned long)oldxdr, ==,
toksize);
}
#undef ENCODE_STR
#undef ENCODE_DATA
#undef ENCODE64
#undef ENCODE
ASSERTCMP(tok, ==, ntoks);
ASSERTCMP((char __user *) xdr - buffer, ==, size);
_leave(" = %zu", size);
return size;
fault:
_leave(" = -EFAULT");
return -EFAULT;
}
| gpl-2.0 |
smksyj/linux_modified_mlock | drivers/acpi/processor_thermal.c | 1382 | 6820 | /*
* processor_thermal.c - Passive cooling submodule of the ACPI processor driver
*
* Copyright (C) 2001, 2002 Andy Grover <andrew.grover@intel.com>
* Copyright (C) 2001, 2002 Paul Diefenbaugh <paul.s.diefenbaugh@intel.com>
* Copyright (C) 2004 Dominik Brodowski <linux@brodo.de>
* Copyright (C) 2004 Anil S Keshavamurthy <anil.s.keshavamurthy@intel.com>
* - Added processor hotplug support
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/cpufreq.h>
#include <linux/acpi.h>
#include <acpi/processor.h>
#include <asm/uaccess.h>
#define PREFIX "ACPI: "
#define ACPI_PROCESSOR_CLASS "processor"
#define _COMPONENT ACPI_PROCESSOR_COMPONENT
ACPI_MODULE_NAME("processor_thermal");
#ifdef CONFIG_CPU_FREQ
/* If a passive cooling situation is detected, primarily CPUfreq is used, as it
* offers (in most cases) voltage scaling in addition to frequency scaling, and
* thus a cubic (instead of linear) reduction of energy. Also, we allow for
* _any_ cpufreq driver and not only the acpi-cpufreq driver.
*/
#define CPUFREQ_THERMAL_MIN_STEP 0
#define CPUFREQ_THERMAL_MAX_STEP 3
static DEFINE_PER_CPU(unsigned int, cpufreq_thermal_reduction_pctg);
static unsigned int acpi_thermal_cpufreq_is_init = 0;
#define reduction_pctg(cpu) \
per_cpu(cpufreq_thermal_reduction_pctg, phys_package_first_cpu(cpu))
/*
* Emulate "per package data" using per cpu data (which should really be
* provided elsewhere)
*
* Note we can lose a CPU on cpu hotunplug, in this case we forget the state
* temporarily. Fortunately that's not a big issue here (I hope)
*/
static int phys_package_first_cpu(int cpu)
{
int i;
int id = topology_physical_package_id(cpu);
for_each_online_cpu(i)
if (topology_physical_package_id(i) == id)
return i;
return 0;
}
static int cpu_has_cpufreq(unsigned int cpu)
{
struct cpufreq_policy policy;
if (!acpi_thermal_cpufreq_is_init || cpufreq_get_policy(&policy, cpu))
return 0;
return 1;
}
static int acpi_thermal_cpufreq_notifier(struct notifier_block *nb,
unsigned long event, void *data)
{
struct cpufreq_policy *policy = data;
unsigned long max_freq = 0;
if (event != CPUFREQ_ADJUST)
goto out;
max_freq = (
policy->cpuinfo.max_freq *
(100 - reduction_pctg(policy->cpu) * 20)
) / 100;
cpufreq_verify_within_limits(policy, 0, max_freq);
out:
return 0;
}
static struct notifier_block acpi_thermal_cpufreq_notifier_block = {
.notifier_call = acpi_thermal_cpufreq_notifier,
};
static int cpufreq_get_max_state(unsigned int cpu)
{
if (!cpu_has_cpufreq(cpu))
return 0;
return CPUFREQ_THERMAL_MAX_STEP;
}
static int cpufreq_get_cur_state(unsigned int cpu)
{
if (!cpu_has_cpufreq(cpu))
return 0;
return reduction_pctg(cpu);
}
static int cpufreq_set_cur_state(unsigned int cpu, int state)
{
int i;
if (!cpu_has_cpufreq(cpu))
return 0;
reduction_pctg(cpu) = state;
/*
* Update all the CPUs in the same package because they all
* contribute to the temperature and often share the same
* frequency.
*/
for_each_online_cpu(i) {
if (topology_physical_package_id(i) ==
topology_physical_package_id(cpu))
cpufreq_update_policy(i);
}
return 0;
}
void acpi_thermal_cpufreq_init(void)
{
int i;
i = cpufreq_register_notifier(&acpi_thermal_cpufreq_notifier_block,
CPUFREQ_POLICY_NOTIFIER);
if (!i)
acpi_thermal_cpufreq_is_init = 1;
}
void acpi_thermal_cpufreq_exit(void)
{
if (acpi_thermal_cpufreq_is_init)
cpufreq_unregister_notifier
(&acpi_thermal_cpufreq_notifier_block,
CPUFREQ_POLICY_NOTIFIER);
acpi_thermal_cpufreq_is_init = 0;
}
#else /* ! CONFIG_CPU_FREQ */
static int cpufreq_get_max_state(unsigned int cpu)
{
return 0;
}
static int cpufreq_get_cur_state(unsigned int cpu)
{
return 0;
}
static int cpufreq_set_cur_state(unsigned int cpu, int state)
{
return 0;
}
#endif
/* thermal cooling device callbacks */
static int acpi_processor_max_state(struct acpi_processor *pr)
{
int max_state = 0;
/*
* There exists four states according to
* cpufreq_thermal_reduction_pctg. 0, 1, 2, 3
*/
max_state += cpufreq_get_max_state(pr->id);
if (pr->flags.throttling)
max_state += (pr->throttling.state_count -1);
return max_state;
}
static int
processor_get_max_state(struct thermal_cooling_device *cdev,
unsigned long *state)
{
struct acpi_device *device = cdev->devdata;
struct acpi_processor *pr;
if (!device)
return -EINVAL;
pr = acpi_driver_data(device);
if (!pr)
return -EINVAL;
*state = acpi_processor_max_state(pr);
return 0;
}
static int
processor_get_cur_state(struct thermal_cooling_device *cdev,
unsigned long *cur_state)
{
struct acpi_device *device = cdev->devdata;
struct acpi_processor *pr;
if (!device)
return -EINVAL;
pr = acpi_driver_data(device);
if (!pr)
return -EINVAL;
*cur_state = cpufreq_get_cur_state(pr->id);
if (pr->flags.throttling)
*cur_state += pr->throttling.state;
return 0;
}
static int
processor_set_cur_state(struct thermal_cooling_device *cdev,
unsigned long state)
{
struct acpi_device *device = cdev->devdata;
struct acpi_processor *pr;
int result = 0;
int max_pstate;
if (!device)
return -EINVAL;
pr = acpi_driver_data(device);
if (!pr)
return -EINVAL;
max_pstate = cpufreq_get_max_state(pr->id);
if (state > acpi_processor_max_state(pr))
return -EINVAL;
if (state <= max_pstate) {
if (pr->flags.throttling && pr->throttling.state)
result = acpi_processor_set_throttling(pr, 0, false);
cpufreq_set_cur_state(pr->id, state);
} else {
cpufreq_set_cur_state(pr->id, max_pstate);
result = acpi_processor_set_throttling(pr,
state - max_pstate, false);
}
return result;
}
const struct thermal_cooling_device_ops processor_cooling_ops = {
.get_max_state = processor_get_max_state,
.get_cur_state = processor_get_cur_state,
.set_cur_state = processor_set_cur_state,
};
| gpl-2.0 |
captivo/linux-captivo | tools/perf/builtin-mem.c | 2150 | 5933 | #include "builtin.h"
#include "perf.h"
#include "util/parse-options.h"
#include "util/trace-event.h"
#include "util/tool.h"
#include "util/session.h"
#define MEM_OPERATION_LOAD "load"
#define MEM_OPERATION_STORE "store"
static const char *mem_operation = MEM_OPERATION_LOAD;
struct perf_mem {
struct perf_tool tool;
char const *input_name;
symbol_filter_t annotate_init;
bool hide_unresolved;
bool dump_raw;
const char *cpu_list;
DECLARE_BITMAP(cpu_bitmap, MAX_NR_CPUS);
};
static const char * const mem_usage[] = {
"perf mem [<options>] {record <command> |report}",
NULL
};
static int __cmd_record(int argc, const char **argv)
{
int rec_argc, i = 0, j;
const char **rec_argv;
char event[64];
int ret;
rec_argc = argc + 4;
rec_argv = calloc(rec_argc + 1, sizeof(char *));
if (!rec_argv)
return -1;
rec_argv[i++] = strdup("record");
if (!strcmp(mem_operation, MEM_OPERATION_LOAD))
rec_argv[i++] = strdup("-W");
rec_argv[i++] = strdup("-d");
rec_argv[i++] = strdup("-e");
if (strcmp(mem_operation, MEM_OPERATION_LOAD))
sprintf(event, "cpu/mem-stores/pp");
else
sprintf(event, "cpu/mem-loads/pp");
rec_argv[i++] = strdup(event);
for (j = 1; j < argc; j++, i++)
rec_argv[i] = argv[j];
ret = cmd_record(i, rec_argv, NULL);
free(rec_argv);
return ret;
}
static int
dump_raw_samples(struct perf_tool *tool,
union perf_event *event,
struct perf_sample *sample,
struct perf_evsel *evsel __maybe_unused,
struct machine *machine)
{
struct perf_mem *mem = container_of(tool, struct perf_mem, tool);
struct addr_location al;
const char *fmt;
if (perf_event__preprocess_sample(event, machine, &al, sample,
mem->annotate_init) < 0) {
fprintf(stderr, "problem processing %d event, skipping it.\n",
event->header.type);
return -1;
}
if (al.filtered || (mem->hide_unresolved && al.sym == NULL))
return 0;
if (al.map != NULL)
al.map->dso->hit = 1;
if (symbol_conf.field_sep) {
fmt = "%d%s%d%s0x%"PRIx64"%s0x%"PRIx64"%s%"PRIu64
"%s0x%"PRIx64"%s%s:%s\n";
} else {
fmt = "%5d%s%5d%s0x%016"PRIx64"%s0x016%"PRIx64
"%s%5"PRIu64"%s0x%06"PRIx64"%s%s:%s\n";
symbol_conf.field_sep = " ";
}
printf(fmt,
sample->pid,
symbol_conf.field_sep,
sample->tid,
symbol_conf.field_sep,
event->ip.ip,
symbol_conf.field_sep,
sample->addr,
symbol_conf.field_sep,
sample->weight,
symbol_conf.field_sep,
sample->data_src,
symbol_conf.field_sep,
al.map ? (al.map->dso ? al.map->dso->long_name : "???") : "???",
al.sym ? al.sym->name : "???");
return 0;
}
static int process_sample_event(struct perf_tool *tool,
union perf_event *event,
struct perf_sample *sample,
struct perf_evsel *evsel,
struct machine *machine)
{
return dump_raw_samples(tool, event, sample, evsel, machine);
}
static int report_raw_events(struct perf_mem *mem)
{
int err = -EINVAL;
int ret;
struct perf_session *session = perf_session__new(input_name, O_RDONLY,
0, false, &mem->tool);
if (session == NULL)
return -ENOMEM;
if (mem->cpu_list) {
ret = perf_session__cpu_bitmap(session, mem->cpu_list,
mem->cpu_bitmap);
if (ret)
goto out_delete;
}
if (symbol__init() < 0)
return -1;
printf("# PID, TID, IP, ADDR, LOCAL WEIGHT, DSRC, SYMBOL\n");
err = perf_session__process_events(session, &mem->tool);
if (err)
return err;
return 0;
out_delete:
perf_session__delete(session);
return err;
}
static int report_events(int argc, const char **argv, struct perf_mem *mem)
{
const char **rep_argv;
int ret, i = 0, j, rep_argc;
if (mem->dump_raw)
return report_raw_events(mem);
rep_argc = argc + 3;
rep_argv = calloc(rep_argc + 1, sizeof(char *));
if (!rep_argv)
return -1;
rep_argv[i++] = strdup("report");
rep_argv[i++] = strdup("--mem-mode");
rep_argv[i++] = strdup("-n"); /* display number of samples */
/*
* there is no weight (cost) associated with stores, so don't print
* the column
*/
if (strcmp(mem_operation, MEM_OPERATION_LOAD))
rep_argv[i++] = strdup("--sort=mem,sym,dso,symbol_daddr,"
"dso_daddr,tlb,locked");
for (j = 1; j < argc; j++, i++)
rep_argv[i] = argv[j];
ret = cmd_report(i, rep_argv, NULL);
free(rep_argv);
return ret;
}
int cmd_mem(int argc, const char **argv, const char *prefix __maybe_unused)
{
struct stat st;
struct perf_mem mem = {
.tool = {
.sample = process_sample_event,
.mmap = perf_event__process_mmap,
.comm = perf_event__process_comm,
.lost = perf_event__process_lost,
.fork = perf_event__process_fork,
.build_id = perf_event__process_build_id,
.ordered_samples = true,
},
.input_name = "perf.data",
};
const struct option mem_options[] = {
OPT_STRING('t', "type", &mem_operation,
"type", "memory operations(load/store)"),
OPT_BOOLEAN('D', "dump-raw-samples", &mem.dump_raw,
"dump raw samples in ASCII"),
OPT_BOOLEAN('U', "hide-unresolved", &mem.hide_unresolved,
"Only display entries resolved to a symbol"),
OPT_STRING('i', "input", &input_name, "file",
"input file name"),
OPT_STRING('C', "cpu", &mem.cpu_list, "cpu",
"list of cpus to profile"),
OPT_STRING('x', "field-separator", &symbol_conf.field_sep,
"separator",
"separator for columns, no spaces will be added"
" between columns '.' is reserved."),
OPT_END()
};
argc = parse_options(argc, argv, mem_options, mem_usage,
PARSE_OPT_STOP_AT_NON_OPTION);
if (!argc || !(strncmp(argv[0], "rec", 3) || mem_operation))
usage_with_options(mem_usage, mem_options);
if (!mem.input_name || !strlen(mem.input_name)) {
if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
mem.input_name = "-";
else
mem.input_name = "perf.data";
}
if (!strncmp(argv[0], "rec", 3))
return __cmd_record(argc, argv);
else if (!strncmp(argv[0], "rep", 3))
return report_events(argc, argv, &mem);
else
usage_with_options(mem_usage, mem_options);
return 0;
}
| gpl-2.0 |
Jackeagle/kernel_caf | fs/nfs/read.c | 2150 | 17916 | /*
* linux/fs/nfs/read.c
*
* Block I/O for NFS
*
* Partial copy of Linus' read cache modifications to fs/nfs/file.c
* modified for async RPC by okir@monad.swb.de
*/
#include <linux/time.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/fcntl.h>
#include <linux/stat.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/pagemap.h>
#include <linux/sunrpc/clnt.h>
#include <linux/nfs_fs.h>
#include <linux/nfs_page.h>
#include <linux/module.h>
#include "nfs4_fs.h"
#include "internal.h"
#include "iostat.h"
#include "fscache.h"
#define NFSDBG_FACILITY NFSDBG_PAGECACHE
static const struct nfs_pageio_ops nfs_pageio_read_ops;
static const struct rpc_call_ops nfs_read_common_ops;
static const struct nfs_pgio_completion_ops nfs_async_read_completion_ops;
static struct kmem_cache *nfs_rdata_cachep;
struct nfs_read_header *nfs_readhdr_alloc(void)
{
struct nfs_read_header *rhdr;
rhdr = kmem_cache_zalloc(nfs_rdata_cachep, GFP_KERNEL);
if (rhdr) {
struct nfs_pgio_header *hdr = &rhdr->header;
INIT_LIST_HEAD(&hdr->pages);
INIT_LIST_HEAD(&hdr->rpc_list);
spin_lock_init(&hdr->lock);
atomic_set(&hdr->refcnt, 0);
}
return rhdr;
}
EXPORT_SYMBOL_GPL(nfs_readhdr_alloc);
static struct nfs_read_data *nfs_readdata_alloc(struct nfs_pgio_header *hdr,
unsigned int pagecount)
{
struct nfs_read_data *data, *prealloc;
prealloc = &container_of(hdr, struct nfs_read_header, header)->rpc_data;
if (prealloc->header == NULL)
data = prealloc;
else
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (!data)
goto out;
if (nfs_pgarray_set(&data->pages, pagecount)) {
data->header = hdr;
atomic_inc(&hdr->refcnt);
} else {
if (data != prealloc)
kfree(data);
data = NULL;
}
out:
return data;
}
void nfs_readhdr_free(struct nfs_pgio_header *hdr)
{
struct nfs_read_header *rhdr = container_of(hdr, struct nfs_read_header, header);
kmem_cache_free(nfs_rdata_cachep, rhdr);
}
EXPORT_SYMBOL_GPL(nfs_readhdr_free);
void nfs_readdata_release(struct nfs_read_data *rdata)
{
struct nfs_pgio_header *hdr = rdata->header;
struct nfs_read_header *read_header = container_of(hdr, struct nfs_read_header, header);
put_nfs_open_context(rdata->args.context);
if (rdata->pages.pagevec != rdata->pages.page_array)
kfree(rdata->pages.pagevec);
if (rdata == &read_header->rpc_data) {
rdata->header = NULL;
rdata = NULL;
}
if (atomic_dec_and_test(&hdr->refcnt))
hdr->completion_ops->completion(hdr);
/* Note: we only free the rpc_task after callbacks are done.
* See the comment in rpc_free_task() for why
*/
kfree(rdata);
}
EXPORT_SYMBOL_GPL(nfs_readdata_release);
static
int nfs_return_empty_page(struct page *page)
{
zero_user(page, 0, PAGE_CACHE_SIZE);
SetPageUptodate(page);
unlock_page(page);
return 0;
}
void nfs_pageio_init_read(struct nfs_pageio_descriptor *pgio,
struct inode *inode,
const struct nfs_pgio_completion_ops *compl_ops)
{
nfs_pageio_init(pgio, inode, &nfs_pageio_read_ops, compl_ops,
NFS_SERVER(inode)->rsize, 0);
}
EXPORT_SYMBOL_GPL(nfs_pageio_init_read);
void nfs_pageio_reset_read_mds(struct nfs_pageio_descriptor *pgio)
{
pgio->pg_ops = &nfs_pageio_read_ops;
pgio->pg_bsize = NFS_SERVER(pgio->pg_inode)->rsize;
}
EXPORT_SYMBOL_GPL(nfs_pageio_reset_read_mds);
int nfs_readpage_async(struct nfs_open_context *ctx, struct inode *inode,
struct page *page)
{
struct nfs_page *new;
unsigned int len;
struct nfs_pageio_descriptor pgio;
len = nfs_page_length(page);
if (len == 0)
return nfs_return_empty_page(page);
new = nfs_create_request(ctx, inode, page, 0, len);
if (IS_ERR(new)) {
unlock_page(page);
return PTR_ERR(new);
}
if (len < PAGE_CACHE_SIZE)
zero_user_segment(page, len, PAGE_CACHE_SIZE);
NFS_PROTO(inode)->read_pageio_init(&pgio, inode, &nfs_async_read_completion_ops);
nfs_pageio_add_request(&pgio, new);
nfs_pageio_complete(&pgio);
NFS_I(inode)->read_io += pgio.pg_bytes_written;
return 0;
}
static void nfs_readpage_release(struct nfs_page *req)
{
struct inode *d_inode = req->wb_context->dentry->d_inode;
if (PageUptodate(req->wb_page))
nfs_readpage_to_fscache(d_inode, req->wb_page, 0);
unlock_page(req->wb_page);
dprintk("NFS: read done (%s/%Ld %d@%Ld)\n",
req->wb_context->dentry->d_inode->i_sb->s_id,
(long long)NFS_FILEID(req->wb_context->dentry->d_inode),
req->wb_bytes,
(long long)req_offset(req));
nfs_release_request(req);
}
/* Note io was page aligned */
static void nfs_read_completion(struct nfs_pgio_header *hdr)
{
unsigned long bytes = 0;
if (test_bit(NFS_IOHDR_REDO, &hdr->flags))
goto out;
while (!list_empty(&hdr->pages)) {
struct nfs_page *req = nfs_list_entry(hdr->pages.next);
struct page *page = req->wb_page;
if (test_bit(NFS_IOHDR_EOF, &hdr->flags)) {
if (bytes > hdr->good_bytes)
zero_user(page, 0, PAGE_SIZE);
else if (hdr->good_bytes - bytes < PAGE_SIZE)
zero_user_segment(page,
hdr->good_bytes & ~PAGE_MASK,
PAGE_SIZE);
}
bytes += req->wb_bytes;
if (test_bit(NFS_IOHDR_ERROR, &hdr->flags)) {
if (bytes <= hdr->good_bytes)
SetPageUptodate(page);
} else
SetPageUptodate(page);
nfs_list_remove_request(req);
nfs_readpage_release(req);
}
out:
hdr->release(hdr);
}
int nfs_initiate_read(struct rpc_clnt *clnt,
struct nfs_read_data *data,
const struct rpc_call_ops *call_ops, int flags)
{
struct inode *inode = data->header->inode;
int swap_flags = IS_SWAPFILE(inode) ? NFS_RPC_SWAPFLAGS : 0;
struct rpc_task *task;
struct rpc_message msg = {
.rpc_argp = &data->args,
.rpc_resp = &data->res,
.rpc_cred = data->header->cred,
};
struct rpc_task_setup task_setup_data = {
.task = &data->task,
.rpc_client = clnt,
.rpc_message = &msg,
.callback_ops = call_ops,
.callback_data = data,
.workqueue = nfsiod_workqueue,
.flags = RPC_TASK_ASYNC | swap_flags | flags,
};
/* Set up the initial task struct. */
NFS_PROTO(inode)->read_setup(data, &msg);
dprintk("NFS: %5u initiated read call (req %s/%lld, %u bytes @ "
"offset %llu)\n",
data->task.tk_pid,
inode->i_sb->s_id,
(long long)NFS_FILEID(inode),
data->args.count,
(unsigned long long)data->args.offset);
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task))
return PTR_ERR(task);
rpc_put_task(task);
return 0;
}
EXPORT_SYMBOL_GPL(nfs_initiate_read);
/*
* Set up the NFS read request struct
*/
static void nfs_read_rpcsetup(struct nfs_read_data *data,
unsigned int count, unsigned int offset)
{
struct nfs_page *req = data->header->req;
data->args.fh = NFS_FH(data->header->inode);
data->args.offset = req_offset(req) + offset;
data->args.pgbase = req->wb_pgbase + offset;
data->args.pages = data->pages.pagevec;
data->args.count = count;
data->args.context = get_nfs_open_context(req->wb_context);
data->args.lock_context = req->wb_lock_context;
data->res.fattr = &data->fattr;
data->res.count = count;
data->res.eof = 0;
nfs_fattr_init(&data->fattr);
}
static int nfs_do_read(struct nfs_read_data *data,
const struct rpc_call_ops *call_ops)
{
struct inode *inode = data->header->inode;
return nfs_initiate_read(NFS_CLIENT(inode), data, call_ops, 0);
}
static int
nfs_do_multiple_reads(struct list_head *head,
const struct rpc_call_ops *call_ops)
{
struct nfs_read_data *data;
int ret = 0;
while (!list_empty(head)) {
int ret2;
data = list_first_entry(head, struct nfs_read_data, list);
list_del_init(&data->list);
ret2 = nfs_do_read(data, call_ops);
if (ret == 0)
ret = ret2;
}
return ret;
}
static void
nfs_async_read_error(struct list_head *head)
{
struct nfs_page *req;
while (!list_empty(head)) {
req = nfs_list_entry(head->next);
nfs_list_remove_request(req);
nfs_readpage_release(req);
}
}
static const struct nfs_pgio_completion_ops nfs_async_read_completion_ops = {
.error_cleanup = nfs_async_read_error,
.completion = nfs_read_completion,
};
static void nfs_pagein_error(struct nfs_pageio_descriptor *desc,
struct nfs_pgio_header *hdr)
{
set_bit(NFS_IOHDR_REDO, &hdr->flags);
while (!list_empty(&hdr->rpc_list)) {
struct nfs_read_data *data = list_first_entry(&hdr->rpc_list,
struct nfs_read_data, list);
list_del(&data->list);
nfs_readdata_release(data);
}
desc->pg_completion_ops->error_cleanup(&desc->pg_list);
}
/*
* Generate multiple requests to fill a single page.
*
* We optimize to reduce the number of read operations on the wire. If we
* detect that we're reading a page, or an area of a page, that is past the
* end of file, we do not generate NFS read operations but just clear the
* parts of the page that would have come back zero from the server anyway.
*
* We rely on the cached value of i_size to make this determination; another
* client can fill pages on the server past our cached end-of-file, but we
* won't see the new data until our attribute cache is updated. This is more
* or less conventional NFS client behavior.
*/
static int nfs_pagein_multi(struct nfs_pageio_descriptor *desc,
struct nfs_pgio_header *hdr)
{
struct nfs_page *req = hdr->req;
struct page *page = req->wb_page;
struct nfs_read_data *data;
size_t rsize = desc->pg_bsize, nbytes;
unsigned int offset;
offset = 0;
nbytes = desc->pg_count;
do {
size_t len = min(nbytes,rsize);
data = nfs_readdata_alloc(hdr, 1);
if (!data) {
nfs_pagein_error(desc, hdr);
return -ENOMEM;
}
data->pages.pagevec[0] = page;
nfs_read_rpcsetup(data, len, offset);
list_add(&data->list, &hdr->rpc_list);
nbytes -= len;
offset += len;
} while (nbytes != 0);
nfs_list_remove_request(req);
nfs_list_add_request(req, &hdr->pages);
desc->pg_rpc_callops = &nfs_read_common_ops;
return 0;
}
static int nfs_pagein_one(struct nfs_pageio_descriptor *desc,
struct nfs_pgio_header *hdr)
{
struct nfs_page *req;
struct page **pages;
struct nfs_read_data *data;
struct list_head *head = &desc->pg_list;
data = nfs_readdata_alloc(hdr, nfs_page_array_len(desc->pg_base,
desc->pg_count));
if (!data) {
nfs_pagein_error(desc, hdr);
return -ENOMEM;
}
pages = data->pages.pagevec;
while (!list_empty(head)) {
req = nfs_list_entry(head->next);
nfs_list_remove_request(req);
nfs_list_add_request(req, &hdr->pages);
*pages++ = req->wb_page;
}
nfs_read_rpcsetup(data, desc->pg_count, 0);
list_add(&data->list, &hdr->rpc_list);
desc->pg_rpc_callops = &nfs_read_common_ops;
return 0;
}
int nfs_generic_pagein(struct nfs_pageio_descriptor *desc,
struct nfs_pgio_header *hdr)
{
if (desc->pg_bsize < PAGE_CACHE_SIZE)
return nfs_pagein_multi(desc, hdr);
return nfs_pagein_one(desc, hdr);
}
EXPORT_SYMBOL_GPL(nfs_generic_pagein);
static int nfs_generic_pg_readpages(struct nfs_pageio_descriptor *desc)
{
struct nfs_read_header *rhdr;
struct nfs_pgio_header *hdr;
int ret;
rhdr = nfs_readhdr_alloc();
if (!rhdr) {
desc->pg_completion_ops->error_cleanup(&desc->pg_list);
return -ENOMEM;
}
hdr = &rhdr->header;
nfs_pgheader_init(desc, hdr, nfs_readhdr_free);
atomic_inc(&hdr->refcnt);
ret = nfs_generic_pagein(desc, hdr);
if (ret == 0)
ret = nfs_do_multiple_reads(&hdr->rpc_list,
desc->pg_rpc_callops);
if (atomic_dec_and_test(&hdr->refcnt))
hdr->completion_ops->completion(hdr);
return ret;
}
static const struct nfs_pageio_ops nfs_pageio_read_ops = {
.pg_test = nfs_generic_pg_test,
.pg_doio = nfs_generic_pg_readpages,
};
/*
* This is the callback from RPC telling us whether a reply was
* received or some error occurred (timeout or socket shutdown).
*/
int nfs_readpage_result(struct rpc_task *task, struct nfs_read_data *data)
{
struct inode *inode = data->header->inode;
int status;
dprintk("NFS: %s: %5u, (status %d)\n", __func__, task->tk_pid,
task->tk_status);
status = NFS_PROTO(inode)->read_done(task, data);
if (status != 0)
return status;
nfs_add_stats(inode, NFSIOS_SERVERREADBYTES, data->res.count);
if (task->tk_status == -ESTALE) {
set_bit(NFS_INO_STALE, &NFS_I(inode)->flags);
nfs_mark_for_revalidate(inode);
}
return 0;
}
static void nfs_readpage_retry(struct rpc_task *task, struct nfs_read_data *data)
{
struct nfs_readargs *argp = &data->args;
struct nfs_readres *resp = &data->res;
/* This is a short read! */
nfs_inc_stats(data->header->inode, NFSIOS_SHORTREAD);
/* Has the server at least made some progress? */
if (resp->count == 0) {
nfs_set_pgio_error(data->header, -EIO, argp->offset);
return;
}
/* Yes, so retry the read at the end of the data */
data->mds_offset += resp->count;
argp->offset += resp->count;
argp->pgbase += resp->count;
argp->count -= resp->count;
rpc_restart_call_prepare(task);
}
static void nfs_readpage_result_common(struct rpc_task *task, void *calldata)
{
struct nfs_read_data *data = calldata;
struct nfs_pgio_header *hdr = data->header;
/* Note the only returns of nfs_readpage_result are 0 and -EAGAIN */
if (nfs_readpage_result(task, data) != 0)
return;
if (task->tk_status < 0)
nfs_set_pgio_error(hdr, task->tk_status, data->args.offset);
else if (data->res.eof) {
loff_t bound;
bound = data->args.offset + data->res.count;
spin_lock(&hdr->lock);
if (bound < hdr->io_start + hdr->good_bytes) {
set_bit(NFS_IOHDR_EOF, &hdr->flags);
clear_bit(NFS_IOHDR_ERROR, &hdr->flags);
hdr->good_bytes = bound - hdr->io_start;
}
spin_unlock(&hdr->lock);
} else if (data->res.count != data->args.count)
nfs_readpage_retry(task, data);
}
static void nfs_readpage_release_common(void *calldata)
{
nfs_readdata_release(calldata);
}
void nfs_read_prepare(struct rpc_task *task, void *calldata)
{
struct nfs_read_data *data = calldata;
NFS_PROTO(data->header->inode)->read_rpc_prepare(task, data);
if (unlikely(test_bit(NFS_CONTEXT_BAD, &data->args.context->flags)))
rpc_exit(task, -EIO);
}
static const struct rpc_call_ops nfs_read_common_ops = {
.rpc_call_prepare = nfs_read_prepare,
.rpc_call_done = nfs_readpage_result_common,
.rpc_release = nfs_readpage_release_common,
};
/*
* Read a page over NFS.
* We read the page synchronously in the following case:
* - The error flag is set for this page. This happens only when a
* previous async read operation failed.
*/
int nfs_readpage(struct file *file, struct page *page)
{
struct nfs_open_context *ctx;
struct inode *inode = page_file_mapping(page)->host;
int error;
dprintk("NFS: nfs_readpage (%p %ld@%lu)\n",
page, PAGE_CACHE_SIZE, page_file_index(page));
nfs_inc_stats(inode, NFSIOS_VFSREADPAGE);
nfs_add_stats(inode, NFSIOS_READPAGES, 1);
/*
* Try to flush any pending writes to the file..
*
* NOTE! Because we own the page lock, there cannot
* be any new pending writes generated at this point
* for this page (other pages can be written to).
*/
error = nfs_wb_page(inode, page);
if (error)
goto out_unlock;
if (PageUptodate(page))
goto out_unlock;
error = -ESTALE;
if (NFS_STALE(inode))
goto out_unlock;
if (file == NULL) {
error = -EBADF;
ctx = nfs_find_open_context(inode, NULL, FMODE_READ);
if (ctx == NULL)
goto out_unlock;
} else
ctx = get_nfs_open_context(nfs_file_open_context(file));
if (!IS_SYNC(inode)) {
error = nfs_readpage_from_fscache(ctx, inode, page);
if (error == 0)
goto out;
}
error = nfs_readpage_async(ctx, inode, page);
out:
put_nfs_open_context(ctx);
return error;
out_unlock:
unlock_page(page);
return error;
}
struct nfs_readdesc {
struct nfs_pageio_descriptor *pgio;
struct nfs_open_context *ctx;
};
static int
readpage_async_filler(void *data, struct page *page)
{
struct nfs_readdesc *desc = (struct nfs_readdesc *)data;
struct inode *inode = page_file_mapping(page)->host;
struct nfs_page *new;
unsigned int len;
int error;
len = nfs_page_length(page);
if (len == 0)
return nfs_return_empty_page(page);
new = nfs_create_request(desc->ctx, inode, page, 0, len);
if (IS_ERR(new))
goto out_error;
if (len < PAGE_CACHE_SIZE)
zero_user_segment(page, len, PAGE_CACHE_SIZE);
if (!nfs_pageio_add_request(desc->pgio, new)) {
error = desc->pgio->pg_error;
goto out_unlock;
}
return 0;
out_error:
error = PTR_ERR(new);
out_unlock:
unlock_page(page);
return error;
}
int nfs_readpages(struct file *filp, struct address_space *mapping,
struct list_head *pages, unsigned nr_pages)
{
struct nfs_pageio_descriptor pgio;
struct nfs_readdesc desc = {
.pgio = &pgio,
};
struct inode *inode = mapping->host;
unsigned long npages;
int ret = -ESTALE;
dprintk("NFS: nfs_readpages (%s/%Ld %d)\n",
inode->i_sb->s_id,
(long long)NFS_FILEID(inode),
nr_pages);
nfs_inc_stats(inode, NFSIOS_VFSREADPAGES);
if (NFS_STALE(inode))
goto out;
if (filp == NULL) {
desc.ctx = nfs_find_open_context(inode, NULL, FMODE_READ);
if (desc.ctx == NULL)
return -EBADF;
} else
desc.ctx = get_nfs_open_context(nfs_file_open_context(filp));
/* attempt to read as many of the pages as possible from the cache
* - this returns -ENOBUFS immediately if the cookie is negative
*/
ret = nfs_readpages_from_fscache(desc.ctx, inode, mapping,
pages, &nr_pages);
if (ret == 0)
goto read_complete; /* all pages were read */
NFS_PROTO(inode)->read_pageio_init(&pgio, inode, &nfs_async_read_completion_ops);
ret = read_cache_pages(mapping, pages, readpage_async_filler, &desc);
nfs_pageio_complete(&pgio);
NFS_I(inode)->read_io += pgio.pg_bytes_written;
npages = (pgio.pg_bytes_written + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
nfs_add_stats(inode, NFSIOS_READPAGES, npages);
read_complete:
put_nfs_open_context(desc.ctx);
out:
return ret;
}
int __init nfs_init_readpagecache(void)
{
nfs_rdata_cachep = kmem_cache_create("nfs_read_data",
sizeof(struct nfs_read_header),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (nfs_rdata_cachep == NULL)
return -ENOMEM;
return 0;
}
void nfs_destroy_readpagecache(void)
{
kmem_cache_destroy(nfs_rdata_cachep);
}
| gpl-2.0 |
faux123/pantech_vega_racer_2_kernel | sound/soc/pxa/tosa.c | 2918 | 7314 | /*
* tosa.c -- SoC audio for Tosa
*
* Copyright 2005 Wolfson Microelectronics PLC.
* Copyright 2005 Openedhand Ltd.
*
* Authors: Liam Girdwood <lrg@slimlogic.co.uk>
* Richard Purdie <richard@openedhand.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.
*
* GPIO's
* 1 - Jack Insertion
* 5 - Hookswitch (headset answer/hang up switch)
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/device.h>
#include <linux/gpio.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <asm/mach-types.h>
#include <mach/tosa.h>
#include <mach/audio.h>
#include "../codecs/wm9712.h"
#include "pxa2xx-ac97.h"
static struct snd_soc_card tosa;
#define TOSA_HP 0
#define TOSA_MIC_INT 1
#define TOSA_HEADSET 2
#define TOSA_HP_OFF 3
#define TOSA_SPK_ON 0
#define TOSA_SPK_OFF 1
static int tosa_jack_func;
static int tosa_spk_func;
static void tosa_ext_control(struct snd_soc_codec *codec)
{
struct snd_soc_dapm_context *dapm = &codec->dapm;
/* set up jack connection */
switch (tosa_jack_func) {
case TOSA_HP:
snd_soc_dapm_disable_pin(dapm, "Mic (Internal)");
snd_soc_dapm_enable_pin(dapm, "Headphone Jack");
snd_soc_dapm_disable_pin(dapm, "Headset Jack");
break;
case TOSA_MIC_INT:
snd_soc_dapm_enable_pin(dapm, "Mic (Internal)");
snd_soc_dapm_disable_pin(dapm, "Headphone Jack");
snd_soc_dapm_disable_pin(dapm, "Headset Jack");
break;
case TOSA_HEADSET:
snd_soc_dapm_disable_pin(dapm, "Mic (Internal)");
snd_soc_dapm_disable_pin(dapm, "Headphone Jack");
snd_soc_dapm_enable_pin(dapm, "Headset Jack");
break;
}
if (tosa_spk_func == TOSA_SPK_ON)
snd_soc_dapm_enable_pin(dapm, "Speaker");
else
snd_soc_dapm_disable_pin(dapm, "Speaker");
snd_soc_dapm_sync(dapm);
}
static int tosa_startup(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_codec *codec = rtd->codec;
mutex_lock(&codec->mutex);
/* check the jack status at stream startup */
tosa_ext_control(codec);
mutex_unlock(&codec->mutex);
return 0;
}
static struct snd_soc_ops tosa_ops = {
.startup = tosa_startup,
};
static int tosa_get_jack(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] = tosa_jack_func;
return 0;
}
static int tosa_set_jack(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
if (tosa_jack_func == ucontrol->value.integer.value[0])
return 0;
tosa_jack_func = ucontrol->value.integer.value[0];
tosa_ext_control(codec);
return 1;
}
static int tosa_get_spk(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] = tosa_spk_func;
return 0;
}
static int tosa_set_spk(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
if (tosa_spk_func == ucontrol->value.integer.value[0])
return 0;
tosa_spk_func = ucontrol->value.integer.value[0];
tosa_ext_control(codec);
return 1;
}
/* tosa dapm event handlers */
static int tosa_hp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *k, int event)
{
gpio_set_value(TOSA_GPIO_L_MUTE, SND_SOC_DAPM_EVENT_ON(event) ? 1 :0);
return 0;
}
/* tosa machine dapm widgets */
static const struct snd_soc_dapm_widget tosa_dapm_widgets[] = {
SND_SOC_DAPM_HP("Headphone Jack", tosa_hp_event),
SND_SOC_DAPM_HP("Headset Jack", NULL),
SND_SOC_DAPM_MIC("Mic (Internal)", NULL),
SND_SOC_DAPM_SPK("Speaker", NULL),
};
/* tosa audio map */
static const struct snd_soc_dapm_route audio_map[] = {
/* headphone connected to HPOUTL, HPOUTR */
{"Headphone Jack", NULL, "HPOUTL"},
{"Headphone Jack", NULL, "HPOUTR"},
/* ext speaker connected to LOUT2, ROUT2 */
{"Speaker", NULL, "LOUT2"},
{"Speaker", NULL, "ROUT2"},
/* internal mic is connected to mic1, mic2 differential - with bias */
{"MIC1", NULL, "Mic Bias"},
{"MIC2", NULL, "Mic Bias"},
{"Mic Bias", NULL, "Mic (Internal)"},
/* headset is connected to HPOUTR, and LINEINR with bias */
{"Headset Jack", NULL, "HPOUTR"},
{"LINEINR", NULL, "Mic Bias"},
{"Mic Bias", NULL, "Headset Jack"},
};
static const char *jack_function[] = {"Headphone", "Mic", "Line", "Headset",
"Off"};
static const char *spk_function[] = {"On", "Off"};
static const struct soc_enum tosa_enum[] = {
SOC_ENUM_SINGLE_EXT(5, jack_function),
SOC_ENUM_SINGLE_EXT(2, spk_function),
};
static const struct snd_kcontrol_new tosa_controls[] = {
SOC_ENUM_EXT("Jack Function", tosa_enum[0], tosa_get_jack,
tosa_set_jack),
SOC_ENUM_EXT("Speaker Function", tosa_enum[1], tosa_get_spk,
tosa_set_spk),
};
static int tosa_ac97_init(struct snd_soc_pcm_runtime *rtd)
{
struct snd_soc_codec *codec = rtd->codec;
struct snd_soc_dapm_context *dapm = &codec->dapm;
int err;
snd_soc_dapm_nc_pin(dapm, "OUT3");
snd_soc_dapm_nc_pin(dapm, "MONOOUT");
/* add tosa specific controls */
err = snd_soc_add_controls(codec, tosa_controls,
ARRAY_SIZE(tosa_controls));
if (err < 0)
return err;
/* add tosa specific widgets */
snd_soc_dapm_new_controls(dapm, tosa_dapm_widgets,
ARRAY_SIZE(tosa_dapm_widgets));
/* set up tosa specific audio path audio_map */
snd_soc_dapm_add_routes(dapm, audio_map, ARRAY_SIZE(audio_map));
snd_soc_dapm_sync(dapm);
return 0;
}
static struct snd_soc_dai_link tosa_dai[] = {
{
.name = "AC97",
.stream_name = "AC97 HiFi",
.cpu_dai_name = "pxa2xx-ac97",
.codec_dai_name = "wm9712-hifi",
.platform_name = "pxa-pcm-audio",
.codec_name = "wm9712-codec",
.init = tosa_ac97_init,
.ops = &tosa_ops,
},
{
.name = "AC97 Aux",
.stream_name = "AC97 Aux",
.cpu_dai_name = "pxa2xx-ac97-aux",
.codec_dai_name = "wm9712-aux",
.platform_name = "pxa-pcm-audio",
.codec_name = "wm9712-codec",
.ops = &tosa_ops,
},
};
static int tosa_probe(struct snd_soc_card *card)
{
int ret;
ret = gpio_request(TOSA_GPIO_L_MUTE, "Headphone Jack");
if (ret)
return ret;
ret = gpio_direction_output(TOSA_GPIO_L_MUTE, 0);
if (ret)
gpio_free(TOSA_GPIO_L_MUTE);
return ret;
}
static int tosa_remove(struct snd_soc_card *card)
{
gpio_free(TOSA_GPIO_L_MUTE);
return 0;
}
static struct snd_soc_card tosa = {
.name = "Tosa",
.dai_link = tosa_dai,
.num_links = ARRAY_SIZE(tosa_dai),
.probe = tosa_probe,
.remove = tosa_remove,
};
static struct platform_device *tosa_snd_device;
static int __init tosa_init(void)
{
int ret;
if (!machine_is_tosa())
return -ENODEV;
tosa_snd_device = platform_device_alloc("soc-audio", -1);
if (!tosa_snd_device) {
ret = -ENOMEM;
goto err_alloc;
}
platform_set_drvdata(tosa_snd_device, &tosa);
ret = platform_device_add(tosa_snd_device);
if (!ret)
return 0;
platform_device_put(tosa_snd_device);
err_alloc:
return ret;
}
static void __exit tosa_exit(void)
{
platform_device_unregister(tosa_snd_device);
}
module_init(tosa_init);
module_exit(tosa_exit);
/* Module information */
MODULE_AUTHOR("Richard Purdie");
MODULE_DESCRIPTION("ALSA SoC Tosa");
MODULE_LICENSE("GPL");
| gpl-2.0 |
crimsonthunder/kernel_samsung_trlte_5.1.1 | drivers/pinctrl/pinctrl-imx28.c | 2918 | 11279 | /*
* Copyright 2012 Freescale Semiconductor, Inc.
*
* The code contained herein is licensed under the GNU General Public
* License. You may obtain a copy of the GNU General Public License
* Version 2 or later at the following locations:
*
* http://www.opensource.org/licenses/gpl-license.html
* http://www.gnu.org/copyleft/gpl.html
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/of_device.h>
#include <linux/pinctrl/pinctrl.h>
#include "pinctrl-mxs.h"
enum imx28_pin_enum {
GPMI_D00 = PINID(0, 0),
GPMI_D01 = PINID(0, 1),
GPMI_D02 = PINID(0, 2),
GPMI_D03 = PINID(0, 3),
GPMI_D04 = PINID(0, 4),
GPMI_D05 = PINID(0, 5),
GPMI_D06 = PINID(0, 6),
GPMI_D07 = PINID(0, 7),
GPMI_CE0N = PINID(0, 16),
GPMI_CE1N = PINID(0, 17),
GPMI_CE2N = PINID(0, 18),
GPMI_CE3N = PINID(0, 19),
GPMI_RDY0 = PINID(0, 20),
GPMI_RDY1 = PINID(0, 21),
GPMI_RDY2 = PINID(0, 22),
GPMI_RDY3 = PINID(0, 23),
GPMI_RDN = PINID(0, 24),
GPMI_WRN = PINID(0, 25),
GPMI_ALE = PINID(0, 26),
GPMI_CLE = PINID(0, 27),
GPMI_RESETN = PINID(0, 28),
LCD_D00 = PINID(1, 0),
LCD_D01 = PINID(1, 1),
LCD_D02 = PINID(1, 2),
LCD_D03 = PINID(1, 3),
LCD_D04 = PINID(1, 4),
LCD_D05 = PINID(1, 5),
LCD_D06 = PINID(1, 6),
LCD_D07 = PINID(1, 7),
LCD_D08 = PINID(1, 8),
LCD_D09 = PINID(1, 9),
LCD_D10 = PINID(1, 10),
LCD_D11 = PINID(1, 11),
LCD_D12 = PINID(1, 12),
LCD_D13 = PINID(1, 13),
LCD_D14 = PINID(1, 14),
LCD_D15 = PINID(1, 15),
LCD_D16 = PINID(1, 16),
LCD_D17 = PINID(1, 17),
LCD_D18 = PINID(1, 18),
LCD_D19 = PINID(1, 19),
LCD_D20 = PINID(1, 20),
LCD_D21 = PINID(1, 21),
LCD_D22 = PINID(1, 22),
LCD_D23 = PINID(1, 23),
LCD_RD_E = PINID(1, 24),
LCD_WR_RWN = PINID(1, 25),
LCD_RS = PINID(1, 26),
LCD_CS = PINID(1, 27),
LCD_VSYNC = PINID(1, 28),
LCD_HSYNC = PINID(1, 29),
LCD_DOTCLK = PINID(1, 30),
LCD_ENABLE = PINID(1, 31),
SSP0_DATA0 = PINID(2, 0),
SSP0_DATA1 = PINID(2, 1),
SSP0_DATA2 = PINID(2, 2),
SSP0_DATA3 = PINID(2, 3),
SSP0_DATA4 = PINID(2, 4),
SSP0_DATA5 = PINID(2, 5),
SSP0_DATA6 = PINID(2, 6),
SSP0_DATA7 = PINID(2, 7),
SSP0_CMD = PINID(2, 8),
SSP0_DETECT = PINID(2, 9),
SSP0_SCK = PINID(2, 10),
SSP1_SCK = PINID(2, 12),
SSP1_CMD = PINID(2, 13),
SSP1_DATA0 = PINID(2, 14),
SSP1_DATA3 = PINID(2, 15),
SSP2_SCK = PINID(2, 16),
SSP2_MOSI = PINID(2, 17),
SSP2_MISO = PINID(2, 18),
SSP2_SS0 = PINID(2, 19),
SSP2_SS1 = PINID(2, 20),
SSP2_SS2 = PINID(2, 21),
SSP3_SCK = PINID(2, 24),
SSP3_MOSI = PINID(2, 25),
SSP3_MISO = PINID(2, 26),
SSP3_SS0 = PINID(2, 27),
AUART0_RX = PINID(3, 0),
AUART0_TX = PINID(3, 1),
AUART0_CTS = PINID(3, 2),
AUART0_RTS = PINID(3, 3),
AUART1_RX = PINID(3, 4),
AUART1_TX = PINID(3, 5),
AUART1_CTS = PINID(3, 6),
AUART1_RTS = PINID(3, 7),
AUART2_RX = PINID(3, 8),
AUART2_TX = PINID(3, 9),
AUART2_CTS = PINID(3, 10),
AUART2_RTS = PINID(3, 11),
AUART3_RX = PINID(3, 12),
AUART3_TX = PINID(3, 13),
AUART3_CTS = PINID(3, 14),
AUART3_RTS = PINID(3, 15),
PWM0 = PINID(3, 16),
PWM1 = PINID(3, 17),
PWM2 = PINID(3, 18),
SAIF0_MCLK = PINID(3, 20),
SAIF0_LRCLK = PINID(3, 21),
SAIF0_BITCLK = PINID(3, 22),
SAIF0_SDATA0 = PINID(3, 23),
I2C0_SCL = PINID(3, 24),
I2C0_SDA = PINID(3, 25),
SAIF1_SDATA0 = PINID(3, 26),
SPDIF = PINID(3, 27),
PWM3 = PINID(3, 28),
PWM4 = PINID(3, 29),
LCD_RESET = PINID(3, 30),
ENET0_MDC = PINID(4, 0),
ENET0_MDIO = PINID(4, 1),
ENET0_RX_EN = PINID(4, 2),
ENET0_RXD0 = PINID(4, 3),
ENET0_RXD1 = PINID(4, 4),
ENET0_TX_CLK = PINID(4, 5),
ENET0_TX_EN = PINID(4, 6),
ENET0_TXD0 = PINID(4, 7),
ENET0_TXD1 = PINID(4, 8),
ENET0_RXD2 = PINID(4, 9),
ENET0_RXD3 = PINID(4, 10),
ENET0_TXD2 = PINID(4, 11),
ENET0_TXD3 = PINID(4, 12),
ENET0_RX_CLK = PINID(4, 13),
ENET0_COL = PINID(4, 14),
ENET0_CRS = PINID(4, 15),
ENET_CLK = PINID(4, 16),
JTAG_RTCK = PINID(4, 20),
EMI_D00 = PINID(5, 0),
EMI_D01 = PINID(5, 1),
EMI_D02 = PINID(5, 2),
EMI_D03 = PINID(5, 3),
EMI_D04 = PINID(5, 4),
EMI_D05 = PINID(5, 5),
EMI_D06 = PINID(5, 6),
EMI_D07 = PINID(5, 7),
EMI_D08 = PINID(5, 8),
EMI_D09 = PINID(5, 9),
EMI_D10 = PINID(5, 10),
EMI_D11 = PINID(5, 11),
EMI_D12 = PINID(5, 12),
EMI_D13 = PINID(5, 13),
EMI_D14 = PINID(5, 14),
EMI_D15 = PINID(5, 15),
EMI_ODT0 = PINID(5, 16),
EMI_DQM0 = PINID(5, 17),
EMI_ODT1 = PINID(5, 18),
EMI_DQM1 = PINID(5, 19),
EMI_DDR_OPEN_FB = PINID(5, 20),
EMI_CLK = PINID(5, 21),
EMI_DQS0 = PINID(5, 22),
EMI_DQS1 = PINID(5, 23),
EMI_DDR_OPEN = PINID(5, 26),
EMI_A00 = PINID(6, 0),
EMI_A01 = PINID(6, 1),
EMI_A02 = PINID(6, 2),
EMI_A03 = PINID(6, 3),
EMI_A04 = PINID(6, 4),
EMI_A05 = PINID(6, 5),
EMI_A06 = PINID(6, 6),
EMI_A07 = PINID(6, 7),
EMI_A08 = PINID(6, 8),
EMI_A09 = PINID(6, 9),
EMI_A10 = PINID(6, 10),
EMI_A11 = PINID(6, 11),
EMI_A12 = PINID(6, 12),
EMI_A13 = PINID(6, 13),
EMI_A14 = PINID(6, 14),
EMI_BA0 = PINID(6, 16),
EMI_BA1 = PINID(6, 17),
EMI_BA2 = PINID(6, 18),
EMI_CASN = PINID(6, 19),
EMI_RASN = PINID(6, 20),
EMI_WEN = PINID(6, 21),
EMI_CE0N = PINID(6, 22),
EMI_CE1N = PINID(6, 23),
EMI_CKE = PINID(6, 24),
};
static const struct pinctrl_pin_desc imx28_pins[] = {
MXS_PINCTRL_PIN(GPMI_D00),
MXS_PINCTRL_PIN(GPMI_D01),
MXS_PINCTRL_PIN(GPMI_D02),
MXS_PINCTRL_PIN(GPMI_D03),
MXS_PINCTRL_PIN(GPMI_D04),
MXS_PINCTRL_PIN(GPMI_D05),
MXS_PINCTRL_PIN(GPMI_D06),
MXS_PINCTRL_PIN(GPMI_D07),
MXS_PINCTRL_PIN(GPMI_CE0N),
MXS_PINCTRL_PIN(GPMI_CE1N),
MXS_PINCTRL_PIN(GPMI_CE2N),
MXS_PINCTRL_PIN(GPMI_CE3N),
MXS_PINCTRL_PIN(GPMI_RDY0),
MXS_PINCTRL_PIN(GPMI_RDY1),
MXS_PINCTRL_PIN(GPMI_RDY2),
MXS_PINCTRL_PIN(GPMI_RDY3),
MXS_PINCTRL_PIN(GPMI_RDN),
MXS_PINCTRL_PIN(GPMI_WRN),
MXS_PINCTRL_PIN(GPMI_ALE),
MXS_PINCTRL_PIN(GPMI_CLE),
MXS_PINCTRL_PIN(GPMI_RESETN),
MXS_PINCTRL_PIN(LCD_D00),
MXS_PINCTRL_PIN(LCD_D01),
MXS_PINCTRL_PIN(LCD_D02),
MXS_PINCTRL_PIN(LCD_D03),
MXS_PINCTRL_PIN(LCD_D04),
MXS_PINCTRL_PIN(LCD_D05),
MXS_PINCTRL_PIN(LCD_D06),
MXS_PINCTRL_PIN(LCD_D07),
MXS_PINCTRL_PIN(LCD_D08),
MXS_PINCTRL_PIN(LCD_D09),
MXS_PINCTRL_PIN(LCD_D10),
MXS_PINCTRL_PIN(LCD_D11),
MXS_PINCTRL_PIN(LCD_D12),
MXS_PINCTRL_PIN(LCD_D13),
MXS_PINCTRL_PIN(LCD_D14),
MXS_PINCTRL_PIN(LCD_D15),
MXS_PINCTRL_PIN(LCD_D16),
MXS_PINCTRL_PIN(LCD_D17),
MXS_PINCTRL_PIN(LCD_D18),
MXS_PINCTRL_PIN(LCD_D19),
MXS_PINCTRL_PIN(LCD_D20),
MXS_PINCTRL_PIN(LCD_D21),
MXS_PINCTRL_PIN(LCD_D22),
MXS_PINCTRL_PIN(LCD_D23),
MXS_PINCTRL_PIN(LCD_RD_E),
MXS_PINCTRL_PIN(LCD_WR_RWN),
MXS_PINCTRL_PIN(LCD_RS),
MXS_PINCTRL_PIN(LCD_CS),
MXS_PINCTRL_PIN(LCD_VSYNC),
MXS_PINCTRL_PIN(LCD_HSYNC),
MXS_PINCTRL_PIN(LCD_DOTCLK),
MXS_PINCTRL_PIN(LCD_ENABLE),
MXS_PINCTRL_PIN(SSP0_DATA0),
MXS_PINCTRL_PIN(SSP0_DATA1),
MXS_PINCTRL_PIN(SSP0_DATA2),
MXS_PINCTRL_PIN(SSP0_DATA3),
MXS_PINCTRL_PIN(SSP0_DATA4),
MXS_PINCTRL_PIN(SSP0_DATA5),
MXS_PINCTRL_PIN(SSP0_DATA6),
MXS_PINCTRL_PIN(SSP0_DATA7),
MXS_PINCTRL_PIN(SSP0_CMD),
MXS_PINCTRL_PIN(SSP0_DETECT),
MXS_PINCTRL_PIN(SSP0_SCK),
MXS_PINCTRL_PIN(SSP1_SCK),
MXS_PINCTRL_PIN(SSP1_CMD),
MXS_PINCTRL_PIN(SSP1_DATA0),
MXS_PINCTRL_PIN(SSP1_DATA3),
MXS_PINCTRL_PIN(SSP2_SCK),
MXS_PINCTRL_PIN(SSP2_MOSI),
MXS_PINCTRL_PIN(SSP2_MISO),
MXS_PINCTRL_PIN(SSP2_SS0),
MXS_PINCTRL_PIN(SSP2_SS1),
MXS_PINCTRL_PIN(SSP2_SS2),
MXS_PINCTRL_PIN(SSP3_SCK),
MXS_PINCTRL_PIN(SSP3_MOSI),
MXS_PINCTRL_PIN(SSP3_MISO),
MXS_PINCTRL_PIN(SSP3_SS0),
MXS_PINCTRL_PIN(AUART0_RX),
MXS_PINCTRL_PIN(AUART0_TX),
MXS_PINCTRL_PIN(AUART0_CTS),
MXS_PINCTRL_PIN(AUART0_RTS),
MXS_PINCTRL_PIN(AUART1_RX),
MXS_PINCTRL_PIN(AUART1_TX),
MXS_PINCTRL_PIN(AUART1_CTS),
MXS_PINCTRL_PIN(AUART1_RTS),
MXS_PINCTRL_PIN(AUART2_RX),
MXS_PINCTRL_PIN(AUART2_TX),
MXS_PINCTRL_PIN(AUART2_CTS),
MXS_PINCTRL_PIN(AUART2_RTS),
MXS_PINCTRL_PIN(AUART3_RX),
MXS_PINCTRL_PIN(AUART3_TX),
MXS_PINCTRL_PIN(AUART3_CTS),
MXS_PINCTRL_PIN(AUART3_RTS),
MXS_PINCTRL_PIN(PWM0),
MXS_PINCTRL_PIN(PWM1),
MXS_PINCTRL_PIN(PWM2),
MXS_PINCTRL_PIN(SAIF0_MCLK),
MXS_PINCTRL_PIN(SAIF0_LRCLK),
MXS_PINCTRL_PIN(SAIF0_BITCLK),
MXS_PINCTRL_PIN(SAIF0_SDATA0),
MXS_PINCTRL_PIN(I2C0_SCL),
MXS_PINCTRL_PIN(I2C0_SDA),
MXS_PINCTRL_PIN(SAIF1_SDATA0),
MXS_PINCTRL_PIN(SPDIF),
MXS_PINCTRL_PIN(PWM3),
MXS_PINCTRL_PIN(PWM4),
MXS_PINCTRL_PIN(LCD_RESET),
MXS_PINCTRL_PIN(ENET0_MDC),
MXS_PINCTRL_PIN(ENET0_MDIO),
MXS_PINCTRL_PIN(ENET0_RX_EN),
MXS_PINCTRL_PIN(ENET0_RXD0),
MXS_PINCTRL_PIN(ENET0_RXD1),
MXS_PINCTRL_PIN(ENET0_TX_CLK),
MXS_PINCTRL_PIN(ENET0_TX_EN),
MXS_PINCTRL_PIN(ENET0_TXD0),
MXS_PINCTRL_PIN(ENET0_TXD1),
MXS_PINCTRL_PIN(ENET0_RXD2),
MXS_PINCTRL_PIN(ENET0_RXD3),
MXS_PINCTRL_PIN(ENET0_TXD2),
MXS_PINCTRL_PIN(ENET0_TXD3),
MXS_PINCTRL_PIN(ENET0_RX_CLK),
MXS_PINCTRL_PIN(ENET0_COL),
MXS_PINCTRL_PIN(ENET0_CRS),
MXS_PINCTRL_PIN(ENET_CLK),
MXS_PINCTRL_PIN(JTAG_RTCK),
MXS_PINCTRL_PIN(EMI_D00),
MXS_PINCTRL_PIN(EMI_D01),
MXS_PINCTRL_PIN(EMI_D02),
MXS_PINCTRL_PIN(EMI_D03),
MXS_PINCTRL_PIN(EMI_D04),
MXS_PINCTRL_PIN(EMI_D05),
MXS_PINCTRL_PIN(EMI_D06),
MXS_PINCTRL_PIN(EMI_D07),
MXS_PINCTRL_PIN(EMI_D08),
MXS_PINCTRL_PIN(EMI_D09),
MXS_PINCTRL_PIN(EMI_D10),
MXS_PINCTRL_PIN(EMI_D11),
MXS_PINCTRL_PIN(EMI_D12),
MXS_PINCTRL_PIN(EMI_D13),
MXS_PINCTRL_PIN(EMI_D14),
MXS_PINCTRL_PIN(EMI_D15),
MXS_PINCTRL_PIN(EMI_ODT0),
MXS_PINCTRL_PIN(EMI_DQM0),
MXS_PINCTRL_PIN(EMI_ODT1),
MXS_PINCTRL_PIN(EMI_DQM1),
MXS_PINCTRL_PIN(EMI_DDR_OPEN_FB),
MXS_PINCTRL_PIN(EMI_CLK),
MXS_PINCTRL_PIN(EMI_DQS0),
MXS_PINCTRL_PIN(EMI_DQS1),
MXS_PINCTRL_PIN(EMI_DDR_OPEN),
MXS_PINCTRL_PIN(EMI_A00),
MXS_PINCTRL_PIN(EMI_A01),
MXS_PINCTRL_PIN(EMI_A02),
MXS_PINCTRL_PIN(EMI_A03),
MXS_PINCTRL_PIN(EMI_A04),
MXS_PINCTRL_PIN(EMI_A05),
MXS_PINCTRL_PIN(EMI_A06),
MXS_PINCTRL_PIN(EMI_A07),
MXS_PINCTRL_PIN(EMI_A08),
MXS_PINCTRL_PIN(EMI_A09),
MXS_PINCTRL_PIN(EMI_A10),
MXS_PINCTRL_PIN(EMI_A11),
MXS_PINCTRL_PIN(EMI_A12),
MXS_PINCTRL_PIN(EMI_A13),
MXS_PINCTRL_PIN(EMI_A14),
MXS_PINCTRL_PIN(EMI_BA0),
MXS_PINCTRL_PIN(EMI_BA1),
MXS_PINCTRL_PIN(EMI_BA2),
MXS_PINCTRL_PIN(EMI_CASN),
MXS_PINCTRL_PIN(EMI_RASN),
MXS_PINCTRL_PIN(EMI_WEN),
MXS_PINCTRL_PIN(EMI_CE0N),
MXS_PINCTRL_PIN(EMI_CE1N),
MXS_PINCTRL_PIN(EMI_CKE),
};
static struct mxs_regs imx28_regs = {
.muxsel = 0x100,
.drive = 0x300,
.pull = 0x600,
};
static struct mxs_pinctrl_soc_data imx28_pinctrl_data = {
.regs = &imx28_regs,
.pins = imx28_pins,
.npins = ARRAY_SIZE(imx28_pins),
};
static int imx28_pinctrl_probe(struct platform_device *pdev)
{
return mxs_pinctrl_probe(pdev, &imx28_pinctrl_data);
}
static struct of_device_id imx28_pinctrl_of_match[] = {
{ .compatible = "fsl,imx28-pinctrl", },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, imx28_pinctrl_of_match);
static struct platform_driver imx28_pinctrl_driver = {
.driver = {
.name = "imx28-pinctrl",
.owner = THIS_MODULE,
.of_match_table = imx28_pinctrl_of_match,
},
.probe = imx28_pinctrl_probe,
.remove = mxs_pinctrl_remove,
};
static int __init imx28_pinctrl_init(void)
{
return platform_driver_register(&imx28_pinctrl_driver);
}
postcore_initcall(imx28_pinctrl_init);
static void __exit imx28_pinctrl_exit(void)
{
platform_driver_unregister(&imx28_pinctrl_driver);
}
module_exit(imx28_pinctrl_exit);
MODULE_AUTHOR("Shawn Guo <shawn.guo@linaro.org>");
MODULE_DESCRIPTION("Freescale i.MX28 pinctrl driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
satgass/android_kernel_lenovo_msm8916 | lib/argv_split.c | 4454 | 2115 | /*
* Helper function for splitting a string into an argv-like array.
*/
#include <linux/kernel.h>
#include <linux/ctype.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/export.h>
static int count_argc(const char *str)
{
int count = 0;
bool was_space;
for (was_space = true; *str; str++) {
if (isspace(*str)) {
was_space = true;
} else if (was_space) {
was_space = false;
count++;
}
}
return count;
}
/**
* argv_free - free an argv
* @argv - the argument vector to be freed
*
* Frees an argv and the strings it points to.
*/
void argv_free(char **argv)
{
argv--;
kfree(argv[0]);
kfree(argv);
}
EXPORT_SYMBOL(argv_free);
/**
* argv_split - split a string at whitespace, returning an argv
* @gfp: the GFP mask used to allocate memory
* @str: the string to be split
* @argcp: returned argument count
*
* Returns an array of pointers to strings which are split out from
* @str. This is performed by strictly splitting on white-space; no
* quote processing is performed. Multiple whitespace characters are
* considered to be a single argument separator. The returned array
* is always NULL-terminated. Returns NULL on memory allocation
* failure.
*
* The source string at `str' may be undergoing concurrent alteration via
* userspace sysctl activity (at least). The argv_split() implementation
* attempts to handle this gracefully by taking a local copy to work on.
*/
char **argv_split(gfp_t gfp, const char *str, int *argcp)
{
char *argv_str;
bool was_space;
char **argv, **argv_ret;
int argc;
argv_str = kstrndup(str, KMALLOC_MAX_SIZE - 1, gfp);
if (!argv_str)
return NULL;
argc = count_argc(argv_str);
argv = kmalloc(sizeof(*argv) * (argc + 2), gfp);
if (!argv) {
kfree(argv_str);
return NULL;
}
*argv = argv_str;
argv_ret = ++argv;
for (was_space = true; *argv_str; argv_str++) {
if (isspace(*argv_str)) {
was_space = true;
*argv_str = 0;
} else if (was_space) {
was_space = false;
*argv++ = argv_str;
}
}
*argv = NULL;
if (argcp)
*argcp = argc;
return argv_ret;
}
EXPORT_SYMBOL(argv_split);
| gpl-2.0 |
YogeshNain/linux | drivers/xen/fallback.c | 4710 | 1558 | #include <linux/kernel.h>
#include <linux/string.h>
#include <linux/bug.h>
#include <linux/export.h>
#include <asm/hypervisor.h>
#include <asm/xen/hypercall.h>
int xen_event_channel_op_compat(int cmd, void *arg)
{
struct evtchn_op op;
int rc;
op.cmd = cmd;
memcpy(&op.u, arg, sizeof(op.u));
rc = _hypercall1(int, event_channel_op_compat, &op);
switch (cmd) {
case EVTCHNOP_close:
case EVTCHNOP_send:
case EVTCHNOP_bind_vcpu:
case EVTCHNOP_unmask:
/* no output */
break;
#define COPY_BACK(eop) \
case EVTCHNOP_##eop: \
memcpy(arg, &op.u.eop, sizeof(op.u.eop)); \
break
COPY_BACK(bind_interdomain);
COPY_BACK(bind_virq);
COPY_BACK(bind_pirq);
COPY_BACK(status);
COPY_BACK(alloc_unbound);
COPY_BACK(bind_ipi);
#undef COPY_BACK
default:
WARN_ON(rc != -ENOSYS);
break;
}
return rc;
}
EXPORT_SYMBOL_GPL(xen_event_channel_op_compat);
int xen_physdev_op_compat(int cmd, void *arg)
{
struct physdev_op op;
int rc;
op.cmd = cmd;
memcpy(&op.u, arg, sizeof(op.u));
rc = _hypercall1(int, physdev_op_compat, &op);
switch (cmd) {
case PHYSDEVOP_IRQ_UNMASK_NOTIFY:
case PHYSDEVOP_set_iopl:
case PHYSDEVOP_set_iobitmap:
case PHYSDEVOP_apic_write:
/* no output */
break;
#define COPY_BACK(pop, fld) \
case PHYSDEVOP_##pop: \
memcpy(arg, &op.u.fld, sizeof(op.u.fld)); \
break
COPY_BACK(irq_status_query, irq_status_query);
COPY_BACK(apic_read, apic_op);
COPY_BACK(ASSIGN_VECTOR, irq_op);
#undef COPY_BACK
default:
WARN_ON(rc != -ENOSYS);
break;
}
return rc;
}
EXPORT_SYMBOL_GPL(xen_physdev_op_compat);
| gpl-2.0 |
pantech-msm8960/android_kernel_pantech_msm8960 | fs/bfs/dir.c | 4966 | 9070 | /*
* fs/bfs/dir.c
* BFS directory operations.
* Copyright (C) 1999,2000 Tigran Aivazian <tigran@veritas.com>
* Made endianness-clean by Andrew Stribblehill <ads@wompom.org> 2005
*/
#include <linux/time.h>
#include <linux/string.h>
#include <linux/fs.h>
#include <linux/buffer_head.h>
#include <linux/sched.h>
#include "bfs.h"
#undef DEBUG
#ifdef DEBUG
#define dprintf(x...) printf(x)
#else
#define dprintf(x...)
#endif
static int bfs_add_entry(struct inode *dir, const unsigned char *name,
int namelen, int ino);
static struct buffer_head *bfs_find_entry(struct inode *dir,
const unsigned char *name, int namelen,
struct bfs_dirent **res_dir);
static int bfs_readdir(struct file *f, void *dirent, filldir_t filldir)
{
struct inode *dir = f->f_path.dentry->d_inode;
struct buffer_head *bh;
struct bfs_dirent *de;
struct bfs_sb_info *info = BFS_SB(dir->i_sb);
unsigned int offset;
int block;
mutex_lock(&info->bfs_lock);
if (f->f_pos & (BFS_DIRENT_SIZE - 1)) {
printf("Bad f_pos=%08lx for %s:%08lx\n",
(unsigned long)f->f_pos,
dir->i_sb->s_id, dir->i_ino);
mutex_unlock(&info->bfs_lock);
return -EBADF;
}
while (f->f_pos < dir->i_size) {
offset = f->f_pos & (BFS_BSIZE - 1);
block = BFS_I(dir)->i_sblock + (f->f_pos >> BFS_BSIZE_BITS);
bh = sb_bread(dir->i_sb, block);
if (!bh) {
f->f_pos += BFS_BSIZE - offset;
continue;
}
do {
de = (struct bfs_dirent *)(bh->b_data + offset);
if (de->ino) {
int size = strnlen(de->name, BFS_NAMELEN);
if (filldir(dirent, de->name, size, f->f_pos,
le16_to_cpu(de->ino),
DT_UNKNOWN) < 0) {
brelse(bh);
mutex_unlock(&info->bfs_lock);
return 0;
}
}
offset += BFS_DIRENT_SIZE;
f->f_pos += BFS_DIRENT_SIZE;
} while ((offset < BFS_BSIZE) && (f->f_pos < dir->i_size));
brelse(bh);
}
mutex_unlock(&info->bfs_lock);
return 0;
}
const struct file_operations bfs_dir_operations = {
.read = generic_read_dir,
.readdir = bfs_readdir,
.fsync = generic_file_fsync,
.llseek = generic_file_llseek,
};
extern void dump_imap(const char *, struct super_block *);
static int bfs_create(struct inode *dir, struct dentry *dentry, umode_t mode,
struct nameidata *nd)
{
int err;
struct inode *inode;
struct super_block *s = dir->i_sb;
struct bfs_sb_info *info = BFS_SB(s);
unsigned long ino;
inode = new_inode(s);
if (!inode)
return -ENOSPC;
mutex_lock(&info->bfs_lock);
ino = find_first_zero_bit(info->si_imap, info->si_lasti + 1);
if (ino > info->si_lasti) {
mutex_unlock(&info->bfs_lock);
iput(inode);
return -ENOSPC;
}
set_bit(ino, info->si_imap);
info->si_freei--;
inode_init_owner(inode, dir, mode);
inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME_SEC;
inode->i_blocks = 0;
inode->i_op = &bfs_file_inops;
inode->i_fop = &bfs_file_operations;
inode->i_mapping->a_ops = &bfs_aops;
inode->i_ino = ino;
BFS_I(inode)->i_dsk_ino = ino;
BFS_I(inode)->i_sblock = 0;
BFS_I(inode)->i_eblock = 0;
insert_inode_hash(inode);
mark_inode_dirty(inode);
dump_imap("create", s);
err = bfs_add_entry(dir, dentry->d_name.name, dentry->d_name.len,
inode->i_ino);
if (err) {
inode_dec_link_count(inode);
mutex_unlock(&info->bfs_lock);
iput(inode);
return err;
}
mutex_unlock(&info->bfs_lock);
d_instantiate(dentry, inode);
return 0;
}
static struct dentry *bfs_lookup(struct inode *dir, struct dentry *dentry,
struct nameidata *nd)
{
struct inode *inode = NULL;
struct buffer_head *bh;
struct bfs_dirent *de;
struct bfs_sb_info *info = BFS_SB(dir->i_sb);
if (dentry->d_name.len > BFS_NAMELEN)
return ERR_PTR(-ENAMETOOLONG);
mutex_lock(&info->bfs_lock);
bh = bfs_find_entry(dir, dentry->d_name.name, dentry->d_name.len, &de);
if (bh) {
unsigned long ino = (unsigned long)le16_to_cpu(de->ino);
brelse(bh);
inode = bfs_iget(dir->i_sb, ino);
if (IS_ERR(inode)) {
mutex_unlock(&info->bfs_lock);
return ERR_CAST(inode);
}
}
mutex_unlock(&info->bfs_lock);
d_add(dentry, inode);
return NULL;
}
static int bfs_link(struct dentry *old, struct inode *dir,
struct dentry *new)
{
struct inode *inode = old->d_inode;
struct bfs_sb_info *info = BFS_SB(inode->i_sb);
int err;
mutex_lock(&info->bfs_lock);
err = bfs_add_entry(dir, new->d_name.name, new->d_name.len,
inode->i_ino);
if (err) {
mutex_unlock(&info->bfs_lock);
return err;
}
inc_nlink(inode);
inode->i_ctime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
ihold(inode);
d_instantiate(new, inode);
mutex_unlock(&info->bfs_lock);
return 0;
}
static int bfs_unlink(struct inode *dir, struct dentry *dentry)
{
int error = -ENOENT;
struct inode *inode = dentry->d_inode;
struct buffer_head *bh;
struct bfs_dirent *de;
struct bfs_sb_info *info = BFS_SB(inode->i_sb);
mutex_lock(&info->bfs_lock);
bh = bfs_find_entry(dir, dentry->d_name.name, dentry->d_name.len, &de);
if (!bh || (le16_to_cpu(de->ino) != inode->i_ino))
goto out_brelse;
if (!inode->i_nlink) {
printf("unlinking non-existent file %s:%lu (nlink=%d)\n",
inode->i_sb->s_id, inode->i_ino,
inode->i_nlink);
set_nlink(inode, 1);
}
de->ino = 0;
mark_buffer_dirty_inode(bh, dir);
dir->i_ctime = dir->i_mtime = CURRENT_TIME_SEC;
mark_inode_dirty(dir);
inode->i_ctime = dir->i_ctime;
inode_dec_link_count(inode);
error = 0;
out_brelse:
brelse(bh);
mutex_unlock(&info->bfs_lock);
return error;
}
static int bfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
struct inode *old_inode, *new_inode;
struct buffer_head *old_bh, *new_bh;
struct bfs_dirent *old_de, *new_de;
struct bfs_sb_info *info;
int error = -ENOENT;
old_bh = new_bh = NULL;
old_inode = old_dentry->d_inode;
if (S_ISDIR(old_inode->i_mode))
return -EINVAL;
info = BFS_SB(old_inode->i_sb);
mutex_lock(&info->bfs_lock);
old_bh = bfs_find_entry(old_dir,
old_dentry->d_name.name,
old_dentry->d_name.len, &old_de);
if (!old_bh || (le16_to_cpu(old_de->ino) != old_inode->i_ino))
goto end_rename;
error = -EPERM;
new_inode = new_dentry->d_inode;
new_bh = bfs_find_entry(new_dir,
new_dentry->d_name.name,
new_dentry->d_name.len, &new_de);
if (new_bh && !new_inode) {
brelse(new_bh);
new_bh = NULL;
}
if (!new_bh) {
error = bfs_add_entry(new_dir,
new_dentry->d_name.name,
new_dentry->d_name.len,
old_inode->i_ino);
if (error)
goto end_rename;
}
old_de->ino = 0;
old_dir->i_ctime = old_dir->i_mtime = CURRENT_TIME_SEC;
mark_inode_dirty(old_dir);
if (new_inode) {
new_inode->i_ctime = CURRENT_TIME_SEC;
inode_dec_link_count(new_inode);
}
mark_buffer_dirty_inode(old_bh, old_dir);
error = 0;
end_rename:
mutex_unlock(&info->bfs_lock);
brelse(old_bh);
brelse(new_bh);
return error;
}
const struct inode_operations bfs_dir_inops = {
.create = bfs_create,
.lookup = bfs_lookup,
.link = bfs_link,
.unlink = bfs_unlink,
.rename = bfs_rename,
};
static int bfs_add_entry(struct inode *dir, const unsigned char *name,
int namelen, int ino)
{
struct buffer_head *bh;
struct bfs_dirent *de;
int block, sblock, eblock, off, pos;
int i;
dprintf("name=%s, namelen=%d\n", name, namelen);
if (!namelen)
return -ENOENT;
if (namelen > BFS_NAMELEN)
return -ENAMETOOLONG;
sblock = BFS_I(dir)->i_sblock;
eblock = BFS_I(dir)->i_eblock;
for (block = sblock; block <= eblock; block++) {
bh = sb_bread(dir->i_sb, block);
if (!bh)
return -ENOSPC;
for (off = 0; off < BFS_BSIZE; off += BFS_DIRENT_SIZE) {
de = (struct bfs_dirent *)(bh->b_data + off);
if (!de->ino) {
pos = (block - sblock) * BFS_BSIZE + off;
if (pos >= dir->i_size) {
dir->i_size += BFS_DIRENT_SIZE;
dir->i_ctime = CURRENT_TIME_SEC;
}
dir->i_mtime = CURRENT_TIME_SEC;
mark_inode_dirty(dir);
de->ino = cpu_to_le16((u16)ino);
for (i = 0; i < BFS_NAMELEN; i++)
de->name[i] =
(i < namelen) ? name[i] : 0;
mark_buffer_dirty_inode(bh, dir);
brelse(bh);
return 0;
}
}
brelse(bh);
}
return -ENOSPC;
}
static inline int bfs_namecmp(int len, const unsigned char *name,
const char *buffer)
{
if ((len < BFS_NAMELEN) && buffer[len])
return 0;
return !memcmp(name, buffer, len);
}
static struct buffer_head *bfs_find_entry(struct inode *dir,
const unsigned char *name, int namelen,
struct bfs_dirent **res_dir)
{
unsigned long block = 0, offset = 0;
struct buffer_head *bh = NULL;
struct bfs_dirent *de;
*res_dir = NULL;
if (namelen > BFS_NAMELEN)
return NULL;
while (block * BFS_BSIZE + offset < dir->i_size) {
if (!bh) {
bh = sb_bread(dir->i_sb, BFS_I(dir)->i_sblock + block);
if (!bh) {
block++;
continue;
}
}
de = (struct bfs_dirent *)(bh->b_data + offset);
offset += BFS_DIRENT_SIZE;
if (le16_to_cpu(de->ino) &&
bfs_namecmp(namelen, name, de->name)) {
*res_dir = de;
return bh;
}
if (offset < bh->b_size)
continue;
brelse(bh);
bh = NULL;
offset = 0;
block++;
}
brelse(bh);
return NULL;
}
| gpl-2.0 |
Gava97/android_kernel_samsung_GT-i9301 | drivers/mmc/host/bfin_sdh.c | 4966 | 16098 | /*
* bfin_sdh.c - Analog Devices Blackfin SDH Controller
*
* Copyright (C) 2007-2009 Analog Device Inc.
*
* Licensed under the GPL-2 or later.
*/
#define DRIVER_NAME "bfin-sdh"
#include <linux/module.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/mmc/host.h>
#include <linux/proc_fs.h>
#include <linux/gfp.h>
#include <asm/cacheflush.h>
#include <asm/dma.h>
#include <asm/portmux.h>
#include <asm/bfin_sdh.h>
#if defined(CONFIG_BF51x)
#define bfin_read_SDH_PWR_CTL bfin_read_RSI_PWR_CTL
#define bfin_write_SDH_PWR_CTL bfin_write_RSI_PWR_CTL
#define bfin_read_SDH_CLK_CTL bfin_read_RSI_CLK_CTL
#define bfin_write_SDH_CLK_CTL bfin_write_RSI_CLK_CTL
#define bfin_write_SDH_ARGUMENT bfin_write_RSI_ARGUMENT
#define bfin_write_SDH_COMMAND bfin_write_RSI_COMMAND
#define bfin_write_SDH_DATA_TIMER bfin_write_RSI_DATA_TIMER
#define bfin_read_SDH_RESPONSE0 bfin_read_RSI_RESPONSE0
#define bfin_read_SDH_RESPONSE1 bfin_read_RSI_RESPONSE1
#define bfin_read_SDH_RESPONSE2 bfin_read_RSI_RESPONSE2
#define bfin_read_SDH_RESPONSE3 bfin_read_RSI_RESPONSE3
#define bfin_write_SDH_DATA_LGTH bfin_write_RSI_DATA_LGTH
#define bfin_read_SDH_DATA_CTL bfin_read_RSI_DATA_CTL
#define bfin_write_SDH_DATA_CTL bfin_write_RSI_DATA_CTL
#define bfin_read_SDH_DATA_CNT bfin_read_RSI_DATA_CNT
#define bfin_write_SDH_STATUS_CLR bfin_write_RSI_STATUS_CLR
#define bfin_read_SDH_E_STATUS bfin_read_RSI_E_STATUS
#define bfin_write_SDH_E_STATUS bfin_write_RSI_E_STATUS
#define bfin_read_SDH_STATUS bfin_read_RSI_STATUS
#define bfin_write_SDH_MASK0 bfin_write_RSI_MASK0
#define bfin_read_SDH_CFG bfin_read_RSI_CFG
#define bfin_write_SDH_CFG bfin_write_RSI_CFG
#endif
struct dma_desc_array {
unsigned long start_addr;
unsigned short cfg;
unsigned short x_count;
short x_modify;
} __packed;
struct sdh_host {
struct mmc_host *mmc;
spinlock_t lock;
struct resource *res;
void __iomem *base;
int irq;
int stat_irq;
int dma_ch;
int dma_dir;
struct dma_desc_array *sg_cpu;
dma_addr_t sg_dma;
int dma_len;
unsigned int imask;
unsigned int power_mode;
unsigned int clk_div;
struct mmc_request *mrq;
struct mmc_command *cmd;
struct mmc_data *data;
};
static struct bfin_sd_host *get_sdh_data(struct platform_device *pdev)
{
return pdev->dev.platform_data;
}
static void sdh_stop_clock(struct sdh_host *host)
{
bfin_write_SDH_CLK_CTL(bfin_read_SDH_CLK_CTL() & ~CLK_E);
SSYNC();
}
static void sdh_enable_stat_irq(struct sdh_host *host, unsigned int mask)
{
unsigned long flags;
spin_lock_irqsave(&host->lock, flags);
host->imask |= mask;
bfin_write_SDH_MASK0(mask);
SSYNC();
spin_unlock_irqrestore(&host->lock, flags);
}
static void sdh_disable_stat_irq(struct sdh_host *host, unsigned int mask)
{
unsigned long flags;
spin_lock_irqsave(&host->lock, flags);
host->imask &= ~mask;
bfin_write_SDH_MASK0(host->imask);
SSYNC();
spin_unlock_irqrestore(&host->lock, flags);
}
static int sdh_setup_data(struct sdh_host *host, struct mmc_data *data)
{
unsigned int length;
unsigned int data_ctl;
unsigned int dma_cfg;
unsigned int cycle_ns, timeout;
dev_dbg(mmc_dev(host->mmc), "%s enter flags: 0x%x\n", __func__, data->flags);
host->data = data;
data_ctl = 0;
dma_cfg = 0;
length = data->blksz * data->blocks;
bfin_write_SDH_DATA_LGTH(length);
if (data->flags & MMC_DATA_STREAM)
data_ctl |= DTX_MODE;
if (data->flags & MMC_DATA_READ)
data_ctl |= DTX_DIR;
/* Only supports power-of-2 block size */
if (data->blksz & (data->blksz - 1))
return -EINVAL;
data_ctl |= ((ffs(data->blksz) - 1) << 4);
bfin_write_SDH_DATA_CTL(data_ctl);
/* the time of a host clock period in ns */
cycle_ns = 1000000000 / (get_sclk() / (2 * (host->clk_div + 1)));
timeout = data->timeout_ns / cycle_ns;
timeout += data->timeout_clks;
bfin_write_SDH_DATA_TIMER(timeout);
SSYNC();
if (data->flags & MMC_DATA_READ) {
host->dma_dir = DMA_FROM_DEVICE;
dma_cfg |= WNR;
} else
host->dma_dir = DMA_TO_DEVICE;
sdh_enable_stat_irq(host, (DAT_CRC_FAIL | DAT_TIME_OUT | DAT_END));
host->dma_len = dma_map_sg(mmc_dev(host->mmc), data->sg, data->sg_len, host->dma_dir);
#if defined(CONFIG_BF54x)
dma_cfg |= DMAFLOW_ARRAY | NDSIZE_5 | RESTART | WDSIZE_32 | DMAEN;
{
struct scatterlist *sg;
int i;
for_each_sg(data->sg, sg, host->dma_len, i) {
host->sg_cpu[i].start_addr = sg_dma_address(sg);
host->sg_cpu[i].cfg = dma_cfg;
host->sg_cpu[i].x_count = sg_dma_len(sg) / 4;
host->sg_cpu[i].x_modify = 4;
dev_dbg(mmc_dev(host->mmc), "%d: start_addr:0x%lx, "
"cfg:0x%x, x_count:0x%x, x_modify:0x%x\n",
i, host->sg_cpu[i].start_addr,
host->sg_cpu[i].cfg, host->sg_cpu[i].x_count,
host->sg_cpu[i].x_modify);
}
}
flush_dcache_range((unsigned int)host->sg_cpu,
(unsigned int)host->sg_cpu +
host->dma_len * sizeof(struct dma_desc_array));
/* Set the last descriptor to stop mode */
host->sg_cpu[host->dma_len - 1].cfg &= ~(DMAFLOW | NDSIZE);
host->sg_cpu[host->dma_len - 1].cfg |= DI_EN;
set_dma_curr_desc_addr(host->dma_ch, (unsigned long *)host->sg_dma);
set_dma_x_count(host->dma_ch, 0);
set_dma_x_modify(host->dma_ch, 0);
set_dma_config(host->dma_ch, dma_cfg);
#elif defined(CONFIG_BF51x)
/* RSI DMA doesn't work in array mode */
dma_cfg |= WDSIZE_32 | DMAEN;
set_dma_start_addr(host->dma_ch, sg_dma_address(&data->sg[0]));
set_dma_x_count(host->dma_ch, length / 4);
set_dma_x_modify(host->dma_ch, 4);
set_dma_config(host->dma_ch, dma_cfg);
#endif
bfin_write_SDH_DATA_CTL(bfin_read_SDH_DATA_CTL() | DTX_DMA_E | DTX_E);
SSYNC();
dev_dbg(mmc_dev(host->mmc), "%s exit\n", __func__);
return 0;
}
static void sdh_start_cmd(struct sdh_host *host, struct mmc_command *cmd)
{
unsigned int sdh_cmd;
unsigned int stat_mask;
dev_dbg(mmc_dev(host->mmc), "%s enter cmd: 0x%p\n", __func__, cmd);
WARN_ON(host->cmd != NULL);
host->cmd = cmd;
sdh_cmd = 0;
stat_mask = 0;
sdh_cmd |= cmd->opcode;
if (cmd->flags & MMC_RSP_PRESENT) {
sdh_cmd |= CMD_RSP;
stat_mask |= CMD_RESP_END;
} else {
stat_mask |= CMD_SENT;
}
if (cmd->flags & MMC_RSP_136)
sdh_cmd |= CMD_L_RSP;
stat_mask |= CMD_CRC_FAIL | CMD_TIME_OUT;
sdh_enable_stat_irq(host, stat_mask);
bfin_write_SDH_ARGUMENT(cmd->arg);
bfin_write_SDH_COMMAND(sdh_cmd | CMD_E);
bfin_write_SDH_CLK_CTL(bfin_read_SDH_CLK_CTL() | CLK_E);
SSYNC();
}
static void sdh_finish_request(struct sdh_host *host, struct mmc_request *mrq)
{
dev_dbg(mmc_dev(host->mmc), "%s enter\n", __func__);
host->mrq = NULL;
host->cmd = NULL;
host->data = NULL;
mmc_request_done(host->mmc, mrq);
}
static int sdh_cmd_done(struct sdh_host *host, unsigned int stat)
{
struct mmc_command *cmd = host->cmd;
int ret = 0;
dev_dbg(mmc_dev(host->mmc), "%s enter cmd: %p\n", __func__, cmd);
if (!cmd)
return 0;
host->cmd = NULL;
if (cmd->flags & MMC_RSP_PRESENT) {
cmd->resp[0] = bfin_read_SDH_RESPONSE0();
if (cmd->flags & MMC_RSP_136) {
cmd->resp[1] = bfin_read_SDH_RESPONSE1();
cmd->resp[2] = bfin_read_SDH_RESPONSE2();
cmd->resp[3] = bfin_read_SDH_RESPONSE3();
}
}
if (stat & CMD_TIME_OUT)
cmd->error = -ETIMEDOUT;
else if (stat & CMD_CRC_FAIL && cmd->flags & MMC_RSP_CRC)
cmd->error = -EILSEQ;
sdh_disable_stat_irq(host, (CMD_SENT | CMD_RESP_END | CMD_TIME_OUT | CMD_CRC_FAIL));
if (host->data && !cmd->error) {
if (host->data->flags & MMC_DATA_WRITE) {
ret = sdh_setup_data(host, host->data);
if (ret)
return 0;
}
sdh_enable_stat_irq(host, DAT_END | RX_OVERRUN | TX_UNDERRUN | DAT_TIME_OUT);
} else
sdh_finish_request(host, host->mrq);
return 1;
}
static int sdh_data_done(struct sdh_host *host, unsigned int stat)
{
struct mmc_data *data = host->data;
dev_dbg(mmc_dev(host->mmc), "%s enter stat: 0x%x\n", __func__, stat);
if (!data)
return 0;
disable_dma(host->dma_ch);
dma_unmap_sg(mmc_dev(host->mmc), data->sg, data->sg_len,
host->dma_dir);
if (stat & DAT_TIME_OUT)
data->error = -ETIMEDOUT;
else if (stat & DAT_CRC_FAIL)
data->error = -EILSEQ;
else if (stat & (RX_OVERRUN | TX_UNDERRUN))
data->error = -EIO;
if (!data->error)
data->bytes_xfered = data->blocks * data->blksz;
else
data->bytes_xfered = 0;
sdh_disable_stat_irq(host, DAT_END | DAT_TIME_OUT | DAT_CRC_FAIL | RX_OVERRUN | TX_UNDERRUN);
bfin_write_SDH_STATUS_CLR(DAT_END_STAT | DAT_TIMEOUT_STAT | \
DAT_CRC_FAIL_STAT | DAT_BLK_END_STAT | RX_OVERRUN | TX_UNDERRUN);
bfin_write_SDH_DATA_CTL(0);
SSYNC();
host->data = NULL;
if (host->mrq->stop) {
sdh_stop_clock(host);
sdh_start_cmd(host, host->mrq->stop);
} else {
sdh_finish_request(host, host->mrq);
}
return 1;
}
static void sdh_request(struct mmc_host *mmc, struct mmc_request *mrq)
{
struct sdh_host *host = mmc_priv(mmc);
int ret = 0;
dev_dbg(mmc_dev(host->mmc), "%s enter, mrp:%p, cmd:%p\n", __func__, mrq, mrq->cmd);
WARN_ON(host->mrq != NULL);
host->mrq = mrq;
host->data = mrq->data;
if (mrq->data && mrq->data->flags & MMC_DATA_READ) {
ret = sdh_setup_data(host, mrq->data);
if (ret)
return;
}
sdh_start_cmd(host, mrq->cmd);
}
static void sdh_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
{
struct sdh_host *host;
unsigned long flags;
u16 clk_ctl = 0;
u16 pwr_ctl = 0;
u16 cfg;
host = mmc_priv(mmc);
spin_lock_irqsave(&host->lock, flags);
if (ios->clock) {
unsigned long sys_clk, ios_clk;
unsigned char clk_div;
ios_clk = 2 * ios->clock;
sys_clk = get_sclk();
clk_div = sys_clk / ios_clk;
if (sys_clk % ios_clk == 0)
clk_div -= 1;
clk_div = min_t(unsigned char, clk_div, 0xFF);
clk_ctl |= clk_div;
clk_ctl |= CLK_E;
host->clk_div = clk_div;
} else
sdh_stop_clock(host);
if (ios->bus_mode == MMC_BUSMODE_OPENDRAIN)
#ifdef CONFIG_SDH_BFIN_MISSING_CMD_PULLUP_WORKAROUND
pwr_ctl |= ROD_CTL;
#else
pwr_ctl |= SD_CMD_OD | ROD_CTL;
#endif
if (ios->bus_width == MMC_BUS_WIDTH_4) {
cfg = bfin_read_SDH_CFG();
cfg &= ~PD_SDDAT3;
cfg |= PUP_SDDAT3;
/* Enable 4 bit SDIO */
cfg |= (SD4E | MWE);
bfin_write_SDH_CFG(cfg);
clk_ctl |= WIDE_BUS;
} else {
cfg = bfin_read_SDH_CFG();
cfg |= MWE;
bfin_write_SDH_CFG(cfg);
}
bfin_write_SDH_CLK_CTL(clk_ctl);
host->power_mode = ios->power_mode;
if (ios->power_mode == MMC_POWER_ON)
pwr_ctl |= PWR_ON;
bfin_write_SDH_PWR_CTL(pwr_ctl);
SSYNC();
spin_unlock_irqrestore(&host->lock, flags);
dev_dbg(mmc_dev(host->mmc), "SDH: clk_div = 0x%x actual clock:%ld expected clock:%d\n",
host->clk_div,
host->clk_div ? get_sclk() / (2 * (host->clk_div + 1)) : 0,
ios->clock);
}
static const struct mmc_host_ops sdh_ops = {
.request = sdh_request,
.set_ios = sdh_set_ios,
};
static irqreturn_t sdh_dma_irq(int irq, void *devid)
{
struct sdh_host *host = devid;
dev_dbg(mmc_dev(host->mmc), "%s enter, irq_stat: 0x%04x\n", __func__,
get_dma_curr_irqstat(host->dma_ch));
clear_dma_irqstat(host->dma_ch);
SSYNC();
return IRQ_HANDLED;
}
static irqreturn_t sdh_stat_irq(int irq, void *devid)
{
struct sdh_host *host = devid;
unsigned int status;
int handled = 0;
dev_dbg(mmc_dev(host->mmc), "%s enter\n", __func__);
status = bfin_read_SDH_E_STATUS();
if (status & SD_CARD_DET) {
mmc_detect_change(host->mmc, 0);
bfin_write_SDH_E_STATUS(SD_CARD_DET);
}
status = bfin_read_SDH_STATUS();
if (status & (CMD_SENT | CMD_RESP_END | CMD_TIME_OUT | CMD_CRC_FAIL)) {
handled |= sdh_cmd_done(host, status);
bfin_write_SDH_STATUS_CLR(CMD_SENT_STAT | CMD_RESP_END_STAT | \
CMD_TIMEOUT_STAT | CMD_CRC_FAIL_STAT);
SSYNC();
}
status = bfin_read_SDH_STATUS();
if (status & (DAT_END | DAT_TIME_OUT | DAT_CRC_FAIL | RX_OVERRUN | TX_UNDERRUN))
handled |= sdh_data_done(host, status);
dev_dbg(mmc_dev(host->mmc), "%s exit\n\n", __func__);
return IRQ_RETVAL(handled);
}
static int __devinit sdh_probe(struct platform_device *pdev)
{
struct mmc_host *mmc;
struct sdh_host *host;
struct bfin_sd_host *drv_data = get_sdh_data(pdev);
int ret;
if (!drv_data) {
dev_err(&pdev->dev, "missing platform driver data\n");
ret = -EINVAL;
goto out;
}
mmc = mmc_alloc_host(sizeof(struct sdh_host), &pdev->dev);
if (!mmc) {
ret = -ENOMEM;
goto out;
}
mmc->ops = &sdh_ops;
mmc->max_segs = 32;
mmc->max_seg_size = 1 << 16;
mmc->max_blk_size = 1 << 11;
mmc->max_blk_count = 1 << 11;
mmc->max_req_size = PAGE_SIZE;
mmc->ocr_avail = MMC_VDD_32_33 | MMC_VDD_33_34;
mmc->f_max = get_sclk();
mmc->f_min = mmc->f_max >> 9;
mmc->caps = MMC_CAP_4_BIT_DATA | MMC_CAP_NEEDS_POLL;
host = mmc_priv(mmc);
host->mmc = mmc;
spin_lock_init(&host->lock);
host->irq = drv_data->irq_int0;
host->dma_ch = drv_data->dma_chan;
ret = request_dma(host->dma_ch, DRIVER_NAME "DMA");
if (ret) {
dev_err(&pdev->dev, "unable to request DMA channel\n");
goto out1;
}
ret = set_dma_callback(host->dma_ch, sdh_dma_irq, host);
if (ret) {
dev_err(&pdev->dev, "unable to request DMA irq\n");
goto out2;
}
host->sg_cpu = dma_alloc_coherent(&pdev->dev, PAGE_SIZE, &host->sg_dma, GFP_KERNEL);
if (host->sg_cpu == NULL) {
ret = -ENOMEM;
goto out2;
}
platform_set_drvdata(pdev, mmc);
mmc_add_host(mmc);
ret = request_irq(host->irq, sdh_stat_irq, 0, "SDH Status IRQ", host);
if (ret) {
dev_err(&pdev->dev, "unable to request status irq\n");
goto out3;
}
ret = peripheral_request_list(drv_data->pin_req, DRIVER_NAME);
if (ret) {
dev_err(&pdev->dev, "unable to request peripheral pins\n");
goto out4;
}
#if defined(CONFIG_BF54x)
/* Secure Digital Host shares DMA with Nand controller */
bfin_write_DMAC1_PERIMUX(bfin_read_DMAC1_PERIMUX() | 0x1);
#endif
bfin_write_SDH_CFG(bfin_read_SDH_CFG() | CLKS_EN);
SSYNC();
/* Disable card inserting detection pin. set MMC_CAP_NEES_POLL, and
* mmc stack will do the detection.
*/
bfin_write_SDH_CFG((bfin_read_SDH_CFG() & 0x1F) | (PUP_SDDAT | PUP_SDDAT3));
SSYNC();
return 0;
out4:
free_irq(host->irq, host);
out3:
mmc_remove_host(mmc);
dma_free_coherent(&pdev->dev, PAGE_SIZE, host->sg_cpu, host->sg_dma);
out2:
free_dma(host->dma_ch);
out1:
mmc_free_host(mmc);
out:
return ret;
}
static int __devexit sdh_remove(struct platform_device *pdev)
{
struct mmc_host *mmc = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
if (mmc) {
struct sdh_host *host = mmc_priv(mmc);
mmc_remove_host(mmc);
sdh_stop_clock(host);
free_irq(host->irq, host);
free_dma(host->dma_ch);
dma_free_coherent(&pdev->dev, PAGE_SIZE, host->sg_cpu, host->sg_dma);
mmc_free_host(mmc);
}
return 0;
}
#ifdef CONFIG_PM
static int sdh_suspend(struct platform_device *dev, pm_message_t state)
{
struct mmc_host *mmc = platform_get_drvdata(dev);
struct bfin_sd_host *drv_data = get_sdh_data(dev);
int ret = 0;
if (mmc)
ret = mmc_suspend_host(mmc);
bfin_write_SDH_PWR_CTL(bfin_read_SDH_PWR_CTL() & ~PWR_ON);
peripheral_free_list(drv_data->pin_req);
return ret;
}
static int sdh_resume(struct platform_device *dev)
{
struct mmc_host *mmc = platform_get_drvdata(dev);
struct bfin_sd_host *drv_data = get_sdh_data(dev);
int ret = 0;
ret = peripheral_request_list(drv_data->pin_req, DRIVER_NAME);
if (ret) {
dev_err(&dev->dev, "unable to request peripheral pins\n");
return ret;
}
bfin_write_SDH_PWR_CTL(bfin_read_SDH_PWR_CTL() | PWR_ON);
#if defined(CONFIG_BF54x)
/* Secure Digital Host shares DMA with Nand controller */
bfin_write_DMAC1_PERIMUX(bfin_read_DMAC1_PERIMUX() | 0x1);
#endif
bfin_write_SDH_CFG(bfin_read_SDH_CFG() | CLKS_EN);
SSYNC();
bfin_write_SDH_CFG((bfin_read_SDH_CFG() & 0x1F) | (PUP_SDDAT | PUP_SDDAT3));
SSYNC();
if (mmc)
ret = mmc_resume_host(mmc);
return ret;
}
#else
# define sdh_suspend NULL
# define sdh_resume NULL
#endif
static struct platform_driver sdh_driver = {
.probe = sdh_probe,
.remove = __devexit_p(sdh_remove),
.suspend = sdh_suspend,
.resume = sdh_resume,
.driver = {
.name = DRIVER_NAME,
},
};
module_platform_driver(sdh_driver);
MODULE_DESCRIPTION("Blackfin Secure Digital Host Driver");
MODULE_AUTHOR("Cliff Cai, Roy Huang");
MODULE_LICENSE("GPL");
| gpl-2.0 |
deonblaauw/paparazzi | sw/airborne/arch/lpc21/efsl/src/fs.c | 103 | 18106 | /*****************************************************************************\
* efs - General purpose Embedded Filesystem library *
* --------------------- ----------------------------------- *
* *
* Filename : fs.c *
* Description : These are general filesystem functions, supported by the *
* functions of dir.c and fat.c file.c uses these functions *
* heavily, but is not used by fs.c (not true anymore) *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; version 2 *
* of the License. *
*
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* As a special exception, if other files instantiate templates or *
* use macros or inline functions from this file, or you compile this *
* file and link it with other works to produce a work based on this file, *
* this file does not by itself cause the resulting work to be covered *
* by the GNU General Public License. However the source code for this *
* file must still be made available in accordance with section (3) of *
* the GNU General Public License. *
* *
* This exception does not invalidate any other reasons why a work based *
* on this file might be covered by the GNU General Public License. *
* *
* (c)2006 Lennart Yseboodt *
* (c)2006 Michael De Nil *
\*****************************************************************************/
/*****************************************************************************/
#include "fs.h"
#include "fat.h"
#include "dir.h"
/*****************************************************************************/
/* ****************************************************************************
* eint16 fs_initFs(FileSystem *fs,Partition *part)
* Description: This functions glues the initialisation of the filesystem together.
* It loads the volumeID, computes the FS type and searches for the rootsector.
* Return value: Returns 0 on succes and -1 on error (if magic code is wrong)
*/
eint16 fs_initFs(FileSystem *fs,Partition *part)
{
if(!fs_isValidFat(part)){
return(-1);
}
fs->part=part;
fs_loadVolumeId(fs,part);
if(!fs_verifySanity(fs))return(-2);
fs_countDataSectors(fs);
fs_determineFatType(fs);
fs_findFirstSectorRootDir(fs);
fs_initCurrentDir(fs);
return(0);
}
/*****************************************************************************/
/* ****************************************************************************
* eint16 fs_isValidFat(Partition *part)
* Description: This functions loads the volumeID and checks if the magic
* value is present.
* Return value: returns 0 when magic code is missing, 1 if it is there.
*/
eint16 fs_isValidFat(Partition *part)
{
euint8 *buf;
buf=part_getSect(part,0,IOM_MODE_READONLY|IOM_MODE_EXP_REQ); /* Load Volume label */
if( ex_getb16(buf,0x1FE) != 0xAA55 ){
return (0);
}
part_relSect(part,buf);
return(1);
}
/*****************************************************************************/
/* ****************************************************************************
* void fs_loadVolumeId(FileSystem *fs, Partition *part)
* Description: This function loads all relevant fields from the volumeid.
*/
void fs_loadVolumeId(FileSystem *fs, Partition *part)
{
euint8 *buf;
buf=part_getSect(part,0,IOM_MODE_READONLY|IOM_MODE_EXP_REQ);
fs->volumeId.BytesPerSector=ex_getb16(buf,0x0B);
fs->volumeId.SectorsPerCluster=*((eint8*)(buf+0x0D));
fs->volumeId.ReservedSectorCount=ex_getb16(buf,0x0E);
fs->volumeId.NumberOfFats=*((eint8*)(buf+0x10));
fs->volumeId.RootEntryCount=ex_getb16(buf,0x11);
fs->volumeId.SectorCount16=ex_getb16(buf,0x13);
fs->volumeId.FatSectorCount16=ex_getb16(buf,0x16);
fs->volumeId.SectorCount32=ex_getb32(buf,0x20);
fs->volumeId.FatSectorCount32=ex_getb32(buf,0x24);
fs->volumeId.RootCluster=ex_getb32(buf,0x2C);
part_relSect(part,buf);
}
/*****************************************************************************/
/* ****************************************************************************
* esint16 fs_verifySanity(FileSystem *fs)
* Description: Does some sanity calculations.
* Return value: 1 on success, 0 when discrepancies were found.
*/
esint16 fs_verifySanity(FileSystem *fs)
{
esint16 sane=1; /* Sane until proven otherwise */
/* First check, BPS, we only support 512 */
if(fs->volumeId.BytesPerSector!=512)sane=0;
/* Check is SPC is valid (multiple of 2, and clustersize >=32KB */
if(!((fs->volumeId.SectorsPerCluster == 1 ) |
(fs->volumeId.SectorsPerCluster == 2 ) |
(fs->volumeId.SectorsPerCluster == 4 ) |
(fs->volumeId.SectorsPerCluster == 8 ) |
(fs->volumeId.SectorsPerCluster == 16) |
(fs->volumeId.SectorsPerCluster == 32) |
(fs->volumeId.SectorsPerCluster == 64) ))sane=0;
/* Any number of FAT's should be supported... (untested) */
/* There should be at least 1 reserved sector */
if(fs->volumeId.ReservedSectorCount==0)sane=0;
if(fs->volumeId.FatSectorCount16 != 0){
if(fs->volumeId.FatSectorCount16 > fs->part->disc->partitions[fs->part->activePartition].numSectors)sane=0;
}else{
if(fs->volumeId.FatSectorCount32 > fs->part->disc->partitions[fs->part->activePartition].numSectors)sane=0;
}
return(sane);
}
/*****************************************************************************/
/* ****************************************************************************
* void fs_countDataSectors(FileSystem *fs)
* Description: This functions calculates the sectorcounts, fatsectorcounts and
* dataclustercounts. It fills in the general fields.
*/
void fs_countDataSectors(FileSystem *fs)
{
euint32 rootDirSectors,dataSectorCount;
rootDirSectors=((fs->volumeId.RootEntryCount*32) +
(fs->volumeId.BytesPerSector - 1)) /
fs->volumeId.BytesPerSector;
if(fs->volumeId.FatSectorCount16 != 0)
{
fs->FatSectorCount=fs->volumeId.FatSectorCount16;
fs->volumeId.FatSectorCount32=0;
}
else
{
fs->FatSectorCount=fs->volumeId.FatSectorCount32;
fs->volumeId.FatSectorCount16=0;
}
if(fs->volumeId.SectorCount16!=0)
{
fs->SectorCount=fs->volumeId.SectorCount16;
fs->volumeId.SectorCount32=0;
}
else
{
fs->SectorCount=fs->volumeId.SectorCount32;
fs->volumeId.SectorCount16=0;
}
dataSectorCount=fs->SectorCount - (
fs->volumeId.ReservedSectorCount +
(fs->volumeId.NumberOfFats * fs->FatSectorCount) +
rootDirSectors);
fs->DataClusterCount=dataSectorCount/fs->volumeId.SectorsPerCluster;
}
/*****************************************************************************/
/* ****************************************************************************
* void fs_determineFatType(FileSystem *fs)
* Description: This function looks af the Dataclustercount and determines the
* FAT type. It fills in fs->type.
*/
void fs_determineFatType(FileSystem *fs)
{
if(fs->DataClusterCount < 4085)
{
fs->type=FAT12;
fs->volumeId.RootCluster=0;
}
else if(fs->DataClusterCount < 65525)
{
fs->type=FAT16;
fs->volumeId.RootCluster=0;
}
else
{
fs->type=FAT32;
}
}
/*****************************************************************************/
/* ****************************************************************************
* void fs_findFirstSectorRootDir(FileSystem *fs)
* Description: This functions fills in the fs->FirstSectorRootDir field, even
* for FAT32, although that is not necessary (because you have FirstClusterRootDir).
*/
void fs_findFirstSectorRootDir(FileSystem *fs)
{
if(fs->type==FAT32)
fs->FirstSectorRootDir = fs->volumeId.ReservedSectorCount +
(fs->volumeId.NumberOfFats*fs->volumeId.FatSectorCount32) +
(fs->volumeId.RootCluster-2)*fs->volumeId.SectorsPerCluster;
else
fs->FirstSectorRootDir = fs->volumeId.ReservedSectorCount +
(fs->volumeId.NumberOfFats*fs->volumeId.FatSectorCount16);
}
/*****************************************************************************/
void fs_initCurrentDir(FileSystem *fs)
{
fs->FirstClusterCurrentDir = fs_getFirstClusterRootDir(fs);
}
/*****************************************************************************/
/* ****************************************************************************
* long fs_clusterToSector(FileSystem *fs,euint32 cluster)
* Description: This function converts a clusternumber in the effective sector
* number where this cluster starts. Boundary check is not implemented
* Return value: A long is returned representing the sectornumber.
*/
euint32 fs_clusterToSector(FileSystem *fs,euint32 cluster)
{
eint32 base;
if(fs->type==FAT32)
{
base=
fs->volumeId.ReservedSectorCount+
fs->FatSectorCount*fs->volumeId.NumberOfFats;
}
else
{
base=
fs->volumeId.ReservedSectorCount+
fs->FatSectorCount*fs->volumeId.NumberOfFats+
fs->volumeId.RootEntryCount/16;
}
return( base + (cluster-2)*fs->volumeId.SectorsPerCluster );
}
/*****************************************************************************/
/* Function is unused, but may be usefull */
euint32 fs_sectorToCluster(FileSystem *fs,euint32 sector)
{
eint32 base;
if(fs->type==FAT32)
{
base=
fs->volumeId.ReservedSectorCount+
fs->FatSectorCount*fs->volumeId.NumberOfFats;
}
else
{
base=
fs->volumeId.ReservedSectorCount+
fs->FatSectorCount*fs->volumeId.NumberOfFats+
fs->volumeId.RootEntryCount/16;
}
return(((sector-base)-((sector-base)%fs->volumeId.SectorsPerCluster))/fs->volumeId.SectorsPerCluster+2 );
}
/*****************************************************************************/
/* ****************************************************************************
* euint32 fs_getNextFreeCluster(FileSystem *fs,euint32 startingcluster)
* Description: This functions searches for a free cluster, starting it's search at
* cluster startingcluster. This allow to speed up searches and try to avoid
* fragmentation. Implementing rollover search is still to be done.
* Return value: If a free cluster is found it's number is returned. If none is
* found 0 is returned.
*/
euint32 fs_getNextFreeCluster(FileSystem *fs,euint32 startingcluster)
{
euint32 r;
while(startingcluster<fs->DataClusterCount){
r=fat_getNextClusterAddress(fs,startingcluster,0);
if(r==0){
return(startingcluster);
}
startingcluster++;
}
return(0);
}
/*****************************************************************************/
/* ****************************************************************************
* euint32 fs_giveFreeClusterHint(FileSystem *fs)
*
* Description: This function should return a clusternumber that is free or
* lies close before free clusters. The result MUST be checked to see if
* it is free! Implementationhint: search the largest clusternumber in the
* files in the rootdirectory.
*
* Return value: Returns it's best guess.
*/
euint32 fs_giveFreeClusterHint(FileSystem *fs)
{
return(2); /* Now THIS is a hint ;) */
}
/*****************************************************************************/
/* ****************************************************************************
* esint8 fs_findFile(FileSystem *fs,eint8* filename,FileLocation *loc,euint32 *lastDir)
*
* Description: This function looks if the given filename is on the given fs
* and, if found, fills in its location in loc.
* The function will first check if the pathname starts with a slash. If so it will
* set the starting directory to the rootdirectory. Else, it will take the firstcluster-
* currentdir (That you can change with chdir()) as startingpoint.
* The lastdir pointer will be the first cluster of the last directory fs_findfile
* enters. It starts out at the root/current dir and then traverses the path along with
* fs_findFile.
* It is set to 0 in case of errors (like dir/dir/dir/file/dir/dir...)
* Return value: Returns 0 when nothing was found, 1 when the thing found
* was a file and 2 if the thing found was a directory.
*/
esint8 fs_findFile(FileSystem *fs,eint8* filename,FileLocation *loc,euint32 *lastDir)
{
euint32 fccd,tmpclus;
eint8 ffname[11],*next,it=0,filefound=0;
if(*filename=='/'){
fccd = fs_getFirstClusterRootDir(fs);
filename++;
if(lastDir)*lastDir=fccd;
if(!*filename){
return(2);
}
}else{
fccd = fs->FirstClusterCurrentDir;
if(lastDir)*lastDir=fccd;
}
while((next=file_normalToFatName(filename,ffname))!=0){
if((tmpclus=dir_findinDir(fs,ffname,fccd,loc,DIRFIND_FILE))==0){
/* We didn't find what we wanted */
/* We should check, to see if there is more after it, so that
* we can invalidate lastDir
*/
if((file_normalToFatName(next,ffname))!=0){
if(lastDir)*lastDir=0;
}
return(0);
}
it++;
if(loc->attrib&ATTR_DIRECTORY){
fccd = tmpclus;
filename = next;
if(lastDir)*lastDir=fccd;
if(filefound)*lastDir=0;
}else{
filefound=1;
if((file_normalToFatName(next,ffname))!=0){
if(lastDir)*lastDir=0;
return(0);
}else{
filename=next;
}
}
}
if(it==0)return(0);
if(loc->attrib&ATTR_DIRECTORY || !filefound)return(2);
return(1);
}
/*****************************************************************************/
esint16 fs_findFreeFile(FileSystem *fs,eint8* filename,FileLocation *loc,euint8 mode)
{
euint32 targetdir=0;
eint8 ffname[11];
if(fs_findFile(fs,filename,loc,&targetdir))return(0);
if(!dir_getFatFileName(filename,ffname))return(0);
if(dir_findinDir(fs,ffname,targetdir,loc,DIRFIND_FREE)){
return(1);
}else{
if(dir_addCluster(fs,targetdir)){
return(0);
}else{
if(dir_findinDir(fs,ffname,targetdir,loc,DIRFIND_FREE)){
return(1);
}
}
}
return(0);
}
/*****************************************************************************/
/* ****************************************************************************
* euint32 fs_getLastCluster(FileSystem *fs,ClusterChain *Cache)
* Description: This function searches the last cluster of a chain.
* Return value: The LastCluster (also stored in cache);
*/
euint32 fs_getLastCluster(FileSystem *fs,ClusterChain *Cache)
{
if(Cache->DiscCluster==0){
Cache->DiscCluster=Cache->FirstCluster;
Cache->LogicCluster=0;
}
if(Cache->LastCluster==0)
{
while(fat_getNextClusterChain(fs, Cache)==0)
{
Cache->LogicCluster+=Cache->Linear;
Cache->DiscCluster+=Cache->Linear;
Cache->Linear=0;
}
}
return(Cache->LastCluster);
}
/*****************************************************************************/
euint32 fs_getFirstClusterRootDir(FileSystem *fs)
{
switch(fs->type){
case FAT32:
return(fs->volumeId.RootCluster);
break;
default:
return(1);
break;
}
}
/*****************************************************************************/
void fs_initClusterChain(FileSystem *fs,ClusterChain *cache,euint32 cluster_addr)
{
cache->FirstCluster=cluster_addr;
cache->DiscCluster=cluster_addr;
cache->LogicCluster=0;
cache->LastCluster=0; /* Warning flag here */
cache->Linear=0;
cache->ClusterCount=0; /* 0 means NOT known */
}
/*****************************************************************************/
void fs_setFirstClusterInDirEntry(FileRecord *rec,euint32 cluster_addr)
{
rec->FirstClusterHigh=cluster_addr>>16;
rec->FirstClusterLow=cluster_addr&0xFFFF;
}
/*****************************************************************************/
esint8 fs_flushFs(FileSystem *fs)
{
return(part_flushPart(fs->part,0,fs->SectorCount));
}
/*****************************************************************************/
esint8 fs_umount(FileSystem *fs)
{
return(fs_flushFs(fs));
}
/*****************************************************************************/
esint8 fs_clearCluster(FileSystem *fs,euint32 cluster)
{
euint16 c;
euint8* buf;
for(c=0;c<(fs->volumeId.SectorsPerCluster);c++){
buf = part_getSect(fs->part,fs_clusterToSector(fs,cluster)+c,IOM_MODE_READWRITE);
memClr(buf,512);
part_relSect(fs->part,buf);
}
return(0);
}
esint8 fs_getFsInfo(FileSystem *fs,euint8 force_update)
{
euint8 *buf;
if(!fs->type==FAT32)return(0);
buf = part_getSect(fs->part,FS_INFO_SECTOR,IOM_MODE_READONLY);
if(ex_getb32(buf,0)!=FSINFO_MAGIC_BEGIN || ex_getb32(buf,508)!=FSINFO_MAGIC_END){
part_relSect(fs->part,buf);
return(-1);
}
fs->FreeClusterCount = ex_getb32(buf,488);
fs->NextFreeCluster = ex_getb32(buf,492);
part_relSect(fs->part,buf);
if(force_update){
fs->FreeClusterCount=fat_countFreeClusters(fs);
}
return(0);
}
esint8 fs_setFsInfo(FileSystem *fs)
{
euint8* buf;
if(!fs->type==FAT32)return(0);
buf = part_getSect(fs->part,FS_INFO_SECTOR,IOM_MODE_READWRITE);
if(ex_getb32(buf,0)!=FSINFO_MAGIC_BEGIN || ex_getb32(buf,508)!=FSINFO_MAGIC_END){
part_relSect(fs->part,buf);
return(-1);
}
ex_setb32(buf,488,fs->FreeClusterCount);
ex_setb32(buf,492,fs->NextFreeCluster);
part_relSect(fs->part,buf);
return(0);
}
| gpl-2.0 |
tyler6389/android_kernel_samsung_superiorlteskt | arch/arm/mvp/pvtcpkm/comm_os_linux.c | 359 | 9390 | /*
* Linux 2.6.32 and later Kernel module for VMware MVP PVTCP Server
*
* Copyright (C) 2010-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 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; see the file COPYING. If not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#line 5
/**
* @file
*
* @brief Linux-specific functions/types.
*/
#include "comm_os.h"
#define DISPATCH_MAX_CYCLES 8192
/* Type definitions */
typedef struct workqueue_struct CommOSWorkQueue;
/* Static data */
static volatile int running;
static int numCpus;
static CommOSWorkQueue *dispatchWQ;
static CommOSDispatchFunc dispatch;
static CommOSWork dispatchWorksNow[NR_CPUS];
static CommOSWork dispatchWorks[NR_CPUS];
static unsigned int dispatchInterval = 1;
static unsigned int dispatchMaxCycles = 2048;
static CommOSWorkQueue *aioWQ;
/**
* @brief Initializes a workqueue consisting of per-cpu kernel threads.
* @param name workqueue name
* @return workqueue handle if successful, NULL otherwise
*/
static inline CommOSWorkQueue *
CreateWorkqueue(const char *name)
{
return create_workqueue(name);
}
/**
* @brief Destroys a workqueue and stops its threads.
* @param[in,out] wq workqueue to destroy.
* @return workqueue handle is successful, NULL otherwise.
*/
static inline void
DestroyWorkqueue(CommOSWorkQueue *wq)
{
destroy_workqueue(wq);
}
/**
* @brief Force execution of a work item.
* @param[in,out] work work item to dequeue.
*/
static inline void
FlushDelayedWork(CommOSWork *work)
{
flush_delayed_work(work);
}
/**
* @brief Enqueue a work item to a workqueue for execution on a given cpu
* and after the specified interval.
* @param cpu cpu number. If negative, work item is enqueued on current cpu.
* @param[in,out] wq target work queue.
* @param[in,out] work work item to enqueue.
* @param jif delay interval.
* @return zero if successful, non-zero otherwise.
*/
static inline int
QueueDelayedWorkOn(int cpu,
CommOSWorkQueue *wq,
CommOSWork *work,
unsigned long jif)
{
if (cpu < 0) {
return !queue_delayed_work(wq, work, jif) ? -1 : 0;
} else {
return !queue_delayed_work_on(cpu, wq, work, jif) ? -1 : 0;
}
}
/**
* @brief Enqueues a work item to a workqueue for execution on the current cpu
* and after the specified interval.
* @param[in,out] wq target work queue.
* @param[in,out] work work item to enqueue.
* @param jif delay interval.
* @return zero if successful, non-zero otherwise.
*/
static inline int
QueueDelayedWork(CommOSWorkQueue *wq,
CommOSWork *work,
unsigned long jif)
{
return QueueDelayedWorkOn(-1, wq, work, jif);
}
/**
* @brief Cancels a queued delayed work item and synchronizes with its
* completion.
* @param[in,out] work work item to cancel
*/
static inline void
WaitForDelayedWork(CommOSWork *work)
{
cancel_delayed_work_sync(work);
}
/**
* @brief Discards work items queued to the specified workqueue.
* @param[in,out] wq work queue to flush.
*/
static inline void
FlushWorkqueue(CommOSWorkQueue *wq)
{
flush_workqueue(wq);
}
/**
* @brief Schedules dispatcher threads for immediate execution.
*/
void
CommOS_ScheduleDisp(void)
{
CommOSWork *work = &dispatchWorksNow[get_cpu()];
put_cpu();
if (running) {
QueueDelayedWork(dispatchWQ, work, 0);
}
}
/**
* @brief Default delayed work callback function implementation.
* Calls the input function specified at initialization.
* @param[in,out] work work item.
*/
static void
DispatchWrapper(CommOSWork *work)
{
unsigned int misses;
for (misses = 0; running && (misses < dispatchMaxCycles); ) {
/* We run for at most dispatchMaxCycles worth of channel no-ops. */
if (!dispatch()) {
/* No useful work was done, on any of the channels. */
misses++;
if ((misses % 32) == 0) {
CommOS_Yield();
}
} else {
misses = 0;
}
}
if (running &&
(work >= &dispatchWorks[0]) &&
(work <= &dispatchWorks[NR_CPUS - 1])) {
/*
* If still running _and_ this was a regular, time-based run, then
* re-arm the timer.
*/
QueueDelayedWork(dispatchWQ, work, dispatchInterval);
}
}
/**
* @brief Initializes work item with specified callback function.
* @param[in,out] work work queue to initialize.
* @param func work item to initialize the queue with.
*/
void
CommOS_InitWork(CommOSWork *work,
CommOSWorkFunc func)
{
INIT_DELAYED_WORK(work, (work_func_t)func);
}
/**
* @brief Flush execution of a work item
* @param{in,out] work work item to dequeue
*/
void
CommOS_FlushAIOWork(CommOSWork *work)
{
if (aioWQ && work) {
FlushDelayedWork(work);
}
}
/**
* @brief Queue a work item to the AIO workqueue.
* @param[in,out] work work item to enqueue.
* @return zero if work enqueued, non-zero otherwise.
*/
int
CommOS_ScheduleAIOWork(CommOSWork *work)
{
if (running && aioWQ && work) {
return QueueDelayedWork(aioWQ, work, 0);
}
return -1;
}
/**
* @brief Initializes the base IO system.
* @param dispatchTaskName dispatch thread(s) name.
* @param dispatchFunc dispatch function.
* @param intervalMillis periodic interval in milliseconds to call dispatch.
* The floor is 1 jiffy, regardless of how small intervalMillis is
* @param maxCycles number of cycles to do adaptive polling before scheduling.
* The maximum number of cycles is DISPATCH_MAX_CYCLES.
* @param aioTaskName AIO thread(s) name. If NULL, AIO threads aren't started.
* @return zero is successful, -1 otherwise.
* @sideeffects Dispatch threads, and if applicable, AIO threads are started.
*/
int
CommOS_StartIO(const char *dispatchTaskName, // IN
CommOSDispatchFunc dispatchFunc, // IN
unsigned int intervalMillis, // IN
unsigned int maxCycles, // IN
const char *aioTaskName) // IN
{
int rc;
int cpu;
if (running) {
CommOS_Debug(("%s: I/O tasks already running.\n", __FUNCTION__));
return 0;
}
/*
* OK, let's test the handler against NULL. Though, the whole concept
* of checking for NULL pointers, outside cases where NULL is meaningful
* to the implementation, is relatively useless: garbage, random pointers
* rarely happen to be all-zeros.
*/
if (!dispatchFunc) {
CommOS_Log(("%s: a NULL Dispatch handler was passed.\n", __FUNCTION__));
return -1;
}
dispatch = dispatchFunc;
if (intervalMillis == 0) {
intervalMillis = 4;
}
if ((dispatchInterval = msecs_to_jiffies(intervalMillis)) < 1) {
dispatchInterval = 1;
}
if (maxCycles > DISPATCH_MAX_CYCLES) {
dispatchMaxCycles = DISPATCH_MAX_CYCLES;
} else if (maxCycles > 0) {
dispatchMaxCycles = maxCycles;
}
CommOS_Debug(("%s: Interval millis %u (jif:%u).\n", __FUNCTION__,
intervalMillis, dispatchInterval));
CommOS_Debug(("%s: Max cycles %u.\n", __FUNCTION__, dispatchMaxCycles));
numCpus = num_present_cpus();
dispatchWQ = CreateWorkqueue(dispatchTaskName);
if (!dispatchWQ) {
CommOS_Log(("%s: Couldn't create %s task(s).\n", __FUNCTION__,
dispatchTaskName));
return -1;
}
if (aioTaskName) {
aioWQ = CreateWorkqueue(aioTaskName);
if (!aioWQ) {
CommOS_Log(("%s: Couldn't create %s task(s).\n", __FUNCTION__,
aioTaskName));
DestroyWorkqueue(dispatchWQ);
return -1;
}
} else {
aioWQ = NULL;
}
running = 1;
for (cpu = 0; cpu < numCpus; cpu++) {
CommOS_InitWork(&dispatchWorksNow[cpu], DispatchWrapper);
CommOS_InitWork(&dispatchWorks[cpu], DispatchWrapper);
rc = QueueDelayedWorkOn(cpu, dispatchWQ,
&dispatchWorks[cpu],
dispatchInterval);
if (rc != 0) {
CommOS_StopIO();
return -1;
}
}
CommOS_Log(("%s: Created I/O task(s) successfully.\n", __FUNCTION__));
return 0;
}
/**
* @brief Stops the base IO system.
* @sideeffects Dispatch threads, and if applicable, AIO threads are stopped.
*/
void
CommOS_StopIO(void)
{
int cpu;
if (running) {
running = 0;
if (aioWQ) {
FlushWorkqueue(aioWQ);
DestroyWorkqueue(aioWQ);
aioWQ = NULL;
}
FlushWorkqueue(dispatchWQ);
for (cpu = 0; cpu < numCpus; cpu++) {
WaitForDelayedWork(&dispatchWorksNow[cpu]);
WaitForDelayedWork(&dispatchWorks[cpu]);
}
DestroyWorkqueue(dispatchWQ);
dispatchWQ = NULL;
CommOS_Log(("%s: I/O tasks stopped.\n", __FUNCTION__));
}
}
| gpl-2.0 |
changbindu/linux-ok6410 | drivers/clk/at91/clk-pll.c | 359 | 13137 | /*
* Copyright (C) 2013 Boris BREZILLON <b.brezillon@overkiz.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-provider.h>
#include <linux/clkdev.h>
#include <linux/clk/at91_pmc.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/wait.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include "pmc.h"
#define PLL_STATUS_MASK(id) (1 << (1 + (id)))
#define PLL_REG(id) (AT91_CKGR_PLLAR + ((id) * 4))
#define PLL_DIV_MASK 0xff
#define PLL_DIV_MAX PLL_DIV_MASK
#define PLL_DIV(reg) ((reg) & PLL_DIV_MASK)
#define PLL_MUL(reg, layout) (((reg) >> (layout)->mul_shift) & \
(layout)->mul_mask)
#define PLL_MUL_MIN 2
#define PLL_MUL_MASK(layout) ((layout)->mul_mask)
#define PLL_MUL_MAX(layout) (PLL_MUL_MASK(layout) + 1)
#define PLL_ICPR_SHIFT(id) ((id) * 16)
#define PLL_ICPR_MASK(id) (0xffff << PLL_ICPR_SHIFT(id))
#define PLL_MAX_COUNT 0x3f
#define PLL_COUNT_SHIFT 8
#define PLL_OUT_SHIFT 14
#define PLL_MAX_ID 1
struct clk_pll_characteristics {
struct clk_range input;
int num_output;
struct clk_range *output;
u16 *icpll;
u8 *out;
};
struct clk_pll_layout {
u32 pllr_mask;
u16 mul_mask;
u8 mul_shift;
};
#define to_clk_pll(hw) container_of(hw, struct clk_pll, hw)
struct clk_pll {
struct clk_hw hw;
struct at91_pmc *pmc;
unsigned int irq;
wait_queue_head_t wait;
u8 id;
u8 div;
u8 range;
u16 mul;
const struct clk_pll_layout *layout;
const struct clk_pll_characteristics *characteristics;
};
static irqreturn_t clk_pll_irq_handler(int irq, void *dev_id)
{
struct clk_pll *pll = (struct clk_pll *)dev_id;
wake_up(&pll->wait);
disable_irq_nosync(pll->irq);
return IRQ_HANDLED;
}
static int clk_pll_prepare(struct clk_hw *hw)
{
struct clk_pll *pll = to_clk_pll(hw);
struct at91_pmc *pmc = pll->pmc;
const struct clk_pll_layout *layout = pll->layout;
const struct clk_pll_characteristics *characteristics =
pll->characteristics;
u8 id = pll->id;
u32 mask = PLL_STATUS_MASK(id);
int offset = PLL_REG(id);
u8 out = 0;
u32 pllr, icpr;
u8 div;
u16 mul;
pllr = pmc_read(pmc, offset);
div = PLL_DIV(pllr);
mul = PLL_MUL(pllr, layout);
if ((pmc_read(pmc, AT91_PMC_SR) & mask) &&
(div == pll->div && mul == pll->mul))
return 0;
if (characteristics->out)
out = characteristics->out[pll->range];
if (characteristics->icpll) {
icpr = pmc_read(pmc, AT91_PMC_PLLICPR) & ~PLL_ICPR_MASK(id);
icpr |= (characteristics->icpll[pll->range] <<
PLL_ICPR_SHIFT(id));
pmc_write(pmc, AT91_PMC_PLLICPR, icpr);
}
pllr &= ~layout->pllr_mask;
pllr |= layout->pllr_mask &
(pll->div | (PLL_MAX_COUNT << PLL_COUNT_SHIFT) |
(out << PLL_OUT_SHIFT) |
((pll->mul & layout->mul_mask) << layout->mul_shift));
pmc_write(pmc, offset, pllr);
while (!(pmc_read(pmc, AT91_PMC_SR) & mask)) {
enable_irq(pll->irq);
wait_event(pll->wait,
pmc_read(pmc, AT91_PMC_SR) & mask);
}
return 0;
}
static int clk_pll_is_prepared(struct clk_hw *hw)
{
struct clk_pll *pll = to_clk_pll(hw);
struct at91_pmc *pmc = pll->pmc;
return !!(pmc_read(pmc, AT91_PMC_SR) &
PLL_STATUS_MASK(pll->id));
}
static void clk_pll_unprepare(struct clk_hw *hw)
{
struct clk_pll *pll = to_clk_pll(hw);
struct at91_pmc *pmc = pll->pmc;
const struct clk_pll_layout *layout = pll->layout;
int offset = PLL_REG(pll->id);
u32 tmp = pmc_read(pmc, offset) & ~(layout->pllr_mask);
pmc_write(pmc, offset, tmp);
}
static unsigned long clk_pll_recalc_rate(struct clk_hw *hw,
unsigned long parent_rate)
{
struct clk_pll *pll = to_clk_pll(hw);
if (!pll->div || !pll->mul)
return 0;
return (parent_rate / pll->div) * (pll->mul + 1);
}
static long clk_pll_get_best_div_mul(struct clk_pll *pll, unsigned long rate,
unsigned long parent_rate,
u32 *div, u32 *mul,
u32 *index) {
const struct clk_pll_layout *layout = pll->layout;
const struct clk_pll_characteristics *characteristics =
pll->characteristics;
unsigned long bestremainder = ULONG_MAX;
unsigned long maxdiv, mindiv, tmpdiv;
long bestrate = -ERANGE;
unsigned long bestdiv;
unsigned long bestmul;
int i = 0;
/* Check if parent_rate is a valid input rate */
if (parent_rate < characteristics->input.min)
return -ERANGE;
/*
* Calculate minimum divider based on the minimum multiplier, the
* parent_rate and the requested rate.
* Should always be 2 according to the input and output characteristics
* of the PLL blocks.
*/
mindiv = (parent_rate * PLL_MUL_MIN) / rate;
if (!mindiv)
mindiv = 1;
if (parent_rate > characteristics->input.max) {
tmpdiv = DIV_ROUND_UP(parent_rate, characteristics->input.max);
if (tmpdiv > PLL_DIV_MAX)
return -ERANGE;
if (tmpdiv > mindiv)
mindiv = tmpdiv;
}
/*
* Calculate the maximum divider which is limited by PLL register
* layout (limited by the MUL or DIV field size).
*/
maxdiv = DIV_ROUND_UP(parent_rate * PLL_MUL_MAX(layout), rate);
if (maxdiv > PLL_DIV_MAX)
maxdiv = PLL_DIV_MAX;
/*
* Iterate over the acceptable divider values to find the best
* divider/multiplier pair (the one that generates the closest
* rate to the requested one).
*/
for (tmpdiv = mindiv; tmpdiv <= maxdiv; tmpdiv++) {
unsigned long remainder;
unsigned long tmprate;
unsigned long tmpmul;
/*
* Calculate the multiplier associated with the current
* divider that provide the closest rate to the requested one.
*/
tmpmul = DIV_ROUND_CLOSEST(rate, parent_rate / tmpdiv);
tmprate = (parent_rate / tmpdiv) * tmpmul;
if (tmprate > rate)
remainder = tmprate - rate;
else
remainder = rate - tmprate;
/*
* Compare the remainder with the best remainder found until
* now and elect a new best multiplier/divider pair if the
* current remainder is smaller than the best one.
*/
if (remainder < bestremainder) {
bestremainder = remainder;
bestdiv = tmpdiv;
bestmul = tmpmul;
bestrate = tmprate;
}
/*
* We've found a perfect match!
* Stop searching now and use this multiplier/divider pair.
*/
if (!remainder)
break;
}
/* We haven't found any multiplier/divider pair => return -ERANGE */
if (bestrate < 0)
return bestrate;
/* Check if bestrate is a valid output rate */
for (i = 0; i < characteristics->num_output; i++) {
if (bestrate >= characteristics->output[i].min &&
bestrate <= characteristics->output[i].max)
break;
}
if (i >= characteristics->num_output)
return -ERANGE;
if (div)
*div = bestdiv;
if (mul)
*mul = bestmul - 1;
if (index)
*index = i;
return bestrate;
}
static long clk_pll_round_rate(struct clk_hw *hw, unsigned long rate,
unsigned long *parent_rate)
{
struct clk_pll *pll = to_clk_pll(hw);
return clk_pll_get_best_div_mul(pll, rate, *parent_rate,
NULL, NULL, NULL);
}
static int clk_pll_set_rate(struct clk_hw *hw, unsigned long rate,
unsigned long parent_rate)
{
struct clk_pll *pll = to_clk_pll(hw);
long ret;
u32 div;
u32 mul;
u32 index;
ret = clk_pll_get_best_div_mul(pll, rate, parent_rate,
&div, &mul, &index);
if (ret < 0)
return ret;
pll->range = index;
pll->div = div;
pll->mul = mul;
return 0;
}
static const struct clk_ops pll_ops = {
.prepare = clk_pll_prepare,
.unprepare = clk_pll_unprepare,
.is_prepared = clk_pll_is_prepared,
.recalc_rate = clk_pll_recalc_rate,
.round_rate = clk_pll_round_rate,
.set_rate = clk_pll_set_rate,
};
static struct clk * __init
at91_clk_register_pll(struct at91_pmc *pmc, unsigned int irq, const char *name,
const char *parent_name, u8 id,
const struct clk_pll_layout *layout,
const struct clk_pll_characteristics *characteristics)
{
struct clk_pll *pll;
struct clk *clk = NULL;
struct clk_init_data init;
int ret;
int offset = PLL_REG(id);
u32 tmp;
if (id > PLL_MAX_ID)
return ERR_PTR(-EINVAL);
pll = kzalloc(sizeof(*pll), GFP_KERNEL);
if (!pll)
return ERR_PTR(-ENOMEM);
init.name = name;
init.ops = &pll_ops;
init.parent_names = &parent_name;
init.num_parents = 1;
init.flags = CLK_SET_RATE_GATE;
pll->id = id;
pll->hw.init = &init;
pll->layout = layout;
pll->characteristics = characteristics;
pll->pmc = pmc;
pll->irq = irq;
tmp = pmc_read(pmc, offset) & layout->pllr_mask;
pll->div = PLL_DIV(tmp);
pll->mul = PLL_MUL(tmp, layout);
init_waitqueue_head(&pll->wait);
irq_set_status_flags(pll->irq, IRQ_NOAUTOEN);
ret = request_irq(pll->irq, clk_pll_irq_handler, IRQF_TRIGGER_HIGH,
id ? "clk-pllb" : "clk-plla", pll);
if (ret)
return ERR_PTR(ret);
clk = clk_register(NULL, &pll->hw);
if (IS_ERR(clk))
kfree(pll);
return clk;
}
static const struct clk_pll_layout at91rm9200_pll_layout = {
.pllr_mask = 0x7FFFFFF,
.mul_shift = 16,
.mul_mask = 0x7FF,
};
static const struct clk_pll_layout at91sam9g45_pll_layout = {
.pllr_mask = 0xFFFFFF,
.mul_shift = 16,
.mul_mask = 0xFF,
};
static const struct clk_pll_layout at91sam9g20_pllb_layout = {
.pllr_mask = 0x3FFFFF,
.mul_shift = 16,
.mul_mask = 0x3F,
};
static const struct clk_pll_layout sama5d3_pll_layout = {
.pllr_mask = 0x1FFFFFF,
.mul_shift = 18,
.mul_mask = 0x7F,
};
static struct clk_pll_characteristics * __init
of_at91_clk_pll_get_characteristics(struct device_node *np)
{
int i;
int offset;
u32 tmp;
int num_output;
u32 num_cells;
struct clk_range input;
struct clk_range *output;
u8 *out = NULL;
u16 *icpll = NULL;
struct clk_pll_characteristics *characteristics;
if (of_at91_get_clk_range(np, "atmel,clk-input-range", &input))
return NULL;
if (of_property_read_u32(np, "#atmel,pll-clk-output-range-cells",
&num_cells))
return NULL;
if (num_cells < 2 || num_cells > 4)
return NULL;
if (!of_get_property(np, "atmel,pll-clk-output-ranges", &tmp))
return NULL;
num_output = tmp / (sizeof(u32) * num_cells);
characteristics = kzalloc(sizeof(*characteristics), GFP_KERNEL);
if (!characteristics)
return NULL;
output = kzalloc(sizeof(*output) * num_output, GFP_KERNEL);
if (!output)
goto out_free_characteristics;
if (num_cells > 2) {
out = kzalloc(sizeof(*out) * num_output, GFP_KERNEL);
if (!out)
goto out_free_output;
}
if (num_cells > 3) {
icpll = kzalloc(sizeof(*icpll) * num_output, GFP_KERNEL);
if (!icpll)
goto out_free_output;
}
for (i = 0; i < num_output; i++) {
offset = i * num_cells;
if (of_property_read_u32_index(np,
"atmel,pll-clk-output-ranges",
offset, &tmp))
goto out_free_output;
output[i].min = tmp;
if (of_property_read_u32_index(np,
"atmel,pll-clk-output-ranges",
offset + 1, &tmp))
goto out_free_output;
output[i].max = tmp;
if (num_cells == 2)
continue;
if (of_property_read_u32_index(np,
"atmel,pll-clk-output-ranges",
offset + 2, &tmp))
goto out_free_output;
out[i] = tmp;
if (num_cells == 3)
continue;
if (of_property_read_u32_index(np,
"atmel,pll-clk-output-ranges",
offset + 3, &tmp))
goto out_free_output;
icpll[i] = tmp;
}
characteristics->input = input;
characteristics->num_output = num_output;
characteristics->output = output;
characteristics->out = out;
characteristics->icpll = icpll;
return characteristics;
out_free_output:
kfree(icpll);
kfree(out);
kfree(output);
out_free_characteristics:
kfree(characteristics);
return NULL;
}
static void __init
of_at91_clk_pll_setup(struct device_node *np, struct at91_pmc *pmc,
const struct clk_pll_layout *layout)
{
u32 id;
unsigned int irq;
struct clk *clk;
const char *parent_name;
const char *name = np->name;
struct clk_pll_characteristics *characteristics;
if (of_property_read_u32(np, "reg", &id))
return;
parent_name = of_clk_get_parent_name(np, 0);
of_property_read_string(np, "clock-output-names", &name);
characteristics = of_at91_clk_pll_get_characteristics(np);
if (!characteristics)
return;
irq = irq_of_parse_and_map(np, 0);
if (!irq)
return;
clk = at91_clk_register_pll(pmc, irq, name, parent_name, id, layout,
characteristics);
if (IS_ERR(clk))
goto out_free_characteristics;
of_clk_add_provider(np, of_clk_src_simple_get, clk);
return;
out_free_characteristics:
kfree(characteristics);
}
void __init of_at91rm9200_clk_pll_setup(struct device_node *np,
struct at91_pmc *pmc)
{
of_at91_clk_pll_setup(np, pmc, &at91rm9200_pll_layout);
}
void __init of_at91sam9g45_clk_pll_setup(struct device_node *np,
struct at91_pmc *pmc)
{
of_at91_clk_pll_setup(np, pmc, &at91sam9g45_pll_layout);
}
void __init of_at91sam9g20_clk_pllb_setup(struct device_node *np,
struct at91_pmc *pmc)
{
of_at91_clk_pll_setup(np, pmc, &at91sam9g20_pllb_layout);
}
void __init of_sama5d3_clk_pll_setup(struct device_node *np,
struct at91_pmc *pmc)
{
of_at91_clk_pll_setup(np, pmc, &sama5d3_pll_layout);
}
| gpl-2.0 |
NieNs/IM-A840S-kernel-1 | arch/arm/common/cpaccess.c | 359 | 8711 | /* Copyright (c) 2010-2011, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/sysrq.h>
#include <linux/time.h>
#include <linux/proc_fs.h>
#include <linux/kernel_stat.h>
#include <linux/uaccess.h>
#include <linux/sysdev.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/spinlock.h>
#include <linux/semaphore.h>
#include <linux/file.h>
#include <linux/percpu.h>
#include <linux/string.h>
#include <linux/smp.h>
#include <asm/cacheflush.h>
#include <asm/smp_plat.h>
#include <asm/mmu_writeable.h>
#ifdef CONFIG_ARCH_MSM_KRAIT
#include <mach/msm-krait-l2-accessors.h>
#endif
#define TYPE_MAX_CHARACTERS 10
/*
* CP parameters
*/
struct cp_params {
unsigned long il2index;
unsigned long cp;
unsigned long op1;
unsigned long op2;
unsigned long crn;
unsigned long crm;
unsigned long write_value;
char rw;
};
static struct semaphore cp_sem;
static unsigned long il2_output;
static int cpu;
char type[TYPE_MAX_CHARACTERS] = "C";
static DEFINE_PER_CPU(struct cp_params, cp_param)
= { 0, 15, 0, 0, 0, 0, 0, 'r' };
static struct sysdev_class cpaccess_sysclass = {
.name = "cpaccess",
};
#ifdef CONFIG_ARCH_MSM_KRAIT
/*
* do_read_il2 - Read indirect L2 registers
* @ret: Pointer to return value
*
*/
static void do_read_il2(void *ret)
{
*(unsigned long *)ret =
get_l2_indirect_reg(per_cpu(cp_param.il2index, cpu));
}
/*
* do_write_il2 - Write indirect L2 registers
* @ret: Pointer to return value
*
*/
static void do_write_il2(void *ret)
{
*(unsigned long *)ret =
set_get_l2_indirect_reg(per_cpu(cp_param.il2index, cpu),
per_cpu(cp_param.write_value, cpu));
}
/*
* do_il2_rw - Call Read/Write indirect L2 register functions
* @ret: Pointer to return value in case of CP register
*
*/
static int do_il2_rw(char *str_tmp)
{
unsigned long write_value, il2index;
char rw;
int ret = 0;
il2index = 0;
sscanf(str_tmp, "%lx:%c:%lx:%d", &il2index, &rw, &write_value,
&cpu);
per_cpu(cp_param.il2index, cpu) = il2index;
per_cpu(cp_param.rw, cpu) = rw;
per_cpu(cp_param.write_value, cpu) = write_value;
if (per_cpu(cp_param.rw, cpu) == 'r') {
if (is_smp()) {
if (smp_call_function_single(cpu, do_read_il2,
&il2_output, 1))
pr_err("Error cpaccess smp call single\n");
} else
do_read_il2(&il2_output);
} else if (per_cpu(cp_param.rw, cpu) == 'w') {
if (is_smp()) {
if (smp_call_function_single(cpu, do_write_il2,
&il2_output, 1))
pr_err("Error cpaccess smp call single\n");
} else
do_write_il2(&il2_output);
} else {
pr_err("cpaccess: Wrong Entry for 'r' or 'w'.\n");
return -EINVAL;
}
return ret;
}
#else
static void do_il2_rw(char *str_tmp)
{
il2_output = 0;
}
#endif
/*
* get_asm_value - Dummy fuction
* @write_val: Write value incase of a CP register write operation.
*
* This function is just a placeholder. The first 2 instructions
* will be inserted to perform MRC/MCR instruction and a return.
* See do_cpregister_rw function. Value passed to function is
* accessed from r0 register.
*/
static noinline unsigned long cpaccess_dummy(unsigned long write_val)
{
asm("mrc p15, 0, r0, c0, c0, 0\n\t");
asm("bx lr\n\t");
return 0xBEEF;
} __attribute__((aligned(32)))
/*
* get_asm_value - Read/Write CP registers
* @ret: Pointer to return value in case of CP register
* read op.
*
*/
static void get_asm_value(void *ret)
{
*(unsigned long *)ret =
cpaccess_dummy(per_cpu(cp_param.write_value, cpu));
}
/*
* dp_cpregister_rw - Read/Write CP registers
* @write: 1 for Write and 0 for Read operation
*
* Returns value read from CP register
*/
static unsigned long do_cpregister_rw(int write)
{
unsigned long opcode, ret, *p_opcode;
/*
* Mask the crn, crm, op1, op2 and cp values so they do not
* interfer with other fields of the op code.
*/
per_cpu(cp_param.cp, cpu) &= 0xF;
per_cpu(cp_param.crn, cpu) &= 0xF;
per_cpu(cp_param.crm, cpu) &= 0xF;
per_cpu(cp_param.op1, cpu) &= 0x7;
per_cpu(cp_param.op2, cpu) &= 0x7;
/*
* Base MRC opcode for MIDR is EE100010,
* MCR is 0xEE000010
*/
opcode = (write == 1 ? 0xEE000010 : 0xEE100010);
opcode |= (per_cpu(cp_param.crn, cpu)<<16) |
(per_cpu(cp_param.crm, cpu)<<0) |
(per_cpu(cp_param.op1, cpu)<<21) |
(per_cpu(cp_param.op2, cpu)<<5) |
(per_cpu(cp_param.cp, cpu) << 8);
/*
* Grab address of the Dummy function, write the MRC/MCR
* instruction, ensuring cache coherency.
*/
p_opcode = (unsigned long *)&cpaccess_dummy;
mem_text_write_kernel_word(p_opcode, opcode);
#ifdef CONFIG_SMP
/*
* Use smp_call_function_single to do CPU core specific
* get_asm_value function call.
*/
if (smp_call_function_single(cpu, get_asm_value, &ret, 1))
printk(KERN_ERR "Error cpaccess smp call single\n");
#else
get_asm_value(&ret);
#endif
return ret;
}
static int get_register_params(char *str_tmp)
{
unsigned long op1, op2, crn, crm, cp = 15, write_value, il2index;
char rw;
int cnt = 0;
il2index = 0;
strncpy(type, strsep(&str_tmp, ":"), TYPE_MAX_CHARACTERS);
if (strncasecmp(type, "C", TYPE_MAX_CHARACTERS) == 0) {
sscanf(str_tmp, "%lu:%lu:%lu:%lu:%lu:%c:%lx:%d",
&cp, &op1, &crn, &crm, &op2, &rw, &write_value, &cpu);
per_cpu(cp_param.cp, cpu) = cp;
per_cpu(cp_param.op1, cpu) = op1;
per_cpu(cp_param.crn, cpu) = crn;
per_cpu(cp_param.crm, cpu) = crm;
per_cpu(cp_param.op2, cpu) = op2;
per_cpu(cp_param.rw, cpu) = rw;
per_cpu(cp_param.write_value, cpu) = write_value;
if ((per_cpu(cp_param.rw, cpu) != 'w') &&
(per_cpu(cp_param.rw, cpu) != 'r')) {
pr_err("cpaccess: Wrong entry for 'r' or 'w'.\n");
return -EINVAL;
}
if (per_cpu(cp_param.rw, cpu) == 'w')
do_cpregister_rw(1);
} else if (strncasecmp(type, "IL2", TYPE_MAX_CHARACTERS) == 0)
do_il2_rw(str_tmp);
else {
pr_err("cpaccess: Not a valid type. Entered: %s\n", type);
return -EINVAL;
}
return cnt;
}
/*
* cp_register_write_sysfs - sysfs interface for writing to
* CP register
* @dev: sys device
* @attr: device attribute
* @buf: write value
* @cnt: not used
*
*/
static ssize_t cp_register_write_sysfs(struct sys_device *dev,
struct sysdev_attribute *attr, const char *buf, size_t cnt)
{
char *str_tmp = (char *)buf;
if (down_timeout(&cp_sem, 6000))
return -ERESTARTSYS;
get_register_params(str_tmp);
return cnt;
}
/*
* cp_register_read_sysfs - sysfs interface for reading CP registers
* @dev: sys device
* @attr: device attribute
* @buf: write value
*
* Code to read in the CPxx crn, crm, op1, op2 variables, or into
* the base MRC opcode, store to executable memory, clean/invalidate
* caches and then execute the new instruction and provide the
* result to the caller.
*/
static ssize_t cp_register_read_sysfs(struct sys_device *dev,
struct sysdev_attribute *attr, char *buf)
{
int ret;
if (strncasecmp(type, "C", TYPE_MAX_CHARACTERS) == 0)
ret = snprintf(buf, TYPE_MAX_CHARACTERS, "%lx\n",
do_cpregister_rw(0));
else if (strncasecmp(type, "IL2", TYPE_MAX_CHARACTERS) == 0)
ret = snprintf(buf, TYPE_MAX_CHARACTERS, "%lx\n", il2_output);
else
ret = -EINVAL;
if (cp_sem.count <= 0)
up(&cp_sem);
return ret;
}
/*
* Setup sysfs files
*/
SYSDEV_ATTR(cp_rw, 0644, cp_register_read_sysfs, cp_register_write_sysfs);
static struct sys_device device_cpaccess = {
.id = 0,
.cls = &cpaccess_sysclass,
};
/*
* init_cpaccess_sysfs - initialize sys devices
*/
static int __init init_cpaccess_sysfs(void)
{
int error = sysdev_class_register(&cpaccess_sysclass);
if (!error)
error = sysdev_register(&device_cpaccess);
else
pr_err("Error initializing cpaccess interface\n");
if (!error)
error = sysdev_create_file(&device_cpaccess,
&attr_cp_rw);
else {
pr_err("Error initializing cpaccess interface\n");
sysdev_unregister(&device_cpaccess);
sysdev_class_unregister(&cpaccess_sysclass);
}
sema_init(&cp_sem, 1);
return error;
}
static void __exit exit_cpaccess_sysfs(void)
{
sysdev_remove_file(&device_cpaccess, &attr_cp_rw);
sysdev_unregister(&device_cpaccess);
sysdev_class_unregister(&cpaccess_sysclass);
}
module_init(init_cpaccess_sysfs);
module_exit(exit_cpaccess_sysfs);
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
Sudokamikaze/Darkspell-taoshan | drivers/usb/gadget/f_serial.c | 615 | 27093 | /*
* f_serial.c - generic USB serial function driver
*
* Copyright (C) 2003 Al Borchers (alborchers@steinerpoint.com)
* Copyright (C) 2008 by David Brownell
* Copyright (C) 2008 by Nokia Corporation
*
* This software is distributed under the terms of the GNU General
* Public License ("GPL") as published by the Free Software Foundation,
* either version 2 of that License or (at your option) any later version.
*/
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <mach/usb_gadget_xport.h>
#include "u_serial.h"
#include "gadget_chips.h"
/*
* This function packages a simple "generic serial" port with no real
* control mechanisms, just raw data transfer over two bulk endpoints.
*
* Because it's not standardized, this isn't as interoperable as the
* CDC ACM driver. However, for many purposes it's just as functional
* if you can arrange appropriate host side drivers.
*/
#define GSERIAL_NO_PORTS 3
struct f_gser {
struct gserial port;
u8 data_id;
u8 port_num;
u8 online;
enum transport_type transport;
#ifdef CONFIG_MODEM_SUPPORT
u8 pending;
spinlock_t lock;
struct usb_ep *notify;
struct usb_request *notify_req;
struct usb_cdc_line_coding port_line_coding;
/* SetControlLineState request */
u16 port_handshake_bits;
#define ACM_CTRL_RTS (1 << 1) /* unused with full duplex */
#define ACM_CTRL_DTR (1 << 0) /* host is ready for data r/w */
/* SerialState notification */
u16 serial_state;
#define ACM_CTRL_OVERRUN (1 << 6)
#define ACM_CTRL_PARITY (1 << 5)
#define ACM_CTRL_FRAMING (1 << 4)
#define ACM_CTRL_RI (1 << 3)
#define ACM_CTRL_BRK (1 << 2)
#define ACM_CTRL_DSR (1 << 1)
#define ACM_CTRL_DCD (1 << 0)
#endif
};
static unsigned int no_tty_ports;
static unsigned int no_sdio_ports;
static unsigned int no_smd_ports;
static unsigned int no_hsic_sports;
static unsigned int no_hsuart_sports;
static unsigned int nr_ports;
static struct port_info {
enum transport_type transport;
unsigned port_num;
unsigned client_port_num;
} gserial_ports[GSERIAL_NO_PORTS];
static inline bool is_transport_sdio(enum transport_type t)
{
if (t == USB_GADGET_XPORT_SDIO)
return 1;
return 0;
}
static inline struct f_gser *func_to_gser(struct usb_function *f)
{
return container_of(f, struct f_gser, port.func);
}
#ifdef CONFIG_MODEM_SUPPORT
static inline struct f_gser *port_to_gser(struct gserial *p)
{
return container_of(p, struct f_gser, port);
}
#define GS_LOG2_NOTIFY_INTERVAL 5 /* 1 << 5 == 32 msec */
#define GS_NOTIFY_MAXPACKET 16
#endif
/*-------------------------------------------------------------------------*/
/* interface descriptor: */
static struct usb_interface_descriptor gser_interface_desc = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC */
#ifdef CONFIG_MODEM_SUPPORT
.bNumEndpoints = 3,
#else
.bNumEndpoints = 2,
#endif
.bInterfaceClass = USB_CLASS_VENDOR_SPEC,
.bInterfaceSubClass = 0,
.bInterfaceProtocol = 0,
/* .iInterface = DYNAMIC */
};
#ifdef CONFIG_MODEM_SUPPORT
static struct usb_cdc_header_desc gser_header_desc = {
.bLength = sizeof(gser_header_desc),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_HEADER_TYPE,
.bcdCDC = __constant_cpu_to_le16(0x0110),
};
static struct usb_cdc_call_mgmt_descriptor
gser_call_mgmt_descriptor = {
.bLength = sizeof(gser_call_mgmt_descriptor),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_CALL_MANAGEMENT_TYPE,
.bmCapabilities = 0,
/* .bDataInterface = DYNAMIC */
};
static struct usb_cdc_acm_descriptor gser_descriptor = {
.bLength = sizeof(gser_descriptor),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_ACM_TYPE,
.bmCapabilities = USB_CDC_CAP_LINE,
};
static struct usb_cdc_union_desc gser_union_desc = {
.bLength = sizeof(gser_union_desc),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_UNION_TYPE,
/* .bMasterInterface0 = DYNAMIC */
/* .bSlaveInterface0 = DYNAMIC */
};
#endif
/* full speed support: */
#ifdef CONFIG_MODEM_SUPPORT
static struct usb_endpoint_descriptor gser_fs_notify_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = __constant_cpu_to_le16(GS_NOTIFY_MAXPACKET),
.bInterval = 1 << GS_LOG2_NOTIFY_INTERVAL,
};
#endif
static struct usb_endpoint_descriptor gser_fs_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_endpoint_descriptor gser_fs_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_descriptor_header *gser_fs_function[] = {
(struct usb_descriptor_header *) &gser_interface_desc,
#ifdef CONFIG_MODEM_SUPPORT
(struct usb_descriptor_header *) &gser_header_desc,
(struct usb_descriptor_header *) &gser_call_mgmt_descriptor,
(struct usb_descriptor_header *) &gser_descriptor,
(struct usb_descriptor_header *) &gser_union_desc,
(struct usb_descriptor_header *) &gser_fs_notify_desc,
#endif
(struct usb_descriptor_header *) &gser_fs_in_desc,
(struct usb_descriptor_header *) &gser_fs_out_desc,
NULL,
};
/* high speed support: */
#ifdef CONFIG_MODEM_SUPPORT
static struct usb_endpoint_descriptor gser_hs_notify_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = __constant_cpu_to_le16(GS_NOTIFY_MAXPACKET),
.bInterval = GS_LOG2_NOTIFY_INTERVAL+4,
};
#endif
static struct usb_endpoint_descriptor gser_hs_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = __constant_cpu_to_le16(512),
};
static struct usb_endpoint_descriptor gser_hs_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = __constant_cpu_to_le16(512),
};
static struct usb_descriptor_header *gser_hs_function[] = {
(struct usb_descriptor_header *) &gser_interface_desc,
#ifdef CONFIG_MODEM_SUPPORT
(struct usb_descriptor_header *) &gser_header_desc,
(struct usb_descriptor_header *) &gser_call_mgmt_descriptor,
(struct usb_descriptor_header *) &gser_descriptor,
(struct usb_descriptor_header *) &gser_union_desc,
(struct usb_descriptor_header *) &gser_hs_notify_desc,
#endif
(struct usb_descriptor_header *) &gser_hs_in_desc,
(struct usb_descriptor_header *) &gser_hs_out_desc,
NULL,
};
static struct usb_endpoint_descriptor gser_ss_in_desc __initdata = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(1024),
};
static struct usb_endpoint_descriptor gser_ss_out_desc __initdata = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(1024),
};
static struct usb_ss_ep_comp_descriptor gser_ss_bulk_comp_desc __initdata = {
.bLength = sizeof gser_ss_bulk_comp_desc,
.bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
};
static struct usb_descriptor_header *gser_ss_function[] __initdata = {
(struct usb_descriptor_header *) &gser_interface_desc,
(struct usb_descriptor_header *) &gser_ss_in_desc,
(struct usb_descriptor_header *) &gser_ss_bulk_comp_desc,
(struct usb_descriptor_header *) &gser_ss_out_desc,
(struct usb_descriptor_header *) &gser_ss_bulk_comp_desc,
NULL,
};
/* string descriptors: */
static struct usb_string gser_string_defs[] = {
[0].s = "Generic Serial",
{ } /* end of list */
};
static struct usb_gadget_strings gser_string_table = {
.language = 0x0409, /* en-us */
.strings = gser_string_defs,
};
static struct usb_gadget_strings *gser_strings[] = {
&gser_string_table,
NULL,
};
static int gport_setup(struct usb_configuration *c)
{
int ret = 0;
int port_idx;
int i;
pr_debug("%s: no_tty_ports: %u no_sdio_ports: %u"
" no_smd_ports: %u no_hsic_sports: %u no_hsuart_ports: %u nr_ports: %u\n",
__func__, no_tty_ports, no_sdio_ports, no_smd_ports,
no_hsic_sports, no_hsuart_sports, nr_ports);
if (no_tty_ports)
ret = gserial_setup(c->cdev->gadget, no_tty_ports);
if (no_sdio_ports)
ret = gsdio_setup(c->cdev->gadget, no_sdio_ports);
if (no_smd_ports)
ret = gsmd_setup(c->cdev->gadget, no_smd_ports);
if (no_hsic_sports) {
port_idx = ghsic_data_setup(no_hsic_sports, USB_GADGET_SERIAL);
if (port_idx < 0)
return port_idx;
for (i = 0; i < nr_ports; i++) {
if (gserial_ports[i].transport ==
USB_GADGET_XPORT_HSIC) {
gserial_ports[i].client_port_num = port_idx;
port_idx++;
}
}
/*clinet port num is same for data setup and ctrl setup*/
ret = ghsic_ctrl_setup(no_hsic_sports, USB_GADGET_SERIAL);
if (ret < 0)
return ret;
}
if (no_hsuart_sports) {
port_idx = ghsuart_data_setup(no_hsuart_sports,
USB_GADGET_SERIAL);
if (port_idx < 0)
return port_idx;
for (i = 0; i < nr_ports; i++) {
if (gserial_ports[i].transport ==
USB_GADGET_XPORT_HSUART) {
gserial_ports[i].client_port_num = port_idx;
port_idx++;
}
}
}
return ret;
}
static int gport_connect(struct f_gser *gser)
{
unsigned port_num;
int ret;
pr_debug("%s: transport: %s f_gser: %p gserial: %p port_num: %d\n",
__func__, xport_to_str(gser->transport),
gser, &gser->port, gser->port_num);
port_num = gserial_ports[gser->port_num].client_port_num;
switch (gser->transport) {
case USB_GADGET_XPORT_TTY:
gserial_connect(&gser->port, port_num);
break;
case USB_GADGET_XPORT_SDIO:
gsdio_connect(&gser->port, port_num);
break;
case USB_GADGET_XPORT_SMD:
gsmd_connect(&gser->port, port_num);
break;
case USB_GADGET_XPORT_HSIC:
ret = ghsic_ctrl_connect(&gser->port, port_num);
if (ret) {
pr_err("%s: ghsic_ctrl_connect failed: err:%d\n",
__func__, ret);
return ret;
}
ret = ghsic_data_connect(&gser->port, port_num);
if (ret) {
pr_err("%s: ghsic_data_connect failed: err:%d\n",
__func__, ret);
ghsic_ctrl_disconnect(&gser->port, port_num);
return ret;
}
break;
case USB_GADGET_XPORT_HSUART:
ret = ghsuart_data_connect(&gser->port, port_num);
if (ret) {
pr_err("%s: ghsuart_data_connect failed: err:%d\n",
__func__, ret);
return ret;
}
break;
default:
pr_err("%s: Un-supported transport: %s\n", __func__,
xport_to_str(gser->transport));
return -ENODEV;
}
return 0;
}
static int gport_disconnect(struct f_gser *gser)
{
unsigned port_num;
pr_debug("%s: transport: %s f_gser: %p gserial: %p port_num: %d\n",
__func__, xport_to_str(gser->transport),
gser, &gser->port, gser->port_num);
port_num = gserial_ports[gser->port_num].client_port_num;
switch (gser->transport) {
case USB_GADGET_XPORT_TTY:
gserial_disconnect(&gser->port);
break;
case USB_GADGET_XPORT_SDIO:
gsdio_disconnect(&gser->port, port_num);
break;
case USB_GADGET_XPORT_SMD:
gsmd_disconnect(&gser->port, port_num);
break;
case USB_GADGET_XPORT_HSIC:
ghsic_ctrl_disconnect(&gser->port, port_num);
ghsic_data_disconnect(&gser->port, port_num);
break;
case USB_GADGET_XPORT_HSUART:
ghsuart_data_disconnect(&gser->port, port_num);
break;
default:
pr_err("%s: Un-supported transport:%s\n", __func__,
xport_to_str(gser->transport));
return -ENODEV;
}
return 0;
}
#ifdef CONFIG_MODEM_SUPPORT
static void gser_complete_set_line_coding(struct usb_ep *ep,
struct usb_request *req)
{
struct f_gser *gser = ep->driver_data;
struct usb_composite_dev *cdev = gser->port.func.config->cdev;
if (req->status != 0) {
DBG(cdev, "gser ttyGS%d completion, err %d\n",
gser->port_num, req->status);
return;
}
/* normal completion */
if (req->actual != sizeof(gser->port_line_coding)) {
DBG(cdev, "gser ttyGS%d short resp, len %d\n",
gser->port_num, req->actual);
usb_ep_set_halt(ep);
} else {
struct usb_cdc_line_coding *value = req->buf;
gser->port_line_coding = *value;
}
}
/*-------------------------------------------------------------------------*/
static int
gser_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
{
struct f_gser *gser = func_to_gser(f);
struct usb_composite_dev *cdev = f->config->cdev;
struct usb_request *req = cdev->req;
int value = -EOPNOTSUPP;
u16 w_index = le16_to_cpu(ctrl->wIndex);
u16 w_value = le16_to_cpu(ctrl->wValue);
u16 w_length = le16_to_cpu(ctrl->wLength);
switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
/* SET_LINE_CODING ... just read and save what the host sends */
case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
| USB_CDC_REQ_SET_LINE_CODING:
if (w_length != sizeof(struct usb_cdc_line_coding))
goto invalid;
value = w_length;
cdev->gadget->ep0->driver_data = gser;
req->complete = gser_complete_set_line_coding;
break;
/* GET_LINE_CODING ... return what host sent, or initial value */
case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
| USB_CDC_REQ_GET_LINE_CODING:
value = min_t(unsigned, w_length,
sizeof(struct usb_cdc_line_coding));
memcpy(req->buf, &gser->port_line_coding, value);
break;
/* SET_CONTROL_LINE_STATE ... save what the host sent */
case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
| USB_CDC_REQ_SET_CONTROL_LINE_STATE:
value = 0;
gser->port_handshake_bits = w_value;
if (gser->port.notify_modem) {
unsigned port_num =
gserial_ports[gser->port_num].client_port_num;
gser->port.notify_modem(&gser->port,
port_num, w_value);
}
break;
default:
invalid:
DBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
}
/* respond with data transfer or status phase? */
if (value >= 0) {
DBG(cdev, "gser ttyGS%d req%02x.%02x v%04x i%04x l%d\n",
gser->port_num, ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
req->zero = 0;
req->length = value;
value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
if (value < 0)
ERROR(cdev, "gser response on ttyGS%d, err %d\n",
gser->port_num, value);
}
/* device either stalls (value < 0) or reports success */
return value;
}
#endif
static int gser_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
{
struct f_gser *gser = func_to_gser(f);
struct usb_composite_dev *cdev = f->config->cdev;
int rc = 0;
/* we know alt == 0, so this is an activation or a reset */
#ifdef CONFIG_MODEM_SUPPORT
if (gser->notify->driver_data) {
DBG(cdev, "reset generic ctl ttyGS%d\n", gser->port_num);
usb_ep_disable(gser->notify);
}
if (!gser->notify->desc) {
if (config_ep_by_speed(cdev->gadget, f, gser->notify)) {
gser->notify->desc = NULL;
return -EINVAL;
}
}
rc = usb_ep_enable(gser->notify);
if (rc) {
ERROR(cdev, "can't enable %s, result %d\n",
gser->notify->name, rc);
return rc;
}
gser->notify->driver_data = gser;
#endif
if (gser->port.in->driver_data) {
DBG(cdev, "reset generic data ttyGS%d\n", gser->port_num);
gport_disconnect(gser);
}
if (!gser->port.in->desc || !gser->port.out->desc) {
DBG(cdev, "activate generic ttyGS%d\n", gser->port_num);
if (config_ep_by_speed(cdev->gadget, f, gser->port.in) ||
config_ep_by_speed(cdev->gadget, f, gser->port.out)) {
gser->port.in->desc = NULL;
gser->port.out->desc = NULL;
return -EINVAL;
}
}
gport_connect(gser);
gser->online = 1;
return rc;
}
static void gser_disable(struct usb_function *f)
{
struct f_gser *gser = func_to_gser(f);
struct usb_composite_dev *cdev = f->config->cdev;
DBG(cdev, "generic ttyGS%d deactivated\n", gser->port_num);
gport_disconnect(gser);
#ifdef CONFIG_MODEM_SUPPORT
usb_ep_fifo_flush(gser->notify);
usb_ep_disable(gser->notify);
gser->notify->driver_data = NULL;
#endif
gser->online = 0;
}
#ifdef CONFIG_MODEM_SUPPORT
static int gser_notify(struct f_gser *gser, u8 type, u16 value,
void *data, unsigned length)
{
struct usb_ep *ep = gser->notify;
struct usb_request *req;
struct usb_cdc_notification *notify;
const unsigned len = sizeof(*notify) + length;
void *buf;
int status;
struct usb_composite_dev *cdev = gser->port.func.config->cdev;
req = gser->notify_req;
gser->notify_req = NULL;
gser->pending = false;
req->length = len;
notify = req->buf;
buf = notify + 1;
notify->bmRequestType = USB_DIR_IN | USB_TYPE_CLASS
| USB_RECIP_INTERFACE;
notify->bNotificationType = type;
notify->wValue = cpu_to_le16(value);
notify->wIndex = cpu_to_le16(gser->data_id);
notify->wLength = cpu_to_le16(length);
memcpy(buf, data, length);
status = usb_ep_queue(ep, req, GFP_ATOMIC);
if (status < 0) {
ERROR(cdev, "gser ttyGS%d can't notify serial state, %d\n",
gser->port_num, status);
gser->notify_req = req;
}
return status;
}
static int gser_notify_serial_state(struct f_gser *gser)
{
int status;
unsigned long flags;
struct usb_composite_dev *cdev = gser->port.func.config->cdev;
spin_lock_irqsave(&gser->lock, flags);
if (gser->notify_req) {
DBG(cdev, "gser ttyGS%d serial state %04x\n",
gser->port_num, gser->serial_state);
status = gser_notify(gser, USB_CDC_NOTIFY_SERIAL_STATE,
0, &gser->serial_state,
sizeof(gser->serial_state));
} else {
gser->pending = true;
status = 0;
}
spin_unlock_irqrestore(&gser->lock, flags);
return status;
}
static void gser_notify_complete(struct usb_ep *ep, struct usb_request *req)
{
struct f_gser *gser = req->context;
u8 doit = false;
unsigned long flags;
/* on this call path we do NOT hold the port spinlock,
* which is why ACM needs its own spinlock
*/
spin_lock_irqsave(&gser->lock, flags);
if (req->status != -ESHUTDOWN)
doit = gser->pending;
gser->notify_req = req;
spin_unlock_irqrestore(&gser->lock, flags);
if (doit && gser->online)
gser_notify_serial_state(gser);
}
static void gser_connect(struct gserial *port)
{
struct f_gser *gser = port_to_gser(port);
gser->serial_state |= ACM_CTRL_DSR | ACM_CTRL_DCD;
gser_notify_serial_state(gser);
}
unsigned int gser_get_dtr(struct gserial *port)
{
struct f_gser *gser = port_to_gser(port);
if (gser->port_handshake_bits & ACM_CTRL_DTR)
return 1;
else
return 0;
}
unsigned int gser_get_rts(struct gserial *port)
{
struct f_gser *gser = port_to_gser(port);
if (gser->port_handshake_bits & ACM_CTRL_RTS)
return 1;
else
return 0;
}
unsigned int gser_send_carrier_detect(struct gserial *port, unsigned int yes)
{
struct f_gser *gser = port_to_gser(port);
u16 state;
state = gser->serial_state;
state &= ~ACM_CTRL_DCD;
if (yes)
state |= ACM_CTRL_DCD;
gser->serial_state = state;
return gser_notify_serial_state(gser);
}
unsigned int gser_send_ring_indicator(struct gserial *port, unsigned int yes)
{
struct f_gser *gser = port_to_gser(port);
u16 state;
state = gser->serial_state;
state &= ~ACM_CTRL_RI;
if (yes)
state |= ACM_CTRL_RI;
gser->serial_state = state;
return gser_notify_serial_state(gser);
}
static void gser_disconnect(struct gserial *port)
{
struct f_gser *gser = port_to_gser(port);
gser->serial_state &= ~(ACM_CTRL_DSR | ACM_CTRL_DCD);
gser_notify_serial_state(gser);
}
static int gser_send_break(struct gserial *port, int duration)
{
struct f_gser *gser = port_to_gser(port);
u16 state;
state = gser->serial_state;
state &= ~ACM_CTRL_BRK;
if (duration)
state |= ACM_CTRL_BRK;
gser->serial_state = state;
return gser_notify_serial_state(gser);
}
static int gser_send_modem_ctrl_bits(struct gserial *port, int ctrl_bits)
{
struct f_gser *gser = port_to_gser(port);
gser->serial_state = ctrl_bits;
return gser_notify_serial_state(gser);
}
#endif
/*-------------------------------------------------------------------------*/
/* serial function driver setup/binding */
static int
gser_bind(struct usb_configuration *c, struct usb_function *f)
{
struct usb_composite_dev *cdev = c->cdev;
struct f_gser *gser = func_to_gser(f);
int status;
struct usb_ep *ep;
/* allocate instance-specific interface IDs */
status = usb_interface_id(c, f);
if (status < 0)
goto fail;
gser->data_id = status;
gser_interface_desc.bInterfaceNumber = status;
status = -ENODEV;
/* allocate instance-specific endpoints */
ep = usb_ep_autoconfig(cdev->gadget, &gser_fs_in_desc);
if (!ep)
goto fail;
gser->port.in = ep;
ep->driver_data = cdev; /* claim */
ep = usb_ep_autoconfig(cdev->gadget, &gser_fs_out_desc);
if (!ep)
goto fail;
gser->port.out = ep;
ep->driver_data = cdev; /* claim */
#ifdef CONFIG_MODEM_SUPPORT
ep = usb_ep_autoconfig(cdev->gadget, &gser_fs_notify_desc);
if (!ep)
goto fail;
gser->notify = ep;
ep->driver_data = cdev; /* claim */
/* allocate notification */
gser->notify_req = gs_alloc_req(ep,
sizeof(struct usb_cdc_notification) + 2,
GFP_KERNEL);
if (!gser->notify_req)
goto fail;
gser->notify_req->complete = gser_notify_complete;
gser->notify_req->context = gser;
#endif
/* copy descriptors, and track endpoint copies */
f->descriptors = usb_copy_descriptors(gser_fs_function);
if (!f->descriptors)
goto fail;
/* support all relevant hardware speeds... we expect that when
* hardware is dual speed, all bulk-capable endpoints work at
* both speeds
*/
if (gadget_is_dualspeed(c->cdev->gadget)) {
gser_hs_in_desc.bEndpointAddress =
gser_fs_in_desc.bEndpointAddress;
gser_hs_out_desc.bEndpointAddress =
gser_fs_out_desc.bEndpointAddress;
#ifdef CONFIG_MODEM_SUPPORT
gser_hs_notify_desc.bEndpointAddress =
gser_fs_notify_desc.bEndpointAddress;
#endif
/* copy descriptors, and track endpoint copies */
f->hs_descriptors = usb_copy_descriptors(gser_hs_function);
if (!f->hs_descriptors)
goto fail;
}
if (gadget_is_superspeed(c->cdev->gadget)) {
gser_ss_in_desc.bEndpointAddress =
gser_fs_in_desc.bEndpointAddress;
gser_ss_out_desc.bEndpointAddress =
gser_fs_out_desc.bEndpointAddress;
/* copy descriptors, and track endpoint copies */
f->ss_descriptors = usb_copy_descriptors(gser_ss_function);
if (!f->ss_descriptors)
goto fail;
}
DBG(cdev, "generic ttyGS%d: %s speed IN/%s OUT/%s\n",
gser->port_num,
gadget_is_superspeed(c->cdev->gadget) ? "super" :
gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
gser->port.in->name, gser->port.out->name);
return 0;
fail:
if (f->descriptors)
usb_free_descriptors(f->descriptors);
#ifdef CONFIG_MODEM_SUPPORT
if (gser->notify_req)
gs_free_req(gser->notify, gser->notify_req);
/* we might as well release our claims on endpoints */
if (gser->notify)
gser->notify->driver_data = NULL;
#endif
/* we might as well release our claims on endpoints */
if (gser->port.out)
gser->port.out->driver_data = NULL;
if (gser->port.in)
gser->port.in->driver_data = NULL;
ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
return status;
}
static void
gser_unbind(struct usb_configuration *c, struct usb_function *f)
{
#ifdef CONFIG_MODEM_SUPPORT
struct f_gser *gser = func_to_gser(f);
#endif
if (gadget_is_dualspeed(c->cdev->gadget))
usb_free_descriptors(f->hs_descriptors);
if (gadget_is_superspeed(c->cdev->gadget))
usb_free_descriptors(f->ss_descriptors);
usb_free_descriptors(f->descriptors);
#ifdef CONFIG_MODEM_SUPPORT
gs_free_req(gser->notify, gser->notify_req);
#endif
kfree(func_to_gser(f));
}
/**
* gser_bind_config - add a generic serial function to a configuration
* @c: the configuration to support the serial instance
* @port_num: /dev/ttyGS* port this interface will use
* Context: single threaded during gadget setup
*
* Returns zero on success, else negative errno.
*
* Caller must have called @gserial_setup() with enough ports to
* handle all the ones it binds. Caller is also responsible
* for calling @gserial_cleanup() before module unload.
*/
int gser_bind_config(struct usb_configuration *c, u8 port_num)
{
struct f_gser *gser;
int status;
/* REVISIT might want instance-specific strings to help
* distinguish instances ...
*/
/* maybe allocate device-global string ID */
if (gser_string_defs[0].id == 0) {
status = usb_string_id(c->cdev);
if (status < 0)
return status;
gser_string_defs[0].id = status;
}
/* allocate and initialize one new instance */
gser = kzalloc(sizeof *gser, GFP_KERNEL);
if (!gser)
return -ENOMEM;
#ifdef CONFIG_MODEM_SUPPORT
spin_lock_init(&gser->lock);
#endif
gser->port_num = port_num;
gser->port.func.name = "gser";
gser->port.func.strings = gser_strings;
gser->port.func.bind = gser_bind;
gser->port.func.unbind = gser_unbind;
gser->port.func.set_alt = gser_set_alt;
gser->port.func.disable = gser_disable;
gser->transport = gserial_ports[port_num].transport;
#ifdef CONFIG_MODEM_SUPPORT
/* We support only three ports for now */
if (port_num == 0)
gser->port.func.name = "modem";
else if (port_num == 1)
gser->port.func.name = "nmea";
else
gser->port.func.name = "modem2";
gser->port.func.setup = gser_setup;
gser->port.connect = gser_connect;
gser->port.get_dtr = gser_get_dtr;
gser->port.get_rts = gser_get_rts;
gser->port.send_carrier_detect = gser_send_carrier_detect;
gser->port.send_ring_indicator = gser_send_ring_indicator;
gser->port.send_modem_ctrl_bits = gser_send_modem_ctrl_bits;
gser->port.disconnect = gser_disconnect;
gser->port.send_break = gser_send_break;
#endif
status = usb_add_function(c, &gser->port.func);
if (status)
kfree(gser);
return status;
}
/**
* gserial_init_port - bind a gserial_port to its transport
*/
static int gserial_init_port(int port_num, const char *name,
const char *port_name)
{
enum transport_type transport;
int ret = 0;
if (port_num >= GSERIAL_NO_PORTS)
return -ENODEV;
transport = str_to_xport(name);
pr_debug("%s, port:%d, transport:%s\n", __func__,
port_num, xport_to_str(transport));
gserial_ports[port_num].transport = transport;
gserial_ports[port_num].port_num = port_num;
switch (transport) {
case USB_GADGET_XPORT_TTY:
gserial_ports[port_num].client_port_num = no_tty_ports;
no_tty_ports++;
break;
case USB_GADGET_XPORT_SDIO:
gserial_ports[port_num].client_port_num = no_sdio_ports;
no_sdio_ports++;
break;
case USB_GADGET_XPORT_SMD:
gserial_ports[port_num].client_port_num = no_smd_ports;
no_smd_ports++;
break;
case USB_GADGET_XPORT_HSIC:
ghsic_ctrl_set_port_name(port_name, name);
ghsic_data_set_port_name(port_name, name);
/*client port number will be updated in gport_setup*/
no_hsic_sports++;
break;
case USB_GADGET_XPORT_HSUART:
/*client port number will be updated in gport_setup*/
no_hsuart_sports++;
break;
default:
pr_err("%s: Un-supported transport transport: %u\n",
__func__, gserial_ports[port_num].transport);
return -ENODEV;
}
nr_ports++;
return ret;
}
| gpl-2.0 |
extremetempz/extremekernel | sound/sparc/dbri.c | 615 | 80387 | /*
* Driver for DBRI sound chip found on Sparcs.
* Copyright (C) 2004, 2005 Martin Habets (mhabets@users.sourceforge.net)
*
* Converted to ring buffered version by Krzysztof Helt (krzysztof.h1@wp.pl)
*
* Based entirely upon drivers/sbus/audio/dbri.c which is:
* Copyright (C) 1997 Rudolf Koenig (rfkoenig@immd4.informatik.uni-erlangen.de)
* Copyright (C) 1998, 1999 Brent Baccala (baccala@freesoft.org)
*
* This is the low level driver for the DBRI & MMCODEC duo used for ISDN & AUDIO
* on Sun SPARCStation 10, 20, LX and Voyager models.
*
* - DBRI: AT&T T5900FX Dual Basic Rates ISDN Interface. It is a 32 channel
* data time multiplexer with ISDN support (aka T7259)
* Interfaces: SBus,ISDN NT & TE, CHI, 4 bits parallel.
* CHI: (spelled ki) Concentration Highway Interface (AT&T or Intel bus ?).
* Documentation:
* - "STP 4000SBus Dual Basic Rate ISDN (DBRI) Transceiver" from
* Sparc Technology Business (courtesy of Sun Support)
* - Data sheet of the T7903, a newer but very similar ISA bus equivalent
* available from the Lucent (formerly AT&T microelectronics) home
* page.
* - http://www.freesoft.org/Linux/DBRI/
* - MMCODEC: Crystal Semiconductor CS4215 16 bit Multimedia Audio Codec
* Interfaces: CHI, Audio In & Out, 2 bits parallel
* Documentation: from the Crystal Semiconductor home page.
*
* The DBRI is a 32 pipe machine, each pipe can transfer some bits between
* memory and a serial device (long pipes, no. 0-15) or between two serial
* devices (short pipes, no. 16-31), or simply send a fixed data to a serial
* device (short pipes).
* A timeslot defines the bit-offset and no. of bits read from a serial device.
* The timeslots are linked to 6 circular lists, one for each direction for
* each serial device (NT,TE,CHI). A timeslot is associated to 1 or 2 pipes
* (the second one is a monitor/tee pipe, valid only for serial input).
*
* The mmcodec is connected via the CHI bus and needs the data & some
* parameters (volume, output selection) time multiplexed in 8 byte
* chunks. It also has a control mode, which serves for audio format setting.
*
* Looking at the CS4215 data sheet it is easy to set up 2 or 4 codecs on
* the same CHI bus, so I thought perhaps it is possible to use the on-board
* & the speakerbox codec simultaneously, giving 2 (not very independent :-)
* audio devices. But the SUN HW group decided against it, at least on my
* LX the speakerbox connector has at least 1 pin missing and 1 wrongly
* connected.
*
* I've tried to stick to the following function naming conventions:
* snd_* ALSA stuff
* cs4215_* CS4215 codec specific stuff
* dbri_* DBRI high-level stuff
* other DBRI low-level stuff
*/
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/dma-mapping.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/info.h>
#include <sound/control.h>
#include <sound/initval.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <asm/atomic.h>
MODULE_AUTHOR("Rudolf Koenig, Brent Baccala and Martin Habets");
MODULE_DESCRIPTION("Sun DBRI");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Sun,DBRI}}");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
/* Enable this card */
static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for Sun DBRI soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for Sun DBRI soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable Sun DBRI soundcard.");
#undef DBRI_DEBUG
#define D_INT (1<<0)
#define D_GEN (1<<1)
#define D_CMD (1<<2)
#define D_MM (1<<3)
#define D_USR (1<<4)
#define D_DESC (1<<5)
static int dbri_debug;
module_param(dbri_debug, int, 0644);
MODULE_PARM_DESC(dbri_debug, "Debug value for Sun DBRI soundcard.");
#ifdef DBRI_DEBUG
static char *cmds[] = {
"WAIT", "PAUSE", "JUMP", "IIQ", "REX", "SDP", "CDP", "DTS",
"SSP", "CHI", "NT", "TE", "CDEC", "TEST", "CDM", "RESRV"
};
#define dprintk(a, x...) if (dbri_debug & a) printk(KERN_DEBUG x)
#else
#define dprintk(a, x...) do { } while (0)
#endif /* DBRI_DEBUG */
#define DBRI_CMD(cmd, intr, value) ((cmd << 28) | \
(intr << 27) | \
value)
/***************************************************************************
CS4215 specific definitions and structures
****************************************************************************/
struct cs4215 {
__u8 data[4]; /* Data mode: Time slots 5-8 */
__u8 ctrl[4]; /* Ctrl mode: Time slots 1-4 */
__u8 onboard;
__u8 offset; /* Bit offset from frame sync to time slot 1 */
volatile __u32 status;
volatile __u32 version;
__u8 precision; /* In bits, either 8 or 16 */
__u8 channels; /* 1 or 2 */
};
/*
* Control mode first
*/
/* Time Slot 1, Status register */
#define CS4215_CLB (1<<2) /* Control Latch Bit */
#define CS4215_OLB (1<<3) /* 1: line: 2.0V, speaker 4V */
/* 0: line: 2.8V, speaker 8V */
#define CS4215_MLB (1<<4) /* 1: Microphone: 20dB gain disabled */
#define CS4215_RSRVD_1 (1<<5)
/* Time Slot 2, Data Format Register */
#define CS4215_DFR_LINEAR16 0
#define CS4215_DFR_ULAW 1
#define CS4215_DFR_ALAW 2
#define CS4215_DFR_LINEAR8 3
#define CS4215_DFR_STEREO (1<<2)
static struct {
unsigned short freq;
unsigned char xtal;
unsigned char csval;
} CS4215_FREQ[] = {
{ 8000, (1 << 4), (0 << 3) },
{ 16000, (1 << 4), (1 << 3) },
{ 27429, (1 << 4), (2 << 3) }, /* Actually 24428.57 */
{ 32000, (1 << 4), (3 << 3) },
/* { NA, (1 << 4), (4 << 3) }, */
/* { NA, (1 << 4), (5 << 3) }, */
{ 48000, (1 << 4), (6 << 3) },
{ 9600, (1 << 4), (7 << 3) },
{ 5512, (2 << 4), (0 << 3) }, /* Actually 5512.5 */
{ 11025, (2 << 4), (1 << 3) },
{ 18900, (2 << 4), (2 << 3) },
{ 22050, (2 << 4), (3 << 3) },
{ 37800, (2 << 4), (4 << 3) },
{ 44100, (2 << 4), (5 << 3) },
{ 33075, (2 << 4), (6 << 3) },
{ 6615, (2 << 4), (7 << 3) },
{ 0, 0, 0}
};
#define CS4215_HPF (1<<7) /* High Pass Filter, 1: Enabled */
#define CS4215_12_MASK 0xfcbf /* Mask off reserved bits in slot 1 & 2 */
/* Time Slot 3, Serial Port Control register */
#define CS4215_XEN (1<<0) /* 0: Enable serial output */
#define CS4215_XCLK (1<<1) /* 1: Master mode: Generate SCLK */
#define CS4215_BSEL_64 (0<<2) /* Bitrate: 64 bits per frame */
#define CS4215_BSEL_128 (1<<2)
#define CS4215_BSEL_256 (2<<2)
#define CS4215_MCK_MAST (0<<4) /* Master clock */
#define CS4215_MCK_XTL1 (1<<4) /* 24.576 MHz clock source */
#define CS4215_MCK_XTL2 (2<<4) /* 16.9344 MHz clock source */
#define CS4215_MCK_CLK1 (3<<4) /* Clockin, 256 x Fs */
#define CS4215_MCK_CLK2 (4<<4) /* Clockin, see DFR */
/* Time Slot 4, Test Register */
#define CS4215_DAD (1<<0) /* 0:Digital-Dig loop, 1:Dig-Analog-Dig loop */
#define CS4215_ENL (1<<1) /* Enable Loopback Testing */
/* Time Slot 5, Parallel Port Register */
/* Read only here and the same as the in data mode */
/* Time Slot 6, Reserved */
/* Time Slot 7, Version Register */
#define CS4215_VERSION_MASK 0xf /* Known versions 0/C, 1/D, 2/E */
/* Time Slot 8, Reserved */
/*
* Data mode
*/
/* Time Slot 1-2: Left Channel Data, 2-3: Right Channel Data */
/* Time Slot 5, Output Setting */
#define CS4215_LO(v) v /* Left Output Attenuation 0x3f: -94.5 dB */
#define CS4215_LE (1<<6) /* Line Out Enable */
#define CS4215_HE (1<<7) /* Headphone Enable */
/* Time Slot 6, Output Setting */
#define CS4215_RO(v) v /* Right Output Attenuation 0x3f: -94.5 dB */
#define CS4215_SE (1<<6) /* Speaker Enable */
#define CS4215_ADI (1<<7) /* A/D Data Invalid: Busy in calibration */
/* Time Slot 7, Input Setting */
#define CS4215_LG(v) v /* Left Gain Setting 0xf: 22.5 dB */
#define CS4215_IS (1<<4) /* Input Select: 1=Microphone, 0=Line */
#define CS4215_OVR (1<<5) /* 1: Over range condition occurred */
#define CS4215_PIO0 (1<<6) /* Parallel I/O 0 */
#define CS4215_PIO1 (1<<7)
/* Time Slot 8, Input Setting */
#define CS4215_RG(v) v /* Right Gain Setting 0xf: 22.5 dB */
#define CS4215_MA(v) (v<<4) /* Monitor Path Attenuation 0xf: mute */
/***************************************************************************
DBRI specific definitions and structures
****************************************************************************/
/* DBRI main registers */
#define REG0 0x00 /* Status and Control */
#define REG1 0x04 /* Mode and Interrupt */
#define REG2 0x08 /* Parallel IO */
#define REG3 0x0c /* Test */
#define REG8 0x20 /* Command Queue Pointer */
#define REG9 0x24 /* Interrupt Queue Pointer */
#define DBRI_NO_CMDS 64
#define DBRI_INT_BLK 64
#define DBRI_NO_DESCS 64
#define DBRI_NO_PIPES 32
#define DBRI_MAX_PIPE (DBRI_NO_PIPES - 1)
#define DBRI_REC 0
#define DBRI_PLAY 1
#define DBRI_NO_STREAMS 2
/* One transmit/receive descriptor */
/* When ba != 0 descriptor is used */
struct dbri_mem {
volatile __u32 word1;
__u32 ba; /* Transmit/Receive Buffer Address */
__u32 nda; /* Next Descriptor Address */
volatile __u32 word4;
};
/* This structure is in a DMA region where it can accessed by both
* the CPU and the DBRI
*/
struct dbri_dma {
s32 cmd[DBRI_NO_CMDS]; /* Place for commands */
volatile s32 intr[DBRI_INT_BLK]; /* Interrupt field */
struct dbri_mem desc[DBRI_NO_DESCS]; /* Xmit/receive descriptors */
};
#define dbri_dma_off(member, elem) \
((u32)(unsigned long) \
(&(((struct dbri_dma *)0)->member[elem])))
enum in_or_out { PIPEinput, PIPEoutput };
struct dbri_pipe {
u32 sdp; /* SDP command word */
int nextpipe; /* Next pipe in linked list */
int length; /* Length of timeslot (bits) */
int first_desc; /* Index of first descriptor */
int desc; /* Index of active descriptor */
volatile __u32 *recv_fixed_ptr; /* Ptr to receive fixed data */
};
/* Per stream (playback or record) information */
struct dbri_streaminfo {
struct snd_pcm_substream *substream;
u32 dvma_buffer; /* Device view of ALSA DMA buffer */
int size; /* Size of DMA buffer */
size_t offset; /* offset in user buffer */
int pipe; /* Data pipe used */
int left_gain; /* mixer elements */
int right_gain;
};
/* This structure holds the information for both chips (DBRI & CS4215) */
struct snd_dbri {
int regs_size, irq; /* Needed for unload */
struct of_device *op; /* OF device info */
spinlock_t lock;
struct dbri_dma *dma; /* Pointer to our DMA block */
u32 dma_dvma; /* DBRI visible DMA address */
void __iomem *regs; /* dbri HW regs */
int dbri_irqp; /* intr queue pointer */
struct dbri_pipe pipes[DBRI_NO_PIPES]; /* DBRI's 32 data pipes */
int next_desc[DBRI_NO_DESCS]; /* Index of next desc, or -1 */
spinlock_t cmdlock; /* Protects cmd queue accesses */
s32 *cmdptr; /* Pointer to the last queued cmd */
int chi_bpf;
struct cs4215 mm; /* mmcodec special info */
/* per stream (playback/record) info */
struct dbri_streaminfo stream_info[DBRI_NO_STREAMS];
};
#define DBRI_MAX_VOLUME 63 /* Output volume */
#define DBRI_MAX_GAIN 15 /* Input gain */
/* DBRI Reg0 - Status Control Register - defines. (Page 17) */
#define D_P (1<<15) /* Program command & queue pointer valid */
#define D_G (1<<14) /* Allow 4-Word SBus Burst */
#define D_S (1<<13) /* Allow 16-Word SBus Burst */
#define D_E (1<<12) /* Allow 8-Word SBus Burst */
#define D_X (1<<7) /* Sanity Timer Disable */
#define D_T (1<<6) /* Permit activation of the TE interface */
#define D_N (1<<5) /* Permit activation of the NT interface */
#define D_C (1<<4) /* Permit activation of the CHI interface */
#define D_F (1<<3) /* Force Sanity Timer Time-Out */
#define D_D (1<<2) /* Disable Master Mode */
#define D_H (1<<1) /* Halt for Analysis */
#define D_R (1<<0) /* Soft Reset */
/* DBRI Reg1 - Mode and Interrupt Register - defines. (Page 18) */
#define D_LITTLE_END (1<<8) /* Byte Order */
#define D_BIG_END (0<<8) /* Byte Order */
#define D_MRR (1<<4) /* Multiple Error Ack on SBus (read only) */
#define D_MLE (1<<3) /* Multiple Late Error on SBus (read only) */
#define D_LBG (1<<2) /* Lost Bus Grant on SBus (read only) */
#define D_MBE (1<<1) /* Burst Error on SBus (read only) */
#define D_IR (1<<0) /* Interrupt Indicator (read only) */
/* DBRI Reg2 - Parallel IO Register - defines. (Page 18) */
#define D_ENPIO3 (1<<7) /* Enable Pin 3 */
#define D_ENPIO2 (1<<6) /* Enable Pin 2 */
#define D_ENPIO1 (1<<5) /* Enable Pin 1 */
#define D_ENPIO0 (1<<4) /* Enable Pin 0 */
#define D_ENPIO (0xf0) /* Enable all the pins */
#define D_PIO3 (1<<3) /* Pin 3: 1: Data mode, 0: Ctrl mode */
#define D_PIO2 (1<<2) /* Pin 2: 1: Onboard PDN */
#define D_PIO1 (1<<1) /* Pin 1: 0: Reset */
#define D_PIO0 (1<<0) /* Pin 0: 1: Speakerbox PDN */
/* DBRI Commands (Page 20) */
#define D_WAIT 0x0 /* Stop execution */
#define D_PAUSE 0x1 /* Flush long pipes */
#define D_JUMP 0x2 /* New command queue */
#define D_IIQ 0x3 /* Initialize Interrupt Queue */
#define D_REX 0x4 /* Report command execution via interrupt */
#define D_SDP 0x5 /* Setup Data Pipe */
#define D_CDP 0x6 /* Continue Data Pipe (reread NULL Pointer) */
#define D_DTS 0x7 /* Define Time Slot */
#define D_SSP 0x8 /* Set short Data Pipe */
#define D_CHI 0x9 /* Set CHI Global Mode */
#define D_NT 0xa /* NT Command */
#define D_TE 0xb /* TE Command */
#define D_CDEC 0xc /* Codec setup */
#define D_TEST 0xd /* No comment */
#define D_CDM 0xe /* CHI Data mode command */
/* Special bits for some commands */
#define D_PIPE(v) ((v)<<0) /* Pipe No.: 0-15 long, 16-21 short */
/* Setup Data Pipe */
/* IRM */
#define D_SDP_2SAME (1<<18) /* Report 2nd time in a row value received */
#define D_SDP_CHANGE (2<<18) /* Report any changes */
#define D_SDP_EVERY (3<<18) /* Report any changes */
#define D_SDP_EOL (1<<17) /* EOL interrupt enable */
#define D_SDP_IDLE (1<<16) /* HDLC idle interrupt enable */
/* Pipe data MODE */
#define D_SDP_MEM (0<<13) /* To/from memory */
#define D_SDP_HDLC (2<<13)
#define D_SDP_HDLC_D (3<<13) /* D Channel (prio control) */
#define D_SDP_SER (4<<13) /* Serial to serial */
#define D_SDP_FIXED (6<<13) /* Short only */
#define D_SDP_MODE(v) ((v)&(7<<13))
#define D_SDP_TO_SER (1<<12) /* Direction */
#define D_SDP_FROM_SER (0<<12) /* Direction */
#define D_SDP_MSB (1<<11) /* Bit order within Byte */
#define D_SDP_LSB (0<<11) /* Bit order within Byte */
#define D_SDP_P (1<<10) /* Pointer Valid */
#define D_SDP_A (1<<8) /* Abort */
#define D_SDP_C (1<<7) /* Clear */
/* Define Time Slot */
#define D_DTS_VI (1<<17) /* Valid Input Time-Slot Descriptor */
#define D_DTS_VO (1<<16) /* Valid Output Time-Slot Descriptor */
#define D_DTS_INS (1<<15) /* Insert Time Slot */
#define D_DTS_DEL (0<<15) /* Delete Time Slot */
#define D_DTS_PRVIN(v) ((v)<<10) /* Previous In Pipe */
#define D_DTS_PRVOUT(v) ((v)<<5) /* Previous Out Pipe */
/* Time Slot defines */
#define D_TS_LEN(v) ((v)<<24) /* Number of bits in this time slot */
#define D_TS_CYCLE(v) ((v)<<14) /* Bit Count at start of TS */
#define D_TS_DI (1<<13) /* Data Invert */
#define D_TS_1CHANNEL (0<<10) /* Single Channel / Normal mode */
#define D_TS_MONITOR (2<<10) /* Monitor pipe */
#define D_TS_NONCONTIG (3<<10) /* Non contiguous mode */
#define D_TS_ANCHOR (7<<10) /* Starting short pipes */
#define D_TS_MON(v) ((v)<<5) /* Monitor Pipe */
#define D_TS_NEXT(v) ((v)<<0) /* Pipe no.: 0-15 long, 16-21 short */
/* Concentration Highway Interface Modes */
#define D_CHI_CHICM(v) ((v)<<16) /* Clock mode */
#define D_CHI_IR (1<<15) /* Immediate Interrupt Report */
#define D_CHI_EN (1<<14) /* CHIL Interrupt enabled */
#define D_CHI_OD (1<<13) /* Open Drain Enable */
#define D_CHI_FE (1<<12) /* Sample CHIFS on Rising Frame Edge */
#define D_CHI_FD (1<<11) /* Frame Drive */
#define D_CHI_BPF(v) ((v)<<0) /* Bits per Frame */
/* NT: These are here for completeness */
#define D_NT_FBIT (1<<17) /* Frame Bit */
#define D_NT_NBF (1<<16) /* Number of bad frames to loose framing */
#define D_NT_IRM_IMM (1<<15) /* Interrupt Report & Mask: Immediate */
#define D_NT_IRM_EN (1<<14) /* Interrupt Report & Mask: Enable */
#define D_NT_ISNT (1<<13) /* Configure interface as NT */
#define D_NT_FT (1<<12) /* Fixed Timing */
#define D_NT_EZ (1<<11) /* Echo Channel is Zeros */
#define D_NT_IFA (1<<10) /* Inhibit Final Activation */
#define D_NT_ACT (1<<9) /* Activate Interface */
#define D_NT_MFE (1<<8) /* Multiframe Enable */
#define D_NT_RLB(v) ((v)<<5) /* Remote Loopback */
#define D_NT_LLB(v) ((v)<<2) /* Local Loopback */
#define D_NT_FACT (1<<1) /* Force Activation */
#define D_NT_ABV (1<<0) /* Activate Bipolar Violation */
/* Codec Setup */
#define D_CDEC_CK(v) ((v)<<24) /* Clock Select */
#define D_CDEC_FED(v) ((v)<<12) /* FSCOD Falling Edge Delay */
#define D_CDEC_RED(v) ((v)<<0) /* FSCOD Rising Edge Delay */
/* Test */
#define D_TEST_RAM(v) ((v)<<16) /* RAM Pointer */
#define D_TEST_SIZE(v) ((v)<<11) /* */
#define D_TEST_ROMONOFF 0x5 /* Toggle ROM opcode monitor on/off */
#define D_TEST_PROC 0x6 /* Microprocessor test */
#define D_TEST_SER 0x7 /* Serial-Controller test */
#define D_TEST_RAMREAD 0x8 /* Copy from Ram to system memory */
#define D_TEST_RAMWRITE 0x9 /* Copy into Ram from system memory */
#define D_TEST_RAMBIST 0xa /* RAM Built-In Self Test */
#define D_TEST_MCBIST 0xb /* Microcontroller Built-In Self Test */
#define D_TEST_DUMP 0xe /* ROM Dump */
/* CHI Data Mode */
#define D_CDM_THI (1 << 8) /* Transmit Data on CHIDR Pin */
#define D_CDM_RHI (1 << 7) /* Receive Data on CHIDX Pin */
#define D_CDM_RCE (1 << 6) /* Receive on Rising Edge of CHICK */
#define D_CDM_XCE (1 << 2) /* Transmit Data on Rising Edge of CHICK */
#define D_CDM_XEN (1 << 1) /* Transmit Highway Enable */
#define D_CDM_REN (1 << 0) /* Receive Highway Enable */
/* The Interrupts */
#define D_INTR_BRDY 1 /* Buffer Ready for processing */
#define D_INTR_MINT 2 /* Marked Interrupt in RD/TD */
#define D_INTR_IBEG 3 /* Flag to idle transition detected (HDLC) */
#define D_INTR_IEND 4 /* Idle to flag transition detected (HDLC) */
#define D_INTR_EOL 5 /* End of List */
#define D_INTR_CMDI 6 /* Command has bean read */
#define D_INTR_XCMP 8 /* Transmission of frame complete */
#define D_INTR_SBRI 9 /* BRI status change info */
#define D_INTR_FXDT 10 /* Fixed data change */
#define D_INTR_CHIL 11 /* CHI lost frame sync (channel 36 only) */
#define D_INTR_COLL 11 /* Unrecoverable D-Channel collision */
#define D_INTR_DBYT 12 /* Dropped by frame slip */
#define D_INTR_RBYT 13 /* Repeated by frame slip */
#define D_INTR_LINT 14 /* Lost Interrupt */
#define D_INTR_UNDR 15 /* DMA underrun */
#define D_INTR_TE 32
#define D_INTR_NT 34
#define D_INTR_CHI 36
#define D_INTR_CMD 38
#define D_INTR_GETCHAN(v) (((v) >> 24) & 0x3f)
#define D_INTR_GETCODE(v) (((v) >> 20) & 0xf)
#define D_INTR_GETCMD(v) (((v) >> 16) & 0xf)
#define D_INTR_GETVAL(v) ((v) & 0xffff)
#define D_INTR_GETRVAL(v) ((v) & 0xfffff)
#define D_P_0 0 /* TE receive anchor */
#define D_P_1 1 /* TE transmit anchor */
#define D_P_2 2 /* NT transmit anchor */
#define D_P_3 3 /* NT receive anchor */
#define D_P_4 4 /* CHI send data */
#define D_P_5 5 /* CHI receive data */
#define D_P_6 6 /* */
#define D_P_7 7 /* */
#define D_P_8 8 /* */
#define D_P_9 9 /* */
#define D_P_10 10 /* */
#define D_P_11 11 /* */
#define D_P_12 12 /* */
#define D_P_13 13 /* */
#define D_P_14 14 /* */
#define D_P_15 15 /* */
#define D_P_16 16 /* CHI anchor pipe */
#define D_P_17 17 /* CHI send */
#define D_P_18 18 /* CHI receive */
#define D_P_19 19 /* CHI receive */
#define D_P_20 20 /* CHI receive */
#define D_P_21 21 /* */
#define D_P_22 22 /* */
#define D_P_23 23 /* */
#define D_P_24 24 /* */
#define D_P_25 25 /* */
#define D_P_26 26 /* */
#define D_P_27 27 /* */
#define D_P_28 28 /* */
#define D_P_29 29 /* */
#define D_P_30 30 /* */
#define D_P_31 31 /* */
/* Transmit descriptor defines */
#define DBRI_TD_F (1 << 31) /* End of Frame */
#define DBRI_TD_D (1 << 30) /* Do not append CRC */
#define DBRI_TD_CNT(v) ((v) << 16) /* Number of valid bytes in the buffer */
#define DBRI_TD_B (1 << 15) /* Final interrupt */
#define DBRI_TD_M (1 << 14) /* Marker interrupt */
#define DBRI_TD_I (1 << 13) /* Transmit Idle Characters */
#define DBRI_TD_FCNT(v) (v) /* Flag Count */
#define DBRI_TD_UNR (1 << 3) /* Underrun: transmitter is out of data */
#define DBRI_TD_ABT (1 << 2) /* Abort: frame aborted */
#define DBRI_TD_TBC (1 << 0) /* Transmit buffer Complete */
#define DBRI_TD_STATUS(v) ((v) & 0xff) /* Transmit status */
/* Maximum buffer size per TD: almost 8KB */
#define DBRI_TD_MAXCNT ((1 << 13) - 4)
/* Receive descriptor defines */
#define DBRI_RD_F (1 << 31) /* End of Frame */
#define DBRI_RD_C (1 << 30) /* Completed buffer */
#define DBRI_RD_B (1 << 15) /* Final interrupt */
#define DBRI_RD_M (1 << 14) /* Marker interrupt */
#define DBRI_RD_BCNT(v) (v) /* Buffer size */
#define DBRI_RD_CRC (1 << 7) /* 0: CRC is correct */
#define DBRI_RD_BBC (1 << 6) /* 1: Bad Byte received */
#define DBRI_RD_ABT (1 << 5) /* Abort: frame aborted */
#define DBRI_RD_OVRN (1 << 3) /* Overrun: data lost */
#define DBRI_RD_STATUS(v) ((v) & 0xff) /* Receive status */
#define DBRI_RD_CNT(v) (((v) >> 16) & 0x1fff) /* Valid bytes in the buffer */
/* stream_info[] access */
/* Translate the ALSA direction into the array index */
#define DBRI_STREAMNO(substream) \
(substream->stream == \
SNDRV_PCM_STREAM_PLAYBACK ? DBRI_PLAY: DBRI_REC)
/* Return a pointer to dbri_streaminfo */
#define DBRI_STREAM(dbri, substream) \
&dbri->stream_info[DBRI_STREAMNO(substream)]
/*
* Short data pipes transmit LSB first. The CS4215 receives MSB first. Grrr.
* So we have to reverse the bits. Note: not all bit lengths are supported
*/
static __u32 reverse_bytes(__u32 b, int len)
{
switch (len) {
case 32:
b = ((b & 0xffff0000) >> 16) | ((b & 0x0000ffff) << 16);
case 16:
b = ((b & 0xff00ff00) >> 8) | ((b & 0x00ff00ff) << 8);
case 8:
b = ((b & 0xf0f0f0f0) >> 4) | ((b & 0x0f0f0f0f) << 4);
case 4:
b = ((b & 0xcccccccc) >> 2) | ((b & 0x33333333) << 2);
case 2:
b = ((b & 0xaaaaaaaa) >> 1) | ((b & 0x55555555) << 1);
case 1:
case 0:
break;
default:
printk(KERN_ERR "DBRI reverse_bytes: unsupported length\n");
};
return b;
}
/*
****************************************************************************
************** DBRI initialization and command synchronization *************
****************************************************************************
Commands are sent to the DBRI by building a list of them in memory,
then writing the address of the first list item to DBRI register 8.
The list is terminated with a WAIT command, which generates a
CPU interrupt to signal completion.
Since the DBRI can run in parallel with the CPU, several means of
synchronization present themselves. The method implemented here uses
the dbri_cmdwait() to wait for execution of batch of sent commands.
A circular command buffer is used here. A new command is being added
while another can be executed. The scheme works by adding two WAIT commands
after each sent batch of commands. When the next batch is prepared it is
added after the WAIT commands then the WAITs are replaced with single JUMP
command to the new batch. The the DBRI is forced to reread the last WAIT
command (replaced by the JUMP by then). If the DBRI is still executing
previous commands the request to reread the WAIT command is ignored.
Every time a routine wants to write commands to the DBRI, it must
first call dbri_cmdlock() and get pointer to a free space in
dbri->dma->cmd buffer. After this, the commands can be written to
the buffer, and dbri_cmdsend() is called with the final pointer value
to send them to the DBRI.
*/
#define MAXLOOPS 20
/*
* Wait for the current command string to execute
*/
static void dbri_cmdwait(struct snd_dbri *dbri)
{
int maxloops = MAXLOOPS;
unsigned long flags;
/* Delay if previous commands are still being processed */
spin_lock_irqsave(&dbri->lock, flags);
while ((--maxloops) > 0 && (sbus_readl(dbri->regs + REG0) & D_P)) {
spin_unlock_irqrestore(&dbri->lock, flags);
msleep_interruptible(1);
spin_lock_irqsave(&dbri->lock, flags);
}
spin_unlock_irqrestore(&dbri->lock, flags);
if (maxloops == 0)
printk(KERN_ERR "DBRI: Chip never completed command buffer\n");
else
dprintk(D_CMD, "Chip completed command buffer (%d)\n",
MAXLOOPS - maxloops - 1);
}
/*
* Lock the command queue and return pointer to space for len cmd words
* It locks the cmdlock spinlock.
*/
static s32 *dbri_cmdlock(struct snd_dbri *dbri, int len)
{
/* Space for 2 WAIT cmds (replaced later by 1 JUMP cmd) */
len += 2;
spin_lock(&dbri->cmdlock);
if (dbri->cmdptr - dbri->dma->cmd + len < DBRI_NO_CMDS - 2)
return dbri->cmdptr + 2;
else if (len < sbus_readl(dbri->regs + REG8) - dbri->dma_dvma)
return dbri->dma->cmd;
else
printk(KERN_ERR "DBRI: no space for commands.");
return NULL;
}
/*
* Send prepared cmd string. It works by writing a JUMP cmd into
* the last WAIT cmd and force DBRI to reread the cmd.
* The JUMP cmd points to the new cmd string.
* It also releases the cmdlock spinlock.
*
* Lock must be held before calling this.
*/
static void dbri_cmdsend(struct snd_dbri *dbri, s32 *cmd, int len)
{
s32 tmp, addr;
static int wait_id = 0;
wait_id++;
wait_id &= 0xffff; /* restrict it to a 16 bit counter. */
*(cmd) = DBRI_CMD(D_WAIT, 1, wait_id);
*(cmd+1) = DBRI_CMD(D_WAIT, 1, wait_id);
/* Replace the last command with JUMP */
addr = dbri->dma_dvma + (cmd - len - dbri->dma->cmd) * sizeof(s32);
*(dbri->cmdptr+1) = addr;
*(dbri->cmdptr) = DBRI_CMD(D_JUMP, 0, 0);
#ifdef DBRI_DEBUG
if (cmd > dbri->cmdptr) {
s32 *ptr;
for (ptr = dbri->cmdptr; ptr < cmd+2; ptr++)
dprintk(D_CMD, "cmd: %lx:%08x\n",
(unsigned long)ptr, *ptr);
} else {
s32 *ptr = dbri->cmdptr;
dprintk(D_CMD, "cmd: %lx:%08x\n", (unsigned long)ptr, *ptr);
ptr++;
dprintk(D_CMD, "cmd: %lx:%08x\n", (unsigned long)ptr, *ptr);
for (ptr = dbri->dma->cmd; ptr < cmd+2; ptr++)
dprintk(D_CMD, "cmd: %lx:%08x\n",
(unsigned long)ptr, *ptr);
}
#endif
/* Reread the last command */
tmp = sbus_readl(dbri->regs + REG0);
tmp |= D_P;
sbus_writel(tmp, dbri->regs + REG0);
dbri->cmdptr = cmd;
spin_unlock(&dbri->cmdlock);
}
/* Lock must be held when calling this */
static void dbri_reset(struct snd_dbri *dbri)
{
int i;
u32 tmp;
dprintk(D_GEN, "reset 0:%x 2:%x 8:%x 9:%x\n",
sbus_readl(dbri->regs + REG0),
sbus_readl(dbri->regs + REG2),
sbus_readl(dbri->regs + REG8), sbus_readl(dbri->regs + REG9));
sbus_writel(D_R, dbri->regs + REG0); /* Soft Reset */
for (i = 0; (sbus_readl(dbri->regs + REG0) & D_R) && i < 64; i++)
udelay(10);
/* A brute approach - DBRI falls back to working burst size by itself
* On SS20 D_S does not work, so do not try so high. */
tmp = sbus_readl(dbri->regs + REG0);
tmp |= D_G | D_E;
tmp &= ~D_S;
sbus_writel(tmp, dbri->regs + REG0);
}
/* Lock must not be held before calling this */
static void __devinit dbri_initialize(struct snd_dbri *dbri)
{
s32 *cmd;
u32 dma_addr;
unsigned long flags;
int n;
spin_lock_irqsave(&dbri->lock, flags);
dbri_reset(dbri);
/* Initialize pipes */
for (n = 0; n < DBRI_NO_PIPES; n++)
dbri->pipes[n].desc = dbri->pipes[n].first_desc = -1;
spin_lock_init(&dbri->cmdlock);
/*
* Initialize the interrupt ring buffer.
*/
dma_addr = dbri->dma_dvma + dbri_dma_off(intr, 0);
dbri->dma->intr[0] = dma_addr;
dbri->dbri_irqp = 1;
/*
* Set up the interrupt queue
*/
spin_lock(&dbri->cmdlock);
cmd = dbri->cmdptr = dbri->dma->cmd;
*(cmd++) = DBRI_CMD(D_IIQ, 0, 0);
*(cmd++) = dma_addr;
*(cmd++) = DBRI_CMD(D_PAUSE, 0, 0);
dbri->cmdptr = cmd;
*(cmd++) = DBRI_CMD(D_WAIT, 1, 0);
*(cmd++) = DBRI_CMD(D_WAIT, 1, 0);
dma_addr = dbri->dma_dvma + dbri_dma_off(cmd, 0);
sbus_writel(dma_addr, dbri->regs + REG8);
spin_unlock(&dbri->cmdlock);
spin_unlock_irqrestore(&dbri->lock, flags);
dbri_cmdwait(dbri);
}
/*
****************************************************************************
************************** DBRI data pipe management ***********************
****************************************************************************
While DBRI control functions use the command and interrupt buffers, the
main data path takes the form of data pipes, which can be short (command
and interrupt driven), or long (attached to DMA buffers). These functions
provide a rudimentary means of setting up and managing the DBRI's pipes,
but the calling functions have to make sure they respect the pipes' linked
list ordering, among other things. The transmit and receive functions
here interface closely with the transmit and receive interrupt code.
*/
static inline int pipe_active(struct snd_dbri *dbri, int pipe)
{
return ((pipe >= 0) && (dbri->pipes[pipe].desc != -1));
}
/* reset_pipe(dbri, pipe)
*
* Called on an in-use pipe to clear anything being transmitted or received
* Lock must be held before calling this.
*/
static void reset_pipe(struct snd_dbri *dbri, int pipe)
{
int sdp;
int desc;
s32 *cmd;
if (pipe < 0 || pipe > DBRI_MAX_PIPE) {
printk(KERN_ERR "DBRI: reset_pipe called with "
"illegal pipe number\n");
return;
}
sdp = dbri->pipes[pipe].sdp;
if (sdp == 0) {
printk(KERN_ERR "DBRI: reset_pipe called "
"on uninitialized pipe\n");
return;
}
cmd = dbri_cmdlock(dbri, 3);
*(cmd++) = DBRI_CMD(D_SDP, 0, sdp | D_SDP_C | D_SDP_P);
*(cmd++) = 0;
*(cmd++) = DBRI_CMD(D_PAUSE, 0, 0);
dbri_cmdsend(dbri, cmd, 3);
desc = dbri->pipes[pipe].first_desc;
if (desc >= 0)
do {
dbri->dma->desc[desc].ba = 0;
dbri->dma->desc[desc].nda = 0;
desc = dbri->next_desc[desc];
} while (desc != -1 && desc != dbri->pipes[pipe].first_desc);
dbri->pipes[pipe].desc = -1;
dbri->pipes[pipe].first_desc = -1;
}
/*
* Lock must be held before calling this.
*/
static void setup_pipe(struct snd_dbri *dbri, int pipe, int sdp)
{
if (pipe < 0 || pipe > DBRI_MAX_PIPE) {
printk(KERN_ERR "DBRI: setup_pipe called "
"with illegal pipe number\n");
return;
}
if ((sdp & 0xf800) != sdp) {
printk(KERN_ERR "DBRI: setup_pipe called "
"with strange SDP value\n");
/* sdp &= 0xf800; */
}
/* If this is a fixed receive pipe, arrange for an interrupt
* every time its data changes
*/
if (D_SDP_MODE(sdp) == D_SDP_FIXED && !(sdp & D_SDP_TO_SER))
sdp |= D_SDP_CHANGE;
sdp |= D_PIPE(pipe);
dbri->pipes[pipe].sdp = sdp;
dbri->pipes[pipe].desc = -1;
dbri->pipes[pipe].first_desc = -1;
reset_pipe(dbri, pipe);
}
/*
* Lock must be held before calling this.
*/
static void link_time_slot(struct snd_dbri *dbri, int pipe,
int prevpipe, int nextpipe,
int length, int cycle)
{
s32 *cmd;
int val;
if (pipe < 0 || pipe > DBRI_MAX_PIPE
|| prevpipe < 0 || prevpipe > DBRI_MAX_PIPE
|| nextpipe < 0 || nextpipe > DBRI_MAX_PIPE) {
printk(KERN_ERR
"DBRI: link_time_slot called with illegal pipe number\n");
return;
}
if (dbri->pipes[pipe].sdp == 0
|| dbri->pipes[prevpipe].sdp == 0
|| dbri->pipes[nextpipe].sdp == 0) {
printk(KERN_ERR "DBRI: link_time_slot called "
"on uninitialized pipe\n");
return;
}
dbri->pipes[prevpipe].nextpipe = pipe;
dbri->pipes[pipe].nextpipe = nextpipe;
dbri->pipes[pipe].length = length;
cmd = dbri_cmdlock(dbri, 4);
if (dbri->pipes[pipe].sdp & D_SDP_TO_SER) {
/* Deal with CHI special case:
* "If transmission on edges 0 or 1 is desired, then cycle n
* (where n = # of bit times per frame...) must be used."
* - DBRI data sheet, page 11
*/
if (prevpipe == 16 && cycle == 0)
cycle = dbri->chi_bpf;
val = D_DTS_VO | D_DTS_INS | D_DTS_PRVOUT(prevpipe) | pipe;
*(cmd++) = DBRI_CMD(D_DTS, 0, val);
*(cmd++) = 0;
*(cmd++) =
D_TS_LEN(length) | D_TS_CYCLE(cycle) | D_TS_NEXT(nextpipe);
} else {
val = D_DTS_VI | D_DTS_INS | D_DTS_PRVIN(prevpipe) | pipe;
*(cmd++) = DBRI_CMD(D_DTS, 0, val);
*(cmd++) =
D_TS_LEN(length) | D_TS_CYCLE(cycle) | D_TS_NEXT(nextpipe);
*(cmd++) = 0;
}
*(cmd++) = DBRI_CMD(D_PAUSE, 0, 0);
dbri_cmdsend(dbri, cmd, 4);
}
#if 0
/*
* Lock must be held before calling this.
*/
static void unlink_time_slot(struct snd_dbri *dbri, int pipe,
enum in_or_out direction, int prevpipe,
int nextpipe)
{
s32 *cmd;
int val;
if (pipe < 0 || pipe > DBRI_MAX_PIPE
|| prevpipe < 0 || prevpipe > DBRI_MAX_PIPE
|| nextpipe < 0 || nextpipe > DBRI_MAX_PIPE) {
printk(KERN_ERR
"DBRI: unlink_time_slot called with illegal pipe number\n");
return;
}
cmd = dbri_cmdlock(dbri, 4);
if (direction == PIPEinput) {
val = D_DTS_VI | D_DTS_DEL | D_DTS_PRVIN(prevpipe) | pipe;
*(cmd++) = DBRI_CMD(D_DTS, 0, val);
*(cmd++) = D_TS_NEXT(nextpipe);
*(cmd++) = 0;
} else {
val = D_DTS_VO | D_DTS_DEL | D_DTS_PRVOUT(prevpipe) | pipe;
*(cmd++) = DBRI_CMD(D_DTS, 0, val);
*(cmd++) = 0;
*(cmd++) = D_TS_NEXT(nextpipe);
}
*(cmd++) = DBRI_CMD(D_PAUSE, 0, 0);
dbri_cmdsend(dbri, cmd, 4);
}
#endif
/* xmit_fixed() / recv_fixed()
*
* Transmit/receive data on a "fixed" pipe - i.e, one whose contents are not
* expected to change much, and which we don't need to buffer.
* The DBRI only interrupts us when the data changes (receive pipes),
* or only changes the data when this function is called (transmit pipes).
* Only short pipes (numbers 16-31) can be used in fixed data mode.
*
* These function operate on a 32-bit field, no matter how large
* the actual time slot is. The interrupt handler takes care of bit
* ordering and alignment. An 8-bit time slot will always end up
* in the low-order 8 bits, filled either MSB-first or LSB-first,
* depending on the settings passed to setup_pipe().
*
* Lock must not be held before calling it.
*/
static void xmit_fixed(struct snd_dbri *dbri, int pipe, unsigned int data)
{
s32 *cmd;
unsigned long flags;
if (pipe < 16 || pipe > DBRI_MAX_PIPE) {
printk(KERN_ERR "DBRI: xmit_fixed: Illegal pipe number\n");
return;
}
if (D_SDP_MODE(dbri->pipes[pipe].sdp) == 0) {
printk(KERN_ERR "DBRI: xmit_fixed: "
"Uninitialized pipe %d\n", pipe);
return;
}
if (D_SDP_MODE(dbri->pipes[pipe].sdp) != D_SDP_FIXED) {
printk(KERN_ERR "DBRI: xmit_fixed: Non-fixed pipe %d\n", pipe);
return;
}
if (!(dbri->pipes[pipe].sdp & D_SDP_TO_SER)) {
printk(KERN_ERR "DBRI: xmit_fixed: Called on receive pipe %d\n",
pipe);
return;
}
/* DBRI short pipes always transmit LSB first */
if (dbri->pipes[pipe].sdp & D_SDP_MSB)
data = reverse_bytes(data, dbri->pipes[pipe].length);
cmd = dbri_cmdlock(dbri, 3);
*(cmd++) = DBRI_CMD(D_SSP, 0, pipe);
*(cmd++) = data;
*(cmd++) = DBRI_CMD(D_PAUSE, 0, 0);
spin_lock_irqsave(&dbri->lock, flags);
dbri_cmdsend(dbri, cmd, 3);
spin_unlock_irqrestore(&dbri->lock, flags);
dbri_cmdwait(dbri);
}
static void recv_fixed(struct snd_dbri *dbri, int pipe, volatile __u32 *ptr)
{
if (pipe < 16 || pipe > DBRI_MAX_PIPE) {
printk(KERN_ERR "DBRI: recv_fixed called with "
"illegal pipe number\n");
return;
}
if (D_SDP_MODE(dbri->pipes[pipe].sdp) != D_SDP_FIXED) {
printk(KERN_ERR "DBRI: recv_fixed called on "
"non-fixed pipe %d\n", pipe);
return;
}
if (dbri->pipes[pipe].sdp & D_SDP_TO_SER) {
printk(KERN_ERR "DBRI: recv_fixed called on "
"transmit pipe %d\n", pipe);
return;
}
dbri->pipes[pipe].recv_fixed_ptr = ptr;
}
/* setup_descs()
*
* Setup transmit/receive data on a "long" pipe - i.e, one associated
* with a DMA buffer.
*
* Only pipe numbers 0-15 can be used in this mode.
*
* This function takes a stream number pointing to a data buffer,
* and work by building chains of descriptors which identify the
* data buffers. Buffers too large for a single descriptor will
* be spread across multiple descriptors.
*
* All descriptors create a ring buffer.
*
* Lock must be held before calling this.
*/
static int setup_descs(struct snd_dbri *dbri, int streamno, unsigned int period)
{
struct dbri_streaminfo *info = &dbri->stream_info[streamno];
__u32 dvma_buffer;
int desc;
int len;
int first_desc = -1;
int last_desc = -1;
if (info->pipe < 0 || info->pipe > 15) {
printk(KERN_ERR "DBRI: setup_descs: Illegal pipe number\n");
return -2;
}
if (dbri->pipes[info->pipe].sdp == 0) {
printk(KERN_ERR "DBRI: setup_descs: Uninitialized pipe %d\n",
info->pipe);
return -2;
}
dvma_buffer = info->dvma_buffer;
len = info->size;
if (streamno == DBRI_PLAY) {
if (!(dbri->pipes[info->pipe].sdp & D_SDP_TO_SER)) {
printk(KERN_ERR "DBRI: setup_descs: "
"Called on receive pipe %d\n", info->pipe);
return -2;
}
} else {
if (dbri->pipes[info->pipe].sdp & D_SDP_TO_SER) {
printk(KERN_ERR
"DBRI: setup_descs: Called on transmit pipe %d\n",
info->pipe);
return -2;
}
/* Should be able to queue multiple buffers
* to receive on a pipe
*/
if (pipe_active(dbri, info->pipe)) {
printk(KERN_ERR "DBRI: recv_on_pipe: "
"Called on active pipe %d\n", info->pipe);
return -2;
}
/* Make sure buffer size is multiple of four */
len &= ~3;
}
/* Free descriptors if pipe has any */
desc = dbri->pipes[info->pipe].first_desc;
if (desc >= 0)
do {
dbri->dma->desc[desc].ba = 0;
dbri->dma->desc[desc].nda = 0;
desc = dbri->next_desc[desc];
} while (desc != -1 &&
desc != dbri->pipes[info->pipe].first_desc);
dbri->pipes[info->pipe].desc = -1;
dbri->pipes[info->pipe].first_desc = -1;
desc = 0;
while (len > 0) {
int mylen;
for (; desc < DBRI_NO_DESCS; desc++) {
if (!dbri->dma->desc[desc].ba)
break;
}
if (desc == DBRI_NO_DESCS) {
printk(KERN_ERR "DBRI: setup_descs: No descriptors\n");
return -1;
}
if (len > DBRI_TD_MAXCNT)
mylen = DBRI_TD_MAXCNT; /* 8KB - 4 */
else
mylen = len;
if (mylen > period)
mylen = period;
dbri->next_desc[desc] = -1;
dbri->dma->desc[desc].ba = dvma_buffer;
dbri->dma->desc[desc].nda = 0;
if (streamno == DBRI_PLAY) {
dbri->dma->desc[desc].word1 = DBRI_TD_CNT(mylen);
dbri->dma->desc[desc].word4 = 0;
dbri->dma->desc[desc].word1 |= DBRI_TD_F | DBRI_TD_B;
} else {
dbri->dma->desc[desc].word1 = 0;
dbri->dma->desc[desc].word4 =
DBRI_RD_B | DBRI_RD_BCNT(mylen);
}
if (first_desc == -1)
first_desc = desc;
else {
dbri->next_desc[last_desc] = desc;
dbri->dma->desc[last_desc].nda =
dbri->dma_dvma + dbri_dma_off(desc, desc);
}
last_desc = desc;
dvma_buffer += mylen;
len -= mylen;
}
if (first_desc == -1 || last_desc == -1) {
printk(KERN_ERR "DBRI: setup_descs: "
" Not enough descriptors available\n");
return -1;
}
dbri->dma->desc[last_desc].nda =
dbri->dma_dvma + dbri_dma_off(desc, first_desc);
dbri->next_desc[last_desc] = first_desc;
dbri->pipes[info->pipe].first_desc = first_desc;
dbri->pipes[info->pipe].desc = first_desc;
#ifdef DBRI_DEBUG
for (desc = first_desc; desc != -1;) {
dprintk(D_DESC, "DESC %d: %08x %08x %08x %08x\n",
desc,
dbri->dma->desc[desc].word1,
dbri->dma->desc[desc].ba,
dbri->dma->desc[desc].nda, dbri->dma->desc[desc].word4);
desc = dbri->next_desc[desc];
if (desc == first_desc)
break;
}
#endif
return 0;
}
/*
****************************************************************************
************************** DBRI - CHI interface ****************************
****************************************************************************
The CHI is a four-wire (clock, frame sync, data in, data out) time-division
multiplexed serial interface which the DBRI can operate in either master
(give clock/frame sync) or slave (take clock/frame sync) mode.
*/
enum master_or_slave { CHImaster, CHIslave };
/*
* Lock must not be held before calling it.
*/
static void reset_chi(struct snd_dbri *dbri,
enum master_or_slave master_or_slave,
int bits_per_frame)
{
s32 *cmd;
int val;
/* Set CHI Anchor: Pipe 16 */
cmd = dbri_cmdlock(dbri, 4);
val = D_DTS_VO | D_DTS_VI | D_DTS_INS
| D_DTS_PRVIN(16) | D_PIPE(16) | D_DTS_PRVOUT(16);
*(cmd++) = DBRI_CMD(D_DTS, 0, val);
*(cmd++) = D_TS_ANCHOR | D_TS_NEXT(16);
*(cmd++) = D_TS_ANCHOR | D_TS_NEXT(16);
*(cmd++) = DBRI_CMD(D_PAUSE, 0, 0);
dbri_cmdsend(dbri, cmd, 4);
dbri->pipes[16].sdp = 1;
dbri->pipes[16].nextpipe = 16;
cmd = dbri_cmdlock(dbri, 4);
if (master_or_slave == CHIslave) {
/* Setup DBRI for CHI Slave - receive clock, frame sync (FS)
*
* CHICM = 0 (slave mode, 8 kHz frame rate)
* IR = give immediate CHI status interrupt
* EN = give CHI status interrupt upon change
*/
*(cmd++) = DBRI_CMD(D_CHI, 0, D_CHI_CHICM(0));
} else {
/* Setup DBRI for CHI Master - generate clock, FS
*
* BPF = bits per 8 kHz frame
* 12.288 MHz / CHICM_divisor = clock rate
* FD = 1 - drive CHIFS on rising edge of CHICK
*/
int clockrate = bits_per_frame * 8;
int divisor = 12288 / clockrate;
if (divisor > 255 || divisor * clockrate != 12288)
printk(KERN_ERR "DBRI: illegal bits_per_frame "
"in setup_chi\n");
*(cmd++) = DBRI_CMD(D_CHI, 0, D_CHI_CHICM(divisor) | D_CHI_FD
| D_CHI_BPF(bits_per_frame));
}
dbri->chi_bpf = bits_per_frame;
/* CHI Data Mode
*
* RCE = 0 - receive on falling edge of CHICK
* XCE = 1 - transmit on rising edge of CHICK
* XEN = 1 - enable transmitter
* REN = 1 - enable receiver
*/
*(cmd++) = DBRI_CMD(D_PAUSE, 0, 0);
*(cmd++) = DBRI_CMD(D_CDM, 0, D_CDM_XCE | D_CDM_XEN | D_CDM_REN);
*(cmd++) = DBRI_CMD(D_PAUSE, 0, 0);
dbri_cmdsend(dbri, cmd, 4);
}
/*
****************************************************************************
*********************** CS4215 audio codec management **********************
****************************************************************************
In the standard SPARC audio configuration, the CS4215 codec is attached
to the DBRI via the CHI interface and few of the DBRI's PIO pins.
* Lock must not be held before calling it.
*/
static __devinit void cs4215_setup_pipes(struct snd_dbri *dbri)
{
unsigned long flags;
spin_lock_irqsave(&dbri->lock, flags);
/*
* Data mode:
* Pipe 4: Send timeslots 1-4 (audio data)
* Pipe 20: Send timeslots 5-8 (part of ctrl data)
* Pipe 6: Receive timeslots 1-4 (audio data)
* Pipe 21: Receive timeslots 6-7. We can only receive 20 bits via
* interrupt, and the rest of the data (slot 5 and 8) is
* not relevant for us (only for doublechecking).
*
* Control mode:
* Pipe 17: Send timeslots 1-4 (slots 5-8 are read only)
* Pipe 18: Receive timeslot 1 (clb).
* Pipe 19: Receive timeslot 7 (version).
*/
setup_pipe(dbri, 4, D_SDP_MEM | D_SDP_TO_SER | D_SDP_MSB);
setup_pipe(dbri, 20, D_SDP_FIXED | D_SDP_TO_SER | D_SDP_MSB);
setup_pipe(dbri, 6, D_SDP_MEM | D_SDP_FROM_SER | D_SDP_MSB);
setup_pipe(dbri, 21, D_SDP_FIXED | D_SDP_FROM_SER | D_SDP_MSB);
setup_pipe(dbri, 17, D_SDP_FIXED | D_SDP_TO_SER | D_SDP_MSB);
setup_pipe(dbri, 18, D_SDP_FIXED | D_SDP_FROM_SER | D_SDP_MSB);
setup_pipe(dbri, 19, D_SDP_FIXED | D_SDP_FROM_SER | D_SDP_MSB);
spin_unlock_irqrestore(&dbri->lock, flags);
dbri_cmdwait(dbri);
}
static __devinit int cs4215_init_data(struct cs4215 *mm)
{
/*
* No action, memory resetting only.
*
* Data Time Slot 5-8
* Speaker,Line and Headphone enable. Gain set to the half.
* Input is mike.
*/
mm->data[0] = CS4215_LO(0x20) | CS4215_HE | CS4215_LE;
mm->data[1] = CS4215_RO(0x20) | CS4215_SE;
mm->data[2] = CS4215_LG(0x8) | CS4215_IS | CS4215_PIO0 | CS4215_PIO1;
mm->data[3] = CS4215_RG(0x8) | CS4215_MA(0xf);
/*
* Control Time Slot 1-4
* 0: Default I/O voltage scale
* 1: 8 bit ulaw, 8kHz, mono, high pass filter disabled
* 2: Serial enable, CHI master, 128 bits per frame, clock 1
* 3: Tests disabled
*/
mm->ctrl[0] = CS4215_RSRVD_1 | CS4215_MLB;
mm->ctrl[1] = CS4215_DFR_ULAW | CS4215_FREQ[0].csval;
mm->ctrl[2] = CS4215_XCLK | CS4215_BSEL_128 | CS4215_FREQ[0].xtal;
mm->ctrl[3] = 0;
mm->status = 0;
mm->version = 0xff;
mm->precision = 8; /* For ULAW */
mm->channels = 1;
return 0;
}
static void cs4215_setdata(struct snd_dbri *dbri, int muted)
{
if (muted) {
dbri->mm.data[0] |= 63;
dbri->mm.data[1] |= 63;
dbri->mm.data[2] &= ~15;
dbri->mm.data[3] &= ~15;
} else {
/* Start by setting the playback attenuation. */
struct dbri_streaminfo *info = &dbri->stream_info[DBRI_PLAY];
int left_gain = info->left_gain & 0x3f;
int right_gain = info->right_gain & 0x3f;
dbri->mm.data[0] &= ~0x3f; /* Reset the volume bits */
dbri->mm.data[1] &= ~0x3f;
dbri->mm.data[0] |= (DBRI_MAX_VOLUME - left_gain);
dbri->mm.data[1] |= (DBRI_MAX_VOLUME - right_gain);
/* Now set the recording gain. */
info = &dbri->stream_info[DBRI_REC];
left_gain = info->left_gain & 0xf;
right_gain = info->right_gain & 0xf;
dbri->mm.data[2] |= CS4215_LG(left_gain);
dbri->mm.data[3] |= CS4215_RG(right_gain);
}
xmit_fixed(dbri, 20, *(int *)dbri->mm.data);
}
/*
* Set the CS4215 to data mode.
*/
static void cs4215_open(struct snd_dbri *dbri)
{
int data_width;
u32 tmp;
unsigned long flags;
dprintk(D_MM, "cs4215_open: %d channels, %d bits\n",
dbri->mm.channels, dbri->mm.precision);
/* Temporarily mute outputs, and wait 1/8000 sec (125 us)
* to make sure this takes. This avoids clicking noises.
*/
cs4215_setdata(dbri, 1);
udelay(125);
/*
* Data mode:
* Pipe 4: Send timeslots 1-4 (audio data)
* Pipe 20: Send timeslots 5-8 (part of ctrl data)
* Pipe 6: Receive timeslots 1-4 (audio data)
* Pipe 21: Receive timeslots 6-7. We can only receive 20 bits via
* interrupt, and the rest of the data (slot 5 and 8) is
* not relevant for us (only for doublechecking).
*
* Just like in control mode, the time slots are all offset by eight
* bits. The CS4215, it seems, observes TSIN (the delayed signal)
* even if it's the CHI master. Don't ask me...
*/
spin_lock_irqsave(&dbri->lock, flags);
tmp = sbus_readl(dbri->regs + REG0);
tmp &= ~(D_C); /* Disable CHI */
sbus_writel(tmp, dbri->regs + REG0);
/* Switch CS4215 to data mode - set PIO3 to 1 */
sbus_writel(D_ENPIO | D_PIO1 | D_PIO3 |
(dbri->mm.onboard ? D_PIO0 : D_PIO2), dbri->regs + REG2);
reset_chi(dbri, CHIslave, 128);
/* Note: this next doesn't work for 8-bit stereo, because the two
* channels would be on timeslots 1 and 3, with 2 and 4 idle.
* (See CS4215 datasheet Fig 15)
*
* DBRI non-contiguous mode would be required to make this work.
*/
data_width = dbri->mm.channels * dbri->mm.precision;
link_time_slot(dbri, 4, 16, 16, data_width, dbri->mm.offset);
link_time_slot(dbri, 20, 4, 16, 32, dbri->mm.offset + 32);
link_time_slot(dbri, 6, 16, 16, data_width, dbri->mm.offset);
link_time_slot(dbri, 21, 6, 16, 16, dbri->mm.offset + 40);
/* FIXME: enable CHI after _setdata? */
tmp = sbus_readl(dbri->regs + REG0);
tmp |= D_C; /* Enable CHI */
sbus_writel(tmp, dbri->regs + REG0);
spin_unlock_irqrestore(&dbri->lock, flags);
cs4215_setdata(dbri, 0);
}
/*
* Send the control information (i.e. audio format)
*/
static int cs4215_setctrl(struct snd_dbri *dbri)
{
int i, val;
u32 tmp;
unsigned long flags;
/* FIXME - let the CPU do something useful during these delays */
/* Temporarily mute outputs, and wait 1/8000 sec (125 us)
* to make sure this takes. This avoids clicking noises.
*/
cs4215_setdata(dbri, 1);
udelay(125);
/*
* Enable Control mode: Set DBRI's PIO3 (4215's D/~C) to 0, then wait
* 12 cycles <= 12/(5512.5*64) sec = 34.01 usec
*/
val = D_ENPIO | D_PIO1 | (dbri->mm.onboard ? D_PIO0 : D_PIO2);
sbus_writel(val, dbri->regs + REG2);
dprintk(D_MM, "cs4215_setctrl: reg2=0x%x\n", val);
udelay(34);
/* In Control mode, the CS4215 is a slave device, so the DBRI must
* operate as CHI master, supplying clocking and frame synchronization.
*
* In Data mode, however, the CS4215 must be CHI master to insure
* that its data stream is synchronous with its codec.
*
* The upshot of all this? We start by putting the DBRI into master
* mode, program the CS4215 in Control mode, then switch the CS4215
* into Data mode and put the DBRI into slave mode. Various timing
* requirements must be observed along the way.
*
* Oh, and one more thing, on a SPARCStation 20 (and maybe
* others?), the addressing of the CS4215's time slots is
* offset by eight bits, so we add eight to all the "cycle"
* values in the Define Time Slot (DTS) commands. This is
* done in hardware by a TI 248 that delays the DBRI->4215
* frame sync signal by eight clock cycles. Anybody know why?
*/
spin_lock_irqsave(&dbri->lock, flags);
tmp = sbus_readl(dbri->regs + REG0);
tmp &= ~D_C; /* Disable CHI */
sbus_writel(tmp, dbri->regs + REG0);
reset_chi(dbri, CHImaster, 128);
/*
* Control mode:
* Pipe 17: Send timeslots 1-4 (slots 5-8 are read only)
* Pipe 18: Receive timeslot 1 (clb).
* Pipe 19: Receive timeslot 7 (version).
*/
link_time_slot(dbri, 17, 16, 16, 32, dbri->mm.offset);
link_time_slot(dbri, 18, 16, 16, 8, dbri->mm.offset);
link_time_slot(dbri, 19, 18, 16, 8, dbri->mm.offset + 48);
spin_unlock_irqrestore(&dbri->lock, flags);
/* Wait for the chip to echo back CLB (Control Latch Bit) as zero */
dbri->mm.ctrl[0] &= ~CS4215_CLB;
xmit_fixed(dbri, 17, *(int *)dbri->mm.ctrl);
spin_lock_irqsave(&dbri->lock, flags);
tmp = sbus_readl(dbri->regs + REG0);
tmp |= D_C; /* Enable CHI */
sbus_writel(tmp, dbri->regs + REG0);
spin_unlock_irqrestore(&dbri->lock, flags);
for (i = 10; ((dbri->mm.status & 0xe4) != 0x20); --i)
msleep_interruptible(1);
if (i == 0) {
dprintk(D_MM, "CS4215 didn't respond to CLB (0x%02x)\n",
dbri->mm.status);
return -1;
}
/* Disable changes to our copy of the version number, as we are about
* to leave control mode.
*/
recv_fixed(dbri, 19, NULL);
/* Terminate CS4215 control mode - data sheet says
* "Set CLB=1 and send two more frames of valid control info"
*/
dbri->mm.ctrl[0] |= CS4215_CLB;
xmit_fixed(dbri, 17, *(int *)dbri->mm.ctrl);
/* Two frames of control info @ 8kHz frame rate = 250 us delay */
udelay(250);
cs4215_setdata(dbri, 0);
return 0;
}
/*
* Setup the codec with the sampling rate, audio format and number of
* channels.
* As part of the process we resend the settings for the data
* timeslots as well.
*/
static int cs4215_prepare(struct snd_dbri *dbri, unsigned int rate,
snd_pcm_format_t format, unsigned int channels)
{
int freq_idx;
int ret = 0;
/* Lookup index for this rate */
for (freq_idx = 0; CS4215_FREQ[freq_idx].freq != 0; freq_idx++) {
if (CS4215_FREQ[freq_idx].freq == rate)
break;
}
if (CS4215_FREQ[freq_idx].freq != rate) {
printk(KERN_WARNING "DBRI: Unsupported rate %d Hz\n", rate);
return -1;
}
switch (format) {
case SNDRV_PCM_FORMAT_MU_LAW:
dbri->mm.ctrl[1] = CS4215_DFR_ULAW;
dbri->mm.precision = 8;
break;
case SNDRV_PCM_FORMAT_A_LAW:
dbri->mm.ctrl[1] = CS4215_DFR_ALAW;
dbri->mm.precision = 8;
break;
case SNDRV_PCM_FORMAT_U8:
dbri->mm.ctrl[1] = CS4215_DFR_LINEAR8;
dbri->mm.precision = 8;
break;
case SNDRV_PCM_FORMAT_S16_BE:
dbri->mm.ctrl[1] = CS4215_DFR_LINEAR16;
dbri->mm.precision = 16;
break;
default:
printk(KERN_WARNING "DBRI: Unsupported format %d\n", format);
return -1;
}
/* Add rate parameters */
dbri->mm.ctrl[1] |= CS4215_FREQ[freq_idx].csval;
dbri->mm.ctrl[2] = CS4215_XCLK |
CS4215_BSEL_128 | CS4215_FREQ[freq_idx].xtal;
dbri->mm.channels = channels;
if (channels == 2)
dbri->mm.ctrl[1] |= CS4215_DFR_STEREO;
ret = cs4215_setctrl(dbri);
if (ret == 0)
cs4215_open(dbri); /* set codec to data mode */
return ret;
}
/*
*
*/
static __devinit int cs4215_init(struct snd_dbri *dbri)
{
u32 reg2 = sbus_readl(dbri->regs + REG2);
dprintk(D_MM, "cs4215_init: reg2=0x%x\n", reg2);
/* Look for the cs4215 chips */
if (reg2 & D_PIO2) {
dprintk(D_MM, "Onboard CS4215 detected\n");
dbri->mm.onboard = 1;
}
if (reg2 & D_PIO0) {
dprintk(D_MM, "Speakerbox detected\n");
dbri->mm.onboard = 0;
if (reg2 & D_PIO2) {
printk(KERN_INFO "DBRI: Using speakerbox / "
"ignoring onboard mmcodec.\n");
sbus_writel(D_ENPIO2, dbri->regs + REG2);
}
}
if (!(reg2 & (D_PIO0 | D_PIO2))) {
printk(KERN_ERR "DBRI: no mmcodec found.\n");
return -EIO;
}
cs4215_setup_pipes(dbri);
cs4215_init_data(&dbri->mm);
/* Enable capture of the status & version timeslots. */
recv_fixed(dbri, 18, &dbri->mm.status);
recv_fixed(dbri, 19, &dbri->mm.version);
dbri->mm.offset = dbri->mm.onboard ? 0 : 8;
if (cs4215_setctrl(dbri) == -1 || dbri->mm.version == 0xff) {
dprintk(D_MM, "CS4215 failed probe at offset %d\n",
dbri->mm.offset);
return -EIO;
}
dprintk(D_MM, "Found CS4215 at offset %d\n", dbri->mm.offset);
return 0;
}
/*
****************************************************************************
*************************** DBRI interrupt handler *************************
****************************************************************************
The DBRI communicates with the CPU mainly via a circular interrupt
buffer. When an interrupt is signaled, the CPU walks through the
buffer and calls dbri_process_one_interrupt() for each interrupt word.
Complicated interrupts are handled by dedicated functions (which
appear first in this file). Any pending interrupts can be serviced by
calling dbri_process_interrupt_buffer(), which works even if the CPU's
interrupts are disabled.
*/
/* xmit_descs()
*
* Starts transmitting the current TD's for recording/playing.
* For playback, ALSA has filled the DMA memory with new data (we hope).
*/
static void xmit_descs(struct snd_dbri *dbri)
{
struct dbri_streaminfo *info;
s32 *cmd;
unsigned long flags;
int first_td;
if (dbri == NULL)
return; /* Disabled */
info = &dbri->stream_info[DBRI_REC];
spin_lock_irqsave(&dbri->lock, flags);
if (info->pipe >= 0) {
first_td = dbri->pipes[info->pipe].first_desc;
dprintk(D_DESC, "xmit_descs rec @ TD %d\n", first_td);
/* Stream could be closed by the time we run. */
if (first_td >= 0) {
cmd = dbri_cmdlock(dbri, 2);
*(cmd++) = DBRI_CMD(D_SDP, 0,
dbri->pipes[info->pipe].sdp
| D_SDP_P | D_SDP_EVERY | D_SDP_C);
*(cmd++) = dbri->dma_dvma +
dbri_dma_off(desc, first_td);
dbri_cmdsend(dbri, cmd, 2);
/* Reset our admin of the pipe. */
dbri->pipes[info->pipe].desc = first_td;
}
}
info = &dbri->stream_info[DBRI_PLAY];
if (info->pipe >= 0) {
first_td = dbri->pipes[info->pipe].first_desc;
dprintk(D_DESC, "xmit_descs play @ TD %d\n", first_td);
/* Stream could be closed by the time we run. */
if (first_td >= 0) {
cmd = dbri_cmdlock(dbri, 2);
*(cmd++) = DBRI_CMD(D_SDP, 0,
dbri->pipes[info->pipe].sdp
| D_SDP_P | D_SDP_EVERY | D_SDP_C);
*(cmd++) = dbri->dma_dvma +
dbri_dma_off(desc, first_td);
dbri_cmdsend(dbri, cmd, 2);
/* Reset our admin of the pipe. */
dbri->pipes[info->pipe].desc = first_td;
}
}
spin_unlock_irqrestore(&dbri->lock, flags);
}
/* transmission_complete_intr()
*
* Called by main interrupt handler when DBRI signals transmission complete
* on a pipe (interrupt triggered by the B bit in a transmit descriptor).
*
* Walks through the pipe's list of transmit buffer descriptors and marks
* them as available. Stops when the first descriptor is found without
* TBC (Transmit Buffer Complete) set, or we've run through them all.
*
* The DMA buffers are not released. They form a ring buffer and
* they are filled by ALSA while others are transmitted by DMA.
*
*/
static void transmission_complete_intr(struct snd_dbri *dbri, int pipe)
{
struct dbri_streaminfo *info = &dbri->stream_info[DBRI_PLAY];
int td = dbri->pipes[pipe].desc;
int status;
while (td >= 0) {
if (td >= DBRI_NO_DESCS) {
printk(KERN_ERR "DBRI: invalid td on pipe %d\n", pipe);
return;
}
status = DBRI_TD_STATUS(dbri->dma->desc[td].word4);
if (!(status & DBRI_TD_TBC))
break;
dprintk(D_INT, "TD %d, status 0x%02x\n", td, status);
dbri->dma->desc[td].word4 = 0; /* Reset it for next time. */
info->offset += DBRI_RD_CNT(dbri->dma->desc[td].word1);
td = dbri->next_desc[td];
dbri->pipes[pipe].desc = td;
}
/* Notify ALSA */
spin_unlock(&dbri->lock);
snd_pcm_period_elapsed(info->substream);
spin_lock(&dbri->lock);
}
static void reception_complete_intr(struct snd_dbri *dbri, int pipe)
{
struct dbri_streaminfo *info;
int rd = dbri->pipes[pipe].desc;
s32 status;
if (rd < 0 || rd >= DBRI_NO_DESCS) {
printk(KERN_ERR "DBRI: invalid rd on pipe %d\n", pipe);
return;
}
dbri->pipes[pipe].desc = dbri->next_desc[rd];
status = dbri->dma->desc[rd].word1;
dbri->dma->desc[rd].word1 = 0; /* Reset it for next time. */
info = &dbri->stream_info[DBRI_REC];
info->offset += DBRI_RD_CNT(status);
/* FIXME: Check status */
dprintk(D_INT, "Recv RD %d, status 0x%02x, len %d\n",
rd, DBRI_RD_STATUS(status), DBRI_RD_CNT(status));
/* Notify ALSA */
spin_unlock(&dbri->lock);
snd_pcm_period_elapsed(info->substream);
spin_lock(&dbri->lock);
}
static void dbri_process_one_interrupt(struct snd_dbri *dbri, int x)
{
int val = D_INTR_GETVAL(x);
int channel = D_INTR_GETCHAN(x);
int command = D_INTR_GETCMD(x);
int code = D_INTR_GETCODE(x);
#ifdef DBRI_DEBUG
int rval = D_INTR_GETRVAL(x);
#endif
if (channel == D_INTR_CMD) {
dprintk(D_CMD, "INTR: Command: %-5s Value:%d\n",
cmds[command], val);
} else {
dprintk(D_INT, "INTR: Chan:%d Code:%d Val:%#x\n",
channel, code, rval);
}
switch (code) {
case D_INTR_CMDI:
if (command != D_WAIT)
printk(KERN_ERR "DBRI: Command read interrupt\n");
break;
case D_INTR_BRDY:
reception_complete_intr(dbri, channel);
break;
case D_INTR_XCMP:
case D_INTR_MINT:
transmission_complete_intr(dbri, channel);
break;
case D_INTR_UNDR:
/* UNDR - Transmission underrun
* resend SDP command with clear pipe bit (C) set
*/
{
/* FIXME: do something useful in case of underrun */
printk(KERN_ERR "DBRI: Underrun error\n");
#if 0
s32 *cmd;
int pipe = channel;
int td = dbri->pipes[pipe].desc;
dbri->dma->desc[td].word4 = 0;
cmd = dbri_cmdlock(dbri, NoGetLock);
*(cmd++) = DBRI_CMD(D_SDP, 0,
dbri->pipes[pipe].sdp
| D_SDP_P | D_SDP_C | D_SDP_2SAME);
*(cmd++) = dbri->dma_dvma + dbri_dma_off(desc, td);
dbri_cmdsend(dbri, cmd);
#endif
}
break;
case D_INTR_FXDT:
/* FXDT - Fixed data change */
if (dbri->pipes[channel].sdp & D_SDP_MSB)
val = reverse_bytes(val, dbri->pipes[channel].length);
if (dbri->pipes[channel].recv_fixed_ptr)
*(dbri->pipes[channel].recv_fixed_ptr) = val;
break;
default:
if (channel != D_INTR_CMD)
printk(KERN_WARNING
"DBRI: Ignored Interrupt: %d (0x%x)\n", code, x);
}
}
/* dbri_process_interrupt_buffer advances through the DBRI's interrupt
* buffer until it finds a zero word (indicating nothing more to do
* right now). Non-zero words require processing and are handed off
* to dbri_process_one_interrupt AFTER advancing the pointer.
*/
static void dbri_process_interrupt_buffer(struct snd_dbri *dbri)
{
s32 x;
while ((x = dbri->dma->intr[dbri->dbri_irqp]) != 0) {
dbri->dma->intr[dbri->dbri_irqp] = 0;
dbri->dbri_irqp++;
if (dbri->dbri_irqp == DBRI_INT_BLK)
dbri->dbri_irqp = 1;
dbri_process_one_interrupt(dbri, x);
}
}
static irqreturn_t snd_dbri_interrupt(int irq, void *dev_id)
{
struct snd_dbri *dbri = dev_id;
static int errcnt = 0;
int x;
if (dbri == NULL)
return IRQ_NONE;
spin_lock(&dbri->lock);
/*
* Read it, so the interrupt goes away.
*/
x = sbus_readl(dbri->regs + REG1);
if (x & (D_MRR | D_MLE | D_LBG | D_MBE)) {
u32 tmp;
if (x & D_MRR)
printk(KERN_ERR
"DBRI: Multiple Error Ack on SBus reg1=0x%x\n",
x);
if (x & D_MLE)
printk(KERN_ERR
"DBRI: Multiple Late Error on SBus reg1=0x%x\n",
x);
if (x & D_LBG)
printk(KERN_ERR
"DBRI: Lost Bus Grant on SBus reg1=0x%x\n", x);
if (x & D_MBE)
printk(KERN_ERR
"DBRI: Burst Error on SBus reg1=0x%x\n", x);
/* Some of these SBus errors cause the chip's SBus circuitry
* to be disabled, so just re-enable and try to keep going.
*
* The only one I've seen is MRR, which will be triggered
* if you let a transmit pipe underrun, then try to CDP it.
*
* If these things persist, we reset the chip.
*/
if ((++errcnt) % 10 == 0) {
dprintk(D_INT, "Interrupt errors exceeded.\n");
dbri_reset(dbri);
} else {
tmp = sbus_readl(dbri->regs + REG0);
tmp &= ~(D_D);
sbus_writel(tmp, dbri->regs + REG0);
}
}
dbri_process_interrupt_buffer(dbri);
spin_unlock(&dbri->lock);
return IRQ_HANDLED;
}
/****************************************************************************
PCM Interface
****************************************************************************/
static struct snd_pcm_hardware snd_dbri_pcm_hw = {
.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_BATCH,
.formats = SNDRV_PCM_FMTBIT_MU_LAW |
SNDRV_PCM_FMTBIT_A_LAW |
SNDRV_PCM_FMTBIT_U8 |
SNDRV_PCM_FMTBIT_S16_BE,
.rates = SNDRV_PCM_RATE_8000_48000 | SNDRV_PCM_RATE_5512,
.rate_min = 5512,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = 64 * 1024,
.period_bytes_min = 1,
.period_bytes_max = DBRI_TD_MAXCNT,
.periods_min = 1,
.periods_max = 1024,
};
static int snd_hw_rule_format(struct snd_pcm_hw_params *params,
struct snd_pcm_hw_rule *rule)
{
struct snd_interval *c = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
struct snd_mask *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
struct snd_mask fmt;
snd_mask_any(&fmt);
if (c->min > 1) {
fmt.bits[0] &= SNDRV_PCM_FMTBIT_S16_BE;
return snd_mask_refine(f, &fmt);
}
return 0;
}
static int snd_hw_rule_channels(struct snd_pcm_hw_params *params,
struct snd_pcm_hw_rule *rule)
{
struct snd_interval *c = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
struct snd_mask *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
struct snd_interval ch;
snd_interval_any(&ch);
if (!(f->bits[0] & SNDRV_PCM_FMTBIT_S16_BE)) {
ch.min = 1;
ch.max = 1;
ch.integer = 1;
return snd_interval_refine(c, &ch);
}
return 0;
}
static int snd_dbri_open(struct snd_pcm_substream *substream)
{
struct snd_dbri *dbri = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct dbri_streaminfo *info = DBRI_STREAM(dbri, substream);
unsigned long flags;
dprintk(D_USR, "open audio output.\n");
runtime->hw = snd_dbri_pcm_hw;
spin_lock_irqsave(&dbri->lock, flags);
info->substream = substream;
info->offset = 0;
info->dvma_buffer = 0;
info->pipe = -1;
spin_unlock_irqrestore(&dbri->lock, flags);
snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
snd_hw_rule_format, NULL, SNDRV_PCM_HW_PARAM_FORMAT,
-1);
snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
snd_hw_rule_channels, NULL,
SNDRV_PCM_HW_PARAM_CHANNELS,
-1);
cs4215_open(dbri);
return 0;
}
static int snd_dbri_close(struct snd_pcm_substream *substream)
{
struct snd_dbri *dbri = snd_pcm_substream_chip(substream);
struct dbri_streaminfo *info = DBRI_STREAM(dbri, substream);
dprintk(D_USR, "close audio output.\n");
info->substream = NULL;
info->offset = 0;
return 0;
}
static int snd_dbri_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_dbri *dbri = snd_pcm_substream_chip(substream);
struct dbri_streaminfo *info = DBRI_STREAM(dbri, substream);
int direction;
int ret;
/* set sampling rate, audio format and number of channels */
ret = cs4215_prepare(dbri, params_rate(hw_params),
params_format(hw_params),
params_channels(hw_params));
if (ret != 0)
return ret;
if ((ret = snd_pcm_lib_malloc_pages(substream,
params_buffer_bytes(hw_params))) < 0) {
printk(KERN_ERR "malloc_pages failed with %d\n", ret);
return ret;
}
/* hw_params can get called multiple times. Only map the DMA once.
*/
if (info->dvma_buffer == 0) {
if (DBRI_STREAMNO(substream) == DBRI_PLAY)
direction = DMA_TO_DEVICE;
else
direction = DMA_FROM_DEVICE;
info->dvma_buffer =
dma_map_single(&dbri->op->dev,
runtime->dma_area,
params_buffer_bytes(hw_params),
direction);
}
direction = params_buffer_bytes(hw_params);
dprintk(D_USR, "hw_params: %d bytes, dvma=%x\n",
direction, info->dvma_buffer);
return 0;
}
static int snd_dbri_hw_free(struct snd_pcm_substream *substream)
{
struct snd_dbri *dbri = snd_pcm_substream_chip(substream);
struct dbri_streaminfo *info = DBRI_STREAM(dbri, substream);
int direction;
dprintk(D_USR, "hw_free.\n");
/* hw_free can get called multiple times. Only unmap the DMA once.
*/
if (info->dvma_buffer) {
if (DBRI_STREAMNO(substream) == DBRI_PLAY)
direction = DMA_TO_DEVICE;
else
direction = DMA_FROM_DEVICE;
dma_unmap_single(&dbri->op->dev, info->dvma_buffer,
substream->runtime->buffer_size, direction);
info->dvma_buffer = 0;
}
if (info->pipe != -1) {
reset_pipe(dbri, info->pipe);
info->pipe = -1;
}
return snd_pcm_lib_free_pages(substream);
}
static int snd_dbri_prepare(struct snd_pcm_substream *substream)
{
struct snd_dbri *dbri = snd_pcm_substream_chip(substream);
struct dbri_streaminfo *info = DBRI_STREAM(dbri, substream);
int ret;
info->size = snd_pcm_lib_buffer_bytes(substream);
if (DBRI_STREAMNO(substream) == DBRI_PLAY)
info->pipe = 4; /* Send pipe */
else
info->pipe = 6; /* Receive pipe */
spin_lock_irq(&dbri->lock);
info->offset = 0;
/* Setup the all the transmit/receive descriptors to cover the
* whole DMA buffer.
*/
ret = setup_descs(dbri, DBRI_STREAMNO(substream),
snd_pcm_lib_period_bytes(substream));
spin_unlock_irq(&dbri->lock);
dprintk(D_USR, "prepare audio output. %d bytes\n", info->size);
return ret;
}
static int snd_dbri_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct snd_dbri *dbri = snd_pcm_substream_chip(substream);
struct dbri_streaminfo *info = DBRI_STREAM(dbri, substream);
int ret = 0;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
dprintk(D_USR, "start audio, period is %d bytes\n",
(int)snd_pcm_lib_period_bytes(substream));
/* Re-submit the TDs. */
xmit_descs(dbri);
break;
case SNDRV_PCM_TRIGGER_STOP:
dprintk(D_USR, "stop audio.\n");
reset_pipe(dbri, info->pipe);
break;
default:
ret = -EINVAL;
}
return ret;
}
static snd_pcm_uframes_t snd_dbri_pointer(struct snd_pcm_substream *substream)
{
struct snd_dbri *dbri = snd_pcm_substream_chip(substream);
struct dbri_streaminfo *info = DBRI_STREAM(dbri, substream);
snd_pcm_uframes_t ret;
ret = bytes_to_frames(substream->runtime, info->offset)
% substream->runtime->buffer_size;
dprintk(D_USR, "I/O pointer: %ld frames of %ld.\n",
ret, substream->runtime->buffer_size);
return ret;
}
static struct snd_pcm_ops snd_dbri_ops = {
.open = snd_dbri_open,
.close = snd_dbri_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_dbri_hw_params,
.hw_free = snd_dbri_hw_free,
.prepare = snd_dbri_prepare,
.trigger = snd_dbri_trigger,
.pointer = snd_dbri_pointer,
};
static int __devinit snd_dbri_pcm(struct snd_card *card)
{
struct snd_pcm *pcm;
int err;
if ((err = snd_pcm_new(card,
/* ID */ "sun_dbri",
/* device */ 0,
/* playback count */ 1,
/* capture count */ 1, &pcm)) < 0)
return err;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_dbri_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_dbri_ops);
pcm->private_data = card->private_data;
pcm->info_flags = 0;
strcpy(pcm->name, card->shortname);
if ((err = snd_pcm_lib_preallocate_pages_for_all(pcm,
SNDRV_DMA_TYPE_CONTINUOUS,
snd_dma_continuous_data(GFP_KERNEL),
64 * 1024, 64 * 1024)) < 0)
return err;
return 0;
}
/*****************************************************************************
Mixer interface
*****************************************************************************/
static int snd_cs4215_info_volume(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0;
if (kcontrol->private_value == DBRI_PLAY)
uinfo->value.integer.max = DBRI_MAX_VOLUME;
else
uinfo->value.integer.max = DBRI_MAX_GAIN;
return 0;
}
static int snd_cs4215_get_volume(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_dbri *dbri = snd_kcontrol_chip(kcontrol);
struct dbri_streaminfo *info;
if (snd_BUG_ON(!dbri))
return -EINVAL;
info = &dbri->stream_info[kcontrol->private_value];
ucontrol->value.integer.value[0] = info->left_gain;
ucontrol->value.integer.value[1] = info->right_gain;
return 0;
}
static int snd_cs4215_put_volume(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_dbri *dbri = snd_kcontrol_chip(kcontrol);
struct dbri_streaminfo *info =
&dbri->stream_info[kcontrol->private_value];
unsigned int vol[2];
int changed = 0;
vol[0] = ucontrol->value.integer.value[0];
vol[1] = ucontrol->value.integer.value[1];
if (kcontrol->private_value == DBRI_PLAY) {
if (vol[0] > DBRI_MAX_VOLUME || vol[1] > DBRI_MAX_VOLUME)
return -EINVAL;
} else {
if (vol[0] > DBRI_MAX_GAIN || vol[1] > DBRI_MAX_GAIN)
return -EINVAL;
}
if (info->left_gain != vol[0]) {
info->left_gain = vol[0];
changed = 1;
}
if (info->right_gain != vol[1]) {
info->right_gain = vol[1];
changed = 1;
}
if (changed) {
/* First mute outputs, and wait 1/8000 sec (125 us)
* to make sure this takes. This avoids clicking noises.
*/
cs4215_setdata(dbri, 1);
udelay(125);
cs4215_setdata(dbri, 0);
}
return changed;
}
static int snd_cs4215_info_single(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
int mask = (kcontrol->private_value >> 16) & 0xff;
uinfo->type = (mask == 1) ?
SNDRV_CTL_ELEM_TYPE_BOOLEAN : SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = mask;
return 0;
}
static int snd_cs4215_get_single(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_dbri *dbri = snd_kcontrol_chip(kcontrol);
int elem = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 1;
if (snd_BUG_ON(!dbri))
return -EINVAL;
if (elem < 4)
ucontrol->value.integer.value[0] =
(dbri->mm.data[elem] >> shift) & mask;
else
ucontrol->value.integer.value[0] =
(dbri->mm.ctrl[elem - 4] >> shift) & mask;
if (invert == 1)
ucontrol->value.integer.value[0] =
mask - ucontrol->value.integer.value[0];
return 0;
}
static int snd_cs4215_put_single(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_dbri *dbri = snd_kcontrol_chip(kcontrol);
int elem = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 1;
int changed = 0;
unsigned short val;
if (snd_BUG_ON(!dbri))
return -EINVAL;
val = (ucontrol->value.integer.value[0] & mask);
if (invert == 1)
val = mask - val;
val <<= shift;
if (elem < 4) {
dbri->mm.data[elem] = (dbri->mm.data[elem] &
~(mask << shift)) | val;
changed = (val != dbri->mm.data[elem]);
} else {
dbri->mm.ctrl[elem - 4] = (dbri->mm.ctrl[elem - 4] &
~(mask << shift)) | val;
changed = (val != dbri->mm.ctrl[elem - 4]);
}
dprintk(D_GEN, "put_single: mask=0x%x, changed=%d, "
"mixer-value=%ld, mm-value=0x%x\n",
mask, changed, ucontrol->value.integer.value[0],
dbri->mm.data[elem & 3]);
if (changed) {
/* First mute outputs, and wait 1/8000 sec (125 us)
* to make sure this takes. This avoids clicking noises.
*/
cs4215_setdata(dbri, 1);
udelay(125);
cs4215_setdata(dbri, 0);
}
return changed;
}
/* Entries 0-3 map to the 4 data timeslots, entries 4-7 map to the 4 control
timeslots. Shift is the bit offset in the timeslot, mask defines the
number of bits. invert is a boolean for use with attenuation.
*/
#define CS4215_SINGLE(xname, entry, shift, mask, invert) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = (xname), \
.info = snd_cs4215_info_single, \
.get = snd_cs4215_get_single, .put = snd_cs4215_put_single, \
.private_value = (entry) | ((shift) << 8) | ((mask) << 16) | \
((invert) << 24) },
static struct snd_kcontrol_new dbri_controls[] __devinitdata = {
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Playback Volume",
.info = snd_cs4215_info_volume,
.get = snd_cs4215_get_volume,
.put = snd_cs4215_put_volume,
.private_value = DBRI_PLAY,
},
CS4215_SINGLE("Headphone switch", 0, 7, 1, 0)
CS4215_SINGLE("Line out switch", 0, 6, 1, 0)
CS4215_SINGLE("Speaker switch", 1, 6, 1, 0)
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Capture Volume",
.info = snd_cs4215_info_volume,
.get = snd_cs4215_get_volume,
.put = snd_cs4215_put_volume,
.private_value = DBRI_REC,
},
/* FIXME: mic/line switch */
CS4215_SINGLE("Line in switch", 2, 4, 1, 0)
CS4215_SINGLE("High Pass Filter switch", 5, 7, 1, 0)
CS4215_SINGLE("Monitor Volume", 3, 4, 0xf, 1)
CS4215_SINGLE("Mic boost", 4, 4, 1, 1)
};
static int __devinit snd_dbri_mixer(struct snd_card *card)
{
int idx, err;
struct snd_dbri *dbri;
if (snd_BUG_ON(!card || !card->private_data))
return -EINVAL;
dbri = card->private_data;
strcpy(card->mixername, card->shortname);
for (idx = 0; idx < ARRAY_SIZE(dbri_controls); idx++) {
err = snd_ctl_add(card,
snd_ctl_new1(&dbri_controls[idx], dbri));
if (err < 0)
return err;
}
for (idx = DBRI_REC; idx < DBRI_NO_STREAMS; idx++) {
dbri->stream_info[idx].left_gain = 0;
dbri->stream_info[idx].right_gain = 0;
}
return 0;
}
/****************************************************************************
/proc interface
****************************************************************************/
static void dbri_regs_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_dbri *dbri = entry->private_data;
snd_iprintf(buffer, "REG0: 0x%x\n", sbus_readl(dbri->regs + REG0));
snd_iprintf(buffer, "REG2: 0x%x\n", sbus_readl(dbri->regs + REG2));
snd_iprintf(buffer, "REG8: 0x%x\n", sbus_readl(dbri->regs + REG8));
snd_iprintf(buffer, "REG9: 0x%x\n", sbus_readl(dbri->regs + REG9));
}
#ifdef DBRI_DEBUG
static void dbri_debug_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_dbri *dbri = entry->private_data;
int pipe;
snd_iprintf(buffer, "debug=%d\n", dbri_debug);
for (pipe = 0; pipe < 32; pipe++) {
if (pipe_active(dbri, pipe)) {
struct dbri_pipe *pptr = &dbri->pipes[pipe];
snd_iprintf(buffer,
"Pipe %d: %s SDP=0x%x desc=%d, "
"len=%d next %d\n",
pipe,
(pptr->sdp & D_SDP_TO_SER) ? "output" :
"input",
pptr->sdp, pptr->desc,
pptr->length, pptr->nextpipe);
}
}
}
#endif
static void __devinit snd_dbri_proc(struct snd_card *card)
{
struct snd_dbri *dbri = card->private_data;
struct snd_info_entry *entry;
if (!snd_card_proc_new(card, "regs", &entry))
snd_info_set_text_ops(entry, dbri, dbri_regs_read);
#ifdef DBRI_DEBUG
if (!snd_card_proc_new(card, "debug", &entry)) {
snd_info_set_text_ops(entry, dbri, dbri_debug_read);
entry->mode = S_IFREG | S_IRUGO; /* Readable only. */
}
#endif
}
/*
****************************************************************************
**************************** Initialization ********************************
****************************************************************************
*/
static void snd_dbri_free(struct snd_dbri *dbri);
static int __devinit snd_dbri_create(struct snd_card *card,
struct of_device *op,
int irq, int dev)
{
struct snd_dbri *dbri = card->private_data;
int err;
spin_lock_init(&dbri->lock);
dbri->op = op;
dbri->irq = irq;
dbri->dma = dma_alloc_coherent(&op->dev,
sizeof(struct dbri_dma),
&dbri->dma_dvma, GFP_ATOMIC);
if (!dbri->dma)
return -ENOMEM;
memset((void *)dbri->dma, 0, sizeof(struct dbri_dma));
dprintk(D_GEN, "DMA Cmd Block 0x%p (0x%08x)\n",
dbri->dma, dbri->dma_dvma);
/* Map the registers into memory. */
dbri->regs_size = resource_size(&op->resource[0]);
dbri->regs = of_ioremap(&op->resource[0], 0,
dbri->regs_size, "DBRI Registers");
if (!dbri->regs) {
printk(KERN_ERR "DBRI: could not allocate registers\n");
dma_free_coherent(&op->dev, sizeof(struct dbri_dma),
(void *)dbri->dma, dbri->dma_dvma);
return -EIO;
}
err = request_irq(dbri->irq, snd_dbri_interrupt, IRQF_SHARED,
"DBRI audio", dbri);
if (err) {
printk(KERN_ERR "DBRI: Can't get irq %d\n", dbri->irq);
of_iounmap(&op->resource[0], dbri->regs, dbri->regs_size);
dma_free_coherent(&op->dev, sizeof(struct dbri_dma),
(void *)dbri->dma, dbri->dma_dvma);
return err;
}
/* Do low level initialization of the DBRI and CS4215 chips */
dbri_initialize(dbri);
err = cs4215_init(dbri);
if (err) {
snd_dbri_free(dbri);
return err;
}
return 0;
}
static void snd_dbri_free(struct snd_dbri *dbri)
{
dprintk(D_GEN, "snd_dbri_free\n");
dbri_reset(dbri);
if (dbri->irq)
free_irq(dbri->irq, dbri);
if (dbri->regs)
of_iounmap(&dbri->op->resource[0], dbri->regs, dbri->regs_size);
if (dbri->dma)
dma_free_coherent(&dbri->op->dev,
sizeof(struct dbri_dma),
(void *)dbri->dma, dbri->dma_dvma);
}
static int __devinit dbri_probe(struct of_device *op, const struct of_device_id *match)
{
struct snd_dbri *dbri;
struct resource *rp;
struct snd_card *card;
static int dev = 0;
int irq;
int err;
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (!enable[dev]) {
dev++;
return -ENOENT;
}
irq = op->irqs[0];
if (irq <= 0) {
printk(KERN_ERR "DBRI-%d: No IRQ.\n", dev);
return -ENODEV;
}
err = snd_card_create(index[dev], id[dev], THIS_MODULE,
sizeof(struct snd_dbri), &card);
if (err < 0)
return err;
strcpy(card->driver, "DBRI");
strcpy(card->shortname, "Sun DBRI");
rp = &op->resource[0];
sprintf(card->longname, "%s at 0x%02lx:0x%016Lx, irq %d",
card->shortname,
rp->flags & 0xffL, (unsigned long long)rp->start, irq);
err = snd_dbri_create(card, op, irq, dev);
if (err < 0) {
snd_card_free(card);
return err;
}
dbri = card->private_data;
err = snd_dbri_pcm(card);
if (err < 0)
goto _err;
err = snd_dbri_mixer(card);
if (err < 0)
goto _err;
/* /proc file handling */
snd_dbri_proc(card);
dev_set_drvdata(&op->dev, card);
err = snd_card_register(card);
if (err < 0)
goto _err;
printk(KERN_INFO "audio%d at %p (irq %d) is DBRI(%c)+CS4215(%d)\n",
dev, dbri->regs,
dbri->irq, op->node->name[9], dbri->mm.version);
dev++;
return 0;
_err:
snd_dbri_free(dbri);
snd_card_free(card);
return err;
}
static int __devexit dbri_remove(struct of_device *op)
{
struct snd_card *card = dev_get_drvdata(&op->dev);
snd_dbri_free(card->private_data);
snd_card_free(card);
dev_set_drvdata(&op->dev, NULL);
return 0;
}
static const struct of_device_id dbri_match[] = {
{
.name = "SUNW,DBRIe",
},
{
.name = "SUNW,DBRIf",
},
{},
};
MODULE_DEVICE_TABLE(of, dbri_match);
static struct of_platform_driver dbri_sbus_driver = {
.name = "dbri",
.match_table = dbri_match,
.probe = dbri_probe,
.remove = __devexit_p(dbri_remove),
};
/* Probe for the dbri chip and then attach the driver. */
static int __init dbri_init(void)
{
return of_register_driver(&dbri_sbus_driver, &of_bus_type);
}
static void __exit dbri_exit(void)
{
of_unregister_driver(&dbri_sbus_driver);
}
module_init(dbri_init);
module_exit(dbri_exit);
| gpl-2.0 |
invisiblek/android_kernel_lge_vs450pp | drivers/video/msm/mdp.c | 1127 | 80097 | /* drivers/video/msm_fb/mdp.c
*
* MSM MDP Interface (used by framebuffer core)
*
* Copyright (c) 2007-2012, The Linux Foundation. All rights reserved.
* Copyright (C) 2007 Google Incorporated
*
* 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/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/time.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/hrtimer.h>
#include <linux/clk.h>
#include <mach/hardware.h>
#include <linux/io.h>
#include <linux/debugfs.h>
#include <linux/delay.h>
#include <linux/mutex.h>
#include <linux/pm_runtime.h>
#include <linux/regulator/consumer.h>
#include <asm/system.h>
#include <asm/mach-types.h>
#include <linux/semaphore.h>
#include <linux/uaccess.h>
#include <mach/event_timer.h>
#include <mach/clk.h>
#include "mdp.h"
#include "msm_fb.h"
#ifdef CONFIG_FB_MSM_MDP40
#include "mdp4.h"
#endif
#include "mipi_dsi.h"
uint32 mdp4_extn_disp;
static struct clk *mdp_clk;
static struct clk *mdp_pclk;
static struct clk *mdp_lut_clk;
int mdp_rev;
int mdp_iommu_split_domain;
u32 mdp_max_clk = 200000000;
u64 mdp_max_bw = 2000000000;
static struct platform_device *mdp_init_pdev;
static struct regulator *footswitch, *dsi_pll_vdda, *dsi_pll_vddio;
static unsigned int mdp_footswitch_on;
struct completion mdp_ppp_comp;
struct semaphore mdp_ppp_mutex;
struct semaphore mdp_pipe_ctrl_mutex;
unsigned long mdp_timer_duration = (HZ/20); /* 50 msecond */
boolean mdp_ppp_waiting = FALSE;
uint32 mdp_tv_underflow_cnt;
uint32 mdp_lcdc_underflow_cnt;
boolean mdp_current_clk_on = FALSE;
boolean mdp_is_in_isr = FALSE;
struct vsync vsync_cntrl;
/*
* legacy mdp_in_processing is only for DMA2-MDDI
* this applies to DMA2 block only
*/
uint32 mdp_in_processing = FALSE;
#ifdef CONFIG_FB_MSM_MDP40
uint32 mdp_intr_mask = MDP4_ANY_INTR_MASK;
#else
uint32 mdp_intr_mask = MDP_ANY_INTR_MASK;
#endif
MDP_BLOCK_TYPE mdp_debug[MDP_MAX_BLOCK];
atomic_t mdp_block_power_cnt[MDP_MAX_BLOCK];
spinlock_t mdp_spin_lock;
struct workqueue_struct *mdp_dma_wq; /*mdp dma wq */
struct workqueue_struct *mdp_vsync_wq; /*mdp vsync wq */
struct workqueue_struct *mdp_hist_wq; /*mdp histogram wq */
bool mdp_pp_initialized = FALSE;
static struct workqueue_struct *mdp_pipe_ctrl_wq; /* mdp mdp pipe ctrl wq */
static struct delayed_work mdp_pipe_ctrl_worker;
static boolean mdp_suspended = FALSE;
ulong mdp4_display_intf;
DEFINE_MUTEX(mdp_suspend_mutex);
#ifdef CONFIG_FB_MSM_MDP40
struct mdp_dma_data dma2_data;
struct mdp_dma_data dma_s_data;
struct mdp_dma_data dma_e_data;
#else
static struct mdp_dma_data dma2_data;
static struct mdp_dma_data dma_s_data;
#ifndef CONFIG_FB_MSM_MDP303
static struct mdp_dma_data dma_e_data;
#endif
#endif
#ifdef CONFIG_FB_MSM_WRITEBACK_MSM_PANEL
struct mdp_dma_data dma_wb_data;
#endif
static struct mdp_dma_data dma3_data;
extern ktime_t mdp_dma2_last_update_time;
extern uint32 mdp_dma2_update_time_in_usec;
extern int mdp_lcd_rd_cnt_offset_slow;
extern int mdp_lcd_rd_cnt_offset_fast;
extern int mdp_usec_diff_threshold;
extern int first_pixel_start_x;
extern int first_pixel_start_y;
#ifdef MSM_FB_ENABLE_DBGFS
struct dentry *mdp_dir;
#endif
#if defined(CONFIG_PM) && !defined(CONFIG_HAS_EARLYSUSPEND)
static int mdp_suspend(struct platform_device *pdev, pm_message_t state);
#else
#define mdp_suspend NULL
#endif
struct timeval mdp_dma2_timeval;
struct timeval mdp_ppp_timeval;
#ifdef CONFIG_HAS_EARLYSUSPEND
static struct early_suspend early_suspend;
#endif
static u32 mdp_irq;
static uint32 mdp_prim_panel_type = NO_PANEL;
#ifndef CONFIG_FB_MSM_MDP22
struct list_head mdp_hist_lut_list;
DEFINE_MUTEX(mdp_hist_lut_list_mutex);
uint32_t mdp_block2base(uint32_t block)
{
uint32_t base = 0x0;
switch (block) {
case MDP_BLOCK_DMA_P:
base = 0x90000;
break;
case MDP_BLOCK_DMA_S:
base = 0xA0000;
break;
case MDP_BLOCK_VG_1:
base = 0x20000;
break;
case MDP_BLOCK_VG_2:
base = 0x30000;
break;
case MDP_BLOCK_RGB_1:
base = 0x40000;
break;
case MDP_BLOCK_RGB_2:
base = 0x50000;
break;
case MDP_BLOCK_OVERLAY_0:
base = 0x10000;
break;
case MDP_BLOCK_OVERLAY_1:
base = 0x18000;
break;
case MDP_BLOCK_OVERLAY_2:
base = (mdp_rev >= MDP_REV_43) ? 0x88000 : 0;
break;
default:
break;
}
return base;
}
static uint32_t mdp_pp_block2hist_lut(uint32_t block)
{
uint32_t valid = 0;
switch (block) {
case MDP_BLOCK_DMA_P:
valid = (mdp_rev >= MDP_REV_40) ? 1 : 0;
break;
case MDP_BLOCK_DMA_S:
valid = (mdp_rev >= MDP_REV_40) ? 1 : 0;
break;
case MDP_BLOCK_VG_1:
valid = (mdp_rev >= MDP_REV_40) ? 1 : 0;
break;
case MDP_BLOCK_VG_2:
valid = (mdp_rev >= MDP_REV_40) ? 1 : 0;
break;
default:
break;
}
return valid;
}
static void mdp_hist_lut_init_mgmt(struct mdp_hist_lut_mgmt *mgmt,
uint32_t block)
{
mutex_init(&mgmt->lock);
mgmt->block = block;
mutex_lock(&mdp_hist_lut_list_mutex);
list_add(&mgmt->list, &mdp_hist_lut_list);
mutex_unlock(&mdp_hist_lut_list_mutex);
}
static int mdp_hist_lut_destroy(void)
{
struct mdp_hist_lut_mgmt *temp;
struct list_head *pos, *q;
mutex_lock(&mdp_hist_lut_list_mutex);
list_for_each_safe(pos, q, &mdp_hist_lut_list) {
temp = list_entry(pos, struct mdp_hist_lut_mgmt, list);
list_del(pos);
kfree(temp);
}
mutex_unlock(&mdp_hist_lut_list_mutex);
return 0;
}
static int mdp_hist_lut_init(void)
{
struct mdp_hist_lut_mgmt *temp;
if (mdp_pp_initialized)
return -EEXIST;
INIT_LIST_HEAD(&mdp_hist_lut_list);
if (mdp_rev >= MDP_REV_30) {
temp = kmalloc(sizeof(struct mdp_hist_lut_mgmt), GFP_KERNEL);
if (!temp)
goto exit;
mdp_hist_lut_init_mgmt(temp, MDP_BLOCK_DMA_P);
}
if (mdp_rev >= MDP_REV_40) {
temp = kmalloc(sizeof(struct mdp_hist_lut_mgmt), GFP_KERNEL);
if (!temp)
goto exit_list;
mdp_hist_lut_init_mgmt(temp, MDP_BLOCK_VG_1);
temp = kmalloc(sizeof(struct mdp_hist_lut_mgmt), GFP_KERNEL);
if (!temp)
goto exit_list;
mdp_hist_lut_init_mgmt(temp, MDP_BLOCK_VG_2);
}
if (mdp_rev > MDP_REV_42) {
temp = kmalloc(sizeof(struct mdp_hist_lut_mgmt), GFP_KERNEL);
if (!temp)
goto exit_list;
mdp_hist_lut_init_mgmt(temp, MDP_BLOCK_DMA_S);
}
return 0;
exit_list:
mdp_hist_lut_destroy();
exit:
pr_err("Failed initializing histogram LUT memory\n");
return -ENOMEM;
}
static int mdp_hist_lut_block2mgmt(uint32_t block,
struct mdp_hist_lut_mgmt **mgmt)
{
struct mdp_hist_lut_mgmt *temp, *output;
int ret = 0;
output = NULL;
mutex_lock(&mdp_hist_lut_list_mutex);
list_for_each_entry(temp, &mdp_hist_lut_list, list) {
if (temp->block == block)
output = temp;
}
mutex_unlock(&mdp_hist_lut_list_mutex);
if (output == NULL)
ret = -EINVAL;
else
*mgmt = output;
return ret;
}
#define MDP_HIST_LUT_SIZE (256)
static int mdp_hist_lut_write_off(struct mdp_hist_lut_data *data,
struct mdp_hist_lut_info *info, uint32_t offset)
{
int i;
uint32_t element[MDP_HIST_LUT_SIZE];
uint32_t base = mdp_block2base(info->block);
uint32_t sel = info->bank_sel;
if (data->len != MDP_HIST_LUT_SIZE) {
pr_err("%s: data->len != %d", __func__, MDP_HIST_LUT_SIZE);
return -EINVAL;
}
if (copy_from_user(&element, data->data,
MDP_HIST_LUT_SIZE * sizeof(uint32_t))) {
pr_err("%s: Error copying histogram data", __func__);
return -ENOMEM;
}
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
for (i = 0; i < MDP_HIST_LUT_SIZE; i++)
MDP_OUTP(MDP_BASE + base + offset + (0x400*(sel)) + (4*i),
element[i]);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
return 0;
}
static int mdp_hist_lut_write(struct mdp_hist_lut_data *data,
struct mdp_hist_lut_info *info)
{
int ret = 0;
if (data->block != info->block) {
ret = -1;
pr_err("%s, data/info mdp_block mismatch! %d != %d\n",
__func__, data->block, info->block);
goto error;
}
switch (data->block) {
case MDP_BLOCK_VG_1:
case MDP_BLOCK_VG_2:
ret = mdp_hist_lut_write_off(data, info, 0x3400);
break;
case MDP_BLOCK_DMA_P:
case MDP_BLOCK_DMA_S:
ret = mdp_hist_lut_write_off(data, info, 0x4800);
break;
default:
ret = -EINVAL;
goto error;
}
error:
return ret;
}
#define MDP_HIST_LUT_VG_EN_MASK (0x20000)
#define MDP_HIST_LUT_VG_EN_SHIFT (17)
#define MDP_HIST_LUT_VG_EN_OFFSET (0x0058)
#define MDP_HIST_LUT_VG_SEL_OFFSET (0x0064)
static void mdp_hist_lut_commit_vg(struct mdp_hist_lut_info *info)
{
uint32_t out_en, temp_en;
uint32_t base = mdp_block2base(info->block);
temp_en = (info->is_enabled) ? (1 << MDP_HIST_LUT_VG_EN_SHIFT) : 0x0;
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
out_en = inpdw(MDP_BASE + base + MDP_HIST_LUT_VG_EN_OFFSET) &
~MDP_HIST_LUT_VG_EN_MASK;
MDP_OUTP(MDP_BASE + base + MDP_HIST_LUT_VG_EN_OFFSET, out_en | temp_en);
if (info->has_sel_update)
MDP_OUTP(MDP_BASE + base + MDP_HIST_LUT_VG_SEL_OFFSET,
info->bank_sel);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
}
#define MDP_HIST_LUT_DMA_EN_MASK (0x7)
#define MDP_HIST_LUT_DMA_SEL_MASK (0x400)
#define MDP_HIST_LUT_DMA_SEL_SHIFT (10)
#define MDP_HIST_LUT_DMA_P_OFFSET (0x0070)
#define MDP_HIST_LUT_DMA_S_OFFSET (0x0028)
static void mdp_hist_lut_commit_dma(struct mdp_hist_lut_info *info)
{
uint32_t out, temp, mask;
uint32_t base = mdp_block2base(info->block);
uint32_t offset = (info->block == MDP_BLOCK_DMA_P) ?
MDP_HIST_LUT_DMA_P_OFFSET : MDP_HIST_LUT_DMA_S_OFFSET;
mask = MDP_HIST_LUT_DMA_EN_MASK;
temp = (info->is_enabled) ? 0x7 : 0x0;
if (info->has_sel_update) {
mask |= MDP_HIST_LUT_DMA_SEL_MASK;
temp |= ((info->bank_sel & 0x1) << MDP_HIST_LUT_DMA_SEL_SHIFT);
}
out = inpdw(MDP_BASE + base + offset) & ~mask;
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
MDP_OUTP(MDP_BASE + base + offset, out | temp);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
}
static void mdp_hist_lut_commit_info(struct mdp_hist_lut_info *info)
{
switch (info->block) {
case MDP_BLOCK_VG_1:
case MDP_BLOCK_VG_2:
mdp_hist_lut_commit_vg(info);
break;
case MDP_BLOCK_DMA_P:
case MDP_BLOCK_DMA_S:
mdp_hist_lut_commit_dma(info);
break;
default:
goto error;
}
error:
return;
}
static void mdp_hist_lut_update_info(struct mdp_hist_lut_info *info, int ops)
{
info->bank_sel = (ops & 0x8) >> 3;
info->is_enabled = (ops & 0x1) ? TRUE : FALSE;
info->has_sel_update = (ops & 0x10) ? TRUE : FALSE;
}
int mdp_hist_lut_config(struct mdp_hist_lut_data *data)
{
struct mdp_hist_lut_mgmt *mgmt = NULL;
struct mdp_hist_lut_info info;
int ret = 0;
if (!mdp_pp_block2hist_lut(data->block)) {
ret = -ENOTTY;
goto error;
}
ret = mdp_hist_lut_block2mgmt(data->block, &mgmt);
if (ret)
goto error;
mutex_lock(&mgmt->lock);
info.block = mgmt->block;
mdp_hist_lut_update_info(&info, data->ops);
switch ((data->ops & 0x6) >> 1) {
case 0x1:
pr_info("%s: histogram LUT read not supported\n", __func__);
break;
case 0x2:
ret = mdp_hist_lut_write(data, &info);
if (ret)
goto error_lock;
break;
default:
break;
}
mdp_hist_lut_commit_info(&info);
error_lock:
mutex_unlock(&mgmt->lock);
error:
return ret;
}
DEFINE_MUTEX(mdp_lut_push_sem);
static int mdp_lut_i;
static int mdp_lut_hw_update(struct fb_cmap *cmap)
{
int i;
u16 *c[3];
u16 r, g, b;
c[0] = cmap->green;
c[1] = cmap->blue;
c[2] = cmap->red;
for (i = 0; i < cmap->len; i++) {
if (copy_from_user(&r, cmap->red++, sizeof(r)) ||
copy_from_user(&g, cmap->green++, sizeof(g)) ||
copy_from_user(&b, cmap->blue++, sizeof(b)))
return -EFAULT;
#ifdef CONFIG_FB_MSM_MDP40
MDP_OUTP(MDP_BASE + 0x94800 +
#else
MDP_OUTP(MDP_BASE + 0x93800 +
#endif
(0x400*mdp_lut_i) + cmap->start*4 + i*4,
((g & 0xff) |
((b & 0xff) << 8) |
((r & 0xff) << 16)));
}
return 0;
}
static int mdp_lut_push;
static int mdp_lut_push_i;
static int mdp_lut_update_nonlcdc(struct fb_info *info, struct fb_cmap *cmap)
{
int ret;
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
mdp_clk_ctrl(1);
ret = mdp_lut_hw_update(cmap);
mdp_clk_ctrl(0);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
if (ret)
return ret;
mutex_lock(&mdp_lut_push_sem);
mdp_lut_push = 1;
mdp_lut_push_i = mdp_lut_i;
mutex_unlock(&mdp_lut_push_sem);
mdp_lut_i = (mdp_lut_i + 1)%2;
return 0;
}
static int mdp_lut_update_lcdc(struct fb_info *info, struct fb_cmap *cmap)
{
int ret;
uint32_t out;
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
mdp_clk_ctrl(1);
ret = mdp_lut_hw_update(cmap);
if (ret) {
mdp_clk_ctrl(0);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
return ret;
}
/*mask off non LUT select bits*/
out = inpdw(MDP_BASE + 0x90070);
MDP_OUTP(MDP_BASE + 0x90070, (mdp_lut_i << 10) | 0x7 | out);
mdp_clk_ctrl(0);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
mdp_lut_i = (mdp_lut_i + 1)%2;
return 0;
}
static void mdp_lut_enable(void)
{
uint32_t out;
if (mdp_lut_push) {
mutex_lock(&mdp_lut_push_sem);
mdp_lut_push = 0;
out = inpdw(MDP_BASE + 0x90070) & ~((0x1 << 10) | 0x7);
MDP_OUTP(MDP_BASE + 0x90070,
(mdp_lut_push_i << 10) | 0x7 | out);
mutex_unlock(&mdp_lut_push_sem);
}
}
#define MDP_REV42_HIST_MAX_BIN 128
#define MDP_REV41_HIST_MAX_BIN 32
#define MDP_HIST_DATA32_R_OFF 0x0100
#define MDP_HIST_DATA32_G_OFF 0x0200
#define MDP_HIST_DATA32_B_OFF 0x0300
#define MDP_HIST_DATA128_R_OFF 0x0400
#define MDP_HIST_DATA128_G_OFF 0x0800
#define MDP_HIST_DATA128_B_OFF 0x0C00
#define MDP_HIST_DATA_LUMA_OFF 0x0200
#define MDP_HIST_EXTRA_DATA0_OFF 0x0028
#define MDP_HIST_EXTRA_DATA1_OFF 0x002C
struct mdp_hist_mgmt *mdp_hist_mgmt_array[MDP_HIST_MGMT_MAX];
void __mdp_histogram_kickoff(struct mdp_hist_mgmt *mgmt)
{
char *mdp_hist_base = MDP_BASE + mgmt->base;
if (mgmt->mdp_is_hist_data == TRUE) {
MDP_OUTP(mdp_hist_base + 0x0004, mgmt->frame_cnt);
MDP_OUTP(mdp_hist_base, 1);
}
}
void __mdp_histogram_reset(struct mdp_hist_mgmt *mgmt)
{
char *mdp_hist_base = MDP_BASE + mgmt->base;
MDP_OUTP(mdp_hist_base + 0x000C, 1);
}
static void mdp_hist_read_work(struct work_struct *data);
static int mdp_hist_init_mgmt(struct mdp_hist_mgmt *mgmt, uint32_t block)
{
uint32_t bins, extra, index, intr = 0, term = 0;
init_completion(&mgmt->mdp_hist_comp);
mutex_init(&mgmt->mdp_hist_mutex);
mutex_init(&mgmt->mdp_do_hist_mutex);
mgmt->block = block;
mgmt->base = mdp_block2base(block);
mgmt->mdp_is_hist_start = FALSE;
mgmt->mdp_is_hist_data = FALSE;
mgmt->mdp_is_hist_valid = FALSE;
mgmt->mdp_is_hist_init = FALSE;
mgmt->frame_cnt = 0;
mgmt->bit_mask = 0;
mgmt->num_bins = 0;
switch (block) {
case MDP_BLOCK_DMA_P:
term = MDP_HISTOGRAM_TERM_DMA_P;
intr = (mdp_rev >= MDP_REV_40) ? INTR_DMA_P_HISTOGRAM :
MDP_HIST_DONE;
bins = (mdp_rev >= MDP_REV_42) ? MDP_REV42_HIST_MAX_BIN :
MDP_REV41_HIST_MAX_BIN;
extra = 2;
mgmt->base += (mdp_rev >= MDP_REV_40) ? 0x5000 : 0x4000;
index = MDP_HIST_MGMT_DMA_P;
break;
case MDP_BLOCK_DMA_S:
term = MDP_HISTOGRAM_TERM_DMA_S;
intr = INTR_DMA_S_HISTOGRAM;
bins = MDP_REV42_HIST_MAX_BIN;
extra = 2;
mgmt->base += 0x5000;
index = MDP_HIST_MGMT_DMA_S;
break;
case MDP_BLOCK_VG_1:
term = MDP_HISTOGRAM_TERM_VG_1;
intr = INTR_VG1_HISTOGRAM;
bins = MDP_REV42_HIST_MAX_BIN;
extra = 1;
mgmt->base += 0x6000;
index = MDP_HIST_MGMT_VG_1;
break;
case MDP_BLOCK_VG_2:
term = MDP_HISTOGRAM_TERM_VG_2;
intr = INTR_VG2_HISTOGRAM;
bins = MDP_REV42_HIST_MAX_BIN;
extra = 1;
mgmt->base += 0x6000;
index = MDP_HIST_MGMT_VG_2;
break;
default:
term = MDP_HISTOGRAM_TERM_DMA_P;
intr = (mdp_rev >= MDP_REV_40) ? INTR_DMA_P_HISTOGRAM :
MDP_HIST_DONE;
bins = (mdp_rev >= MDP_REV_42) ? MDP_REV42_HIST_MAX_BIN :
MDP_REV41_HIST_MAX_BIN;
extra = 2;
mgmt->base += (mdp_rev >= MDP_REV_40) ? 0x5000 : 0x4000;
index = MDP_HIST_MGMT_DMA_P;
}
mgmt->irq_term = term;
mgmt->intr = intr;
mgmt->c0 = kmalloc(bins * sizeof(uint32_t), GFP_KERNEL);
if (mgmt->c0 == NULL)
goto error;
mgmt->c1 = kmalloc(bins * sizeof(uint32_t), GFP_KERNEL);
if (mgmt->c1 == NULL)
goto error_1;
mgmt->c2 = kmalloc(bins * sizeof(uint32_t), GFP_KERNEL);
if (mgmt->c2 == NULL)
goto error_2;
mgmt->extra_info = kmalloc(extra * sizeof(uint32_t), GFP_KERNEL);
if (mgmt->extra_info == NULL)
goto error_extra;
INIT_WORK(&mgmt->mdp_histogram_worker, mdp_hist_read_work);
mgmt->hist = NULL;
mdp_hist_mgmt_array[index] = mgmt;
return 0;
error_extra:
kfree(mgmt->c2);
error_2:
kfree(mgmt->c1);
error_1:
kfree(mgmt->c0);
error:
return -ENOMEM;
}
static void mdp_hist_del_mgmt(struct mdp_hist_mgmt *mgmt)
{
kfree(mgmt->extra_info);
kfree(mgmt->c2);
kfree(mgmt->c1);
kfree(mgmt->c0);
}
static int mdp_histogram_destroy(void)
{
struct mdp_hist_mgmt *temp;
int i;
for (i = 0; i < MDP_HIST_MGMT_MAX; i++) {
temp = mdp_hist_mgmt_array[i];
if (!temp)
continue;
mdp_hist_del_mgmt(temp);
kfree(temp);
mdp_hist_mgmt_array[i] = NULL;
}
return 0;
}
static int mdp_histogram_init(void)
{
struct mdp_hist_mgmt *temp;
int i, ret;
if (mdp_pp_initialized)
return -EEXIST;
mdp_hist_wq = alloc_workqueue("mdp_hist_wq",
WQ_NON_REENTRANT | WQ_UNBOUND, 0);
for (i = 0; i < MDP_HIST_MGMT_MAX; i++)
mdp_hist_mgmt_array[i] = NULL;
if (mdp_rev >= MDP_REV_30) {
temp = kmalloc(sizeof(struct mdp_hist_mgmt), GFP_KERNEL);
if (!temp)
goto exit;
ret = mdp_hist_init_mgmt(temp, MDP_BLOCK_DMA_P);
if (ret) {
kfree(temp);
goto exit;
}
}
if (mdp_rev >= MDP_REV_40) {
temp = kmalloc(sizeof(struct mdp_hist_mgmt), GFP_KERNEL);
if (!temp)
goto exit_list;
ret = mdp_hist_init_mgmt(temp, MDP_BLOCK_VG_1);
if (ret)
goto exit_list;
temp = kmalloc(sizeof(struct mdp_hist_mgmt), GFP_KERNEL);
if (!temp)
goto exit_list;
ret = mdp_hist_init_mgmt(temp, MDP_BLOCK_VG_2);
if (ret)
goto exit_list;
}
if (mdp_rev >= MDP_REV_42) {
temp = kmalloc(sizeof(struct mdp_hist_mgmt), GFP_KERNEL);
if (!temp)
goto exit_list;
ret = mdp_hist_init_mgmt(temp, MDP_BLOCK_DMA_S);
if (ret)
goto exit_list;
}
return 0;
exit_list:
mdp_histogram_destroy();
exit:
return -ENOMEM;
}
int mdp_histogram_block2mgmt(uint32_t block, struct mdp_hist_mgmt **mgmt)
{
struct mdp_hist_mgmt *temp, *output;
int i, ret = 0;
output = NULL;
for (i = 0; i < MDP_HIST_MGMT_MAX; i++) {
temp = mdp_hist_mgmt_array[i];
if (!temp)
continue;
if (temp->block == block) {
output = temp;
break;
}
}
if (output == NULL)
ret = -EINVAL;
else
*mgmt = output;
return ret;
}
static int mdp_histogram_enable(struct mdp_hist_mgmt *mgmt)
{
uint32_t base;
unsigned long flag;
if (mgmt->mdp_is_hist_data == TRUE) {
pr_err("%s histogram already started\n", __func__);
return -EINVAL;
}
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
base = (uint32_t) (MDP_BASE + mgmt->base);
/*First make sure that device is not collecting histogram*/
mgmt->mdp_is_hist_data = FALSE;
mgmt->mdp_is_hist_valid = FALSE;
mgmt->mdp_is_hist_init = FALSE;
spin_lock_irqsave(&mdp_spin_lock, flag);
outp32(MDP_INTR_CLEAR, mgmt->intr);
mdp_intr_mask &= ~mgmt->intr;
outp32(MDP_INTR_ENABLE, mdp_intr_mask);
MDP_OUTP(base + 0x001C, 0);
MDP_OUTP(base + 0x0018, INTR_HIST_DONE | INTR_HIST_RESET_SEQ_DONE);
MDP_OUTP(base + 0x0024, 0);
spin_unlock_irqrestore(&mdp_spin_lock, flag);
mutex_unlock(&mgmt->mdp_hist_mutex);
cancel_work_sync(&mgmt->mdp_histogram_worker);
mutex_lock(&mgmt->mdp_hist_mutex);
/*Then initialize histogram*/
INIT_COMPLETION(mgmt->mdp_hist_comp);
spin_lock_irqsave(&mdp_spin_lock, flag);
MDP_OUTP(base + 0x0018, INTR_HIST_DONE | INTR_HIST_RESET_SEQ_DONE);
MDP_OUTP(base + 0x0010, 1);
MDP_OUTP(base + 0x001C, INTR_HIST_DONE | INTR_HIST_RESET_SEQ_DONE);
outp32(MDP_INTR_CLEAR, mgmt->intr);
mdp_intr_mask |= mgmt->intr;
outp32(MDP_INTR_ENABLE, mdp_intr_mask);
mdp_enable_irq(mgmt->irq_term);
spin_unlock_irqrestore(&mdp_spin_lock, flag);
MDP_OUTP(base + 0x0004, mgmt->frame_cnt);
if (mgmt->block != MDP_BLOCK_VG_1 && mgmt->block != MDP_BLOCK_VG_2)
MDP_OUTP(base + 0x0008, mgmt->bit_mask);
mgmt->mdp_is_hist_data = TRUE;
mgmt->mdp_is_hist_valid = TRUE;
mgmt->mdp_is_hist_init = FALSE;
__mdp_histogram_reset(mgmt);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
return 0;
}
static int mdp_histogram_disable(struct mdp_hist_mgmt *mgmt)
{
uint32_t base, status;
unsigned long flag;
if (mgmt->mdp_is_hist_data == FALSE) {
pr_err("%s histogram already stopped\n", __func__);
return -EINVAL;
}
mgmt->mdp_is_hist_data = FALSE;
mgmt->mdp_is_hist_valid = FALSE;
mgmt->mdp_is_hist_init = FALSE;
base = (uint32_t) (MDP_BASE + mgmt->base);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
spin_lock_irqsave(&mdp_spin_lock, flag);
outp32(MDP_INTR_CLEAR, mgmt->intr);
mdp_intr_mask &= ~mgmt->intr;
outp32(MDP_INTR_ENABLE, mdp_intr_mask);
mdp_disable_irq_nosync(mgmt->irq_term);
spin_unlock_irqrestore(&mdp_spin_lock, flag);
if (mdp_rev >= MDP_REV_42)
MDP_OUTP(base + 0x0020, 1);
status = inpdw(base + 0x001C);
status &= ~(INTR_HIST_DONE | INTR_HIST_RESET_SEQ_DONE);
MDP_OUTP(base + 0x001C, status);
MDP_OUTP(base + 0x0018, INTR_HIST_DONE | INTR_HIST_RESET_SEQ_DONE);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
if (mgmt->hist != NULL) {
mgmt->hist = NULL;
complete(&mgmt->mdp_hist_comp);
}
return 0;
}
/*call when spanning mgmt_array only*/
int _mdp_histogram_ctrl(boolean en, struct mdp_hist_mgmt *mgmt)
{
int ret = 0;
mutex_lock(&mgmt->mdp_hist_mutex);
if (mgmt->mdp_is_hist_start == TRUE) {
if (en)
ret = mdp_histogram_enable(mgmt);
else
ret = mdp_histogram_disable(mgmt);
}
mutex_unlock(&mgmt->mdp_hist_mutex);
if (en == false)
cancel_work_sync(&mgmt->mdp_histogram_worker);
return ret;
}
int mdp_histogram_ctrl(boolean en, uint32_t block)
{
struct mdp_hist_mgmt *mgmt = NULL;
int ret = 0;
ret = mdp_histogram_block2mgmt(block, &mgmt);
if (ret)
goto error;
ret = _mdp_histogram_ctrl(en, mgmt);
error:
return ret;
}
int mdp_histogram_ctrl_all(boolean en)
{
struct mdp_hist_mgmt *temp;
int i, ret = 0, ret_temp = 0;
for (i = 0; i < MDP_HIST_MGMT_MAX; i++) {
temp = mdp_hist_mgmt_array[i];
if (!temp)
continue;
ret_temp = _mdp_histogram_ctrl(en, temp);
if (ret_temp)
ret = ret_temp;
}
return ret;
}
int mdp_histogram_start(struct mdp_histogram_start_req *req)
{
struct mdp_hist_mgmt *mgmt = NULL;
int ret;
ret = mdp_histogram_block2mgmt(req->block, &mgmt);
if (ret) {
ret = -ENOTTY;
goto error;
}
mutex_lock(&mgmt->mdp_do_hist_mutex);
mutex_lock(&mgmt->mdp_hist_mutex);
if (mgmt->mdp_is_hist_start == TRUE) {
pr_err("%s histogram already started\n", __func__);
ret = -EPERM;
goto error_lock;
}
mgmt->block = req->block;
mgmt->frame_cnt = req->frame_cnt;
mgmt->bit_mask = req->bit_mask;
mgmt->num_bins = req->num_bins;
ret = mdp_histogram_enable(mgmt);
mgmt->mdp_is_hist_start = TRUE;
error_lock:
mutex_unlock(&mgmt->mdp_hist_mutex);
mutex_unlock(&mgmt->mdp_do_hist_mutex);
error:
return ret;
}
int mdp_histogram_stop(struct fb_info *info, uint32_t block)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *) info->par;
struct mdp_hist_mgmt *mgmt = NULL;
int ret;
ret = mdp_histogram_block2mgmt(block, &mgmt);
if (ret) {
ret = -ENOTTY;
goto error;
}
mutex_lock(&mgmt->mdp_do_hist_mutex);
mutex_lock(&mgmt->mdp_hist_mutex);
if (mgmt->mdp_is_hist_start == FALSE) {
pr_err("%s histogram already stopped\n", __func__);
ret = -EPERM;
goto error_lock;
}
mgmt->mdp_is_hist_start = FALSE;
if (!mfd->panel_power_on) {
mgmt->mdp_is_hist_data = FALSE;
if (mgmt->hist != NULL) {
mgmt->hist = NULL;
complete(&mgmt->mdp_hist_comp);
}
ret = -EINVAL;
goto error_lock;
}
ret = mdp_histogram_disable(mgmt);
mutex_unlock(&mgmt->mdp_hist_mutex);
cancel_work_sync(&mgmt->mdp_histogram_worker);
mutex_unlock(&mgmt->mdp_do_hist_mutex);
return ret;
error_lock:
mutex_unlock(&mgmt->mdp_hist_mutex);
mutex_unlock(&mgmt->mdp_do_hist_mutex);
error:
return ret;
}
/*call from within mdp_hist_mutex context*/
static int _mdp_histogram_read_dma_data(struct mdp_hist_mgmt *mgmt)
{
char *mdp_hist_base;
uint32_t r_data_offset, g_data_offset, b_data_offset;
int i, ret = 0;
mdp_hist_base = MDP_BASE + mgmt->base;
r_data_offset = (32 == mgmt->num_bins) ? MDP_HIST_DATA32_R_OFF :
MDP_HIST_DATA128_R_OFF;
g_data_offset = (32 == mgmt->num_bins) ? MDP_HIST_DATA32_G_OFF :
MDP_HIST_DATA128_G_OFF;
b_data_offset = (32 == mgmt->num_bins) ? MDP_HIST_DATA32_B_OFF :
MDP_HIST_DATA128_B_OFF;
if (mgmt->c0 == NULL || mgmt->c1 == NULL || mgmt->c2 == NULL) {
ret = -ENOMEM;
goto hist_err;
}
if (!mgmt->hist) {
pr_err("%s: mgmt->hist not set, mgmt->hist = 0x%08x",
__func__, (uint32_t) mgmt->hist);
return -EINVAL;
}
if (mgmt->hist->bin_cnt != mgmt->num_bins) {
pr_err("%s, bins config = %d, bin requested = %d", __func__,
mgmt->num_bins, mgmt->hist->bin_cnt);
return -EINVAL;
}
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
mdp_clk_ctrl(1);
for (i = 0; i < mgmt->num_bins; i++) {
mgmt->c0[i] = inpdw(mdp_hist_base + r_data_offset + (4*i));
mgmt->c1[i] = inpdw(mdp_hist_base + g_data_offset + (4*i));
mgmt->c2[i] = inpdw(mdp_hist_base + b_data_offset + (4*i));
}
if (mdp_rev >= MDP_REV_42) {
if (mgmt->extra_info) {
mgmt->extra_info[0] = inpdw(mdp_hist_base +
MDP_HIST_EXTRA_DATA0_OFF);
mgmt->extra_info[1] = inpdw(mdp_hist_base +
MDP_HIST_EXTRA_DATA0_OFF + 4);
} else
ret = -ENOMEM;
}
mdp_clk_ctrl(0);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
if (!ret)
return ret;
hist_err:
pr_err("%s: invalid hist buffer\n", __func__);
return ret;
}
/*call from within mdp_hist_mutex context*/
static int _mdp_histogram_read_vg_data(struct mdp_hist_mgmt *mgmt)
{
char *mdp_hist_base;
int i, ret = 0;
mdp_hist_base = MDP_BASE + mgmt->base;
if (mgmt->c0 == NULL) {
ret = -ENOMEM;
goto hist_err;
}
if (!mgmt->hist) {
pr_err("%s: mgmt->hist not set", __func__);
return -EINVAL;
}
if (mgmt->hist->bin_cnt != mgmt->num_bins) {
pr_err("%s, bins config = %d, bin requested = %d", __func__,
mgmt->num_bins, mgmt->hist->bin_cnt);
return -EINVAL;
}
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
mdp_clk_ctrl(1);
for (i = 0; i < mgmt->num_bins; i++)
mgmt->c0[i] = inpdw(mdp_hist_base + MDP_HIST_DATA_LUMA_OFF +
(4*i));
if (mdp_rev >= MDP_REV_42) {
if (mgmt->extra_info) {
mgmt->extra_info[0] = inpdw(mdp_hist_base +
MDP_HIST_EXTRA_DATA0_OFF);
} else
ret = -ENOMEM;
}
mdp_clk_ctrl(0);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
if (!ret)
return ret;
hist_err:
pr_err("%s: invalid hist buffer\n", __func__);
return ret;
}
static void mdp_hist_read_work(struct work_struct *data)
{
struct mdp_hist_mgmt *mgmt = container_of(data, struct mdp_hist_mgmt,
mdp_histogram_worker);
int ret = 0;
bool hist_ready;
mutex_lock(&mgmt->mdp_hist_mutex);
if (mgmt->mdp_is_hist_data == FALSE) {
pr_debug("%s, Histogram disabled before read.\n", __func__);
ret = -EINVAL;
goto error;
}
if (mgmt->hist == NULL) {
if ((mgmt->mdp_is_hist_init == TRUE) &&
((!completion_done(&mgmt->mdp_hist_comp)) &&
waitqueue_active(&mgmt->mdp_hist_comp.wait)))
pr_err("mgmt->hist invalid NULL\n");
ret = -EINVAL;
}
hist_ready = (mgmt->mdp_is_hist_init && mgmt->mdp_is_hist_valid);
if (!ret && hist_ready) {
switch (mgmt->block) {
case MDP_BLOCK_DMA_P:
case MDP_BLOCK_DMA_S:
ret = _mdp_histogram_read_dma_data(mgmt);
break;
case MDP_BLOCK_VG_1:
case MDP_BLOCK_VG_2:
ret = _mdp_histogram_read_vg_data(mgmt);
break;
default:
pr_err("%s, invalid MDP block = %d\n", __func__,
mgmt->block);
ret = -EINVAL;
goto error;
}
}
/*
* if read was triggered by an underrun or failed copying,
* don't wake up readers
*/
if (!ret && hist_ready) {
mgmt->hist = NULL;
if (waitqueue_active(&mgmt->mdp_hist_comp.wait))
complete(&mgmt->mdp_hist_comp);
}
if (mgmt->mdp_is_hist_valid == FALSE)
mgmt->mdp_is_hist_valid = TRUE;
if (mgmt->mdp_is_hist_init == FALSE)
mgmt->mdp_is_hist_init = TRUE;
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
if (!ret && hist_ready)
__mdp_histogram_kickoff(mgmt);
else
__mdp_histogram_reset(mgmt);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
error:
mutex_unlock(&mgmt->mdp_hist_mutex);
}
/*call from within mdp_hist_mutex*/
static int _mdp_copy_hist_data(struct mdp_histogram_data *hist,
struct mdp_hist_mgmt *mgmt)
{
int ret;
if (hist->c0) {
ret = copy_to_user(hist->c0, mgmt->c0,
sizeof(uint32_t) * (hist->bin_cnt));
if (ret)
goto err;
}
if (hist->c1) {
ret = copy_to_user(hist->c1, mgmt->c1,
sizeof(uint32_t) * (hist->bin_cnt));
if (ret)
goto err;
}
if (hist->c2) {
ret = copy_to_user(hist->c2, mgmt->c2,
sizeof(uint32_t) * (hist->bin_cnt));
if (ret)
goto err;
}
if (hist->extra_info) {
ret = copy_to_user(hist->extra_info, mgmt->extra_info,
sizeof(uint32_t) * ((hist->block > MDP_BLOCK_VG_2) ? 2 : 1));
if (ret)
goto err;
}
err:
return ret;
}
#define MDP_HISTOGRAM_TIMEOUT_MS 84 /*5 Frames*/
static int mdp_do_histogram(struct fb_info *info,
struct mdp_histogram_data *hist)
{
struct mdp_hist_mgmt *mgmt = NULL;
int ret = 0;
unsigned long timeout = (MDP_HISTOGRAM_TIMEOUT_MS * HZ) / 1000;
ret = mdp_histogram_block2mgmt(hist->block, &mgmt);
if (ret) {
pr_info("%s - %d", __func__, __LINE__);
ret = -EINVAL;
return ret;
}
mutex_lock(&mgmt->mdp_do_hist_mutex);
if (!mgmt->frame_cnt || (mgmt->num_bins == 0)) {
pr_info("%s - frame_cnt = %d, num_bins = %d", __func__,
mgmt->frame_cnt, mgmt->num_bins);
ret = -EINVAL;
goto error;
}
if ((mdp_rev <= MDP_REV_41 && hist->bin_cnt > MDP_REV41_HIST_MAX_BIN)
|| (mdp_rev == MDP_REV_42 &&
hist->bin_cnt > MDP_REV42_HIST_MAX_BIN)) {
pr_info("%s - mdp_rev = %d, num_bins = %d", __func__, mdp_rev,
hist->bin_cnt);
ret = -EINVAL;
goto error;
}
mutex_lock(&mgmt->mdp_hist_mutex);
if (!mgmt->mdp_is_hist_data) {
pr_info("%s - hist_data = false!", __func__);
ret = -EINVAL;
goto error_lock;
}
if (!mgmt->mdp_is_hist_start) {
pr_err("%s histogram not started\n", __func__);
ret = -EPERM;
goto error_lock;
}
if (mgmt->hist != NULL) {
pr_err("%s; histogram attempted to be read twice\n", __func__);
ret = -EPERM;
goto error_lock;
}
INIT_COMPLETION(mgmt->mdp_hist_comp);
mgmt->hist = hist;
mutex_unlock(&mgmt->mdp_hist_mutex);
ret = wait_for_completion_killable_timeout(&mgmt->mdp_hist_comp,
timeout);
if (ret <= 0) {
if (!ret) {
mgmt->hist = NULL;
ret = -ETIMEDOUT;
pr_debug("%s: bin collection timedout", __func__);
} else {
mgmt->hist = NULL;
pr_debug("%s: bin collection interrupted", __func__);
}
goto error;
}
mutex_lock(&mgmt->mdp_hist_mutex);
if (mgmt->mdp_is_hist_data && mgmt->mdp_is_hist_init)
ret = _mdp_copy_hist_data(hist, mgmt);
else
ret = -ENODATA;
error_lock:
mutex_unlock(&mgmt->mdp_hist_mutex);
error:
mutex_unlock(&mgmt->mdp_do_hist_mutex);
return ret;
}
#endif
#ifdef CONFIG_FB_MSM_MDP303
/* vsync_isr_handler: Called from isr context*/
static void vsync_isr_handler(void)
{
vsync_cntrl.vsync_time = ktime_get();
}
#endif
ssize_t mdp_dma_show_event(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t ret = 0;
if (atomic_read(&vsync_cntrl.suspend) > 0 ||
atomic_read(&vsync_cntrl.vsync_resume) == 0)
return 0;
INIT_COMPLETION(vsync_cntrl.vsync_wait);
wait_for_completion(&vsync_cntrl.vsync_wait);
ret = snprintf(buf, PAGE_SIZE, "VSYNC=%llu",
ktime_to_ns(vsync_cntrl.vsync_time));
buf[strlen(buf) + 1] = '\0';
return ret;
}
/* Returns < 0 on error, 0 on timeout, or > 0 on successful wait */
int mdp_ppp_pipe_wait(void)
{
int ret = 1;
boolean wait;
unsigned long flag;
/* wait 5 seconds for the operation to complete before declaring
the MDP hung */
spin_lock_irqsave(&mdp_spin_lock, flag);
wait = mdp_ppp_waiting;
spin_unlock_irqrestore(&mdp_spin_lock, flag);
if (wait == TRUE) {
ret = wait_for_completion_interruptible_timeout(&mdp_ppp_comp,
5 * HZ);
if (!ret)
printk(KERN_ERR "%s: Timed out waiting for the MDP.\n",
__func__);
}
return ret;
}
#define MAX_VSYNC_GAP 4
#define DEFAULT_FRAME_RATE 60
u32 mdp_get_panel_framerate(struct msm_fb_data_type *mfd)
{
u32 frame_rate = 0, pixel_rate = 0, total_pixel;
struct msm_panel_info *panel_info = &mfd->panel_info;
pixel_rate =
(panel_info->type == MIPI_CMD_PANEL ||
panel_info->type == MIPI_VIDEO_PANEL) ?
panel_info->mipi.dsi_pclk_rate :
panel_info->clk_rate;
if (!pixel_rate)
pr_warn("%s pixel rate is zero\n", __func__);
total_pixel =
(panel_info->lcdc.h_back_porch +
panel_info->lcdc.h_front_porch +
panel_info->lcdc.h_pulse_width +
panel_info->xres) *
(panel_info->lcdc.v_back_porch +
panel_info->lcdc.v_front_porch +
panel_info->lcdc.v_pulse_width +
panel_info->yres);
if (total_pixel)
frame_rate = pixel_rate / total_pixel;
else
pr_warn("%s total pixels are zero\n", __func__);
if (mfd->dest == DISPLAY_LCD) {
if (panel_info->type == MDDI_PANEL && panel_info->mddi.is_type1)
frame_rate = panel_info->lcd.refx100 / (100 * 2);
else if (panel_info->type != MIPI_CMD_PANEL)
frame_rate = panel_info->lcd.refx100 / 100;
}
if (frame_rate == 0) {
frame_rate = DEFAULT_FRAME_RATE;
pr_warn("%s frame rate=%d is default\n", __func__, frame_rate);
}
pr_debug("%s frame rate=%d total_pixel=%d, pixel_rate=%d\n", __func__,
frame_rate, total_pixel, pixel_rate);
return frame_rate;
}
static int mdp_diff_to_next_vsync(ktime_t cur_time,
ktime_t last_vsync, u32 vsync_period)
{
int diff_from_last, diff_to_next;
/*
* Get interval beween last vsync and current time
* Current time = CPU programming MDP for next Vsync
*/
diff_from_last =
(ktime_to_us(ktime_sub(cur_time, last_vsync)));
diff_from_last /= USEC_PER_MSEC;
/*
* If the last Vsync occurred too long ago, skip programming
* the timer
*/
if (diff_from_last < (vsync_period * MAX_VSYNC_GAP)) {
if (diff_from_last > vsync_period)
diff_to_next =
(diff_from_last - vsync_period) % vsync_period;
else
diff_to_next = vsync_period - diff_from_last;
} else {
/* mark it out of range */
diff_to_next = vsync_period + 1;
}
return diff_to_next;
}
void mdp_update_pm(struct msm_fb_data_type *mfd, ktime_t pre_vsync)
{
u32 vsync_period;
int diff_to_next;
ktime_t cur_time, wakeup_time;
if (!mfd->cpu_pm_hdl)
return;
vsync_period = mfd->panel_info.frame_interval;
cur_time = ktime_get();
diff_to_next = mdp_diff_to_next_vsync(cur_time,
pre_vsync,
vsync_period);
if (diff_to_next > vsync_period)
return;
pr_debug("%s cur_time %d, pre_vsync %d, to_next %d\n",
__func__,
(int)ktime_to_ms(cur_time),
(int)ktime_to_ms(pre_vsync),
diff_to_next);
wakeup_time = ktime_add_ns(cur_time, diff_to_next * NSEC_PER_MSEC);
activate_event_timer(mfd->cpu_pm_hdl, wakeup_time);
}
static DEFINE_SPINLOCK(mdp_lock);
static int mdp_irq_mask;
static int mdp_irq_enabled;
/*
* mdp_enable_irq: can not be called from isr
*/
void mdp_enable_irq(uint32 term)
{
unsigned long irq_flags;
spin_lock_irqsave(&mdp_lock, irq_flags);
if (mdp_irq_mask & term) {
printk(KERN_ERR "%s: MDP IRQ term-0x%x is already set, mask=%x irq=%d\n",
__func__, term, mdp_irq_mask, mdp_irq_enabled);
} else {
mdp_irq_mask |= term;
if (mdp_irq_mask && !mdp_irq_enabled) {
mdp_irq_enabled = 1;
enable_irq(mdp_irq);
}
}
spin_unlock_irqrestore(&mdp_lock, irq_flags);
}
/*
* mdp_disable_irq: can not be called from isr
*/
void mdp_disable_irq(uint32 term)
{
unsigned long irq_flags;
spin_lock_irqsave(&mdp_lock, irq_flags);
if (!(mdp_irq_mask & term)) {
printk(KERN_ERR "%s: MDP IRQ term-0x%x is NOT set, mask=%x irq=%d\n",
__func__, term, mdp_irq_mask, mdp_irq_enabled);
} else {
mdp_irq_mask &= ~term;
if (!mdp_irq_mask && mdp_irq_enabled) {
mdp_irq_enabled = 0;
disable_irq(mdp_irq);
}
}
spin_unlock_irqrestore(&mdp_lock, irq_flags);
}
void mdp_disable_irq_nosync(uint32 term)
{
spin_lock(&mdp_lock);
if (!(mdp_irq_mask & term)) {
printk(KERN_ERR "%s: MDP IRQ term-0x%x is NOT set, mask=%x irq=%d\n",
__func__, term, mdp_irq_mask, mdp_irq_enabled);
} else {
mdp_irq_mask &= ~term;
if (!mdp_irq_mask && mdp_irq_enabled) {
mdp_irq_enabled = 0;
disable_irq_nosync(mdp_irq);
}
}
spin_unlock(&mdp_lock);
}
void mdp_pipe_kickoff(uint32 term, struct msm_fb_data_type *mfd)
{
unsigned long flag;
/* complete all the writes before starting */
wmb();
/* kick off PPP engine */
if (term == MDP_PPP_TERM) {
if (mdp_debug[MDP_PPP_BLOCK])
jiffies_to_timeval(jiffies, &mdp_ppp_timeval);
/* let's turn on PPP block */
mdp_pipe_ctrl(MDP_PPP_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
mdp_enable_irq(term);
INIT_COMPLETION(mdp_ppp_comp);
spin_lock_irqsave(&mdp_spin_lock, flag);
mdp_ppp_waiting = TRUE;
spin_unlock_irqrestore(&mdp_spin_lock, flag);
outpdw(MDP_BASE + 0x30, 0x1000);
wait_for_completion_killable(&mdp_ppp_comp);
mdp_disable_irq(term);
if (mdp_debug[MDP_PPP_BLOCK]) {
struct timeval now;
jiffies_to_timeval(jiffies, &now);
mdp_ppp_timeval.tv_usec =
now.tv_usec - mdp_ppp_timeval.tv_usec;
MSM_FB_DEBUG("MDP-PPP: %d\n",
(int)mdp_ppp_timeval.tv_usec);
}
} else if (term == MDP_DMA2_TERM) {
if (mdp_debug[MDP_DMA2_BLOCK]) {
MSM_FB_DEBUG("MDP-DMA2: %d\n",
(int)mdp_dma2_timeval.tv_usec);
jiffies_to_timeval(jiffies, &mdp_dma2_timeval);
}
/* DMA update timestamp */
mdp_dma2_last_update_time = ktime_get_real();
/* let's turn on DMA2 block */
#ifdef CONFIG_FB_MSM_MDP22
outpdw(MDP_CMD_DEBUG_ACCESS_BASE + 0x0044, 0x0);/* start DMA */
#else
mdp_lut_enable();
#ifdef CONFIG_FB_MSM_MDP40
outpdw(MDP_BASE + 0x000c, 0x0); /* start DMA */
#else
outpdw(MDP_BASE + 0x0044, 0x0); /* start DMA */
#ifdef CONFIG_FB_MSM_MDP303
#ifdef CONFIG_FB_MSM_MIPI_DSI
mipi_dsi_cmd_mdp_start();
#endif
#endif
#endif
#endif
#ifdef CONFIG_FB_MSM_MDP40
} else if (term == MDP_DMA_S_TERM) {
mdp_pipe_ctrl(MDP_DMA_S_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
outpdw(MDP_BASE + 0x0010, 0x0); /* start DMA */
} else if (term == MDP_DMA_E_TERM) {
mdp_pipe_ctrl(MDP_DMA_E_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
outpdw(MDP_BASE + 0x0014, 0x0); /* start DMA */
} else if (term == MDP_OVERLAY0_TERM) {
mdp_pipe_ctrl(MDP_OVERLAY0_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
outpdw(MDP_BASE + 0x0004, 0);
} else if (term == MDP_OVERLAY1_TERM) {
mdp_pipe_ctrl(MDP_OVERLAY1_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
outpdw(MDP_BASE + 0x0008, 0);
} else if (term == MDP_OVERLAY2_TERM) {
mdp_pipe_ctrl(MDP_OVERLAY2_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
outpdw(MDP_BASE + 0x00D0, 0);
}
#else
} else if (term == MDP_DMA_S_TERM) {
mdp_pipe_ctrl(MDP_DMA_S_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
outpdw(MDP_BASE + 0x0048, 0x0); /* start DMA */
} else if (term == MDP_DMA_E_TERM) {
mdp_pipe_ctrl(MDP_DMA_E_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
outpdw(MDP_BASE + 0x004C, 0x0);
}
#endif
}
static struct platform_device *pdev_list[MSM_FB_MAX_DEV_LIST];
static int pdev_list_cnt;
static void mdp_pipe_ctrl_workqueue_handler(struct work_struct *work)
{
mdp_pipe_ctrl(MDP_MASTER_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
}
static int mdp_clk_rate;
#ifdef CONFIG_FB_MSM_NO_MDP_PIPE_CTRL
/*
* mdp_clk_disable_unprepare(void) called from thread context
*/
static void mdp_clk_disable_unprepare(void)
{
mb();
vsync_clk_disable_unprepare();
if (mdp_clk != NULL)
clk_disable_unprepare(mdp_clk);
if (mdp_pclk != NULL)
clk_disable_unprepare(mdp_pclk);
if (mdp_lut_clk != NULL)
clk_disable_unprepare(mdp_lut_clk);
}
/*
* mdp_clk_prepare_enable(void) called from thread context
*/
static void mdp_clk_prepare_enable(void)
{
if (mdp_clk != NULL)
clk_prepare_enable(mdp_clk);
if (mdp_pclk != NULL)
clk_prepare_enable(mdp_pclk);
if (mdp_lut_clk != NULL)
clk_prepare_enable(mdp_lut_clk);
vsync_clk_prepare_enable();
}
/*
* mdp_clk_ctrl: called from thread context
*/
void mdp_clk_ctrl(int on)
{
static int mdp_clk_cnt;
mutex_lock(&mdp_suspend_mutex);
if (on) {
if (mdp_clk_cnt == 0)
mdp_clk_prepare_enable();
mdp_clk_cnt++;
} else {
if (mdp_clk_cnt) {
mdp_clk_cnt--;
if (mdp_clk_cnt == 0)
mdp_clk_disable_unprepare();
} else
pr_err("%s: %d: mdp clk off is invalid\n",
__func__, __LINE__);
}
pr_debug("%s: on=%d cnt=%d\n", __func__, on, mdp_clk_cnt);
mutex_unlock(&mdp_suspend_mutex);
}
void mdp_pipe_ctrl(MDP_BLOCK_TYPE block, MDP_BLOCK_POWER_STATE state,
boolean isr)
{
/* do nothing */
}
#else
void mdp_pipe_ctrl(MDP_BLOCK_TYPE block, MDP_BLOCK_POWER_STATE state,
boolean isr)
{
boolean mdp_all_blocks_off = TRUE;
int i;
unsigned long flag;
struct msm_fb_panel_data *pdata;
/*
* It is assumed that if isr = TRUE then start = OFF
* if start = ON when isr = TRUE it could happen that the usercontext
* could turn off the clocks while the interrupt is updating the
* power to ON
*/
WARN_ON(isr == TRUE && state == MDP_BLOCK_POWER_ON);
spin_lock_irqsave(&mdp_spin_lock, flag);
if (MDP_BLOCK_POWER_ON == state) {
atomic_inc(&mdp_block_power_cnt[block]);
if (MDP_DMA2_BLOCK == block)
mdp_in_processing = TRUE;
} else {
atomic_dec(&mdp_block_power_cnt[block]);
if (atomic_read(&mdp_block_power_cnt[block]) < 0) {
/*
* Master has to serve a request to power off MDP always
* It also has a timer to power off. So, in case of
* timer expires first and DMA2 finishes later,
* master has to power off two times
* There shouldn't be multiple power-off request for
* other blocks
*/
if (block != MDP_MASTER_BLOCK) {
MSM_FB_INFO("mdp_block_power_cnt[block=%d] \
multiple power-off request\n", block);
}
atomic_set(&mdp_block_power_cnt[block], 0);
}
if (MDP_DMA2_BLOCK == block)
mdp_in_processing = FALSE;
}
spin_unlock_irqrestore(&mdp_spin_lock, flag);
/*
* If it's in isr, we send our request to workqueue.
* Otherwise, processing happens in the current context
*/
if (isr) {
if (mdp_current_clk_on) {
/* checking all blocks power state */
for (i = 0; i < MDP_MAX_BLOCK; i++) {
if (atomic_read(&mdp_block_power_cnt[i]) > 0) {
mdp_all_blocks_off = FALSE;
break;
}
}
if (mdp_all_blocks_off) {
/* send workqueue to turn off mdp power */
queue_delayed_work(mdp_pipe_ctrl_wq,
&mdp_pipe_ctrl_worker,
mdp_timer_duration);
}
}
} else {
down(&mdp_pipe_ctrl_mutex);
/* checking all blocks power state */
for (i = 0; i < MDP_MAX_BLOCK; i++) {
if (atomic_read(&mdp_block_power_cnt[i]) > 0) {
mdp_all_blocks_off = FALSE;
break;
}
}
/*
* find out whether a delayable work item is currently
* pending
*/
if (delayed_work_pending(&mdp_pipe_ctrl_worker)) {
/*
* try to cancel the current work if it fails to
* stop (which means del_timer can't delete it
* from the list, it's about to expire and run),
* we have to let it run. queue_delayed_work won't
* accept the next job which is same as
* queue_delayed_work(mdp_timer_duration = 0)
*/
cancel_delayed_work(&mdp_pipe_ctrl_worker);
}
if ((mdp_all_blocks_off) && (mdp_current_clk_on)) {
mutex_lock(&mdp_suspend_mutex);
if (block == MDP_MASTER_BLOCK || mdp_suspended) {
mdp_current_clk_on = FALSE;
mb();
/* turn off MDP clks */
mdp_vsync_clk_disable();
for (i = 0; i < pdev_list_cnt; i++) {
pdata = (struct msm_fb_panel_data *)
pdev_list[i]->dev.platform_data;
if (pdata && pdata->clk_func)
pdata->clk_func(0);
}
if (mdp_clk != NULL) {
mdp_clk_rate = clk_get_rate(mdp_clk);
clk_disable_unprepare(mdp_clk);
if (mdp_hw_revision <=
MDP4_REVISION_V2_1 &&
mdp_clk_rate > 122880000) {
clk_set_rate(mdp_clk,
122880000);
}
MSM_FB_DEBUG("MDP CLK OFF\n");
}
if (mdp_pclk != NULL) {
clk_disable_unprepare(mdp_pclk);
MSM_FB_DEBUG("MDP PCLK OFF\n");
}
if (mdp_lut_clk != NULL)
clk_disable_unprepare(mdp_lut_clk);
} else {
/* send workqueue to turn off mdp power */
queue_delayed_work(mdp_pipe_ctrl_wq,
&mdp_pipe_ctrl_worker,
mdp_timer_duration);
}
mutex_unlock(&mdp_suspend_mutex);
} else if ((!mdp_all_blocks_off) && (!mdp_current_clk_on)) {
mdp_current_clk_on = TRUE;
/* turn on MDP clks */
for (i = 0; i < pdev_list_cnt; i++) {
pdata = (struct msm_fb_panel_data *)
pdev_list[i]->dev.platform_data;
if (pdata && pdata->clk_func)
pdata->clk_func(1);
}
if (mdp_clk != NULL) {
if (mdp_hw_revision <=
MDP4_REVISION_V2_1 &&
mdp_clk_rate > 122880000) {
clk_set_rate(mdp_clk,
mdp_clk_rate);
}
clk_prepare_enable(mdp_clk);
MSM_FB_DEBUG("MDP CLK ON\n");
}
if (mdp_pclk != NULL) {
clk_prepare_enable(mdp_pclk);
MSM_FB_DEBUG("MDP PCLK ON\n");
}
if (mdp_lut_clk != NULL)
clk_prepare_enable(mdp_lut_clk);
mdp_vsync_clk_enable();
}
up(&mdp_pipe_ctrl_mutex);
}
}
void mdp_clk_ctrl(int on)
{
/* do nothing */
}
#endif
void mdp_histogram_handle_isr(struct mdp_hist_mgmt *mgmt)
{
uint32 isr, mask;
char *base_addr = MDP_BASE + mgmt->base;
isr = inpdw(base_addr + MDP_HIST_INTR_STATUS_OFF);
mask = inpdw(base_addr + MDP_HIST_INTR_ENABLE_OFF);
outpdw(base_addr + MDP_HIST_INTR_CLEAR_OFF, isr);
mb();
isr &= mask;
if (isr & INTR_HIST_RESET_SEQ_DONE)
__mdp_histogram_kickoff(mgmt);
else if (isr & INTR_HIST_DONE)
queue_work(mdp_hist_wq, &mgmt->mdp_histogram_worker);
}
#ifndef CONFIG_FB_MSM_MDP40
irqreturn_t mdp_isr(int irq, void *ptr)
{
uint32 mdp_interrupt = 0;
struct mdp_dma_data *dma;
unsigned long flag;
struct mdp_hist_mgmt *mgmt = NULL;
int i, ret;
int vsync_isr, disabled_clocks;
/* Ensure all the register write are complete */
mb();
mdp_is_in_isr = TRUE;
mdp_interrupt = inp32(MDP_INTR_STATUS);
outp32(MDP_INTR_CLEAR, mdp_interrupt);
mdp_interrupt &= mdp_intr_mask;
if (mdp_interrupt & TV_ENC_UNDERRUN) {
mdp_interrupt &= ~(TV_ENC_UNDERRUN);
mdp_tv_underflow_cnt++;
}
if (!mdp_interrupt)
goto out;
/*Primary Vsync interrupt*/
if (mdp_interrupt & MDP_PRIM_RDPTR) {
spin_lock_irqsave(&mdp_spin_lock, flag);
vsync_isr = vsync_cntrl.vsync_irq_enabled;
disabled_clocks = vsync_cntrl.disabled_clocks;
if ((!vsync_isr && !vsync_cntrl.disabled_clocks)
|| (!vsync_isr && vsync_cntrl.vsync_dma_enabled)) {
mdp_intr_mask &= ~MDP_PRIM_RDPTR;
outp32(MDP_INTR_ENABLE, mdp_intr_mask);
mdp_disable_irq_nosync(MDP_VSYNC_TERM);
vsync_cntrl.disabled_clocks = 1;
} else if (vsync_isr) {
vsync_isr_handler();
}
vsync_cntrl.vsync_dma_enabled = 0;
spin_unlock_irqrestore(&mdp_spin_lock, flag);
complete(&vsync_cntrl.vsync_comp);
if (!vsync_isr && !disabled_clocks)
mdp_pipe_ctrl(MDP_CMD_BLOCK,
MDP_BLOCK_POWER_OFF, TRUE);
complete_all(&vsync_cntrl.vsync_wait);
}
/* DMA3 TV-Out Start */
if (mdp_interrupt & TV_OUT_DMA3_START) {
/* let's disable TV out interrupt */
mdp_intr_mask &= ~TV_OUT_DMA3_START;
outp32(MDP_INTR_ENABLE, mdp_intr_mask);
dma = &dma3_data;
if (dma->waiting) {
dma->waiting = FALSE;
complete(&dma->comp);
}
}
if (mdp_rev >= MDP_REV_30) {
/* Only DMA_P histogram exists for this MDP rev*/
if (mdp_interrupt & MDP_HIST_DONE) {
ret = mdp_histogram_block2mgmt(MDP_BLOCK_DMA_P, &mgmt);
if (!ret)
mdp_histogram_handle_isr(mgmt);
outp32(MDP_INTR_CLEAR, MDP_HIST_DONE);
}
/* LCDC UnderFlow */
if (mdp_interrupt & LCDC_UNDERFLOW) {
mdp_lcdc_underflow_cnt++;
/*when underflow happens HW resets all the histogram
registers that were set before so restore them back
to normal.*/
for (i = 0; i < MDP_HIST_MGMT_MAX; i++) {
mgmt = mdp_hist_mgmt_array[i];
if (!mgmt)
continue;
mgmt->mdp_is_hist_valid = FALSE;
}
}
/* LCDC Frame Start */
if (mdp_interrupt & LCDC_FRAME_START) {
dma = &dma2_data;
spin_lock_irqsave(&mdp_spin_lock, flag);
vsync_isr = vsync_cntrl.vsync_irq_enabled;
/* let's disable LCDC interrupt */
if (dma->waiting) {
dma->waiting = FALSE;
complete(&dma->comp);
}
if (!vsync_isr) {
mdp_intr_mask &= ~LCDC_FRAME_START;
outp32(MDP_INTR_ENABLE, mdp_intr_mask);
mdp_disable_irq_nosync(MDP_VSYNC_TERM);
vsync_cntrl.disabled_clocks = 1;
} else {
vsync_isr_handler();
}
spin_unlock_irqrestore(&mdp_spin_lock, flag);
if (!vsync_isr)
mdp_pipe_ctrl(MDP_CMD_BLOCK,
MDP_BLOCK_POWER_OFF, TRUE);
complete_all(&vsync_cntrl.vsync_wait);
}
/* DMA2 LCD-Out Complete */
if (mdp_interrupt & MDP_DMA_S_DONE) {
dma = &dma_s_data;
dma->busy = FALSE;
mdp_pipe_ctrl(MDP_DMA_S_BLOCK, MDP_BLOCK_POWER_OFF,
TRUE);
complete(&dma->comp);
}
/* DMA_E LCD-Out Complete */
if (mdp_interrupt & MDP_DMA_E_DONE) {
dma = &dma_s_data;
dma->busy = FALSE;
mdp_pipe_ctrl(MDP_DMA_E_BLOCK, MDP_BLOCK_POWER_OFF,
TRUE);
complete(&dma->comp);
}
}
/* DMA2 LCD-Out Complete */
if (mdp_interrupt & MDP_DMA_P_DONE) {
struct timeval now;
mdp_dma2_last_update_time = ktime_sub(ktime_get_real(),
mdp_dma2_last_update_time);
if (mdp_debug[MDP_DMA2_BLOCK]) {
jiffies_to_timeval(jiffies, &now);
mdp_dma2_timeval.tv_usec =
now.tv_usec - mdp_dma2_timeval.tv_usec;
}
#ifndef CONFIG_FB_MSM_MDP303
dma = &dma2_data;
spin_lock_irqsave(&mdp_spin_lock, flag);
dma->busy = FALSE;
spin_unlock_irqrestore(&mdp_spin_lock, flag);
mdp_pipe_ctrl(MDP_DMA2_BLOCK, MDP_BLOCK_POWER_OFF, TRUE);
complete(&dma->comp);
#else
if (mdp_prim_panel_type == MIPI_CMD_PANEL) {
dma = &dma2_data;
spin_lock_irqsave(&mdp_spin_lock, flag);
dma->busy = FALSE;
spin_unlock_irqrestore(&mdp_spin_lock, flag);
mdp_pipe_ctrl(MDP_DMA2_BLOCK, MDP_BLOCK_POWER_OFF,
TRUE);
mdp_disable_irq_nosync(MDP_DMA2_TERM);
complete(&dma->comp);
}
#endif
}
/* PPP Complete */
if (mdp_interrupt & MDP_PPP_DONE) {
#ifdef CONFIG_FB_MSM_MDP31
MDP_OUTP(MDP_BASE + 0x00100, 0xFFFF);
#endif
mdp_pipe_ctrl(MDP_PPP_BLOCK, MDP_BLOCK_POWER_OFF, TRUE);
spin_lock_irqsave(&mdp_spin_lock, flag);
if (mdp_ppp_waiting) {
mdp_ppp_waiting = FALSE;
complete(&mdp_ppp_comp);
}
spin_unlock_irqrestore(&mdp_spin_lock, flag);
}
out:
mdp_is_in_isr = FALSE;
return IRQ_HANDLED;
}
#endif
static void mdp_drv_init(void)
{
int i;
for (i = 0; i < MDP_MAX_BLOCK; i++) {
mdp_debug[i] = 0;
}
/* initialize spin lock and workqueue */
spin_lock_init(&mdp_spin_lock);
mdp_dma_wq = create_singlethread_workqueue("mdp_dma_wq");
mdp_vsync_wq = create_singlethread_workqueue("mdp_vsync_wq");
mdp_pipe_ctrl_wq = create_singlethread_workqueue("mdp_pipe_ctrl_wq");
INIT_DELAYED_WORK(&mdp_pipe_ctrl_worker,
mdp_pipe_ctrl_workqueue_handler);
/* initialize semaphore */
init_completion(&mdp_ppp_comp);
sema_init(&mdp_ppp_mutex, 1);
sema_init(&mdp_pipe_ctrl_mutex, 1);
dma2_data.busy = FALSE;
dma2_data.dmap_busy = FALSE;
dma2_data.waiting = FALSE;
init_completion(&dma2_data.comp);
init_completion(&vsync_cntrl.vsync_comp);
init_completion(&dma2_data.dmap_comp);
sema_init(&dma2_data.mutex, 1);
mutex_init(&dma2_data.ov_mutex);
dma3_data.busy = FALSE;
dma3_data.waiting = FALSE;
init_completion(&dma3_data.comp);
sema_init(&dma3_data.mutex, 1);
dma_s_data.busy = FALSE;
dma_s_data.waiting = FALSE;
init_completion(&dma_s_data.comp);
sema_init(&dma_s_data.mutex, 1);
#ifndef CONFIG_FB_MSM_MDP303
dma_e_data.busy = FALSE;
dma_e_data.waiting = FALSE;
init_completion(&dma_e_data.comp);
mutex_init(&dma_e_data.ov_mutex);
#endif
#ifdef CONFIG_FB_MSM_WRITEBACK_MSM_PANEL
dma_wb_data.busy = FALSE;
dma_wb_data.waiting = FALSE;
init_completion(&dma_wb_data.comp);
mutex_init(&dma_wb_data.ov_mutex);
#endif
/* initializing mdp power block counter to 0 */
for (i = 0; i < MDP_MAX_BLOCK; i++) {
atomic_set(&mdp_block_power_cnt[i], 0);
}
vsync_cntrl.disabled_clocks = 1;
init_completion(&vsync_cntrl.vsync_wait);
atomic_set(&vsync_cntrl.vsync_resume, 1);
#ifdef MSM_FB_ENABLE_DBGFS
{
struct dentry *root;
char sub_name[] = "mdp";
root = msm_fb_get_debugfs_root();
if (root != NULL) {
mdp_dir = debugfs_create_dir(sub_name, root);
if (mdp_dir) {
msm_fb_debugfs_file_create(mdp_dir,
"dma2_update_time_in_usec",
(u32 *) &mdp_dma2_update_time_in_usec);
msm_fb_debugfs_file_create(mdp_dir,
"vs_rdcnt_slow",
(u32 *) &mdp_lcd_rd_cnt_offset_slow);
msm_fb_debugfs_file_create(mdp_dir,
"vs_rdcnt_fast",
(u32 *) &mdp_lcd_rd_cnt_offset_fast);
msm_fb_debugfs_file_create(mdp_dir,
"mdp_usec_diff_threshold",
(u32 *) &mdp_usec_diff_threshold);
msm_fb_debugfs_file_create(mdp_dir,
"mdp_current_clk_on",
(u32 *) &mdp_current_clk_on);
#ifdef CONFIG_FB_MSM_LCDC
msm_fb_debugfs_file_create(mdp_dir,
"lcdc_start_x",
(u32 *) &first_pixel_start_x);
msm_fb_debugfs_file_create(mdp_dir,
"lcdc_start_y",
(u32 *) &first_pixel_start_y);
#endif
}
}
}
#endif
}
static int mdp_probe(struct platform_device *pdev);
static int mdp_remove(struct platform_device *pdev);
static int mdp_runtime_suspend(struct device *dev)
{
dev_dbg(dev, "pm_runtime: suspending...\n");
return 0;
}
static int mdp_runtime_resume(struct device *dev)
{
dev_dbg(dev, "pm_runtime: resuming...\n");
return 0;
}
static struct dev_pm_ops mdp_dev_pm_ops = {
.runtime_suspend = mdp_runtime_suspend,
.runtime_resume = mdp_runtime_resume,
};
static struct platform_driver mdp_driver = {
.probe = mdp_probe,
.remove = mdp_remove,
#ifndef CONFIG_HAS_EARLYSUSPEND
.suspend = mdp_suspend,
.resume = NULL,
#endif
.shutdown = NULL,
.driver = {
/*
* Driver name must match the device name added in
* platform.c.
*/
.name = "mdp",
.pm = &mdp_dev_pm_ops,
},
};
static int mdp_off(struct platform_device *pdev)
{
int ret = 0;
struct msm_fb_data_type *mfd = platform_get_drvdata(pdev);
pr_debug("%s:+\n", __func__);
mdp_histogram_ctrl_all(FALSE);
atomic_set(&vsync_cntrl.suspend, 1);
atomic_set(&vsync_cntrl.vsync_resume, 0);
complete_all(&vsync_cntrl.vsync_wait);
mdp_clk_ctrl(1);
if (mfd->panel.type == MIPI_CMD_PANEL)
mdp4_dsi_cmd_off(pdev);
else if (mfd->panel.type == MIPI_VIDEO_PANEL)
mdp4_dsi_video_off(pdev);
else if (mfd->panel.type == HDMI_PANEL ||
mfd->panel.type == LCDC_PANEL ||
mfd->panel.type == LVDS_PANEL)
mdp4_lcdc_off(pdev);
else if (mfd->panel.type == MDDI_PANEL)
mdp4_mddi_off(pdev);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
ret = panel_next_off(pdev);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
mdp_clk_ctrl(0);
#ifdef CONFIG_MSM_BUS_SCALING
mdp_bus_scale_update_request(0, 0);
#endif
if (mdp_rev >= MDP_REV_41 && mfd->panel.type == MIPI_CMD_PANEL)
mdp_dsi_cmd_overlay_suspend(mfd);
pr_debug("%s:-\n", __func__);
return ret;
}
#ifdef CONFIG_FB_MSM_MDP303
unsigned is_mdp4_hw_reset(void)
{
return 0;
}
void mdp4_hw_init(void)
{
/* empty */
}
#endif
static int mdp_on(struct platform_device *pdev)
{
int ret = 0;
struct msm_fb_data_type *mfd;
mfd = platform_get_drvdata(pdev);
pr_debug("%s:+\n", __func__);
if (mdp_rev >= MDP_REV_40) {
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
mdp_clk_ctrl(1);
mdp4_hw_init();
outpdw(MDP_BASE + 0x0038, mdp4_display_intf);
if (mfd->panel.type == MIPI_CMD_PANEL) {
mdp_vsync_cfg_regs(mfd, FALSE);
mdp4_dsi_cmd_on(pdev);
} else if (mfd->panel.type == MIPI_VIDEO_PANEL) {
mdp4_dsi_video_on(pdev);
} else if (mfd->panel.type == HDMI_PANEL ||
mfd->panel.type == LCDC_PANEL ||
mfd->panel.type == LVDS_PANEL) {
mdp4_lcdc_on(pdev);
} else if (mfd->panel.type == MDDI_PANEL) {
mdp_vsync_cfg_regs(mfd, FALSE);
mdp4_mddi_on(pdev);
}
mdp_clk_ctrl(0);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
}
if (mdp_rev == MDP_REV_303 && mfd->panel.type == MIPI_CMD_PANEL) {
vsync_cntrl.dev = mfd->fbi->dev;
atomic_set(&vsync_cntrl.suspend, 0);
atomic_set(&vsync_cntrl.vsync_resume, 1);
}
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
ret = panel_next_on(pdev);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
mdp_histogram_ctrl_all(TRUE);
if (ret == 0)
ret = panel_next_late_init(pdev);
pr_debug("%s:-\n", __func__);
return ret;
}
static int mdp_resource_initialized;
static struct msm_panel_common_pdata *mdp_pdata;
uint32 mdp_hw_revision;
/*
* mdp_hw_revision:
* 0 == V1
* 1 == V2
* 2 == V2.1
*
*/
void mdp_hw_version(void)
{
char *cp;
uint32 *hp;
if (mdp_pdata == NULL)
return;
mdp_hw_revision = MDP4_REVISION_NONE;
if (mdp_pdata->hw_revision_addr == 0)
return;
/* tlmmgpio2 shadow */
cp = (char *)ioremap(mdp_pdata->hw_revision_addr, 0x16);
if (cp == NULL)
return;
hp = (uint32 *)cp; /* HW_REVISION_NUMBER */
mdp_hw_revision = *hp;
iounmap(cp);
mdp_hw_revision >>= 28; /* bit 31:28 */
mdp_hw_revision &= 0x0f;
MSM_FB_DEBUG("%s: mdp_hw_revision=%x\n",
__func__, mdp_hw_revision);
}
#ifdef CONFIG_MSM_BUS_SCALING
#ifndef MDP_BUS_VECTOR_ENTRY
#define MDP_BUS_VECTOR_ENTRY(ab_val, ib_val) \
{ \
.src = MSM_BUS_MASTER_MDP_PORT0, \
.dst = MSM_BUS_SLAVE_EBI_CH0, \
.ab = (ab_val), \
.ib = (ib_val), \
}
#endif
/*
* Entry 0 hold 0 request
* Entry 1 and 2 do ping pong request
*/
static struct msm_bus_vectors mdp_bus_vectors[] = {
MDP_BUS_VECTOR_ENTRY(0, 0),
MDP_BUS_VECTOR_ENTRY( 128000000, 160000000),
MDP_BUS_VECTOR_ENTRY( 128000000, 160000000),
};
static struct msm_bus_paths mdp_bus_usecases[ARRAY_SIZE(mdp_bus_vectors)];
static struct msm_bus_scale_pdata mdp_bus_scale_table = {
.usecase = mdp_bus_usecases,
.num_usecases = ARRAY_SIZE(mdp_bus_usecases),
.name = "mdp",
};
static uint32_t mdp_bus_scale_handle;
static int mdp_bus_scale_register(void)
{
struct msm_bus_scale_pdata *bus_pdata = &mdp_bus_scale_table;
int i;
for (i = 0; i < bus_pdata->num_usecases; i++) {
mdp_bus_usecases[i].num_paths = 1;
mdp_bus_usecases[i].vectors = &mdp_bus_vectors[i];
}
mdp_bus_scale_handle = msm_bus_scale_register_client(bus_pdata);
if (!mdp_bus_scale_handle) {
pr_err("%s: not able to get bus scale!\n", __func__);
return -ENOMEM;
}
return 0;
}
int mdp_bus_scale_update_request(u64 ab, u64 ib)
{
static int bus_index = 1;
if (mdp_bus_scale_handle < 1) {
pr_err("%s invalid bus handle\n", __func__);
return -EINVAL;
}
if (!ab)
return msm_bus_scale_client_update_request
(mdp_bus_scale_handle, 0);
/* ping pong bus_index between table entry 1 and 2 */
bus_index++;
bus_index = (bus_index > 2) ? 1 : bus_index;
mdp_bus_usecases[bus_index].vectors->ab = min(ab, mdp_max_bw);
ib = max(ib, ab);
mdp_bus_usecases[bus_index].vectors->ib = min(ib, mdp_max_bw);
pr_debug("%s: handle=%d index=%d ab=%llu ib=%llu\n", __func__,
(u32)mdp_bus_scale_handle, bus_index,
mdp_bus_usecases[bus_index].vectors->ab,
mdp_bus_usecases[bus_index].vectors->ib);
return msm_bus_scale_client_update_request
(mdp_bus_scale_handle, bus_index);
}
#endif
DEFINE_MUTEX(mdp_clk_lock);
int mdp_set_core_clk(u32 rate)
{
int ret = -EINVAL;
if (mdp_clk)
ret = clk_set_rate(mdp_clk, rate);
if (ret)
pr_err("%s unable to set mdp clk rate", __func__);
else
pr_debug("%s mdp clk rate to be set %d: actual rate %ld\n",
__func__, rate, clk_get_rate(mdp_clk));
return ret;
}
int mdp_clk_round_rate(u32 rate)
{
return clk_round_rate(mdp_clk, rate);
}
unsigned long mdp_get_core_clk(void)
{
unsigned long clk_rate = 0;
if (mdp_clk) {
mutex_lock(&mdp_clk_lock);
clk_rate = clk_get_rate(mdp_clk);
mutex_unlock(&mdp_clk_lock);
}
return clk_rate;
}
static int mdp_irq_clk_setup(struct platform_device *pdev,
char cont_splashScreen)
{
int ret;
#ifdef CONFIG_FB_MSM_MDP40
ret = request_irq(mdp_irq, mdp4_isr, IRQF_DISABLED, "MDP", 0);
#else
ret = request_irq(mdp_irq, mdp_isr, IRQF_DISABLED, "MDP", 0);
#endif
if (ret) {
printk(KERN_ERR "mdp request_irq() failed!\n");
return ret;
}
disable_irq(mdp_irq);
dsi_pll_vdda = regulator_get(&pdev->dev, "dsi_pll_vdda");
if (IS_ERR(dsi_pll_vdda)) {
dsi_pll_vdda = NULL;
} else {
if (mdp_rev == MDP_REV_42 || mdp_rev == MDP_REV_44) {
ret = regulator_set_voltage(dsi_pll_vdda, 1200000,
1200000);
if (ret) {
pr_err("set_voltage failed for dsi_pll_vdda, ret=%d\n",
ret);
}
}
}
dsi_pll_vddio = regulator_get(&pdev->dev, "dsi_pll_vddio");
if (IS_ERR(dsi_pll_vddio)) {
dsi_pll_vddio = NULL;
} else {
if (mdp_rev == MDP_REV_42) {
ret = regulator_set_voltage(dsi_pll_vddio, 1800000,
1800000);
if (ret) {
pr_err("set_voltage failed for dsi_pll_vddio, ret=%d\n",
ret);
}
}
}
footswitch = regulator_get(&pdev->dev, "vdd");
if (IS_ERR(footswitch)) {
footswitch = NULL;
} else {
regulator_enable(footswitch);
mdp_footswitch_on = 1;
}
mdp_clk = clk_get(&pdev->dev, "core_clk");
if (IS_ERR(mdp_clk)) {
ret = PTR_ERR(mdp_clk);
printk(KERN_ERR "can't get mdp_clk error:%d!\n", ret);
free_irq(mdp_irq, 0);
return ret;
}
mdp_pclk = clk_get(&pdev->dev, "iface_clk");
if (IS_ERR(mdp_pclk))
mdp_pclk = NULL;
if (mdp_rev >= MDP_REV_42) {
mdp_lut_clk = clk_get(&pdev->dev, "lut_clk");
if (IS_ERR(mdp_lut_clk)) {
ret = PTR_ERR(mdp_lut_clk);
pr_err("can't get mdp_clk error:%d!\n", ret);
clk_put(mdp_clk);
free_irq(mdp_irq, 0);
return ret;
}
} else {
mdp_lut_clk = NULL;
}
#ifdef CONFIG_FB_MSM_MDP40
if (mdp_pdata)
mdp_max_clk = mdp_pdata->mdp_max_clk;
else
pr_err("%s cannot get mdp max clk!\n", __func__);
if (!mdp_max_clk)
pr_err("%s mdp max clk is zero!\n", __func__);
if (cont_splashScreen)
mdp_clk_rate = clk_get_rate(mdp_clk);
else
mdp_clk_rate = mdp_max_clk;
mutex_lock(&mdp_clk_lock);
clk_set_rate(mdp_clk, mdp_clk_rate);
if (mdp_lut_clk != NULL)
clk_set_rate(mdp_lut_clk, mdp_clk_rate);
mutex_unlock(&mdp_clk_lock);
MSM_FB_DEBUG("mdp_clk: mdp_clk=%d\n", (int)clk_get_rate(mdp_clk));
#endif
if (mdp_rev == MDP_REV_42 && !cont_splashScreen) {
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
/* DSI Video Timing generator disable */
outpdw(MDP_BASE + 0xE0000, 0x0);
/* Clear MDP Interrupt Enable register */
outpdw(MDP_BASE + 0x50, 0x0);
/* Set Overlay Proc 0 to reset state */
outpdw(MDP_BASE + 0x10004, 0x3);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
}
return 0;
}
static int mdp_probe(struct platform_device *pdev)
{
struct platform_device *msm_fb_dev = NULL;
struct msm_fb_data_type *mfd;
struct msm_fb_panel_data *pdata = NULL;
int rc;
resource_size_t size ;
unsigned long flag;
u32 frame_rate;
#ifdef CONFIG_FB_MSM_MDP40
int intf, if_no;
#endif
#if defined(CONFIG_FB_MSM_MIPI_DSI) && defined(CONFIG_FB_MSM_MDP40)
struct mipi_panel_info *mipi;
#endif
if ((pdev->id == 0) && (pdev->num_resources > 0)) {
mdp_init_pdev = pdev;
mdp_pdata = pdev->dev.platform_data;
size = resource_size(&pdev->resource[0]);
msm_mdp_base = ioremap(pdev->resource[0].start, size);
MSM_FB_DEBUG("MDP HW Base phy_Address = 0x%x virt = 0x%x\n",
(int)pdev->resource[0].start, (int)msm_mdp_base);
if (unlikely(!msm_mdp_base))
return -ENOMEM;
mdp_irq = platform_get_irq(pdev, 0);
if (mdp_irq < 0) {
pr_err("mdp: can not get mdp irq\n");
return -ENOMEM;
}
mdp_rev = mdp_pdata->mdp_rev;
mdp_iommu_split_domain = mdp_pdata->mdp_iommu_split_domain;
rc = mdp_irq_clk_setup(pdev, mdp_pdata->cont_splash_enabled);
if (rc)
return rc;
mdp_clk_ctrl(1);
mdp_hw_version();
/* initializing mdp hw */
#ifdef CONFIG_FB_MSM_MDP40
if (!(mdp_pdata->cont_splash_enabled))
mdp4_hw_init();
#else
mdp_hw_init(mdp_pdata->cont_splash_enabled);
#endif
#ifdef CONFIG_FB_MSM_OVERLAY
mdp_hw_cursor_init();
#endif
if (!(mdp_pdata->cont_splash_enabled))
mdp_clk_ctrl(0);
mdp_resource_initialized = 1;
return 0;
}
if (!mdp_resource_initialized)
return -EPERM;
mfd = platform_get_drvdata(pdev);
if (!mfd)
return -ENODEV;
if (mfd->key != MFD_KEY)
return -EINVAL;
if (pdev_list_cnt >= MSM_FB_MAX_DEV_LIST)
return -ENOMEM;
msm_fb_dev = platform_device_alloc("msm_fb", pdev->id);
if (!msm_fb_dev)
return -ENOMEM;
/* link to the latest pdev */
mfd->pdev = msm_fb_dev;
mfd->mdp_rev = mdp_rev;
mfd->vsync_init = NULL;
mfd->ov0_wb_buf = MDP_ALLOC(sizeof(struct mdp_buf_type));
mfd->ov1_wb_buf = MDP_ALLOC(sizeof(struct mdp_buf_type));
memset((void *)mfd->ov0_wb_buf, 0, sizeof(struct mdp_buf_type));
memset((void *)mfd->ov1_wb_buf, 0, sizeof(struct mdp_buf_type));
if (mdp_pdata) {
mfd->ov0_wb_buf->size = mdp_pdata->ov0_wb_size;
mfd->ov1_wb_buf->size = mdp_pdata->ov1_wb_size;
mfd->mem_hid = mdp_pdata->mem_hid;
mfd->avtimer_phy = mdp_pdata->avtimer_phy;
} else {
mfd->ov0_wb_buf->size = 0;
mfd->ov1_wb_buf->size = 0;
mfd->mem_hid = 0;
mfd->avtimer_phy = 0;
}
/* initialize Post Processing data*/
mdp_hist_lut_init();
mdp_histogram_init();
mdp_pp_initialized = TRUE;
/* add panel data */
if (platform_device_add_data
(msm_fb_dev, pdev->dev.platform_data,
sizeof(struct msm_fb_panel_data))) {
printk(KERN_ERR "mdp_probe: platform_device_add_data failed!\n");
rc = -ENOMEM;
goto mdp_probe_err;
}
if (mdp_pdata) {
if (mdp_pdata->cont_splash_enabled &&
mfd->panel_info.pdest == DISPLAY_1) {
char *cp;
uint32 bpp = 3;
/*read panel wxh and calculate splash screen
size*/
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
mdp_pdata->splash_screen_size =
inpdw(MDP_BASE + 0x90004);
mdp_pdata->splash_screen_size =
(((mdp_pdata->splash_screen_size >> 16) &
0x00000FFF) * (
mdp_pdata->splash_screen_size &
0x00000FFF)) * bpp;
mdp_pdata->splash_screen_addr =
inpdw(MDP_BASE + 0x90008);
mfd->copy_splash_buf = dma_alloc_coherent(NULL,
mdp_pdata->splash_screen_size,
(dma_addr_t *) &(mfd->copy_splash_phys),
GFP_KERNEL);
if (!mfd->copy_splash_buf) {
pr_err("DMA ALLOC FAILED for SPLASH\n");
return -ENOMEM;
}
cp = (char *)ioremap(
mdp_pdata->splash_screen_addr,
mdp_pdata->splash_screen_size);
if (!cp) {
pr_err("IOREMAP FAILED for SPLASH\n");
return -ENOMEM;
}
memcpy(mfd->copy_splash_buf, cp,
mdp_pdata->splash_screen_size);
MDP_OUTP(MDP_BASE + 0x90008,
mfd->copy_splash_phys);
}
mfd->cont_splash_done = (1 - mdp_pdata->cont_splash_enabled);
}
/* data chain */
pdata = msm_fb_dev->dev.platform_data;
pdata->on = mdp_on;
pdata->off = mdp_off;
pdata->late_init = NULL;
pdata->next = pdev;
mdp_clk_ctrl(1);
mdp_prim_panel_type = mfd->panel.type;
switch (mfd->panel.type) {
case EXT_MDDI_PANEL:
case MDDI_PANEL:
case EBI2_PANEL:
INIT_WORK(&mfd->dma_update_worker,
mdp_lcd_update_workqueue_handler);
INIT_WORK(&mfd->vsync_resync_worker,
mdp_vsync_resync_workqueue_handler);
mfd->hw_refresh = FALSE;
if (mfd->panel.type == MDDI_PANEL)
mdp4_mddi_rdptr_init(0);
if (mfd->panel.type == EXT_MDDI_PANEL) {
/* 15 fps -> 66 msec */
mfd->refresh_timer_duration = (66 * HZ / 1000);
} else {
/* 24 fps -> 42 msec */
mfd->refresh_timer_duration = (42 * HZ / 1000);
}
#ifdef CONFIG_FB_MSM_MDP22
mfd->dma_fnc = mdp_dma2_update;
mfd->dma = &dma2_data;
#else
if (mfd->panel_info.pdest == DISPLAY_1) {
#if defined(CONFIG_FB_MSM_OVERLAY) && defined(CONFIG_FB_MSM_MDDI)
mfd->dma_fnc = mdp4_mddi_overlay;
mfd->cursor_update = mdp4_mddi_overlay_cursor;
#else
mfd->dma_fnc = mdp_dma2_update;
#endif
mfd->dma = &dma2_data;
mfd->lut_update = mdp_lut_update_nonlcdc;
mfd->do_histogram = mdp_do_histogram;
mfd->start_histogram = mdp_histogram_start;
mfd->stop_histogram = mdp_histogram_stop;
} else {
mfd->dma_fnc = mdp_dma_s_update;
mfd->dma = &dma_s_data;
}
#endif
if (mdp_pdata)
mfd->vsync_gpio = mdp_pdata->gpio;
else
mfd->vsync_gpio = -1;
#ifdef CONFIG_FB_MSM_MDP40
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
spin_lock_irqsave(&mdp_spin_lock, flag);
mdp_intr_mask |= INTR_OVERLAY0_DONE;
if (mdp_hw_revision < MDP4_REVISION_V2_1) {
/* dmas dmap switch */
mdp_intr_mask |= INTR_DMA_S_DONE;
}
outp32(MDP_INTR_ENABLE, mdp_intr_mask);
spin_unlock_irqrestore(&mdp_spin_lock, flag);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
if (mfd->panel.type == EBI2_PANEL)
intf = EBI2_INTF;
else
intf = MDDI_INTF;
if (mfd->panel_info.pdest == DISPLAY_1)
if_no = PRIMARY_INTF_SEL;
else
if_no = SECONDARY_INTF_SEL;
mdp4_display_intf_sel(if_no, intf);
#endif
mdp_config_vsync(mdp_init_pdev, mfd);
break;
#ifdef CONFIG_FB_MSM_MIPI_DSI
case MIPI_VIDEO_PANEL:
#ifndef CONFIG_FB_MSM_MDP303
mipi = &mfd->panel_info.mipi;
mfd->vsync_init = mdp4_dsi_vsync_init;
mfd->vsync_show = mdp4_dsi_video_show_event;
mfd->hw_refresh = TRUE;
mfd->dma_fnc = mdp4_dsi_video_overlay;
mfd->lut_update = mdp_lut_update_lcdc;
mfd->do_histogram = mdp_do_histogram;
mfd->start_histogram = mdp_histogram_start;
mfd->stop_histogram = mdp_histogram_stop;
if (mfd->panel_info.pdest == DISPLAY_1) {
if_no = PRIMARY_INTF_SEL;
mfd->dma = &dma2_data;
} else {
if_no = EXTERNAL_INTF_SEL;
mfd->dma = &dma_e_data;
}
mdp4_display_intf_sel(if_no, DSI_VIDEO_INTF);
#else
pdata->on = mdp_dsi_video_on;
pdata->off = mdp_dsi_video_off;
mfd->hw_refresh = TRUE;
mfd->dma_fnc = mdp_dsi_video_update;
mfd->do_histogram = mdp_do_histogram;
mfd->start_histogram = mdp_histogram_start;
mfd->stop_histogram = mdp_histogram_stop;
mfd->vsync_ctrl = mdp_dma_video_vsync_ctrl;
mfd->vsync_show = mdp_dma_video_show_event;
if (mfd->panel_info.pdest == DISPLAY_1)
mfd->dma = &dma2_data;
else {
printk(KERN_ERR "Invalid Selection of destination panel\n");
rc = -ENODEV;
mdp_clk_ctrl(0);
goto mdp_probe_err;
}
#endif
if (mdp_rev >= MDP_REV_40)
mfd->cursor_update = mdp_hw_cursor_sync_update;
else
mfd->cursor_update = mdp_hw_cursor_update;
break;
case MIPI_CMD_PANEL:
#ifndef CONFIG_FB_MSM_MDP303
mfd->dma_fnc = mdp4_dsi_cmd_overlay;
mipi = &mfd->panel_info.mipi;
mfd->vsync_init = mdp4_dsi_rdptr_init;
mfd->vsync_show = mdp4_dsi_cmd_show_event;
if (mfd->panel_info.pdest == DISPLAY_1) {
if_no = PRIMARY_INTF_SEL;
mfd->dma = &dma2_data;
} else {
if_no = SECONDARY_INTF_SEL;
mfd->dma = &dma_s_data;
}
mfd->lut_update = mdp_lut_update_nonlcdc;
mfd->do_histogram = mdp_do_histogram;
mfd->start_histogram = mdp_histogram_start;
mfd->stop_histogram = mdp_histogram_stop;
mdp4_display_intf_sel(if_no, DSI_CMD_INTF);
#else
mfd->dma_fnc = mdp_dma2_update;
mfd->do_histogram = mdp_do_histogram;
mfd->start_histogram = mdp_histogram_start;
mfd->stop_histogram = mdp_histogram_stop;
mfd->vsync_ctrl = mdp_dma_vsync_ctrl;
mfd->vsync_show = mdp_dma_show_event;
if (mfd->panel_info.pdest == DISPLAY_1)
mfd->dma = &dma2_data;
else {
printk(KERN_ERR "Invalid Selection of destination panel\n");
rc = -ENODEV;
mdp_clk_ctrl(0);
goto mdp_probe_err;
}
INIT_WORK(&mfd->dma_update_worker,
mdp_lcd_update_workqueue_handler);
#endif
mdp_config_vsync(mdp_init_pdev, mfd);
break;
#endif
#ifdef CONFIG_FB_MSM_DTV
case DTV_PANEL:
mfd->vsync_init = mdp4_dtv_vsync_init;
mfd->vsync_show = mdp4_dtv_show_event;
pdata->on = mdp4_dtv_on;
pdata->off = mdp4_dtv_off;
mfd->hw_refresh = TRUE;
mfd->cursor_update = mdp_hw_cursor_sync_update;
mfd->dma_fnc = mdp4_dtv_overlay;
mfd->dma = &dma_e_data;
mfd->do_histogram = mdp_do_histogram;
mfd->start_histogram = mdp_histogram_start;
mfd->stop_histogram = mdp_histogram_stop;
mdp4_display_intf_sel(EXTERNAL_INTF_SEL, DTV_INTF);
break;
#endif
case HDMI_PANEL:
case LCDC_PANEL:
case LVDS_PANEL:
#ifdef CONFIG_FB_MSM_MDP303
pdata->on = mdp_lcdc_on;
pdata->off = mdp_lcdc_off;
#endif
mfd->hw_refresh = TRUE;
#if defined(CONFIG_FB_MSM_OVERLAY) && defined(CONFIG_FB_MSM_MDP40)
mfd->cursor_update = mdp_hw_cursor_sync_update;
#else
mfd->cursor_update = mdp_hw_cursor_update;
#endif
#ifndef CONFIG_FB_MSM_MDP22
mfd->lut_update = mdp_lut_update_lcdc;
mfd->do_histogram = mdp_do_histogram;
mfd->start_histogram = mdp_histogram_start;
mfd->stop_histogram = mdp_histogram_stop;
#endif
#ifdef CONFIG_FB_MSM_OVERLAY
mfd->dma_fnc = mdp4_lcdc_overlay;
#else
mfd->dma_fnc = mdp_lcdc_update;
#endif
#ifdef CONFIG_FB_MSM_MDP40
mfd->vsync_init = mdp4_lcdc_vsync_init;
mfd->vsync_show = mdp4_lcdc_show_event;
if (mfd->panel.type == HDMI_PANEL) {
mfd->dma = &dma_e_data;
mdp4_display_intf_sel(EXTERNAL_INTF_SEL, LCDC_RGB_INTF);
} else {
mfd->dma = &dma2_data;
mdp4_display_intf_sel(PRIMARY_INTF_SEL, LCDC_RGB_INTF);
}
#else
mfd->dma = &dma2_data;
mfd->vsync_ctrl = mdp_dma_lcdc_vsync_ctrl;
mfd->vsync_show = mdp_dma_lcdc_show_event;
spin_lock_irqsave(&mdp_spin_lock, flag);
mdp_intr_mask &= ~MDP_DMA_P_DONE;
outp32(MDP_INTR_ENABLE, mdp_intr_mask);
spin_unlock_irqrestore(&mdp_spin_lock, flag);
#endif
break;
case TV_PANEL:
#if defined(CONFIG_FB_MSM_OVERLAY) && defined(CONFIG_FB_MSM_TVOUT)
pdata->on = mdp4_atv_on;
pdata->off = mdp4_atv_off;
mfd->dma_fnc = mdp4_atv_overlay;
mfd->dma = &dma_e_data;
mdp4_display_intf_sel(EXTERNAL_INTF_SEL, TV_INTF);
#else
pdata->on = mdp_dma3_on;
pdata->off = mdp_dma3_off;
mfd->hw_refresh = TRUE;
mfd->dma_fnc = mdp_dma3_update;
mfd->dma = &dma3_data;
#endif
break;
#ifdef CONFIG_FB_MSM_WRITEBACK_MSM_PANEL
case WRITEBACK_PANEL:
{
unsigned int mdp_version;
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON,
FALSE);
mdp_version = inpdw(MDP_BASE + 0x0);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF,
FALSE);
if (mdp_version < 0x04030303) {
pr_err("%s: writeback panel not supprted\n",
__func__);
platform_device_put(msm_fb_dev);
mdp_clk_ctrl(0);
return -ENODEV;
}
mdp4_wfd_init(0);
pdata->on = mdp4_overlay_writeback_on;
pdata->off = mdp4_overlay_writeback_off;
mfd->dma_fnc = mdp4_writeback_overlay;
mfd->dma = &dma_wb_data;
mdp4_display_intf_sel(EXTERNAL_INTF_SEL, DTV_INTF);
}
break;
#endif
default:
printk(KERN_ERR "mdp_probe: unknown device type!\n");
rc = -ENODEV;
mdp_clk_ctrl(0);
goto mdp_probe_err;
}
if (mdp_rev >= MDP_REV_40) {
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
mdp4_display_intf = inpdw(MDP_BASE + 0x0038);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
}
frame_rate = mdp_get_panel_framerate(mfd);
if (frame_rate) {
mfd->panel_info.frame_interval = 1000 / frame_rate;
mfd->cpu_pm_hdl = add_event_timer(NULL, (void *)mfd);
}
mdp_clk_ctrl(0);
#ifdef CONFIG_MSM_BUS_SCALING
if (mdp_bus_scale_register())
return -ENOMEM;
/* req bus bandwidth immediately */
if (!(mfd->cont_splash_done))
mdp_bus_scale_update_request
(MDP_BUS_SCALE_INIT, MDP_BUS_SCALE_INIT);
#endif
/* set driver data */
platform_set_drvdata(msm_fb_dev, mfd);
rc = platform_device_add(msm_fb_dev);
if (rc) {
goto mdp_probe_err;
}
pm_runtime_set_active(&pdev->dev);
pm_runtime_enable(&pdev->dev);
pdev_list[pdev_list_cnt++] = pdev;
mdp4_extn_disp = 0;
/*
* vsync_init call not required for mdp3.
* vsync_init call required for mdp4 targets.
*/
if ((mfd->vsync_init != NULL) || (mdp_rev < MDP_REV_40)) {
if (mdp_rev >= MDP_REV_40)
mfd->vsync_init(0);
if (!mfd->vsync_sysfs_created) {
mfd->dev_attr.attr.name = "vsync_event";
mfd->dev_attr.attr.mode = S_IRUGO;
mfd->dev_attr.show = mfd->vsync_show;
sysfs_attr_init(&mfd->dev_attr.attr);
rc = sysfs_create_file(&mfd->fbi->dev->kobj,
&mfd->dev_attr.attr);
if (rc) {
pr_err("%s: sysfs creation failed, ret=%d\n",
__func__, rc);
return rc;
}
kobject_uevent(&mfd->fbi->dev->kobj, KOBJ_ADD);
pr_debug("%s: kobject_uevent(KOBJ_ADD)\n", __func__);
mfd->vsync_sysfs_created = 1;
}
}
return 0;
mdp_probe_err:
platform_device_put(msm_fb_dev);
#ifdef CONFIG_MSM_BUS_SCALING
if (mdp_bus_scale_handle > 0)
msm_bus_scale_unregister_client(mdp_bus_scale_handle);
#endif
return rc;
}
void mdp_footswitch_ctrl(boolean on)
{
mutex_lock(&mdp_suspend_mutex);
if (!mdp_suspended || mdp4_extn_disp || !footswitch ||
mdp_rev <= MDP_REV_41) {
mutex_unlock(&mdp_suspend_mutex);
return;
}
if (dsi_pll_vddio)
regulator_enable(dsi_pll_vddio);
if (dsi_pll_vdda)
regulator_enable(dsi_pll_vdda);
mipi_dsi_prepare_clocks();
mipi_dsi_ahb_ctrl(1);
mipi_dsi_phy_ctrl(1);
mipi_dsi_clk_enable();
if (on && !mdp_footswitch_on) {
pr_debug("Enable MDP FS\n");
regulator_enable(footswitch);
mdp_footswitch_on = 1;
} else if (!on && mdp_footswitch_on) {
pr_debug("Disable MDP FS\n");
regulator_disable(footswitch);
mdp_footswitch_on = 0;
}
mipi_dsi_clk_disable();
mipi_dsi_phy_ctrl(0);
mipi_dsi_ahb_ctrl(0);
mipi_dsi_unprepare_clocks();
if (dsi_pll_vdda)
regulator_disable(dsi_pll_vdda);
if (dsi_pll_vddio)
regulator_disable(dsi_pll_vddio);
mutex_unlock(&mdp_suspend_mutex);
}
void mdp_free_splash_buffer(struct msm_fb_data_type *mfd)
{
if (mfd->copy_splash_buf) {
dma_free_coherent(NULL, mdp_pdata->splash_screen_size,
mfd->copy_splash_buf,
(dma_addr_t) mfd->copy_splash_phys);
mfd->copy_splash_buf = NULL;
}
}
#ifdef CONFIG_PM
static void mdp_suspend_sub(void)
{
/* cancel pipe ctrl worker */
cancel_delayed_work(&mdp_pipe_ctrl_worker);
/* for workder can't be cancelled... */
flush_workqueue(mdp_pipe_ctrl_wq);
/* let's wait for PPP completion */
while (atomic_read(&mdp_block_power_cnt[MDP_PPP_BLOCK]) > 0)
cpu_relax();
/* try to power down */
mdp_pipe_ctrl(MDP_MASTER_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
mutex_lock(&mdp_suspend_mutex);
mdp_suspended = TRUE;
mutex_unlock(&mdp_suspend_mutex);
}
#endif
#if defined(CONFIG_PM) && !defined(CONFIG_HAS_EARLYSUSPEND)
static int mdp_suspend(struct platform_device *pdev, pm_message_t state)
{
if (pdev->id == 0) {
mdp_suspend_sub();
if (mdp_current_clk_on) {
printk(KERN_WARNING"MDP suspend failed\n");
return -EBUSY;
}
}
return 0;
}
#endif
#ifdef CONFIG_HAS_EARLYSUSPEND
static void mdp_early_suspend(struct early_suspend *h)
{
mdp_suspend_sub();
#ifdef CONFIG_FB_MSM_DTV
mdp4_solidfill_commit(MDP4_MIXER1);
mdp4_dtv_set_black_screen();
#endif
mdp_footswitch_ctrl(FALSE);
}
static void mdp_early_resume(struct early_suspend *h)
{
mdp_footswitch_ctrl(TRUE);
mutex_lock(&mdp_suspend_mutex);
mdp_suspended = FALSE;
mutex_unlock(&mdp_suspend_mutex);
}
#endif
static int mdp_remove(struct platform_device *pdev)
{
if (footswitch != NULL)
regulator_put(footswitch);
/*free post processing memory*/
mdp_histogram_destroy();
mdp_hist_lut_destroy();
mdp_pp_initialized = FALSE;
iounmap(msm_mdp_base);
pm_runtime_disable(&pdev->dev);
#ifdef CONFIG_MSM_BUS_SCALING
if (mdp_bus_scale_handle > 0)
msm_bus_scale_unregister_client(mdp_bus_scale_handle);
#endif
return 0;
}
static int mdp_register_driver(void)
{
#ifdef CONFIG_HAS_EARLYSUSPEND
early_suspend.level = EARLY_SUSPEND_LEVEL_DISABLE_FB - 1;
early_suspend.suspend = mdp_early_suspend;
early_suspend.resume = mdp_early_resume;
register_early_suspend(&early_suspend);
#endif
return platform_driver_register(&mdp_driver);
}
static int __init mdp_driver_init(void)
{
int ret;
mdp_drv_init();
ret = mdp_register_driver();
if (ret) {
printk(KERN_ERR "mdp_register_driver() failed!\n");
return ret;
}
#if defined(CONFIG_DEBUG_FS)
mdp_debugfs_init();
#endif
return 0;
}
module_init(mdp_driver_init);
| gpl-2.0 |
Motorhead1991/android_kernel_zte_roamer | drivers/video/aty/radeon_i2c.c | 1639 | 3971 | #include "radeonfb.h"
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/fb.h>
#include <linux/i2c.h>
#include <linux/i2c-id.h>
#include <linux/i2c-algo-bit.h>
#include <asm/io.h>
#include <video/radeon.h>
#include "../edid.h"
static void radeon_gpio_setscl(void* data, int state)
{
struct radeon_i2c_chan *chan = data;
struct radeonfb_info *rinfo = chan->rinfo;
u32 val;
val = INREG(chan->ddc_reg) & ~(VGA_DDC_CLK_OUT_EN);
if (!state)
val |= VGA_DDC_CLK_OUT_EN;
OUTREG(chan->ddc_reg, val);
(void)INREG(chan->ddc_reg);
}
static void radeon_gpio_setsda(void* data, int state)
{
struct radeon_i2c_chan *chan = data;
struct radeonfb_info *rinfo = chan->rinfo;
u32 val;
val = INREG(chan->ddc_reg) & ~(VGA_DDC_DATA_OUT_EN);
if (!state)
val |= VGA_DDC_DATA_OUT_EN;
OUTREG(chan->ddc_reg, val);
(void)INREG(chan->ddc_reg);
}
static int radeon_gpio_getscl(void* data)
{
struct radeon_i2c_chan *chan = data;
struct radeonfb_info *rinfo = chan->rinfo;
u32 val;
val = INREG(chan->ddc_reg);
return (val & VGA_DDC_CLK_INPUT) ? 1 : 0;
}
static int radeon_gpio_getsda(void* data)
{
struct radeon_i2c_chan *chan = data;
struct radeonfb_info *rinfo = chan->rinfo;
u32 val;
val = INREG(chan->ddc_reg);
return (val & VGA_DDC_DATA_INPUT) ? 1 : 0;
}
static int radeon_setup_i2c_bus(struct radeon_i2c_chan *chan, const char *name)
{
int rc;
snprintf(chan->adapter.name, sizeof(chan->adapter.name),
"radeonfb %s", name);
chan->adapter.owner = THIS_MODULE;
chan->adapter.algo_data = &chan->algo;
chan->adapter.dev.parent = &chan->rinfo->pdev->dev;
chan->algo.setsda = radeon_gpio_setsda;
chan->algo.setscl = radeon_gpio_setscl;
chan->algo.getsda = radeon_gpio_getsda;
chan->algo.getscl = radeon_gpio_getscl;
chan->algo.udelay = 10;
chan->algo.timeout = 20;
chan->algo.data = chan;
i2c_set_adapdata(&chan->adapter, chan);
/* Raise SCL and SDA */
radeon_gpio_setsda(chan, 1);
radeon_gpio_setscl(chan, 1);
udelay(20);
rc = i2c_bit_add_bus(&chan->adapter);
if (rc == 0)
dev_dbg(&chan->rinfo->pdev->dev, "I2C bus %s registered.\n", name);
else
dev_warn(&chan->rinfo->pdev->dev, "Failed to register I2C bus %s.\n", name);
return rc;
}
void radeon_create_i2c_busses(struct radeonfb_info *rinfo)
{
rinfo->i2c[0].rinfo = rinfo;
rinfo->i2c[0].ddc_reg = GPIO_MONID;
radeon_setup_i2c_bus(&rinfo->i2c[0], "monid");
rinfo->i2c[1].rinfo = rinfo;
rinfo->i2c[1].ddc_reg = GPIO_DVI_DDC;
radeon_setup_i2c_bus(&rinfo->i2c[1], "dvi");
rinfo->i2c[2].rinfo = rinfo;
rinfo->i2c[2].ddc_reg = GPIO_VGA_DDC;
radeon_setup_i2c_bus(&rinfo->i2c[2], "vga");
rinfo->i2c[3].rinfo = rinfo;
rinfo->i2c[3].ddc_reg = GPIO_CRT2_DDC;
radeon_setup_i2c_bus(&rinfo->i2c[3], "crt2");
}
void radeon_delete_i2c_busses(struct radeonfb_info *rinfo)
{
if (rinfo->i2c[0].rinfo)
i2c_del_adapter(&rinfo->i2c[0].adapter);
rinfo->i2c[0].rinfo = NULL;
if (rinfo->i2c[1].rinfo)
i2c_del_adapter(&rinfo->i2c[1].adapter);
rinfo->i2c[1].rinfo = NULL;
if (rinfo->i2c[2].rinfo)
i2c_del_adapter(&rinfo->i2c[2].adapter);
rinfo->i2c[2].rinfo = NULL;
if (rinfo->i2c[3].rinfo)
i2c_del_adapter(&rinfo->i2c[3].adapter);
rinfo->i2c[3].rinfo = NULL;
}
int radeon_probe_i2c_connector(struct radeonfb_info *rinfo, int conn,
u8 **out_edid)
{
u8 *edid;
edid = fb_ddc_read(&rinfo->i2c[conn-1].adapter);
if (out_edid)
*out_edid = edid;
if (!edid) {
pr_debug("radeonfb: I2C (port %d) ... not found\n", conn);
return MT_NONE;
}
if (edid[0x14] & 0x80) {
/* Fix detection using BIOS tables */
if (rinfo->is_mobility /*&& conn == ddc_dvi*/ &&
(INREG(LVDS_GEN_CNTL) & LVDS_ON)) {
pr_debug("radeonfb: I2C (port %d) ... found LVDS panel\n", conn);
return MT_LCD;
} else {
pr_debug("radeonfb: I2C (port %d) ... found TMDS panel\n", conn);
return MT_DFP;
}
}
pr_debug("radeonfb: I2C (port %d) ... found CRT display\n", conn);
return MT_CRT;
}
| gpl-2.0 |
AndroidOpenDevelopment-Devices/android_kernel_moto_shamu | drivers/media/i2c/adv7343.c | 2151 | 12808 | /*
* adv7343 - ADV7343 Video Encoder Driver
*
* The encoder hardware does not support SECAM.
*
* Copyright (C) 2009 Texas Instruments Incorporated - http://www.ti.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.
*
* This program is distributed .as is. WITHOUT ANY WARRANTY of any
* kind, whether express or implied; 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/ctype.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/videodev2.h>
#include <linux/uaccess.h>
#include <media/adv7343.h>
#include <media/v4l2-device.h>
#include <media/v4l2-chip-ident.h>
#include <media/v4l2-ctrls.h>
#include "adv7343_regs.h"
MODULE_DESCRIPTION("ADV7343 video encoder driver");
MODULE_LICENSE("GPL");
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Debug level 0-1");
struct adv7343_state {
struct v4l2_subdev sd;
struct v4l2_ctrl_handler hdl;
const struct adv7343_platform_data *pdata;
u8 reg00;
u8 reg01;
u8 reg02;
u8 reg35;
u8 reg80;
u8 reg82;
u32 output;
v4l2_std_id std;
};
static inline struct adv7343_state *to_state(struct v4l2_subdev *sd)
{
return container_of(sd, struct adv7343_state, sd);
}
static inline struct v4l2_subdev *to_sd(struct v4l2_ctrl *ctrl)
{
return &container_of(ctrl->handler, struct adv7343_state, hdl)->sd;
}
static inline int adv7343_write(struct v4l2_subdev *sd, u8 reg, u8 value)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
return i2c_smbus_write_byte_data(client, reg, value);
}
static const u8 adv7343_init_reg_val[] = {
ADV7343_SOFT_RESET, ADV7343_SOFT_RESET_DEFAULT,
ADV7343_POWER_MODE_REG, ADV7343_POWER_MODE_REG_DEFAULT,
ADV7343_HD_MODE_REG1, ADV7343_HD_MODE_REG1_DEFAULT,
ADV7343_HD_MODE_REG2, ADV7343_HD_MODE_REG2_DEFAULT,
ADV7343_HD_MODE_REG3, ADV7343_HD_MODE_REG3_DEFAULT,
ADV7343_HD_MODE_REG4, ADV7343_HD_MODE_REG4_DEFAULT,
ADV7343_HD_MODE_REG5, ADV7343_HD_MODE_REG5_DEFAULT,
ADV7343_HD_MODE_REG6, ADV7343_HD_MODE_REG6_DEFAULT,
ADV7343_HD_MODE_REG7, ADV7343_HD_MODE_REG7_DEFAULT,
ADV7343_SD_MODE_REG1, ADV7343_SD_MODE_REG1_DEFAULT,
ADV7343_SD_MODE_REG2, ADV7343_SD_MODE_REG2_DEFAULT,
ADV7343_SD_MODE_REG3, ADV7343_SD_MODE_REG3_DEFAULT,
ADV7343_SD_MODE_REG4, ADV7343_SD_MODE_REG4_DEFAULT,
ADV7343_SD_MODE_REG5, ADV7343_SD_MODE_REG5_DEFAULT,
ADV7343_SD_MODE_REG6, ADV7343_SD_MODE_REG6_DEFAULT,
ADV7343_SD_MODE_REG7, ADV7343_SD_MODE_REG7_DEFAULT,
ADV7343_SD_MODE_REG8, ADV7343_SD_MODE_REG8_DEFAULT,
ADV7343_SD_HUE_REG, ADV7343_SD_HUE_REG_DEFAULT,
ADV7343_SD_CGMS_WSS0, ADV7343_SD_CGMS_WSS0_DEFAULT,
ADV7343_SD_BRIGHTNESS_WSS, ADV7343_SD_BRIGHTNESS_WSS_DEFAULT,
};
/*
* 2^32
* FSC(reg) = FSC (HZ) * --------
* 27000000
*/
static const struct adv7343_std_info stdinfo[] = {
{
/* FSC(Hz) = 3,579,545.45 Hz */
SD_STD_NTSC, 569408542, V4L2_STD_NTSC,
}, {
/* FSC(Hz) = 3,575,611.00 Hz */
SD_STD_PAL_M, 568782678, V4L2_STD_PAL_M,
}, {
/* FSC(Hz) = 3,582,056.00 */
SD_STD_PAL_N, 569807903, V4L2_STD_PAL_Nc,
}, {
/* FSC(Hz) = 4,433,618.75 Hz */
SD_STD_PAL_N, 705268427, V4L2_STD_PAL_N,
}, {
/* FSC(Hz) = 4,433,618.75 Hz */
SD_STD_PAL_BDGHI, 705268427, V4L2_STD_PAL,
}, {
/* FSC(Hz) = 4,433,618.75 Hz */
SD_STD_NTSC, 705268427, V4L2_STD_NTSC_443,
}, {
/* FSC(Hz) = 4,433,618.75 Hz */
SD_STD_PAL_M, 705268427, V4L2_STD_PAL_60,
},
};
static int adv7343_setstd(struct v4l2_subdev *sd, v4l2_std_id std)
{
struct adv7343_state *state = to_state(sd);
struct adv7343_std_info *std_info;
int num_std;
char *fsc_ptr;
u8 reg, val;
int err = 0;
int i = 0;
std_info = (struct adv7343_std_info *)stdinfo;
num_std = ARRAY_SIZE(stdinfo);
for (i = 0; i < num_std; i++) {
if (std_info[i].stdid & std)
break;
}
if (i == num_std) {
v4l2_dbg(1, debug, sd,
"Invalid std or std is not supported: %llx\n",
(unsigned long long)std);
return -EINVAL;
}
/* Set the standard */
val = state->reg80 & (~(SD_STD_MASK));
val |= std_info[i].standard_val3;
err = adv7343_write(sd, ADV7343_SD_MODE_REG1, val);
if (err < 0)
goto setstd_exit;
state->reg80 = val;
/* Configure the input mode register */
val = state->reg01 & (~((u8) INPUT_MODE_MASK));
val |= SD_INPUT_MODE;
err = adv7343_write(sd, ADV7343_MODE_SELECT_REG, val);
if (err < 0)
goto setstd_exit;
state->reg01 = val;
/* Program the sub carrier frequency registers */
fsc_ptr = (unsigned char *)&std_info[i].fsc_val;
reg = ADV7343_FSC_REG0;
for (i = 0; i < 4; i++, reg++, fsc_ptr++) {
err = adv7343_write(sd, reg, *fsc_ptr);
if (err < 0)
goto setstd_exit;
}
val = state->reg80;
/* Filter settings */
if (std & (V4L2_STD_NTSC | V4L2_STD_NTSC_443))
val &= 0x03;
else if (std & ~V4L2_STD_SECAM)
val |= 0x04;
err = adv7343_write(sd, ADV7343_SD_MODE_REG1, val);
if (err < 0)
goto setstd_exit;
state->reg80 = val;
setstd_exit:
if (err != 0)
v4l2_err(sd, "Error setting std, write failed\n");
return err;
}
static int adv7343_setoutput(struct v4l2_subdev *sd, u32 output_type)
{
struct adv7343_state *state = to_state(sd);
unsigned char val;
int err = 0;
if (output_type > ADV7343_SVIDEO_ID) {
v4l2_dbg(1, debug, sd,
"Invalid output type or output type not supported:%d\n",
output_type);
return -EINVAL;
}
/* Enable Appropriate DAC */
val = state->reg00 & 0x03;
/* configure default configuration */
if (!state->pdata)
if (output_type == ADV7343_COMPOSITE_ID)
val |= ADV7343_COMPOSITE_POWER_VALUE;
else if (output_type == ADV7343_COMPONENT_ID)
val |= ADV7343_COMPONENT_POWER_VALUE;
else
val |= ADV7343_SVIDEO_POWER_VALUE;
else
val = state->pdata->mode_config.sleep_mode << 0 |
state->pdata->mode_config.pll_control << 1 |
state->pdata->mode_config.dac_3 << 2 |
state->pdata->mode_config.dac_2 << 3 |
state->pdata->mode_config.dac_1 << 4 |
state->pdata->mode_config.dac_6 << 5 |
state->pdata->mode_config.dac_5 << 6 |
state->pdata->mode_config.dac_4 << 7;
err = adv7343_write(sd, ADV7343_POWER_MODE_REG, val);
if (err < 0)
goto setoutput_exit;
state->reg00 = val;
/* Enable YUV output */
val = state->reg02 | YUV_OUTPUT_SELECT;
err = adv7343_write(sd, ADV7343_MODE_REG0, val);
if (err < 0)
goto setoutput_exit;
state->reg02 = val;
/* configure SD DAC Output 2 and SD DAC Output 1 bit to zero */
val = state->reg82 & (SD_DAC_1_DI & SD_DAC_2_DI);
if (state->pdata && state->pdata->sd_config.sd_dac_out1)
val = val | (state->pdata->sd_config.sd_dac_out1 << 1);
else if (state->pdata && !state->pdata->sd_config.sd_dac_out1)
val = val & ~(state->pdata->sd_config.sd_dac_out1 << 1);
if (state->pdata && state->pdata->sd_config.sd_dac_out2)
val = val | (state->pdata->sd_config.sd_dac_out2 << 2);
else if (state->pdata && !state->pdata->sd_config.sd_dac_out2)
val = val & ~(state->pdata->sd_config.sd_dac_out2 << 2);
err = adv7343_write(sd, ADV7343_SD_MODE_REG2, val);
if (err < 0)
goto setoutput_exit;
state->reg82 = val;
/* configure ED/HD Color DAC Swap and ED/HD RGB Input Enable bit to
* zero */
val = state->reg35 & (HD_RGB_INPUT_DI & HD_DAC_SWAP_DI);
err = adv7343_write(sd, ADV7343_HD_MODE_REG6, val);
if (err < 0)
goto setoutput_exit;
state->reg35 = val;
setoutput_exit:
if (err != 0)
v4l2_err(sd, "Error setting output, write failed\n");
return err;
}
static int adv7343_log_status(struct v4l2_subdev *sd)
{
struct adv7343_state *state = to_state(sd);
v4l2_info(sd, "Standard: %llx\n", (unsigned long long)state->std);
v4l2_info(sd, "Output: %s\n", (state->output == 0) ? "Composite" :
((state->output == 1) ? "Component" : "S-Video"));
return 0;
}
static int adv7343_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct v4l2_subdev *sd = to_sd(ctrl);
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
return adv7343_write(sd, ADV7343_SD_BRIGHTNESS_WSS,
ctrl->val);
case V4L2_CID_HUE:
return adv7343_write(sd, ADV7343_SD_HUE_REG, ctrl->val);
case V4L2_CID_GAIN:
return adv7343_write(sd, ADV7343_DAC2_OUTPUT_LEVEL, ctrl->val);
}
return -EINVAL;
}
static int adv7343_g_chip_ident(struct v4l2_subdev *sd,
struct v4l2_dbg_chip_ident *chip)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_ADV7343, 0);
}
static const struct v4l2_ctrl_ops adv7343_ctrl_ops = {
.s_ctrl = adv7343_s_ctrl,
};
static const struct v4l2_subdev_core_ops adv7343_core_ops = {
.log_status = adv7343_log_status,
.g_chip_ident = adv7343_g_chip_ident,
.g_ext_ctrls = v4l2_subdev_g_ext_ctrls,
.try_ext_ctrls = v4l2_subdev_try_ext_ctrls,
.s_ext_ctrls = v4l2_subdev_s_ext_ctrls,
.g_ctrl = v4l2_subdev_g_ctrl,
.s_ctrl = v4l2_subdev_s_ctrl,
.queryctrl = v4l2_subdev_queryctrl,
.querymenu = v4l2_subdev_querymenu,
};
static int adv7343_s_std_output(struct v4l2_subdev *sd, v4l2_std_id std)
{
struct adv7343_state *state = to_state(sd);
int err = 0;
if (state->std == std)
return 0;
err = adv7343_setstd(sd, std);
if (!err)
state->std = std;
return err;
}
static int adv7343_s_routing(struct v4l2_subdev *sd,
u32 input, u32 output, u32 config)
{
struct adv7343_state *state = to_state(sd);
int err = 0;
if (state->output == output)
return 0;
err = adv7343_setoutput(sd, output);
if (!err)
state->output = output;
return err;
}
static const struct v4l2_subdev_video_ops adv7343_video_ops = {
.s_std_output = adv7343_s_std_output,
.s_routing = adv7343_s_routing,
};
static const struct v4l2_subdev_ops adv7343_ops = {
.core = &adv7343_core_ops,
.video = &adv7343_video_ops,
};
static int adv7343_initialize(struct v4l2_subdev *sd)
{
struct adv7343_state *state = to_state(sd);
int err = 0;
int i;
for (i = 0; i < ARRAY_SIZE(adv7343_init_reg_val); i += 2) {
err = adv7343_write(sd, adv7343_init_reg_val[i],
adv7343_init_reg_val[i+1]);
if (err) {
v4l2_err(sd, "Error initializing\n");
return err;
}
}
/* Configure for default video standard */
err = adv7343_setoutput(sd, state->output);
if (err < 0) {
v4l2_err(sd, "Error setting output during init\n");
return -EINVAL;
}
err = adv7343_setstd(sd, state->std);
if (err < 0) {
v4l2_err(sd, "Error setting std during init\n");
return -EINVAL;
}
return err;
}
static int adv7343_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct adv7343_state *state;
int err;
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
v4l_info(client, "chip found @ 0x%x (%s)\n",
client->addr << 1, client->adapter->name);
state = devm_kzalloc(&client->dev, sizeof(struct adv7343_state),
GFP_KERNEL);
if (state == NULL)
return -ENOMEM;
/* Copy board specific information here */
state->pdata = client->dev.platform_data;
state->reg00 = 0x80;
state->reg01 = 0x00;
state->reg02 = 0x20;
state->reg35 = 0x00;
state->reg80 = ADV7343_SD_MODE_REG1_DEFAULT;
state->reg82 = ADV7343_SD_MODE_REG2_DEFAULT;
state->output = ADV7343_COMPOSITE_ID;
state->std = V4L2_STD_NTSC;
v4l2_i2c_subdev_init(&state->sd, client, &adv7343_ops);
v4l2_ctrl_handler_init(&state->hdl, 2);
v4l2_ctrl_new_std(&state->hdl, &adv7343_ctrl_ops,
V4L2_CID_BRIGHTNESS, ADV7343_BRIGHTNESS_MIN,
ADV7343_BRIGHTNESS_MAX, 1,
ADV7343_BRIGHTNESS_DEF);
v4l2_ctrl_new_std(&state->hdl, &adv7343_ctrl_ops,
V4L2_CID_HUE, ADV7343_HUE_MIN,
ADV7343_HUE_MAX, 1,
ADV7343_HUE_DEF);
v4l2_ctrl_new_std(&state->hdl, &adv7343_ctrl_ops,
V4L2_CID_GAIN, ADV7343_GAIN_MIN,
ADV7343_GAIN_MAX, 1,
ADV7343_GAIN_DEF);
state->sd.ctrl_handler = &state->hdl;
if (state->hdl.error) {
int err = state->hdl.error;
v4l2_ctrl_handler_free(&state->hdl);
return err;
}
v4l2_ctrl_handler_setup(&state->hdl);
err = adv7343_initialize(&state->sd);
if (err)
v4l2_ctrl_handler_free(&state->hdl);
return err;
}
static int adv7343_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
struct adv7343_state *state = to_state(sd);
v4l2_device_unregister_subdev(sd);
v4l2_ctrl_handler_free(&state->hdl);
return 0;
}
static const struct i2c_device_id adv7343_id[] = {
{"adv7343", 0},
{},
};
MODULE_DEVICE_TABLE(i2c, adv7343_id);
static struct i2c_driver adv7343_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "adv7343",
},
.probe = adv7343_probe,
.remove = adv7343_remove,
.id_table = adv7343_id,
};
module_i2c_driver(adv7343_driver);
| gpl-2.0 |
shizhai/wprobe | build_dir/target-mips_r2_uClibc-0.9.33.2/linux-ar71xx_generic/compat-wireless-2013-06-27/drivers/media/i2c/cx25840/cx25840-ir.c | 2151 | 36192 | /*
* Driver for the Conexant CX2584x Audio/Video decoder chip and related cores
*
* Integrated Consumer Infrared Controller
*
* Copyright (C) 2010 Andy Walls <awalls@md.metrocast.net>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <linux/slab.h>
#include <linux/kfifo.h>
#include <linux/module.h>
#include <media/cx25840.h>
#include <media/rc-core.h>
#include "cx25840-core.h"
static unsigned int ir_debug;
module_param(ir_debug, int, 0644);
MODULE_PARM_DESC(ir_debug, "enable integrated IR debug messages");
#define CX25840_IR_REG_BASE 0x200
#define CX25840_IR_CNTRL_REG 0x200
#define CNTRL_WIN_3_3 0x00000000
#define CNTRL_WIN_4_3 0x00000001
#define CNTRL_WIN_3_4 0x00000002
#define CNTRL_WIN_4_4 0x00000003
#define CNTRL_WIN 0x00000003
#define CNTRL_EDG_NONE 0x00000000
#define CNTRL_EDG_FALL 0x00000004
#define CNTRL_EDG_RISE 0x00000008
#define CNTRL_EDG_BOTH 0x0000000C
#define CNTRL_EDG 0x0000000C
#define CNTRL_DMD 0x00000010
#define CNTRL_MOD 0x00000020
#define CNTRL_RFE 0x00000040
#define CNTRL_TFE 0x00000080
#define CNTRL_RXE 0x00000100
#define CNTRL_TXE 0x00000200
#define CNTRL_RIC 0x00000400
#define CNTRL_TIC 0x00000800
#define CNTRL_CPL 0x00001000
#define CNTRL_LBM 0x00002000
#define CNTRL_R 0x00004000
#define CX25840_IR_TXCLK_REG 0x204
#define TXCLK_TCD 0x0000FFFF
#define CX25840_IR_RXCLK_REG 0x208
#define RXCLK_RCD 0x0000FFFF
#define CX25840_IR_CDUTY_REG 0x20C
#define CDUTY_CDC 0x0000000F
#define CX25840_IR_STATS_REG 0x210
#define STATS_RTO 0x00000001
#define STATS_ROR 0x00000002
#define STATS_RBY 0x00000004
#define STATS_TBY 0x00000008
#define STATS_RSR 0x00000010
#define STATS_TSR 0x00000020
#define CX25840_IR_IRQEN_REG 0x214
#define IRQEN_RTE 0x00000001
#define IRQEN_ROE 0x00000002
#define IRQEN_RSE 0x00000010
#define IRQEN_TSE 0x00000020
#define IRQEN_MSK 0x00000033
#define CX25840_IR_FILTR_REG 0x218
#define FILTR_LPF 0x0000FFFF
#define CX25840_IR_FIFO_REG 0x23C
#define FIFO_RXTX 0x0000FFFF
#define FIFO_RXTX_LVL 0x00010000
#define FIFO_RXTX_RTO 0x0001FFFF
#define FIFO_RX_NDV 0x00020000
#define FIFO_RX_DEPTH 8
#define FIFO_TX_DEPTH 8
#define CX25840_VIDCLK_FREQ 108000000 /* 108 MHz, BT.656 */
#define CX25840_IR_REFCLK_FREQ (CX25840_VIDCLK_FREQ / 2)
/*
* We use this union internally for convenience, but callers to tx_write
* and rx_read will be expecting records of type struct ir_raw_event.
* Always ensure the size of this union is dictated by struct ir_raw_event.
*/
union cx25840_ir_fifo_rec {
u32 hw_fifo_data;
struct ir_raw_event ir_core_data;
};
#define CX25840_IR_RX_KFIFO_SIZE (256 * sizeof(union cx25840_ir_fifo_rec))
#define CX25840_IR_TX_KFIFO_SIZE (256 * sizeof(union cx25840_ir_fifo_rec))
struct cx25840_ir_state {
struct i2c_client *c;
struct v4l2_subdev_ir_parameters rx_params;
struct mutex rx_params_lock; /* protects Rx parameter settings cache */
atomic_t rxclk_divider;
atomic_t rx_invert;
struct kfifo rx_kfifo;
spinlock_t rx_kfifo_lock; /* protect Rx data kfifo */
struct v4l2_subdev_ir_parameters tx_params;
struct mutex tx_params_lock; /* protects Tx parameter settings cache */
atomic_t txclk_divider;
};
static inline struct cx25840_ir_state *to_ir_state(struct v4l2_subdev *sd)
{
struct cx25840_state *state = to_state(sd);
return state ? state->ir_state : NULL;
}
/*
* Rx and Tx Clock Divider register computations
*
* Note the largest clock divider value of 0xffff corresponds to:
* (0xffff + 1) * 1000 / 108/2 MHz = 1,213,629.629... ns
* which fits in 21 bits, so we'll use unsigned int for time arguments.
*/
static inline u16 count_to_clock_divider(unsigned int d)
{
if (d > RXCLK_RCD + 1)
d = RXCLK_RCD;
else if (d < 2)
d = 1;
else
d--;
return (u16) d;
}
static inline u16 ns_to_clock_divider(unsigned int ns)
{
return count_to_clock_divider(
DIV_ROUND_CLOSEST(CX25840_IR_REFCLK_FREQ / 1000000 * ns, 1000));
}
static inline unsigned int clock_divider_to_ns(unsigned int divider)
{
/* Period of the Rx or Tx clock in ns */
return DIV_ROUND_CLOSEST((divider + 1) * 1000,
CX25840_IR_REFCLK_FREQ / 1000000);
}
static inline u16 carrier_freq_to_clock_divider(unsigned int freq)
{
return count_to_clock_divider(
DIV_ROUND_CLOSEST(CX25840_IR_REFCLK_FREQ, freq * 16));
}
static inline unsigned int clock_divider_to_carrier_freq(unsigned int divider)
{
return DIV_ROUND_CLOSEST(CX25840_IR_REFCLK_FREQ, (divider + 1) * 16);
}
static inline u16 freq_to_clock_divider(unsigned int freq,
unsigned int rollovers)
{
return count_to_clock_divider(
DIV_ROUND_CLOSEST(CX25840_IR_REFCLK_FREQ, freq * rollovers));
}
static inline unsigned int clock_divider_to_freq(unsigned int divider,
unsigned int rollovers)
{
return DIV_ROUND_CLOSEST(CX25840_IR_REFCLK_FREQ,
(divider + 1) * rollovers);
}
/*
* Low Pass Filter register calculations
*
* Note the largest count value of 0xffff corresponds to:
* 0xffff * 1000 / 108/2 MHz = 1,213,611.11... ns
* which fits in 21 bits, so we'll use unsigned int for time arguments.
*/
static inline u16 count_to_lpf_count(unsigned int d)
{
if (d > FILTR_LPF)
d = FILTR_LPF;
else if (d < 4)
d = 0;
return (u16) d;
}
static inline u16 ns_to_lpf_count(unsigned int ns)
{
return count_to_lpf_count(
DIV_ROUND_CLOSEST(CX25840_IR_REFCLK_FREQ / 1000000 * ns, 1000));
}
static inline unsigned int lpf_count_to_ns(unsigned int count)
{
/* Duration of the Low Pass Filter rejection window in ns */
return DIV_ROUND_CLOSEST(count * 1000,
CX25840_IR_REFCLK_FREQ / 1000000);
}
static inline unsigned int lpf_count_to_us(unsigned int count)
{
/* Duration of the Low Pass Filter rejection window in us */
return DIV_ROUND_CLOSEST(count, CX25840_IR_REFCLK_FREQ / 1000000);
}
/*
* FIFO register pulse width count compuations
*/
static u32 clock_divider_to_resolution(u16 divider)
{
/*
* Resolution is the duration of 1 tick of the readable portion of
* of the pulse width counter as read from the FIFO. The two lsb's are
* not readable, hence the << 2. This function returns ns.
*/
return DIV_ROUND_CLOSEST((1 << 2) * ((u32) divider + 1) * 1000,
CX25840_IR_REFCLK_FREQ / 1000000);
}
static u64 pulse_width_count_to_ns(u16 count, u16 divider)
{
u64 n;
u32 rem;
/*
* The 2 lsb's of the pulse width timer count are not readable, hence
* the (count << 2) | 0x3
*/
n = (((u64) count << 2) | 0x3) * (divider + 1) * 1000; /* millicycles */
rem = do_div(n, CX25840_IR_REFCLK_FREQ / 1000000); /* / MHz => ns */
if (rem >= CX25840_IR_REFCLK_FREQ / 1000000 / 2)
n++;
return n;
}
#if 0
/* Keep as we will need this for Transmit functionality */
static u16 ns_to_pulse_width_count(u32 ns, u16 divider)
{
u64 n;
u32 d;
u32 rem;
/*
* The 2 lsb's of the pulse width timer count are not accessible, hence
* the (1 << 2)
*/
n = ((u64) ns) * CX25840_IR_REFCLK_FREQ / 1000000; /* millicycles */
d = (1 << 2) * ((u32) divider + 1) * 1000; /* millicycles/count */
rem = do_div(n, d);
if (rem >= d / 2)
n++;
if (n > FIFO_RXTX)
n = FIFO_RXTX;
else if (n == 0)
n = 1;
return (u16) n;
}
#endif
static unsigned int pulse_width_count_to_us(u16 count, u16 divider)
{
u64 n;
u32 rem;
/*
* The 2 lsb's of the pulse width timer count are not readable, hence
* the (count << 2) | 0x3
*/
n = (((u64) count << 2) | 0x3) * (divider + 1); /* cycles */
rem = do_div(n, CX25840_IR_REFCLK_FREQ / 1000000); /* / MHz => us */
if (rem >= CX25840_IR_REFCLK_FREQ / 1000000 / 2)
n++;
return (unsigned int) n;
}
/*
* Pulse Clocks computations: Combined Pulse Width Count & Rx Clock Counts
*
* The total pulse clock count is an 18 bit pulse width timer count as the most
* significant part and (up to) 16 bit clock divider count as a modulus.
* When the Rx clock divider ticks down to 0, it increments the 18 bit pulse
* width timer count's least significant bit.
*/
static u64 ns_to_pulse_clocks(u32 ns)
{
u64 clocks;
u32 rem;
clocks = CX25840_IR_REFCLK_FREQ / 1000000 * (u64) ns; /* millicycles */
rem = do_div(clocks, 1000); /* /1000 = cycles */
if (rem >= 1000 / 2)
clocks++;
return clocks;
}
static u16 pulse_clocks_to_clock_divider(u64 count)
{
do_div(count, (FIFO_RXTX << 2) | 0x3);
/* net result needs to be rounded down and decremented by 1 */
if (count > RXCLK_RCD + 1)
count = RXCLK_RCD;
else if (count < 2)
count = 1;
else
count--;
return (u16) count;
}
/*
* IR Control Register helpers
*/
enum tx_fifo_watermark {
TX_FIFO_HALF_EMPTY = 0,
TX_FIFO_EMPTY = CNTRL_TIC,
};
enum rx_fifo_watermark {
RX_FIFO_HALF_FULL = 0,
RX_FIFO_NOT_EMPTY = CNTRL_RIC,
};
static inline void control_tx_irq_watermark(struct i2c_client *c,
enum tx_fifo_watermark level)
{
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_TIC, level);
}
static inline void control_rx_irq_watermark(struct i2c_client *c,
enum rx_fifo_watermark level)
{
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_RIC, level);
}
static inline void control_tx_enable(struct i2c_client *c, bool enable)
{
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~(CNTRL_TXE | CNTRL_TFE),
enable ? (CNTRL_TXE | CNTRL_TFE) : 0);
}
static inline void control_rx_enable(struct i2c_client *c, bool enable)
{
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~(CNTRL_RXE | CNTRL_RFE),
enable ? (CNTRL_RXE | CNTRL_RFE) : 0);
}
static inline void control_tx_modulation_enable(struct i2c_client *c,
bool enable)
{
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_MOD,
enable ? CNTRL_MOD : 0);
}
static inline void control_rx_demodulation_enable(struct i2c_client *c,
bool enable)
{
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_DMD,
enable ? CNTRL_DMD : 0);
}
static inline void control_rx_s_edge_detection(struct i2c_client *c,
u32 edge_types)
{
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_EDG_BOTH,
edge_types & CNTRL_EDG_BOTH);
}
static void control_rx_s_carrier_window(struct i2c_client *c,
unsigned int carrier,
unsigned int *carrier_range_low,
unsigned int *carrier_range_high)
{
u32 v;
unsigned int c16 = carrier * 16;
if (*carrier_range_low < DIV_ROUND_CLOSEST(c16, 16 + 3)) {
v = CNTRL_WIN_3_4;
*carrier_range_low = DIV_ROUND_CLOSEST(c16, 16 + 4);
} else {
v = CNTRL_WIN_3_3;
*carrier_range_low = DIV_ROUND_CLOSEST(c16, 16 + 3);
}
if (*carrier_range_high > DIV_ROUND_CLOSEST(c16, 16 - 3)) {
v |= CNTRL_WIN_4_3;
*carrier_range_high = DIV_ROUND_CLOSEST(c16, 16 - 4);
} else {
v |= CNTRL_WIN_3_3;
*carrier_range_high = DIV_ROUND_CLOSEST(c16, 16 - 3);
}
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_WIN, v);
}
static inline void control_tx_polarity_invert(struct i2c_client *c,
bool invert)
{
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_CPL,
invert ? CNTRL_CPL : 0);
}
/*
* IR Rx & Tx Clock Register helpers
*/
static unsigned int txclk_tx_s_carrier(struct i2c_client *c,
unsigned int freq,
u16 *divider)
{
*divider = carrier_freq_to_clock_divider(freq);
cx25840_write4(c, CX25840_IR_TXCLK_REG, *divider);
return clock_divider_to_carrier_freq(*divider);
}
static unsigned int rxclk_rx_s_carrier(struct i2c_client *c,
unsigned int freq,
u16 *divider)
{
*divider = carrier_freq_to_clock_divider(freq);
cx25840_write4(c, CX25840_IR_RXCLK_REG, *divider);
return clock_divider_to_carrier_freq(*divider);
}
static u32 txclk_tx_s_max_pulse_width(struct i2c_client *c, u32 ns,
u16 *divider)
{
u64 pulse_clocks;
if (ns > IR_MAX_DURATION)
ns = IR_MAX_DURATION;
pulse_clocks = ns_to_pulse_clocks(ns);
*divider = pulse_clocks_to_clock_divider(pulse_clocks);
cx25840_write4(c, CX25840_IR_TXCLK_REG, *divider);
return (u32) pulse_width_count_to_ns(FIFO_RXTX, *divider);
}
static u32 rxclk_rx_s_max_pulse_width(struct i2c_client *c, u32 ns,
u16 *divider)
{
u64 pulse_clocks;
if (ns > IR_MAX_DURATION)
ns = IR_MAX_DURATION;
pulse_clocks = ns_to_pulse_clocks(ns);
*divider = pulse_clocks_to_clock_divider(pulse_clocks);
cx25840_write4(c, CX25840_IR_RXCLK_REG, *divider);
return (u32) pulse_width_count_to_ns(FIFO_RXTX, *divider);
}
/*
* IR Tx Carrier Duty Cycle register helpers
*/
static unsigned int cduty_tx_s_duty_cycle(struct i2c_client *c,
unsigned int duty_cycle)
{
u32 n;
n = DIV_ROUND_CLOSEST(duty_cycle * 100, 625); /* 16ths of 100% */
if (n != 0)
n--;
if (n > 15)
n = 15;
cx25840_write4(c, CX25840_IR_CDUTY_REG, n);
return DIV_ROUND_CLOSEST((n + 1) * 100, 16);
}
/*
* IR Filter Register helpers
*/
static u32 filter_rx_s_min_width(struct i2c_client *c, u32 min_width_ns)
{
u32 count = ns_to_lpf_count(min_width_ns);
cx25840_write4(c, CX25840_IR_FILTR_REG, count);
return lpf_count_to_ns(count);
}
/*
* IR IRQ Enable Register helpers
*/
static inline void irqenable_rx(struct v4l2_subdev *sd, u32 mask)
{
struct cx25840_state *state = to_state(sd);
if (is_cx23885(state) || is_cx23887(state))
mask ^= IRQEN_MSK;
mask &= (IRQEN_RTE | IRQEN_ROE | IRQEN_RSE);
cx25840_and_or4(state->c, CX25840_IR_IRQEN_REG,
~(IRQEN_RTE | IRQEN_ROE | IRQEN_RSE), mask);
}
static inline void irqenable_tx(struct v4l2_subdev *sd, u32 mask)
{
struct cx25840_state *state = to_state(sd);
if (is_cx23885(state) || is_cx23887(state))
mask ^= IRQEN_MSK;
mask &= IRQEN_TSE;
cx25840_and_or4(state->c, CX25840_IR_IRQEN_REG, ~IRQEN_TSE, mask);
}
/*
* V4L2 Subdevice IR Ops
*/
int cx25840_ir_irq_handler(struct v4l2_subdev *sd, u32 status, bool *handled)
{
struct cx25840_state *state = to_state(sd);
struct cx25840_ir_state *ir_state = to_ir_state(sd);
struct i2c_client *c = NULL;
unsigned long flags;
union cx25840_ir_fifo_rec rx_data[FIFO_RX_DEPTH];
unsigned int i, j, k;
u32 events, v;
int tsr, rsr, rto, ror, tse, rse, rte, roe, kror;
u32 cntrl, irqen, stats;
*handled = false;
if (ir_state == NULL)
return -ENODEV;
c = ir_state->c;
/* Only support the IR controller for the CX2388[57] AV Core for now */
if (!(is_cx23885(state) || is_cx23887(state)))
return -ENODEV;
cntrl = cx25840_read4(c, CX25840_IR_CNTRL_REG);
irqen = cx25840_read4(c, CX25840_IR_IRQEN_REG);
if (is_cx23885(state) || is_cx23887(state))
irqen ^= IRQEN_MSK;
stats = cx25840_read4(c, CX25840_IR_STATS_REG);
tsr = stats & STATS_TSR; /* Tx FIFO Service Request */
rsr = stats & STATS_RSR; /* Rx FIFO Service Request */
rto = stats & STATS_RTO; /* Rx Pulse Width Timer Time Out */
ror = stats & STATS_ROR; /* Rx FIFO Over Run */
tse = irqen & IRQEN_TSE; /* Tx FIFO Service Request IRQ Enable */
rse = irqen & IRQEN_RSE; /* Rx FIFO Service Reuqest IRQ Enable */
rte = irqen & IRQEN_RTE; /* Rx Pulse Width Timer Time Out IRQ Enable */
roe = irqen & IRQEN_ROE; /* Rx FIFO Over Run IRQ Enable */
v4l2_dbg(2, ir_debug, sd, "IR IRQ Status: %s %s %s %s %s %s\n",
tsr ? "tsr" : " ", rsr ? "rsr" : " ",
rto ? "rto" : " ", ror ? "ror" : " ",
stats & STATS_TBY ? "tby" : " ",
stats & STATS_RBY ? "rby" : " ");
v4l2_dbg(2, ir_debug, sd, "IR IRQ Enables: %s %s %s %s\n",
tse ? "tse" : " ", rse ? "rse" : " ",
rte ? "rte" : " ", roe ? "roe" : " ");
/*
* Transmitter interrupt service
*/
if (tse && tsr) {
/*
* TODO:
* Check the watermark threshold setting
* Pull FIFO_TX_DEPTH or FIFO_TX_DEPTH/2 entries from tx_kfifo
* Push the data to the hardware FIFO.
* If there was nothing more to send in the tx_kfifo, disable
* the TSR IRQ and notify the v4l2_device.
* If there was something in the tx_kfifo, check the tx_kfifo
* level and notify the v4l2_device, if it is low.
*/
/* For now, inhibit TSR interrupt until Tx is implemented */
irqenable_tx(sd, 0);
events = V4L2_SUBDEV_IR_TX_FIFO_SERVICE_REQ;
v4l2_subdev_notify(sd, V4L2_SUBDEV_IR_TX_NOTIFY, &events);
*handled = true;
}
/*
* Receiver interrupt service
*/
kror = 0;
if ((rse && rsr) || (rte && rto)) {
/*
* Receive data on RSR to clear the STATS_RSR.
* Receive data on RTO, since we may not have yet hit the RSR
* watermark when we receive the RTO.
*/
for (i = 0, v = FIFO_RX_NDV;
(v & FIFO_RX_NDV) && !kror; i = 0) {
for (j = 0;
(v & FIFO_RX_NDV) && j < FIFO_RX_DEPTH; j++) {
v = cx25840_read4(c, CX25840_IR_FIFO_REG);
rx_data[i].hw_fifo_data = v & ~FIFO_RX_NDV;
i++;
}
if (i == 0)
break;
j = i * sizeof(union cx25840_ir_fifo_rec);
k = kfifo_in_locked(&ir_state->rx_kfifo,
(unsigned char *) rx_data, j,
&ir_state->rx_kfifo_lock);
if (k != j)
kror++; /* rx_kfifo over run */
}
*handled = true;
}
events = 0;
v = 0;
if (kror) {
events |= V4L2_SUBDEV_IR_RX_SW_FIFO_OVERRUN;
v4l2_err(sd, "IR receiver software FIFO overrun\n");
}
if (roe && ror) {
/*
* The RX FIFO Enable (CNTRL_RFE) must be toggled to clear
* the Rx FIFO Over Run status (STATS_ROR)
*/
v |= CNTRL_RFE;
events |= V4L2_SUBDEV_IR_RX_HW_FIFO_OVERRUN;
v4l2_err(sd, "IR receiver hardware FIFO overrun\n");
}
if (rte && rto) {
/*
* The IR Receiver Enable (CNTRL_RXE) must be toggled to clear
* the Rx Pulse Width Timer Time Out (STATS_RTO)
*/
v |= CNTRL_RXE;
events |= V4L2_SUBDEV_IR_RX_END_OF_RX_DETECTED;
}
if (v) {
/* Clear STATS_ROR & STATS_RTO as needed by reseting hardware */
cx25840_write4(c, CX25840_IR_CNTRL_REG, cntrl & ~v);
cx25840_write4(c, CX25840_IR_CNTRL_REG, cntrl);
*handled = true;
}
spin_lock_irqsave(&ir_state->rx_kfifo_lock, flags);
if (kfifo_len(&ir_state->rx_kfifo) >= CX25840_IR_RX_KFIFO_SIZE / 2)
events |= V4L2_SUBDEV_IR_RX_FIFO_SERVICE_REQ;
spin_unlock_irqrestore(&ir_state->rx_kfifo_lock, flags);
if (events)
v4l2_subdev_notify(sd, V4L2_SUBDEV_IR_RX_NOTIFY, &events);
return 0;
}
/* Receiver */
static int cx25840_ir_rx_read(struct v4l2_subdev *sd, u8 *buf, size_t count,
ssize_t *num)
{
struct cx25840_ir_state *ir_state = to_ir_state(sd);
bool invert;
u16 divider;
unsigned int i, n;
union cx25840_ir_fifo_rec *p;
unsigned u, v, w;
if (ir_state == NULL)
return -ENODEV;
invert = (bool) atomic_read(&ir_state->rx_invert);
divider = (u16) atomic_read(&ir_state->rxclk_divider);
n = count / sizeof(union cx25840_ir_fifo_rec)
* sizeof(union cx25840_ir_fifo_rec);
if (n == 0) {
*num = 0;
return 0;
}
n = kfifo_out_locked(&ir_state->rx_kfifo, buf, n,
&ir_state->rx_kfifo_lock);
n /= sizeof(union cx25840_ir_fifo_rec);
*num = n * sizeof(union cx25840_ir_fifo_rec);
for (p = (union cx25840_ir_fifo_rec *) buf, i = 0; i < n; p++, i++) {
if ((p->hw_fifo_data & FIFO_RXTX_RTO) == FIFO_RXTX_RTO) {
/* Assume RTO was because of no IR light input */
u = 0;
w = 1;
} else {
u = (p->hw_fifo_data & FIFO_RXTX_LVL) ? 1 : 0;
if (invert)
u = u ? 0 : 1;
w = 0;
}
v = (unsigned) pulse_width_count_to_ns(
(u16) (p->hw_fifo_data & FIFO_RXTX), divider);
if (v > IR_MAX_DURATION)
v = IR_MAX_DURATION;
init_ir_raw_event(&p->ir_core_data);
p->ir_core_data.pulse = u;
p->ir_core_data.duration = v;
p->ir_core_data.timeout = w;
v4l2_dbg(2, ir_debug, sd, "rx read: %10u ns %s %s\n",
v, u ? "mark" : "space", w ? "(timed out)" : "");
if (w)
v4l2_dbg(2, ir_debug, sd, "rx read: end of rx\n");
}
return 0;
}
static int cx25840_ir_rx_g_parameters(struct v4l2_subdev *sd,
struct v4l2_subdev_ir_parameters *p)
{
struct cx25840_ir_state *ir_state = to_ir_state(sd);
if (ir_state == NULL)
return -ENODEV;
mutex_lock(&ir_state->rx_params_lock);
memcpy(p, &ir_state->rx_params,
sizeof(struct v4l2_subdev_ir_parameters));
mutex_unlock(&ir_state->rx_params_lock);
return 0;
}
static int cx25840_ir_rx_shutdown(struct v4l2_subdev *sd)
{
struct cx25840_ir_state *ir_state = to_ir_state(sd);
struct i2c_client *c;
if (ir_state == NULL)
return -ENODEV;
c = ir_state->c;
mutex_lock(&ir_state->rx_params_lock);
/* Disable or slow down all IR Rx circuits and counters */
irqenable_rx(sd, 0);
control_rx_enable(c, false);
control_rx_demodulation_enable(c, false);
control_rx_s_edge_detection(c, CNTRL_EDG_NONE);
filter_rx_s_min_width(c, 0);
cx25840_write4(c, CX25840_IR_RXCLK_REG, RXCLK_RCD);
ir_state->rx_params.shutdown = true;
mutex_unlock(&ir_state->rx_params_lock);
return 0;
}
static int cx25840_ir_rx_s_parameters(struct v4l2_subdev *sd,
struct v4l2_subdev_ir_parameters *p)
{
struct cx25840_ir_state *ir_state = to_ir_state(sd);
struct i2c_client *c;
struct v4l2_subdev_ir_parameters *o;
u16 rxclk_divider;
if (ir_state == NULL)
return -ENODEV;
if (p->shutdown)
return cx25840_ir_rx_shutdown(sd);
if (p->mode != V4L2_SUBDEV_IR_MODE_PULSE_WIDTH)
return -ENOSYS;
c = ir_state->c;
o = &ir_state->rx_params;
mutex_lock(&ir_state->rx_params_lock);
o->shutdown = p->shutdown;
p->mode = V4L2_SUBDEV_IR_MODE_PULSE_WIDTH;
o->mode = p->mode;
p->bytes_per_data_element = sizeof(union cx25840_ir_fifo_rec);
o->bytes_per_data_element = p->bytes_per_data_element;
/* Before we tweak the hardware, we have to disable the receiver */
irqenable_rx(sd, 0);
control_rx_enable(c, false);
control_rx_demodulation_enable(c, p->modulation);
o->modulation = p->modulation;
if (p->modulation) {
p->carrier_freq = rxclk_rx_s_carrier(c, p->carrier_freq,
&rxclk_divider);
o->carrier_freq = p->carrier_freq;
p->duty_cycle = 50;
o->duty_cycle = p->duty_cycle;
control_rx_s_carrier_window(c, p->carrier_freq,
&p->carrier_range_lower,
&p->carrier_range_upper);
o->carrier_range_lower = p->carrier_range_lower;
o->carrier_range_upper = p->carrier_range_upper;
p->max_pulse_width =
(u32) pulse_width_count_to_ns(FIFO_RXTX, rxclk_divider);
} else {
p->max_pulse_width =
rxclk_rx_s_max_pulse_width(c, p->max_pulse_width,
&rxclk_divider);
}
o->max_pulse_width = p->max_pulse_width;
atomic_set(&ir_state->rxclk_divider, rxclk_divider);
p->noise_filter_min_width =
filter_rx_s_min_width(c, p->noise_filter_min_width);
o->noise_filter_min_width = p->noise_filter_min_width;
p->resolution = clock_divider_to_resolution(rxclk_divider);
o->resolution = p->resolution;
/* FIXME - make this dependent on resolution for better performance */
control_rx_irq_watermark(c, RX_FIFO_HALF_FULL);
control_rx_s_edge_detection(c, CNTRL_EDG_BOTH);
o->invert_level = p->invert_level;
atomic_set(&ir_state->rx_invert, p->invert_level);
o->interrupt_enable = p->interrupt_enable;
o->enable = p->enable;
if (p->enable) {
unsigned long flags;
spin_lock_irqsave(&ir_state->rx_kfifo_lock, flags);
kfifo_reset(&ir_state->rx_kfifo);
spin_unlock_irqrestore(&ir_state->rx_kfifo_lock, flags);
if (p->interrupt_enable)
irqenable_rx(sd, IRQEN_RSE | IRQEN_RTE | IRQEN_ROE);
control_rx_enable(c, p->enable);
}
mutex_unlock(&ir_state->rx_params_lock);
return 0;
}
/* Transmitter */
static int cx25840_ir_tx_write(struct v4l2_subdev *sd, u8 *buf, size_t count,
ssize_t *num)
{
struct cx25840_ir_state *ir_state = to_ir_state(sd);
if (ir_state == NULL)
return -ENODEV;
#if 0
/*
* FIXME - the code below is an incomplete and untested sketch of what
* may need to be done. The critical part is to get 4 (or 8) pulses
* from the tx_kfifo, or converted from ns to the proper units from the
* input, and push them off to the hardware Tx FIFO right away, if the
* HW TX fifo needs service. The rest can be pushed to the tx_kfifo in
* a less critical timeframe. Also watch out for overruning the
* tx_kfifo - don't let it happen and let the caller know not all his
* pulses were written.
*/
u32 *ns_pulse = (u32 *) buf;
unsigned int n;
u32 fifo_pulse[FIFO_TX_DEPTH];
u32 mark;
/* Compute how much we can fit in the tx kfifo */
n = CX25840_IR_TX_KFIFO_SIZE - kfifo_len(ir_state->tx_kfifo);
n = min(n, (unsigned int) count);
n /= sizeof(u32);
/* FIXME - turn on Tx Fifo service interrupt
* check hardware fifo level, and other stuff
*/
for (i = 0; i < n; ) {
for (j = 0; j < FIFO_TX_DEPTH / 2 && i < n; j++) {
mark = ns_pulse[i] & LEVEL_MASK;
fifo_pulse[j] = ns_to_pulse_width_count(
ns_pulse[i] &
~LEVEL_MASK,
ir_state->txclk_divider);
if (mark)
fifo_pulse[j] &= FIFO_RXTX_LVL;
i++;
}
kfifo_put(ir_state->tx_kfifo, (u8 *) fifo_pulse,
j * sizeof(u32));
}
*num = n * sizeof(u32);
#else
/* For now enable the Tx FIFO Service interrupt & pretend we did work */
irqenable_tx(sd, IRQEN_TSE);
*num = count;
#endif
return 0;
}
static int cx25840_ir_tx_g_parameters(struct v4l2_subdev *sd,
struct v4l2_subdev_ir_parameters *p)
{
struct cx25840_ir_state *ir_state = to_ir_state(sd);
if (ir_state == NULL)
return -ENODEV;
mutex_lock(&ir_state->tx_params_lock);
memcpy(p, &ir_state->tx_params,
sizeof(struct v4l2_subdev_ir_parameters));
mutex_unlock(&ir_state->tx_params_lock);
return 0;
}
static int cx25840_ir_tx_shutdown(struct v4l2_subdev *sd)
{
struct cx25840_ir_state *ir_state = to_ir_state(sd);
struct i2c_client *c;
if (ir_state == NULL)
return -ENODEV;
c = ir_state->c;
mutex_lock(&ir_state->tx_params_lock);
/* Disable or slow down all IR Tx circuits and counters */
irqenable_tx(sd, 0);
control_tx_enable(c, false);
control_tx_modulation_enable(c, false);
cx25840_write4(c, CX25840_IR_TXCLK_REG, TXCLK_TCD);
ir_state->tx_params.shutdown = true;
mutex_unlock(&ir_state->tx_params_lock);
return 0;
}
static int cx25840_ir_tx_s_parameters(struct v4l2_subdev *sd,
struct v4l2_subdev_ir_parameters *p)
{
struct cx25840_ir_state *ir_state = to_ir_state(sd);
struct i2c_client *c;
struct v4l2_subdev_ir_parameters *o;
u16 txclk_divider;
if (ir_state == NULL)
return -ENODEV;
if (p->shutdown)
return cx25840_ir_tx_shutdown(sd);
if (p->mode != V4L2_SUBDEV_IR_MODE_PULSE_WIDTH)
return -ENOSYS;
c = ir_state->c;
o = &ir_state->tx_params;
mutex_lock(&ir_state->tx_params_lock);
o->shutdown = p->shutdown;
p->mode = V4L2_SUBDEV_IR_MODE_PULSE_WIDTH;
o->mode = p->mode;
p->bytes_per_data_element = sizeof(union cx25840_ir_fifo_rec);
o->bytes_per_data_element = p->bytes_per_data_element;
/* Before we tweak the hardware, we have to disable the transmitter */
irqenable_tx(sd, 0);
control_tx_enable(c, false);
control_tx_modulation_enable(c, p->modulation);
o->modulation = p->modulation;
if (p->modulation) {
p->carrier_freq = txclk_tx_s_carrier(c, p->carrier_freq,
&txclk_divider);
o->carrier_freq = p->carrier_freq;
p->duty_cycle = cduty_tx_s_duty_cycle(c, p->duty_cycle);
o->duty_cycle = p->duty_cycle;
p->max_pulse_width =
(u32) pulse_width_count_to_ns(FIFO_RXTX, txclk_divider);
} else {
p->max_pulse_width =
txclk_tx_s_max_pulse_width(c, p->max_pulse_width,
&txclk_divider);
}
o->max_pulse_width = p->max_pulse_width;
atomic_set(&ir_state->txclk_divider, txclk_divider);
p->resolution = clock_divider_to_resolution(txclk_divider);
o->resolution = p->resolution;
/* FIXME - make this dependent on resolution for better performance */
control_tx_irq_watermark(c, TX_FIFO_HALF_EMPTY);
control_tx_polarity_invert(c, p->invert_carrier_sense);
o->invert_carrier_sense = p->invert_carrier_sense;
/*
* FIXME: we don't have hardware help for IO pin level inversion
* here like we have on the CX23888.
* Act on this with some mix of logical inversion of data levels,
* carrier polarity, and carrier duty cycle.
*/
o->invert_level = p->invert_level;
o->interrupt_enable = p->interrupt_enable;
o->enable = p->enable;
if (p->enable) {
/* reset tx_fifo here */
if (p->interrupt_enable)
irqenable_tx(sd, IRQEN_TSE);
control_tx_enable(c, p->enable);
}
mutex_unlock(&ir_state->tx_params_lock);
return 0;
}
/*
* V4L2 Subdevice Core Ops support
*/
int cx25840_ir_log_status(struct v4l2_subdev *sd)
{
struct cx25840_state *state = to_state(sd);
struct i2c_client *c = state->c;
char *s;
int i, j;
u32 cntrl, txclk, rxclk, cduty, stats, irqen, filtr;
/* The CX23888 chip doesn't have an IR controller on the A/V core */
if (is_cx23888(state))
return 0;
cntrl = cx25840_read4(c, CX25840_IR_CNTRL_REG);
txclk = cx25840_read4(c, CX25840_IR_TXCLK_REG) & TXCLK_TCD;
rxclk = cx25840_read4(c, CX25840_IR_RXCLK_REG) & RXCLK_RCD;
cduty = cx25840_read4(c, CX25840_IR_CDUTY_REG) & CDUTY_CDC;
stats = cx25840_read4(c, CX25840_IR_STATS_REG);
irqen = cx25840_read4(c, CX25840_IR_IRQEN_REG);
if (is_cx23885(state) || is_cx23887(state))
irqen ^= IRQEN_MSK;
filtr = cx25840_read4(c, CX25840_IR_FILTR_REG) & FILTR_LPF;
v4l2_info(sd, "IR Receiver:\n");
v4l2_info(sd, "\tEnabled: %s\n",
cntrl & CNTRL_RXE ? "yes" : "no");
v4l2_info(sd, "\tDemodulation from a carrier: %s\n",
cntrl & CNTRL_DMD ? "enabled" : "disabled");
v4l2_info(sd, "\tFIFO: %s\n",
cntrl & CNTRL_RFE ? "enabled" : "disabled");
switch (cntrl & CNTRL_EDG) {
case CNTRL_EDG_NONE:
s = "disabled";
break;
case CNTRL_EDG_FALL:
s = "falling edge";
break;
case CNTRL_EDG_RISE:
s = "rising edge";
break;
case CNTRL_EDG_BOTH:
s = "rising & falling edges";
break;
default:
s = "??? edge";
break;
}
v4l2_info(sd, "\tPulse timers' start/stop trigger: %s\n", s);
v4l2_info(sd, "\tFIFO data on pulse timer overflow: %s\n",
cntrl & CNTRL_R ? "not loaded" : "overflow marker");
v4l2_info(sd, "\tFIFO interrupt watermark: %s\n",
cntrl & CNTRL_RIC ? "not empty" : "half full or greater");
v4l2_info(sd, "\tLoopback mode: %s\n",
cntrl & CNTRL_LBM ? "loopback active" : "normal receive");
if (cntrl & CNTRL_DMD) {
v4l2_info(sd, "\tExpected carrier (16 clocks): %u Hz\n",
clock_divider_to_carrier_freq(rxclk));
switch (cntrl & CNTRL_WIN) {
case CNTRL_WIN_3_3:
i = 3;
j = 3;
break;
case CNTRL_WIN_4_3:
i = 4;
j = 3;
break;
case CNTRL_WIN_3_4:
i = 3;
j = 4;
break;
case CNTRL_WIN_4_4:
i = 4;
j = 4;
break;
default:
i = 0;
j = 0;
break;
}
v4l2_info(sd, "\tNext carrier edge window: 16 clocks "
"-%1d/+%1d, %u to %u Hz\n", i, j,
clock_divider_to_freq(rxclk, 16 + j),
clock_divider_to_freq(rxclk, 16 - i));
}
v4l2_info(sd, "\tMax measurable pulse width: %u us, %llu ns\n",
pulse_width_count_to_us(FIFO_RXTX, rxclk),
pulse_width_count_to_ns(FIFO_RXTX, rxclk));
v4l2_info(sd, "\tLow pass filter: %s\n",
filtr ? "enabled" : "disabled");
if (filtr)
v4l2_info(sd, "\tMin acceptable pulse width (LPF): %u us, "
"%u ns\n",
lpf_count_to_us(filtr),
lpf_count_to_ns(filtr));
v4l2_info(sd, "\tPulse width timer timed-out: %s\n",
stats & STATS_RTO ? "yes" : "no");
v4l2_info(sd, "\tPulse width timer time-out intr: %s\n",
irqen & IRQEN_RTE ? "enabled" : "disabled");
v4l2_info(sd, "\tFIFO overrun: %s\n",
stats & STATS_ROR ? "yes" : "no");
v4l2_info(sd, "\tFIFO overrun interrupt: %s\n",
irqen & IRQEN_ROE ? "enabled" : "disabled");
v4l2_info(sd, "\tBusy: %s\n",
stats & STATS_RBY ? "yes" : "no");
v4l2_info(sd, "\tFIFO service requested: %s\n",
stats & STATS_RSR ? "yes" : "no");
v4l2_info(sd, "\tFIFO service request interrupt: %s\n",
irqen & IRQEN_RSE ? "enabled" : "disabled");
v4l2_info(sd, "IR Transmitter:\n");
v4l2_info(sd, "\tEnabled: %s\n",
cntrl & CNTRL_TXE ? "yes" : "no");
v4l2_info(sd, "\tModulation onto a carrier: %s\n",
cntrl & CNTRL_MOD ? "enabled" : "disabled");
v4l2_info(sd, "\tFIFO: %s\n",
cntrl & CNTRL_TFE ? "enabled" : "disabled");
v4l2_info(sd, "\tFIFO interrupt watermark: %s\n",
cntrl & CNTRL_TIC ? "not empty" : "half full or less");
v4l2_info(sd, "\tCarrier polarity: %s\n",
cntrl & CNTRL_CPL ? "space:burst mark:noburst"
: "space:noburst mark:burst");
if (cntrl & CNTRL_MOD) {
v4l2_info(sd, "\tCarrier (16 clocks): %u Hz\n",
clock_divider_to_carrier_freq(txclk));
v4l2_info(sd, "\tCarrier duty cycle: %2u/16\n",
cduty + 1);
}
v4l2_info(sd, "\tMax pulse width: %u us, %llu ns\n",
pulse_width_count_to_us(FIFO_RXTX, txclk),
pulse_width_count_to_ns(FIFO_RXTX, txclk));
v4l2_info(sd, "\tBusy: %s\n",
stats & STATS_TBY ? "yes" : "no");
v4l2_info(sd, "\tFIFO service requested: %s\n",
stats & STATS_TSR ? "yes" : "no");
v4l2_info(sd, "\tFIFO service request interrupt: %s\n",
irqen & IRQEN_TSE ? "enabled" : "disabled");
return 0;
}
const struct v4l2_subdev_ir_ops cx25840_ir_ops = {
.rx_read = cx25840_ir_rx_read,
.rx_g_parameters = cx25840_ir_rx_g_parameters,
.rx_s_parameters = cx25840_ir_rx_s_parameters,
.tx_write = cx25840_ir_tx_write,
.tx_g_parameters = cx25840_ir_tx_g_parameters,
.tx_s_parameters = cx25840_ir_tx_s_parameters,
};
static const struct v4l2_subdev_ir_parameters default_rx_params = {
.bytes_per_data_element = sizeof(union cx25840_ir_fifo_rec),
.mode = V4L2_SUBDEV_IR_MODE_PULSE_WIDTH,
.enable = false,
.interrupt_enable = false,
.shutdown = true,
.modulation = true,
.carrier_freq = 36000, /* 36 kHz - RC-5, and RC-6 carrier */
/* RC-5: 666,667 ns = 1/36 kHz * 32 cycles * 1 mark * 0.75 */
/* RC-6: 333,333 ns = 1/36 kHz * 16 cycles * 1 mark * 0.75 */
.noise_filter_min_width = 333333, /* ns */
.carrier_range_lower = 35000,
.carrier_range_upper = 37000,
.invert_level = false,
};
static const struct v4l2_subdev_ir_parameters default_tx_params = {
.bytes_per_data_element = sizeof(union cx25840_ir_fifo_rec),
.mode = V4L2_SUBDEV_IR_MODE_PULSE_WIDTH,
.enable = false,
.interrupt_enable = false,
.shutdown = true,
.modulation = true,
.carrier_freq = 36000, /* 36 kHz - RC-5 carrier */
.duty_cycle = 25, /* 25 % - RC-5 carrier */
.invert_level = false,
.invert_carrier_sense = false,
};
int cx25840_ir_probe(struct v4l2_subdev *sd)
{
struct cx25840_state *state = to_state(sd);
struct cx25840_ir_state *ir_state;
struct v4l2_subdev_ir_parameters default_params;
/* Only init the IR controller for the CX2388[57] AV Core for now */
if (!(is_cx23885(state) || is_cx23887(state)))
return 0;
ir_state = kzalloc(sizeof(struct cx25840_ir_state), GFP_KERNEL);
if (ir_state == NULL)
return -ENOMEM;
spin_lock_init(&ir_state->rx_kfifo_lock);
if (kfifo_alloc(&ir_state->rx_kfifo,
CX25840_IR_RX_KFIFO_SIZE, GFP_KERNEL)) {
kfree(ir_state);
return -ENOMEM;
}
ir_state->c = state->c;
state->ir_state = ir_state;
/* Ensure no interrupts arrive yet */
if (is_cx23885(state) || is_cx23887(state))
cx25840_write4(ir_state->c, CX25840_IR_IRQEN_REG, IRQEN_MSK);
else
cx25840_write4(ir_state->c, CX25840_IR_IRQEN_REG, 0);
mutex_init(&ir_state->rx_params_lock);
default_params = default_rx_params;
v4l2_subdev_call(sd, ir, rx_s_parameters, &default_params);
mutex_init(&ir_state->tx_params_lock);
default_params = default_tx_params;
v4l2_subdev_call(sd, ir, tx_s_parameters, &default_params);
return 0;
}
int cx25840_ir_remove(struct v4l2_subdev *sd)
{
struct cx25840_state *state = to_state(sd);
struct cx25840_ir_state *ir_state = to_ir_state(sd);
if (ir_state == NULL)
return -ENODEV;
cx25840_ir_rx_shutdown(sd);
cx25840_ir_tx_shutdown(sd);
kfifo_free(&ir_state->rx_kfifo);
kfree(ir_state);
state->ir_state = NULL;
return 0;
}
| gpl-2.0 |
cpaasch/mptcp-net-next | arch/arm/kernel/thumbee.c | 2919 | 2029 | /*
* arch/arm/kernel/thumbee.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
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <asm/cputype.h>
#include <asm/system_info.h>
#include <asm/thread_notify.h>
/*
* Access to the ThumbEE Handler Base register
*/
static inline unsigned long teehbr_read(void)
{
unsigned long v;
asm("mrc p14, 6, %0, c1, c0, 0\n" : "=r" (v));
return v;
}
static inline void teehbr_write(unsigned long v)
{
asm("mcr p14, 6, %0, c1, c0, 0\n" : : "r" (v));
}
static int thumbee_notifier(struct notifier_block *self, unsigned long cmd, void *t)
{
struct thread_info *thread = t;
switch (cmd) {
case THREAD_NOTIFY_FLUSH:
thread->thumbee_state = 0;
break;
case THREAD_NOTIFY_SWITCH:
current_thread_info()->thumbee_state = teehbr_read();
teehbr_write(thread->thumbee_state);
break;
}
return NOTIFY_DONE;
}
static struct notifier_block thumbee_notifier_block = {
.notifier_call = thumbee_notifier,
};
static int __init thumbee_init(void)
{
unsigned long pfr0;
unsigned int cpu_arch = cpu_architecture();
if (cpu_arch < CPU_ARCH_ARMv7)
return 0;
pfr0 = read_cpuid_ext(CPUID_EXT_PFR0);
if ((pfr0 & 0x0000f000) != 0x00001000)
return 0;
printk(KERN_INFO "ThumbEE CPU extension supported.\n");
elf_hwcap |= HWCAP_THUMBEE;
thread_register_notifier(&thumbee_notifier_block);
return 0;
}
late_initcall(thumbee_init);
| gpl-2.0 |
nicosoftdroid/kernel_tegra3 | arch/alpha/kernel/irq.c | 2919 | 3315 | /*
* linux/arch/alpha/kernel/irq.c
*
* Copyright (C) 1995 Linus Torvalds
*
* This file contains the code used by various IRQ handling routines:
* asking for different IRQ's should be done through these routines
* instead of just grabbing them. Thus setups with different IRQ numbers
* shouldn't result in any weird surprises, and installing new handlers
* should be easier.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/kernel_stat.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/ptrace.h>
#include <linux/interrupt.h>
#include <linux/random.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/profile.h>
#include <linux/bitops.h>
#include <asm/system.h>
#include <asm/io.h>
#include <asm/uaccess.h>
volatile unsigned long irq_err_count;
DEFINE_PER_CPU(unsigned long, irq_pmi_count);
void ack_bad_irq(unsigned int irq)
{
irq_err_count++;
printk(KERN_CRIT "Unexpected IRQ trap at vector %u\n", irq);
}
#ifdef CONFIG_SMP
static char irq_user_affinity[NR_IRQS];
int irq_select_affinity(unsigned int irq)
{
struct irq_data *data = irq_get_irq_data(irq);
struct irq_chip *chip;
static int last_cpu;
int cpu = last_cpu + 1;
if (!data)
return 1;
chip = irq_data_get_irq_chip(data);
if (!chip->irq_set_affinity || irq_user_affinity[irq])
return 1;
while (!cpu_possible(cpu) ||
!cpumask_test_cpu(cpu, irq_default_affinity))
cpu = (cpu < (NR_CPUS-1) ? cpu + 1 : 0);
last_cpu = cpu;
cpumask_copy(data->affinity, cpumask_of(cpu));
chip->irq_set_affinity(data, cpumask_of(cpu), false);
return 0;
}
#endif /* CONFIG_SMP */
int arch_show_interrupts(struct seq_file *p, int prec)
{
int j;
#ifdef CONFIG_SMP
seq_puts(p, "IPI: ");
for_each_online_cpu(j)
seq_printf(p, "%10lu ", cpu_data[j].ipi_count);
seq_putc(p, '\n');
#endif
seq_puts(p, "PMI: ");
for_each_online_cpu(j)
seq_printf(p, "%10lu ", per_cpu(irq_pmi_count, j));
seq_puts(p, " Performance Monitoring\n");
seq_printf(p, "ERR: %10lu\n", irq_err_count);
return 0;
}
/*
* handle_irq handles all normal device IRQ's (the special
* SMP cross-CPU interrupts have their own specific
* handlers).
*/
#define MAX_ILLEGAL_IRQS 16
void
handle_irq(int irq)
{
/*
* We ack quickly, we don't want the irq controller
* thinking we're snobs just because some other CPU has
* disabled global interrupts (we have already done the
* INT_ACK cycles, it's too late to try to pretend to the
* controller that we aren't taking the interrupt).
*
* 0 return value means that this irq is already being
* handled by some other CPU. (or is disabled)
*/
static unsigned int illegal_count=0;
struct irq_desc *desc = irq_to_desc(irq);
if (!desc || ((unsigned) irq > ACTUAL_NR_IRQS &&
illegal_count < MAX_ILLEGAL_IRQS)) {
irq_err_count++;
illegal_count++;
printk(KERN_CRIT "device_interrupt: invalid interrupt %d\n",
irq);
return;
}
/*
* From here we must proceed with IPL_MAX. Note that we do not
* explicitly enable interrupts afterwards - some MILO PALcode
* (namely LX164 one) seems to have severe problems with RTI
* at IPL 0.
*/
local_irq_disable();
irq_enter();
generic_handle_irq_desc(irq, desc);
irq_exit();
}
| gpl-2.0 |
Pafcholini/android_kernel_c8690 | drivers/net/stmmac/norm_desc.c | 2919 | 5809 | /*******************************************************************************
This contains the functions to handle the normal descriptors.
Copyright (C) 2007-2009 STMicroelectronics Ltd
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Author: Giuseppe Cavallaro <peppe.cavallaro@st.com>
*******************************************************************************/
#include "common.h"
static int ndesc_get_tx_status(void *data, struct stmmac_extra_stats *x,
struct dma_desc *p, void __iomem *ioaddr)
{
int ret = 0;
struct net_device_stats *stats = (struct net_device_stats *)data;
if (unlikely(p->des01.tx.error_summary)) {
if (unlikely(p->des01.tx.underflow_error)) {
x->tx_underflow++;
stats->tx_fifo_errors++;
}
if (unlikely(p->des01.tx.no_carrier)) {
x->tx_carrier++;
stats->tx_carrier_errors++;
}
if (unlikely(p->des01.tx.loss_carrier)) {
x->tx_losscarrier++;
stats->tx_carrier_errors++;
}
if (unlikely((p->des01.tx.excessive_deferral) ||
(p->des01.tx.excessive_collisions) ||
(p->des01.tx.late_collision)))
stats->collisions += p->des01.tx.collision_count;
ret = -1;
}
if (unlikely(p->des01.tx.heartbeat_fail)) {
x->tx_heartbeat++;
stats->tx_heartbeat_errors++;
ret = -1;
}
if (unlikely(p->des01.tx.deferred))
x->tx_deferred++;
return ret;
}
static int ndesc_get_tx_len(struct dma_desc *p)
{
return p->des01.tx.buffer1_size;
}
/* This function verifies if each incoming frame has some errors
* and, if required, updates the multicast statistics.
* In case of success, it returns csum_none because the device
* is not able to compute the csum in HW. */
static int ndesc_get_rx_status(void *data, struct stmmac_extra_stats *x,
struct dma_desc *p)
{
int ret = csum_none;
struct net_device_stats *stats = (struct net_device_stats *)data;
if (unlikely(p->des01.rx.last_descriptor == 0)) {
pr_warning("ndesc Error: Oversized Ethernet "
"frame spanned multiple buffers\n");
stats->rx_length_errors++;
return discard_frame;
}
if (unlikely(p->des01.rx.error_summary)) {
if (unlikely(p->des01.rx.descriptor_error))
x->rx_desc++;
if (unlikely(p->des01.rx.partial_frame_error))
x->rx_partial++;
if (unlikely(p->des01.rx.run_frame))
x->rx_runt++;
if (unlikely(p->des01.rx.frame_too_long))
x->rx_toolong++;
if (unlikely(p->des01.rx.collision)) {
x->rx_collision++;
stats->collisions++;
}
if (unlikely(p->des01.rx.crc_error)) {
x->rx_crc++;
stats->rx_crc_errors++;
}
ret = discard_frame;
}
if (unlikely(p->des01.rx.dribbling))
ret = discard_frame;
if (unlikely(p->des01.rx.length_error)) {
x->rx_length++;
ret = discard_frame;
}
if (unlikely(p->des01.rx.mii_error)) {
x->rx_mii++;
ret = discard_frame;
}
if (p->des01.rx.multicast_frame) {
x->rx_multicast++;
stats->multicast++;
}
return ret;
}
static void ndesc_init_rx_desc(struct dma_desc *p, unsigned int ring_size,
int disable_rx_ic)
{
int i;
for (i = 0; i < ring_size; i++) {
p->des01.rx.own = 1;
p->des01.rx.buffer1_size = BUF_SIZE_2KiB - 1;
if (i == ring_size - 1)
p->des01.rx.end_ring = 1;
if (disable_rx_ic)
p->des01.rx.disable_ic = 1;
p++;
}
}
static void ndesc_init_tx_desc(struct dma_desc *p, unsigned int ring_size)
{
int i;
for (i = 0; i < ring_size; i++) {
p->des01.tx.own = 0;
if (i == ring_size - 1)
p->des01.tx.end_ring = 1;
p++;
}
}
static int ndesc_get_tx_owner(struct dma_desc *p)
{
return p->des01.tx.own;
}
static int ndesc_get_rx_owner(struct dma_desc *p)
{
return p->des01.rx.own;
}
static void ndesc_set_tx_owner(struct dma_desc *p)
{
p->des01.tx.own = 1;
}
static void ndesc_set_rx_owner(struct dma_desc *p)
{
p->des01.rx.own = 1;
}
static int ndesc_get_tx_ls(struct dma_desc *p)
{
return p->des01.tx.last_segment;
}
static void ndesc_release_tx_desc(struct dma_desc *p)
{
int ter = p->des01.tx.end_ring;
memset(p, 0, offsetof(struct dma_desc, des2));
/* set termination field */
p->des01.tx.end_ring = ter;
}
static void ndesc_prepare_tx_desc(struct dma_desc *p, int is_fs, int len,
int csum_flag)
{
p->des01.tx.first_segment = is_fs;
p->des01.tx.buffer1_size = len;
}
static void ndesc_clear_tx_ic(struct dma_desc *p)
{
p->des01.tx.interrupt = 0;
}
static void ndesc_close_tx_desc(struct dma_desc *p)
{
p->des01.tx.last_segment = 1;
p->des01.tx.interrupt = 1;
}
static int ndesc_get_rx_frame_len(struct dma_desc *p)
{
return p->des01.rx.frame_length;
}
const struct stmmac_desc_ops ndesc_ops = {
.tx_status = ndesc_get_tx_status,
.rx_status = ndesc_get_rx_status,
.get_tx_len = ndesc_get_tx_len,
.init_rx_desc = ndesc_init_rx_desc,
.init_tx_desc = ndesc_init_tx_desc,
.get_tx_owner = ndesc_get_tx_owner,
.get_rx_owner = ndesc_get_rx_owner,
.release_tx_desc = ndesc_release_tx_desc,
.prepare_tx_desc = ndesc_prepare_tx_desc,
.clear_tx_ic = ndesc_clear_tx_ic,
.close_tx_desc = ndesc_close_tx_desc,
.get_tx_ls = ndesc_get_tx_ls,
.set_tx_owner = ndesc_set_tx_owner,
.set_rx_owner = ndesc_set_rx_owner,
.get_rx_frame_len = ndesc_get_rx_frame_len,
};
| gpl-2.0 |
moguriso/isw11sc-kernel | drivers/usb/host/ohci-dbg.c | 3175 | 21596 | /*
* OHCI HCD (Host Controller Driver) for USB.
*
* (C) Copyright 1999 Roman Weissgaerber <weissg@vienna.at>
* (C) Copyright 2000-2002 David Brownell <dbrownell@users.sourceforge.net>
*
* This file is licenced under the GPL.
*/
/*-------------------------------------------------------------------------*/
#ifdef DEBUG
#define edstring(ed_type) ({ char *temp; \
switch (ed_type) { \
case PIPE_CONTROL: temp = "ctrl"; break; \
case PIPE_BULK: temp = "bulk"; break; \
case PIPE_INTERRUPT: temp = "intr"; break; \
default: temp = "isoc"; break; \
}; temp;})
#define pipestring(pipe) edstring(usb_pipetype(pipe))
/* debug| print the main components of an URB
* small: 0) header + data packets 1) just header
*/
static void __maybe_unused
urb_print(struct urb * urb, char * str, int small, int status)
{
unsigned int pipe= urb->pipe;
if (!urb->dev || !urb->dev->bus) {
dbg("%s URB: no dev", str);
return;
}
#ifndef OHCI_VERBOSE_DEBUG
if (status != 0)
#endif
dbg("%s %p dev=%d ep=%d%s-%s flags=%x len=%d/%d stat=%d",
str,
urb,
usb_pipedevice (pipe),
usb_pipeendpoint (pipe),
usb_pipeout (pipe)? "out" : "in",
pipestring (pipe),
urb->transfer_flags,
urb->actual_length,
urb->transfer_buffer_length,
status);
#ifdef OHCI_VERBOSE_DEBUG
if (!small) {
int i, len;
if (usb_pipecontrol (pipe)) {
printk (KERN_DEBUG "%s: setup(8):", __FILE__);
for (i = 0; i < 8 ; i++)
printk (" %02x", ((__u8 *) urb->setup_packet) [i]);
printk ("\n");
}
if (urb->transfer_buffer_length > 0 && urb->transfer_buffer) {
printk (KERN_DEBUG "%s: data(%d/%d):", __FILE__,
urb->actual_length,
urb->transfer_buffer_length);
len = usb_pipeout (pipe)?
urb->transfer_buffer_length: urb->actual_length;
for (i = 0; i < 16 && i < len; i++)
printk (" %02x", ((__u8 *) urb->transfer_buffer) [i]);
printk ("%s stat:%d\n", i < len? "...": "", status);
}
}
#endif
}
#define ohci_dbg_sw(ohci, next, size, format, arg...) \
do { \
if (next != NULL) { \
unsigned s_len; \
s_len = scnprintf (*next, *size, format, ## arg ); \
*size -= s_len; *next += s_len; \
} else \
ohci_dbg(ohci,format, ## arg ); \
} while (0);
static void ohci_dump_intr_mask (
struct ohci_hcd *ohci,
char *label,
u32 mask,
char **next,
unsigned *size)
{
ohci_dbg_sw (ohci, next, size, "%s 0x%08x%s%s%s%s%s%s%s%s%s\n",
label,
mask,
(mask & OHCI_INTR_MIE) ? " MIE" : "",
(mask & OHCI_INTR_OC) ? " OC" : "",
(mask & OHCI_INTR_RHSC) ? " RHSC" : "",
(mask & OHCI_INTR_FNO) ? " FNO" : "",
(mask & OHCI_INTR_UE) ? " UE" : "",
(mask & OHCI_INTR_RD) ? " RD" : "",
(mask & OHCI_INTR_SF) ? " SF" : "",
(mask & OHCI_INTR_WDH) ? " WDH" : "",
(mask & OHCI_INTR_SO) ? " SO" : ""
);
}
static void maybe_print_eds (
struct ohci_hcd *ohci,
char *label,
u32 value,
char **next,
unsigned *size)
{
if (value)
ohci_dbg_sw (ohci, next, size, "%s %08x\n", label, value);
}
static char *hcfs2string (int state)
{
switch (state) {
case OHCI_USB_RESET: return "reset";
case OHCI_USB_RESUME: return "resume";
case OHCI_USB_OPER: return "operational";
case OHCI_USB_SUSPEND: return "suspend";
}
return "?";
}
// dump control and status registers
static void
ohci_dump_status (struct ohci_hcd *controller, char **next, unsigned *size)
{
struct ohci_regs __iomem *regs = controller->regs;
u32 temp;
temp = ohci_readl (controller, ®s->revision) & 0xff;
ohci_dbg_sw (controller, next, size,
"OHCI %d.%d, %s legacy support registers\n",
0x03 & (temp >> 4), (temp & 0x0f),
(temp & 0x0100) ? "with" : "NO");
temp = ohci_readl (controller, ®s->control);
ohci_dbg_sw (controller, next, size,
"control 0x%03x%s%s%s HCFS=%s%s%s%s%s CBSR=%d\n",
temp,
(temp & OHCI_CTRL_RWE) ? " RWE" : "",
(temp & OHCI_CTRL_RWC) ? " RWC" : "",
(temp & OHCI_CTRL_IR) ? " IR" : "",
hcfs2string (temp & OHCI_CTRL_HCFS),
(temp & OHCI_CTRL_BLE) ? " BLE" : "",
(temp & OHCI_CTRL_CLE) ? " CLE" : "",
(temp & OHCI_CTRL_IE) ? " IE" : "",
(temp & OHCI_CTRL_PLE) ? " PLE" : "",
temp & OHCI_CTRL_CBSR
);
temp = ohci_readl (controller, ®s->cmdstatus);
ohci_dbg_sw (controller, next, size,
"cmdstatus 0x%05x SOC=%d%s%s%s%s\n", temp,
(temp & OHCI_SOC) >> 16,
(temp & OHCI_OCR) ? " OCR" : "",
(temp & OHCI_BLF) ? " BLF" : "",
(temp & OHCI_CLF) ? " CLF" : "",
(temp & OHCI_HCR) ? " HCR" : ""
);
ohci_dump_intr_mask (controller, "intrstatus",
ohci_readl (controller, ®s->intrstatus),
next, size);
ohci_dump_intr_mask (controller, "intrenable",
ohci_readl (controller, ®s->intrenable),
next, size);
// intrdisable always same as intrenable
maybe_print_eds (controller, "ed_periodcurrent",
ohci_readl (controller, ®s->ed_periodcurrent),
next, size);
maybe_print_eds (controller, "ed_controlhead",
ohci_readl (controller, ®s->ed_controlhead),
next, size);
maybe_print_eds (controller, "ed_controlcurrent",
ohci_readl (controller, ®s->ed_controlcurrent),
next, size);
maybe_print_eds (controller, "ed_bulkhead",
ohci_readl (controller, ®s->ed_bulkhead),
next, size);
maybe_print_eds (controller, "ed_bulkcurrent",
ohci_readl (controller, ®s->ed_bulkcurrent),
next, size);
maybe_print_eds (controller, "donehead",
ohci_readl (controller, ®s->donehead), next, size);
}
#define dbg_port_sw(hc,num,value,next,size) \
ohci_dbg_sw (hc, next, size, \
"roothub.portstatus [%d] " \
"0x%08x%s%s%s%s%s%s%s%s%s%s%s%s\n", \
num, temp, \
(temp & RH_PS_PRSC) ? " PRSC" : "", \
(temp & RH_PS_OCIC) ? " OCIC" : "", \
(temp & RH_PS_PSSC) ? " PSSC" : "", \
(temp & RH_PS_PESC) ? " PESC" : "", \
(temp & RH_PS_CSC) ? " CSC" : "", \
\
(temp & RH_PS_LSDA) ? " LSDA" : "", \
(temp & RH_PS_PPS) ? " PPS" : "", \
(temp & RH_PS_PRS) ? " PRS" : "", \
(temp & RH_PS_POCI) ? " POCI" : "", \
(temp & RH_PS_PSS) ? " PSS" : "", \
\
(temp & RH_PS_PES) ? " PES" : "", \
(temp & RH_PS_CCS) ? " CCS" : "" \
);
static void
ohci_dump_roothub (
struct ohci_hcd *controller,
int verbose,
char **next,
unsigned *size)
{
u32 temp, i;
temp = roothub_a (controller);
if (temp == ~(u32)0)
return;
if (verbose) {
ohci_dbg_sw (controller, next, size,
"roothub.a %08x POTPGT=%d%s%s%s%s%s NDP=%d(%d)\n", temp,
((temp & RH_A_POTPGT) >> 24) & 0xff,
(temp & RH_A_NOCP) ? " NOCP" : "",
(temp & RH_A_OCPM) ? " OCPM" : "",
(temp & RH_A_DT) ? " DT" : "",
(temp & RH_A_NPS) ? " NPS" : "",
(temp & RH_A_PSM) ? " PSM" : "",
(temp & RH_A_NDP), controller->num_ports
);
temp = roothub_b (controller);
ohci_dbg_sw (controller, next, size,
"roothub.b %08x PPCM=%04x DR=%04x\n",
temp,
(temp & RH_B_PPCM) >> 16,
(temp & RH_B_DR)
);
temp = roothub_status (controller);
ohci_dbg_sw (controller, next, size,
"roothub.status %08x%s%s%s%s%s%s\n",
temp,
(temp & RH_HS_CRWE) ? " CRWE" : "",
(temp & RH_HS_OCIC) ? " OCIC" : "",
(temp & RH_HS_LPSC) ? " LPSC" : "",
(temp & RH_HS_DRWE) ? " DRWE" : "",
(temp & RH_HS_OCI) ? " OCI" : "",
(temp & RH_HS_LPS) ? " LPS" : ""
);
}
for (i = 0; i < controller->num_ports; i++) {
temp = roothub_portstatus (controller, i);
dbg_port_sw (controller, i, temp, next, size);
}
}
static void ohci_dump (struct ohci_hcd *controller, int verbose)
{
ohci_dbg (controller, "OHCI controller state\n");
// dumps some of the state we know about
ohci_dump_status (controller, NULL, NULL);
if (controller->hcca)
ohci_dbg (controller,
"hcca frame #%04x\n", ohci_frame_no(controller));
ohci_dump_roothub (controller, 1, NULL, NULL);
}
static const char data0 [] = "DATA0";
static const char data1 [] = "DATA1";
static void ohci_dump_td (const struct ohci_hcd *ohci, const char *label,
const struct td *td)
{
u32 tmp = hc32_to_cpup (ohci, &td->hwINFO);
ohci_dbg (ohci, "%s td %p%s; urb %p index %d; hw next td %08x\n",
label, td,
(tmp & TD_DONE) ? " (DONE)" : "",
td->urb, td->index,
hc32_to_cpup (ohci, &td->hwNextTD));
if ((tmp & TD_ISO) == 0) {
const char *toggle, *pid;
u32 cbp, be;
switch (tmp & TD_T) {
case TD_T_DATA0: toggle = data0; break;
case TD_T_DATA1: toggle = data1; break;
case TD_T_TOGGLE: toggle = "(CARRY)"; break;
default: toggle = "(?)"; break;
}
switch (tmp & TD_DP) {
case TD_DP_SETUP: pid = "SETUP"; break;
case TD_DP_IN: pid = "IN"; break;
case TD_DP_OUT: pid = "OUT"; break;
default: pid = "(bad pid)"; break;
}
ohci_dbg (ohci, " info %08x CC=%x %s DI=%d %s %s\n", tmp,
TD_CC_GET(tmp), /* EC, */ toggle,
(tmp & TD_DI) >> 21, pid,
(tmp & TD_R) ? "R" : "");
cbp = hc32_to_cpup (ohci, &td->hwCBP);
be = hc32_to_cpup (ohci, &td->hwBE);
ohci_dbg (ohci, " cbp %08x be %08x (len %d)\n", cbp, be,
cbp ? (be + 1 - cbp) : 0);
} else {
unsigned i;
ohci_dbg (ohci, " info %08x CC=%x FC=%d DI=%d SF=%04x\n", tmp,
TD_CC_GET(tmp),
(tmp >> 24) & 0x07,
(tmp & TD_DI) >> 21,
tmp & 0x0000ffff);
ohci_dbg (ohci, " bp0 %08x be %08x\n",
hc32_to_cpup (ohci, &td->hwCBP) & ~0x0fff,
hc32_to_cpup (ohci, &td->hwBE));
for (i = 0; i < MAXPSW; i++) {
u16 psw = ohci_hwPSW (ohci, td, i);
int cc = (psw >> 12) & 0x0f;
ohci_dbg (ohci, " psw [%d] = %2x, CC=%x %s=%d\n", i,
psw, cc,
(cc >= 0x0e) ? "OFFSET" : "SIZE",
psw & 0x0fff);
}
}
}
/* caller MUST own hcd spinlock if verbose is set! */
static void __maybe_unused
ohci_dump_ed (const struct ohci_hcd *ohci, const char *label,
const struct ed *ed, int verbose)
{
u32 tmp = hc32_to_cpu (ohci, ed->hwINFO);
char *type = "";
ohci_dbg (ohci, "%s, ed %p state 0x%x type %s; next ed %08x\n",
label,
ed, ed->state, edstring (ed->type),
hc32_to_cpup (ohci, &ed->hwNextED));
switch (tmp & (ED_IN|ED_OUT)) {
case ED_OUT: type = "-OUT"; break;
case ED_IN: type = "-IN"; break;
/* else from TDs ... control */
}
ohci_dbg (ohci,
" info %08x MAX=%d%s%s%s%s EP=%d%s DEV=%d\n", tmp,
0x03ff & (tmp >> 16),
(tmp & ED_DEQUEUE) ? " DQ" : "",
(tmp & ED_ISO) ? " ISO" : "",
(tmp & ED_SKIP) ? " SKIP" : "",
(tmp & ED_LOWSPEED) ? " LOW" : "",
0x000f & (tmp >> 7),
type,
0x007f & tmp);
tmp = hc32_to_cpup (ohci, &ed->hwHeadP);
ohci_dbg (ohci, " tds: head %08x %s%s tail %08x%s\n",
tmp,
(tmp & ED_C) ? data1 : data0,
(tmp & ED_H) ? " HALT" : "",
hc32_to_cpup (ohci, &ed->hwTailP),
verbose ? "" : " (not listing)");
if (verbose) {
struct list_head *tmp;
/* use ed->td_list because HC concurrently modifies
* hwNextTD as it accumulates ed_donelist.
*/
list_for_each (tmp, &ed->td_list) {
struct td *td;
td = list_entry (tmp, struct td, td_list);
ohci_dump_td (ohci, " ->", td);
}
}
}
#else
static inline void ohci_dump (struct ohci_hcd *controller, int verbose) {}
#undef OHCI_VERBOSE_DEBUG
#endif /* DEBUG */
/*-------------------------------------------------------------------------*/
#ifdef STUB_DEBUG_FILES
static inline void create_debug_files (struct ohci_hcd *bus) { }
static inline void remove_debug_files (struct ohci_hcd *bus) { }
#else
static int debug_async_open(struct inode *, struct file *);
static int debug_periodic_open(struct inode *, struct file *);
static int debug_registers_open(struct inode *, struct file *);
static int debug_async_open(struct inode *, struct file *);
static ssize_t debug_output(struct file*, char __user*, size_t, loff_t*);
static int debug_close(struct inode *, struct file *);
static const struct file_operations debug_async_fops = {
.owner = THIS_MODULE,
.open = debug_async_open,
.read = debug_output,
.release = debug_close,
.llseek = default_llseek,
};
static const struct file_operations debug_periodic_fops = {
.owner = THIS_MODULE,
.open = debug_periodic_open,
.read = debug_output,
.release = debug_close,
.llseek = default_llseek,
};
static const struct file_operations debug_registers_fops = {
.owner = THIS_MODULE,
.open = debug_registers_open,
.read = debug_output,
.release = debug_close,
.llseek = default_llseek,
};
static struct dentry *ohci_debug_root;
struct debug_buffer {
ssize_t (*fill_func)(struct debug_buffer *); /* fill method */
struct ohci_hcd *ohci;
struct mutex mutex; /* protect filling of buffer */
size_t count; /* number of characters filled into buffer */
char *page;
};
static ssize_t
show_list (struct ohci_hcd *ohci, char *buf, size_t count, struct ed *ed)
{
unsigned temp, size = count;
if (!ed)
return 0;
/* print first --> last */
while (ed->ed_prev)
ed = ed->ed_prev;
/* dump a snapshot of the bulk or control schedule */
while (ed) {
u32 info = hc32_to_cpu (ohci, ed->hwINFO);
u32 headp = hc32_to_cpu (ohci, ed->hwHeadP);
struct list_head *entry;
struct td *td;
temp = scnprintf (buf, size,
"ed/%p %cs dev%d ep%d%s max %d %08x%s%s %s",
ed,
(info & ED_LOWSPEED) ? 'l' : 'f',
info & 0x7f,
(info >> 7) & 0xf,
(info & ED_IN) ? "in" : "out",
0x03ff & (info >> 16),
info,
(info & ED_SKIP) ? " s" : "",
(headp & ED_H) ? " H" : "",
(headp & ED_C) ? data1 : data0);
size -= temp;
buf += temp;
list_for_each (entry, &ed->td_list) {
u32 cbp, be;
td = list_entry (entry, struct td, td_list);
info = hc32_to_cpup (ohci, &td->hwINFO);
cbp = hc32_to_cpup (ohci, &td->hwCBP);
be = hc32_to_cpup (ohci, &td->hwBE);
temp = scnprintf (buf, size,
"\n\ttd %p %s %d cc=%x urb %p (%08x)",
td,
({ char *pid;
switch (info & TD_DP) {
case TD_DP_SETUP: pid = "setup"; break;
case TD_DP_IN: pid = "in"; break;
case TD_DP_OUT: pid = "out"; break;
default: pid = "(?)"; break;
} pid;}),
cbp ? (be + 1 - cbp) : 0,
TD_CC_GET (info), td->urb, info);
size -= temp;
buf += temp;
}
temp = scnprintf (buf, size, "\n");
size -= temp;
buf += temp;
ed = ed->ed_next;
}
return count - size;
}
static ssize_t fill_async_buffer(struct debug_buffer *buf)
{
struct ohci_hcd *ohci;
size_t temp;
unsigned long flags;
ohci = buf->ohci;
/* display control and bulk lists together, for simplicity */
spin_lock_irqsave (&ohci->lock, flags);
temp = show_list(ohci, buf->page, buf->count, ohci->ed_controltail);
temp += show_list(ohci, buf->page + temp, buf->count - temp,
ohci->ed_bulktail);
spin_unlock_irqrestore (&ohci->lock, flags);
return temp;
}
#define DBG_SCHED_LIMIT 64
static ssize_t fill_periodic_buffer(struct debug_buffer *buf)
{
struct ohci_hcd *ohci;
struct ed **seen, *ed;
unsigned long flags;
unsigned temp, size, seen_count;
char *next;
unsigned i;
if (!(seen = kmalloc (DBG_SCHED_LIMIT * sizeof *seen, GFP_ATOMIC)))
return 0;
seen_count = 0;
ohci = buf->ohci;
next = buf->page;
size = PAGE_SIZE;
temp = scnprintf (next, size, "size = %d\n", NUM_INTS);
size -= temp;
next += temp;
/* dump a snapshot of the periodic schedule (and load) */
spin_lock_irqsave (&ohci->lock, flags);
for (i = 0; i < NUM_INTS; i++) {
if (!(ed = ohci->periodic [i]))
continue;
temp = scnprintf (next, size, "%2d [%3d]:", i, ohci->load [i]);
size -= temp;
next += temp;
do {
temp = scnprintf (next, size, " ed%d/%p",
ed->interval, ed);
size -= temp;
next += temp;
for (temp = 0; temp < seen_count; temp++) {
if (seen [temp] == ed)
break;
}
/* show more info the first time around */
if (temp == seen_count) {
u32 info = hc32_to_cpu (ohci, ed->hwINFO);
struct list_head *entry;
unsigned qlen = 0;
/* qlen measured here in TDs, not urbs */
list_for_each (entry, &ed->td_list)
qlen++;
temp = scnprintf (next, size,
" (%cs dev%d ep%d%s-%s qlen %u"
" max %d %08x%s%s)",
(info & ED_LOWSPEED) ? 'l' : 'f',
info & 0x7f,
(info >> 7) & 0xf,
(info & ED_IN) ? "in" : "out",
(info & ED_ISO) ? "iso" : "int",
qlen,
0x03ff & (info >> 16),
info,
(info & ED_SKIP) ? " K" : "",
(ed->hwHeadP &
cpu_to_hc32(ohci, ED_H)) ?
" H" : "");
size -= temp;
next += temp;
if (seen_count < DBG_SCHED_LIMIT)
seen [seen_count++] = ed;
ed = ed->ed_next;
} else {
/* we've seen it and what's after */
temp = 0;
ed = NULL;
}
} while (ed);
temp = scnprintf (next, size, "\n");
size -= temp;
next += temp;
}
spin_unlock_irqrestore (&ohci->lock, flags);
kfree (seen);
return PAGE_SIZE - size;
}
#undef DBG_SCHED_LIMIT
static ssize_t fill_registers_buffer(struct debug_buffer *buf)
{
struct usb_hcd *hcd;
struct ohci_hcd *ohci;
struct ohci_regs __iomem *regs;
unsigned long flags;
unsigned temp, size;
char *next;
u32 rdata;
ohci = buf->ohci;
hcd = ohci_to_hcd(ohci);
regs = ohci->regs;
next = buf->page;
size = PAGE_SIZE;
spin_lock_irqsave (&ohci->lock, flags);
/* dump driver info, then registers in spec order */
ohci_dbg_sw (ohci, &next, &size,
"bus %s, device %s\n"
"%s\n"
"%s\n",
hcd->self.controller->bus->name,
dev_name(hcd->self.controller),
hcd->product_desc,
hcd_name);
if (!HCD_HW_ACCESSIBLE(hcd)) {
size -= scnprintf (next, size,
"SUSPENDED (no register access)\n");
goto done;
}
ohci_dump_status(ohci, &next, &size);
/* hcca */
if (ohci->hcca)
ohci_dbg_sw (ohci, &next, &size,
"hcca frame 0x%04x\n", ohci_frame_no(ohci));
/* other registers mostly affect frame timings */
rdata = ohci_readl (ohci, ®s->fminterval);
temp = scnprintf (next, size,
"fmintvl 0x%08x %sFSMPS=0x%04x FI=0x%04x\n",
rdata, (rdata >> 31) ? "FIT " : "",
(rdata >> 16) & 0xefff, rdata & 0xffff);
size -= temp;
next += temp;
rdata = ohci_readl (ohci, ®s->fmremaining);
temp = scnprintf (next, size, "fmremaining 0x%08x %sFR=0x%04x\n",
rdata, (rdata >> 31) ? "FRT " : "",
rdata & 0x3fff);
size -= temp;
next += temp;
rdata = ohci_readl (ohci, ®s->periodicstart);
temp = scnprintf (next, size, "periodicstart 0x%04x\n",
rdata & 0x3fff);
size -= temp;
next += temp;
rdata = ohci_readl (ohci, ®s->lsthresh);
temp = scnprintf (next, size, "lsthresh 0x%04x\n",
rdata & 0x3fff);
size -= temp;
next += temp;
temp = scnprintf (next, size, "hub poll timer %s\n",
HCD_POLL_RH(ohci_to_hcd(ohci)) ? "ON" : "off");
size -= temp;
next += temp;
/* roothub */
ohci_dump_roothub (ohci, 1, &next, &size);
done:
spin_unlock_irqrestore (&ohci->lock, flags);
return PAGE_SIZE - size;
}
static struct debug_buffer *alloc_buffer(struct ohci_hcd *ohci,
ssize_t (*fill_func)(struct debug_buffer *))
{
struct debug_buffer *buf;
buf = kzalloc(sizeof(struct debug_buffer), GFP_KERNEL);
if (buf) {
buf->ohci = ohci;
buf->fill_func = fill_func;
mutex_init(&buf->mutex);
}
return buf;
}
static int fill_buffer(struct debug_buffer *buf)
{
int ret = 0;
if (!buf->page)
buf->page = (char *)get_zeroed_page(GFP_KERNEL);
if (!buf->page) {
ret = -ENOMEM;
goto out;
}
ret = buf->fill_func(buf);
if (ret >= 0) {
buf->count = ret;
ret = 0;
}
out:
return ret;
}
static ssize_t debug_output(struct file *file, char __user *user_buf,
size_t len, loff_t *offset)
{
struct debug_buffer *buf = file->private_data;
int ret = 0;
mutex_lock(&buf->mutex);
if (buf->count == 0) {
ret = fill_buffer(buf);
if (ret != 0) {
mutex_unlock(&buf->mutex);
goto out;
}
}
mutex_unlock(&buf->mutex);
ret = simple_read_from_buffer(user_buf, len, offset,
buf->page, buf->count);
out:
return ret;
}
static int debug_close(struct inode *inode, struct file *file)
{
struct debug_buffer *buf = file->private_data;
if (buf) {
if (buf->page)
free_page((unsigned long)buf->page);
kfree(buf);
}
return 0;
}
static int debug_async_open(struct inode *inode, struct file *file)
{
file->private_data = alloc_buffer(inode->i_private, fill_async_buffer);
return file->private_data ? 0 : -ENOMEM;
}
static int debug_periodic_open(struct inode *inode, struct file *file)
{
file->private_data = alloc_buffer(inode->i_private,
fill_periodic_buffer);
return file->private_data ? 0 : -ENOMEM;
}
static int debug_registers_open(struct inode *inode, struct file *file)
{
file->private_data = alloc_buffer(inode->i_private,
fill_registers_buffer);
return file->private_data ? 0 : -ENOMEM;
}
static inline void create_debug_files (struct ohci_hcd *ohci)
{
struct usb_bus *bus = &ohci_to_hcd(ohci)->self;
ohci->debug_dir = debugfs_create_dir(bus->bus_name, ohci_debug_root);
if (!ohci->debug_dir)
goto dir_error;
ohci->debug_async = debugfs_create_file("async", S_IRUGO,
ohci->debug_dir, ohci,
&debug_async_fops);
if (!ohci->debug_async)
goto async_error;
ohci->debug_periodic = debugfs_create_file("periodic", S_IRUGO,
ohci->debug_dir, ohci,
&debug_periodic_fops);
if (!ohci->debug_periodic)
goto periodic_error;
ohci->debug_registers = debugfs_create_file("registers", S_IRUGO,
ohci->debug_dir, ohci,
&debug_registers_fops);
if (!ohci->debug_registers)
goto registers_error;
ohci_dbg (ohci, "created debug files\n");
return;
registers_error:
debugfs_remove(ohci->debug_periodic);
periodic_error:
debugfs_remove(ohci->debug_async);
async_error:
debugfs_remove(ohci->debug_dir);
dir_error:
ohci->debug_periodic = NULL;
ohci->debug_async = NULL;
ohci->debug_dir = NULL;
}
static inline void remove_debug_files (struct ohci_hcd *ohci)
{
debugfs_remove(ohci->debug_registers);
debugfs_remove(ohci->debug_periodic);
debugfs_remove(ohci->debug_async);
debugfs_remove(ohci->debug_dir);
}
#endif
/*-------------------------------------------------------------------------*/
| gpl-2.0 |
Wonfee/huawei_u9508_kernel | arch/arm/mach-omap1/lcd_dma.c | 3175 | 10920 | /*
* linux/arch/arm/mach-omap1/lcd_dma.c
*
* Extracted from arch/arm/plat-omap/dma.c
* Copyright (C) 2003 - 2008 Nokia Corporation
* Author: Juha Yrjölä <juha.yrjola@nokia.com>
* DMA channel linking for 1610 by Samuel Ortiz <samuel.ortiz@nokia.com>
* Graphics DMA and LCD DMA graphics tranformations
* by Imre Deak <imre.deak@nokia.com>
* OMAP2/3 support Copyright (C) 2004-2007 Texas Instruments, Inc.
* Merged to support both OMAP1 and OMAP2 by Tony Lindgren <tony@atomide.com>
* Some functions based on earlier dma-omap.c Copyright (C) 2001 RidgeRun, Inc.
*
* Copyright (C) 2009 Texas Instruments
* Added OMAP4 support - Santosh Shilimkar <santosh.shilimkar@ti.com>
*
* Support functions for the OMAP internal DMA channels.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <mach/lcdc.h>
#include <plat/dma.h>
int omap_lcd_dma_running(void)
{
/*
* On OMAP1510, internal LCD controller will start the transfer
* when it gets enabled, so assume DMA running if LCD enabled.
*/
if (cpu_is_omap15xx())
if (omap_readw(OMAP_LCDC_CONTROL) & OMAP_LCDC_CTRL_LCD_EN)
return 1;
/* Check if LCD DMA is running */
if (cpu_is_omap16xx())
if (omap_readw(OMAP1610_DMA_LCD_CCR) & OMAP_DMA_CCR_EN)
return 1;
return 0;
}
static struct lcd_dma_info {
spinlock_t lock;
int reserved;
void (*callback)(u16 status, void *data);
void *cb_data;
int active;
unsigned long addr, size;
int rotate, data_type, xres, yres;
int vxres;
int mirror;
int xscale, yscale;
int ext_ctrl;
int src_port;
int single_transfer;
} lcd_dma;
void omap_set_lcd_dma_b1(unsigned long addr, u16 fb_xres, u16 fb_yres,
int data_type)
{
lcd_dma.addr = addr;
lcd_dma.data_type = data_type;
lcd_dma.xres = fb_xres;
lcd_dma.yres = fb_yres;
}
EXPORT_SYMBOL(omap_set_lcd_dma_b1);
void omap_set_lcd_dma_src_port(int port)
{
lcd_dma.src_port = port;
}
void omap_set_lcd_dma_ext_controller(int external)
{
lcd_dma.ext_ctrl = external;
}
EXPORT_SYMBOL(omap_set_lcd_dma_ext_controller);
void omap_set_lcd_dma_single_transfer(int single)
{
lcd_dma.single_transfer = single;
}
EXPORT_SYMBOL(omap_set_lcd_dma_single_transfer);
void omap_set_lcd_dma_b1_rotation(int rotate)
{
if (cpu_is_omap15xx()) {
printk(KERN_ERR "DMA rotation is not supported in 1510 mode\n");
BUG();
return;
}
lcd_dma.rotate = rotate;
}
EXPORT_SYMBOL(omap_set_lcd_dma_b1_rotation);
void omap_set_lcd_dma_b1_mirror(int mirror)
{
if (cpu_is_omap15xx()) {
printk(KERN_ERR "DMA mirror is not supported in 1510 mode\n");
BUG();
}
lcd_dma.mirror = mirror;
}
EXPORT_SYMBOL(omap_set_lcd_dma_b1_mirror);
void omap_set_lcd_dma_b1_vxres(unsigned long vxres)
{
if (cpu_is_omap15xx()) {
printk(KERN_ERR "DMA virtual resulotion is not supported "
"in 1510 mode\n");
BUG();
}
lcd_dma.vxres = vxres;
}
EXPORT_SYMBOL(omap_set_lcd_dma_b1_vxres);
void omap_set_lcd_dma_b1_scale(unsigned int xscale, unsigned int yscale)
{
if (cpu_is_omap15xx()) {
printk(KERN_ERR "DMA scale is not supported in 1510 mode\n");
BUG();
}
lcd_dma.xscale = xscale;
lcd_dma.yscale = yscale;
}
EXPORT_SYMBOL(omap_set_lcd_dma_b1_scale);
static void set_b1_regs(void)
{
unsigned long top, bottom;
int es;
u16 w;
unsigned long en, fn;
long ei, fi;
unsigned long vxres;
unsigned int xscale, yscale;
switch (lcd_dma.data_type) {
case OMAP_DMA_DATA_TYPE_S8:
es = 1;
break;
case OMAP_DMA_DATA_TYPE_S16:
es = 2;
break;
case OMAP_DMA_DATA_TYPE_S32:
es = 4;
break;
default:
BUG();
return;
}
vxres = lcd_dma.vxres ? lcd_dma.vxres : lcd_dma.xres;
xscale = lcd_dma.xscale ? lcd_dma.xscale : 1;
yscale = lcd_dma.yscale ? lcd_dma.yscale : 1;
BUG_ON(vxres < lcd_dma.xres);
#define PIXADDR(x, y) (lcd_dma.addr + \
((y) * vxres * yscale + (x) * xscale) * es)
#define PIXSTEP(sx, sy, dx, dy) (PIXADDR(dx, dy) - PIXADDR(sx, sy) - es + 1)
switch (lcd_dma.rotate) {
case 0:
if (!lcd_dma.mirror) {
top = PIXADDR(0, 0);
bottom = PIXADDR(lcd_dma.xres - 1, lcd_dma.yres - 1);
/* 1510 DMA requires the bottom address to be 2 more
* than the actual last memory access location. */
if (cpu_is_omap15xx() &&
lcd_dma.data_type == OMAP_DMA_DATA_TYPE_S32)
bottom += 2;
ei = PIXSTEP(0, 0, 1, 0);
fi = PIXSTEP(lcd_dma.xres - 1, 0, 0, 1);
} else {
top = PIXADDR(lcd_dma.xres - 1, 0);
bottom = PIXADDR(0, lcd_dma.yres - 1);
ei = PIXSTEP(1, 0, 0, 0);
fi = PIXSTEP(0, 0, lcd_dma.xres - 1, 1);
}
en = lcd_dma.xres;
fn = lcd_dma.yres;
break;
case 90:
if (!lcd_dma.mirror) {
top = PIXADDR(0, lcd_dma.yres - 1);
bottom = PIXADDR(lcd_dma.xres - 1, 0);
ei = PIXSTEP(0, 1, 0, 0);
fi = PIXSTEP(0, 0, 1, lcd_dma.yres - 1);
} else {
top = PIXADDR(lcd_dma.xres - 1, lcd_dma.yres - 1);
bottom = PIXADDR(0, 0);
ei = PIXSTEP(0, 1, 0, 0);
fi = PIXSTEP(1, 0, 0, lcd_dma.yres - 1);
}
en = lcd_dma.yres;
fn = lcd_dma.xres;
break;
case 180:
if (!lcd_dma.mirror) {
top = PIXADDR(lcd_dma.xres - 1, lcd_dma.yres - 1);
bottom = PIXADDR(0, 0);
ei = PIXSTEP(1, 0, 0, 0);
fi = PIXSTEP(0, 1, lcd_dma.xres - 1, 0);
} else {
top = PIXADDR(0, lcd_dma.yres - 1);
bottom = PIXADDR(lcd_dma.xres - 1, 0);
ei = PIXSTEP(0, 0, 1, 0);
fi = PIXSTEP(lcd_dma.xres - 1, 1, 0, 0);
}
en = lcd_dma.xres;
fn = lcd_dma.yres;
break;
case 270:
if (!lcd_dma.mirror) {
top = PIXADDR(lcd_dma.xres - 1, 0);
bottom = PIXADDR(0, lcd_dma.yres - 1);
ei = PIXSTEP(0, 0, 0, 1);
fi = PIXSTEP(1, lcd_dma.yres - 1, 0, 0);
} else {
top = PIXADDR(0, 0);
bottom = PIXADDR(lcd_dma.xres - 1, lcd_dma.yres - 1);
ei = PIXSTEP(0, 0, 0, 1);
fi = PIXSTEP(0, lcd_dma.yres - 1, 1, 0);
}
en = lcd_dma.yres;
fn = lcd_dma.xres;
break;
default:
BUG();
return; /* Suppress warning about uninitialized vars */
}
if (cpu_is_omap15xx()) {
omap_writew(top >> 16, OMAP1510_DMA_LCD_TOP_F1_U);
omap_writew(top, OMAP1510_DMA_LCD_TOP_F1_L);
omap_writew(bottom >> 16, OMAP1510_DMA_LCD_BOT_F1_U);
omap_writew(bottom, OMAP1510_DMA_LCD_BOT_F1_L);
return;
}
/* 1610 regs */
omap_writew(top >> 16, OMAP1610_DMA_LCD_TOP_B1_U);
omap_writew(top, OMAP1610_DMA_LCD_TOP_B1_L);
omap_writew(bottom >> 16, OMAP1610_DMA_LCD_BOT_B1_U);
omap_writew(bottom, OMAP1610_DMA_LCD_BOT_B1_L);
omap_writew(en, OMAP1610_DMA_LCD_SRC_EN_B1);
omap_writew(fn, OMAP1610_DMA_LCD_SRC_FN_B1);
w = omap_readw(OMAP1610_DMA_LCD_CSDP);
w &= ~0x03;
w |= lcd_dma.data_type;
omap_writew(w, OMAP1610_DMA_LCD_CSDP);
w = omap_readw(OMAP1610_DMA_LCD_CTRL);
/* Always set the source port as SDRAM for now*/
w &= ~(0x03 << 6);
if (lcd_dma.callback != NULL)
w |= 1 << 1; /* Block interrupt enable */
else
w &= ~(1 << 1);
omap_writew(w, OMAP1610_DMA_LCD_CTRL);
if (!(lcd_dma.rotate || lcd_dma.mirror ||
lcd_dma.vxres || lcd_dma.xscale || lcd_dma.yscale))
return;
w = omap_readw(OMAP1610_DMA_LCD_CCR);
/* Set the double-indexed addressing mode */
w |= (0x03 << 12);
omap_writew(w, OMAP1610_DMA_LCD_CCR);
omap_writew(ei, OMAP1610_DMA_LCD_SRC_EI_B1);
omap_writew(fi >> 16, OMAP1610_DMA_LCD_SRC_FI_B1_U);
omap_writew(fi, OMAP1610_DMA_LCD_SRC_FI_B1_L);
}
static irqreturn_t lcd_dma_irq_handler(int irq, void *dev_id)
{
u16 w;
w = omap_readw(OMAP1610_DMA_LCD_CTRL);
if (unlikely(!(w & (1 << 3)))) {
printk(KERN_WARNING "Spurious LCD DMA IRQ\n");
return IRQ_NONE;
}
/* Ack the IRQ */
w |= (1 << 3);
omap_writew(w, OMAP1610_DMA_LCD_CTRL);
lcd_dma.active = 0;
if (lcd_dma.callback != NULL)
lcd_dma.callback(w, lcd_dma.cb_data);
return IRQ_HANDLED;
}
int omap_request_lcd_dma(void (*callback)(u16 status, void *data),
void *data)
{
spin_lock_irq(&lcd_dma.lock);
if (lcd_dma.reserved) {
spin_unlock_irq(&lcd_dma.lock);
printk(KERN_ERR "LCD DMA channel already reserved\n");
BUG();
return -EBUSY;
}
lcd_dma.reserved = 1;
spin_unlock_irq(&lcd_dma.lock);
lcd_dma.callback = callback;
lcd_dma.cb_data = data;
lcd_dma.active = 0;
lcd_dma.single_transfer = 0;
lcd_dma.rotate = 0;
lcd_dma.vxres = 0;
lcd_dma.mirror = 0;
lcd_dma.xscale = 0;
lcd_dma.yscale = 0;
lcd_dma.ext_ctrl = 0;
lcd_dma.src_port = 0;
return 0;
}
EXPORT_SYMBOL(omap_request_lcd_dma);
void omap_free_lcd_dma(void)
{
spin_lock(&lcd_dma.lock);
if (!lcd_dma.reserved) {
spin_unlock(&lcd_dma.lock);
printk(KERN_ERR "LCD DMA is not reserved\n");
BUG();
return;
}
if (!cpu_is_omap15xx())
omap_writew(omap_readw(OMAP1610_DMA_LCD_CCR) & ~1,
OMAP1610_DMA_LCD_CCR);
lcd_dma.reserved = 0;
spin_unlock(&lcd_dma.lock);
}
EXPORT_SYMBOL(omap_free_lcd_dma);
void omap_enable_lcd_dma(void)
{
u16 w;
/*
* Set the Enable bit only if an external controller is
* connected. Otherwise the OMAP internal controller will
* start the transfer when it gets enabled.
*/
if (cpu_is_omap15xx() || !lcd_dma.ext_ctrl)
return;
w = omap_readw(OMAP1610_DMA_LCD_CTRL);
w |= 1 << 8;
omap_writew(w, OMAP1610_DMA_LCD_CTRL);
lcd_dma.active = 1;
w = omap_readw(OMAP1610_DMA_LCD_CCR);
w |= 1 << 7;
omap_writew(w, OMAP1610_DMA_LCD_CCR);
}
EXPORT_SYMBOL(omap_enable_lcd_dma);
void omap_setup_lcd_dma(void)
{
BUG_ON(lcd_dma.active);
if (!cpu_is_omap15xx()) {
/* Set some reasonable defaults */
omap_writew(0x5440, OMAP1610_DMA_LCD_CCR);
omap_writew(0x9102, OMAP1610_DMA_LCD_CSDP);
omap_writew(0x0004, OMAP1610_DMA_LCD_LCH_CTRL);
}
set_b1_regs();
if (!cpu_is_omap15xx()) {
u16 w;
w = omap_readw(OMAP1610_DMA_LCD_CCR);
/*
* If DMA was already active set the end_prog bit to have
* the programmed register set loaded into the active
* register set.
*/
w |= 1 << 11; /* End_prog */
if (!lcd_dma.single_transfer)
w |= (3 << 8); /* Auto_init, repeat */
omap_writew(w, OMAP1610_DMA_LCD_CCR);
}
}
EXPORT_SYMBOL(omap_setup_lcd_dma);
void omap_stop_lcd_dma(void)
{
u16 w;
lcd_dma.active = 0;
if (cpu_is_omap15xx() || !lcd_dma.ext_ctrl)
return;
w = omap_readw(OMAP1610_DMA_LCD_CCR);
w &= ~(1 << 7);
omap_writew(w, OMAP1610_DMA_LCD_CCR);
w = omap_readw(OMAP1610_DMA_LCD_CTRL);
w &= ~(1 << 8);
omap_writew(w, OMAP1610_DMA_LCD_CTRL);
}
EXPORT_SYMBOL(omap_stop_lcd_dma);
static int __init omap_init_lcd_dma(void)
{
int r;
if (!cpu_class_is_omap1())
return -ENODEV;
if (cpu_is_omap16xx()) {
u16 w;
/* this would prevent OMAP sleep */
w = omap_readw(OMAP1610_DMA_LCD_CTRL);
w &= ~(1 << 8);
omap_writew(w, OMAP1610_DMA_LCD_CTRL);
}
spin_lock_init(&lcd_dma.lock);
r = request_irq(INT_DMA_LCD, lcd_dma_irq_handler, 0,
"LCD DMA", NULL);
if (r != 0)
printk(KERN_ERR "unable to request IRQ for LCD DMA "
"(error %d)\n", r);
return r;
}
arch_initcall(omap_init_lcd_dma);
| gpl-2.0 |
webos-internals/webos-linux-kernel | arch/um/kernel/skas/clone.c | 4711 | 1295 | /*
* Copyright (C) 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL
*/
#include <signal.h>
#include <sched.h>
#include <asm/unistd.h>
#include <sys/time.h>
#include "as-layout.h"
#include "kern_constants.h"
#include "ptrace_user.h"
#include "stub-data.h"
#include "sysdep/stub.h"
/*
* This is in a separate file because it needs to be compiled with any
* extraneous gcc flags (-pg, -fprofile-arcs, -ftest-coverage) disabled
*
* Use UM_KERN_PAGE_SIZE instead of PAGE_SIZE because that calls getpagesize
* on some systems.
*/
void __attribute__ ((__section__ (".__syscall_stub")))
stub_clone_handler(void)
{
struct stub_data *data = (struct stub_data *) STUB_DATA;
long err;
err = stub_syscall2(__NR_clone, CLONE_PARENT | CLONE_FILES | SIGCHLD,
STUB_DATA + UM_KERN_PAGE_SIZE / 2 - sizeof(void *));
if (err != 0)
goto out;
err = stub_syscall4(__NR_ptrace, PTRACE_TRACEME, 0, 0, 0);
if (err)
goto out;
err = stub_syscall3(__NR_setitimer, ITIMER_VIRTUAL,
(long) &data->timer, 0);
if (err)
goto out;
remap_stack(data->fd, data->offset);
goto done;
out:
/*
* save current result.
* Parent: pid;
* child: retcode of mmap already saved and it jumps around this
* assignment
*/
data->err = err;
done:
trap_myself();
}
| gpl-2.0 |
princeofgiri/ridon-kernel_xiaomi_armani | fs/cifs/netmisc.c | 4711 | 40191 | /*
* fs/cifs/netmisc.c
*
* Copyright (c) International Business Machines Corp., 2002,2008
* Author(s): Steve French (sfrench@us.ibm.com)
*
* Error mapping routines from Samba libsmb/errormap.c
* Copyright (C) Andrew Tridgell 2001
*
* 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/net.h>
#include <linux/string.h>
#include <linux/in.h>
#include <linux/ctype.h>
#include <linux/fs.h>
#include <asm/div64.h>
#include <asm/byteorder.h>
#include <linux/inet.h>
#include "cifsfs.h"
#include "cifspdu.h"
#include "cifsglob.h"
#include "cifsproto.h"
#include "smberr.h"
#include "cifs_debug.h"
#include "nterr.h"
struct smb_to_posix_error {
__u16 smb_err;
int posix_code;
};
static const struct smb_to_posix_error mapping_table_ERRDOS[] = {
{ERRbadfunc, -EINVAL},
{ERRbadfile, -ENOENT},
{ERRbadpath, -ENOTDIR},
{ERRnofids, -EMFILE},
{ERRnoaccess, -EACCES},
{ERRbadfid, -EBADF},
{ERRbadmcb, -EIO},
{ERRnomem, -ENOMEM},
{ERRbadmem, -EFAULT},
{ERRbadenv, -EFAULT},
{ERRbadformat, -EINVAL},
{ERRbadaccess, -EACCES},
{ERRbaddata, -EIO},
{ERRbaddrive, -ENXIO},
{ERRremcd, -EACCES},
{ERRdiffdevice, -EXDEV},
{ERRnofiles, -ENOENT},
{ERRwriteprot, -EROFS},
{ERRbadshare, -ETXTBSY},
{ERRlock, -EACCES},
{ERRunsup, -EINVAL},
{ERRnosuchshare, -ENXIO},
{ERRfilexists, -EEXIST},
{ERRinvparm, -EINVAL},
{ERRdiskfull, -ENOSPC},
{ERRinvname, -ENOENT},
{ERRinvlevel, -EOPNOTSUPP},
{ERRdirnotempty, -ENOTEMPTY},
{ERRnotlocked, -ENOLCK},
{ERRcancelviolation, -ENOLCK},
{ERRalreadyexists, -EEXIST},
{ERRmoredata, -EOVERFLOW},
{ERReasnotsupported, -EOPNOTSUPP},
{ErrQuota, -EDQUOT},
{ErrNotALink, -ENOLINK},
{ERRnetlogonNotStarted, -ENOPROTOOPT},
{ERRsymlink, -EOPNOTSUPP},
{ErrTooManyLinks, -EMLINK},
{0, 0}
};
static const struct smb_to_posix_error mapping_table_ERRSRV[] = {
{ERRerror, -EIO},
{ERRbadpw, -EACCES}, /* was EPERM */
{ERRbadtype, -EREMOTE},
{ERRaccess, -EACCES},
{ERRinvtid, -ENXIO},
{ERRinvnetname, -ENXIO},
{ERRinvdevice, -ENXIO},
{ERRqfull, -ENOSPC},
{ERRqtoobig, -ENOSPC},
{ERRqeof, -EIO},
{ERRinvpfid, -EBADF},
{ERRsmbcmd, -EBADRQC},
{ERRsrverror, -EIO},
{ERRbadBID, -EIO},
{ERRfilespecs, -EINVAL},
{ERRbadLink, -EIO},
{ERRbadpermits, -EINVAL},
{ERRbadPID, -ESRCH},
{ERRsetattrmode, -EINVAL},
{ERRpaused, -EHOSTDOWN},
{ERRmsgoff, -EHOSTDOWN},
{ERRnoroom, -ENOSPC},
{ERRrmuns, -EUSERS},
{ERRtimeout, -ETIME},
{ERRnoresource, -ENOBUFS},
{ERRtoomanyuids, -EUSERS},
{ERRbaduid, -EACCES},
{ERRusempx, -EIO},
{ERRusestd, -EIO},
{ERR_NOTIFY_ENUM_DIR, -ENOBUFS},
{ERRnoSuchUser, -EACCES},
/* {ERRaccountexpired, -EACCES},
{ERRbadclient, -EACCES},
{ERRbadLogonTime, -EACCES},
{ERRpasswordExpired, -EACCES},*/
{ERRaccountexpired, -EKEYEXPIRED},
{ERRbadclient, -EACCES},
{ERRbadLogonTime, -EACCES},
{ERRpasswordExpired, -EKEYEXPIRED},
{ERRnosupport, -EINVAL},
{0, 0}
};
static const struct smb_to_posix_error mapping_table_ERRHRD[] = {
{0, 0}
};
/*
* Convert a string containing text IPv4 or IPv6 address to binary form.
*
* Returns 0 on failure.
*/
static int
cifs_inet_pton(const int address_family, const char *cp, int len, void *dst)
{
int ret = 0;
/* calculate length by finding first slash or NULL */
if (address_family == AF_INET)
ret = in4_pton(cp, len, dst, '\\', NULL);
else if (address_family == AF_INET6)
ret = in6_pton(cp, len, dst , '\\', NULL);
cFYI(DBG2, "address conversion returned %d for %*.*s",
ret, len, len, cp);
if (ret > 0)
ret = 1;
return ret;
}
/*
* Try to convert a string to an IPv4 address and then attempt to convert
* it to an IPv6 address if that fails. Set the family field if either
* succeeds. If it's an IPv6 address and it has a '%' sign in it, try to
* treat the part following it as a numeric sin6_scope_id.
*
* Returns 0 on failure.
*/
int
cifs_convert_address(struct sockaddr *dst, const char *src, int len)
{
int rc, alen, slen;
const char *pct;
char scope_id[13];
struct sockaddr_in *s4 = (struct sockaddr_in *) dst;
struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) dst;
/* IPv4 address */
if (cifs_inet_pton(AF_INET, src, len, &s4->sin_addr.s_addr)) {
s4->sin_family = AF_INET;
return 1;
}
/* attempt to exclude the scope ID from the address part */
pct = memchr(src, '%', len);
alen = pct ? pct - src : len;
rc = cifs_inet_pton(AF_INET6, src, alen, &s6->sin6_addr.s6_addr);
if (!rc)
return rc;
s6->sin6_family = AF_INET6;
if (pct) {
/* grab the scope ID */
slen = len - (alen + 1);
if (slen <= 0 || slen > 12)
return 0;
memcpy(scope_id, pct + 1, slen);
scope_id[slen] = '\0';
rc = kstrtouint(scope_id, 0, &s6->sin6_scope_id);
rc = (rc == 0) ? 1 : 0;
}
return rc;
}
int
cifs_set_port(struct sockaddr *addr, const unsigned short int port)
{
switch (addr->sa_family) {
case AF_INET:
((struct sockaddr_in *)addr)->sin_port = htons(port);
break;
case AF_INET6:
((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
break;
default:
return 0;
}
return 1;
}
int
cifs_fill_sockaddr(struct sockaddr *dst, const char *src, int len,
const unsigned short int port)
{
if (!cifs_convert_address(dst, src, len))
return 0;
return cifs_set_port(dst, port);
}
/*****************************************************************************
convert a NT status code to a dos class/code
*****************************************************************************/
/* NT status -> dos error map */
static const struct {
__u8 dos_class;
__u16 dos_code;
__u32 ntstatus;
} ntstatus_to_dos_map[] = {
{
ERRDOS, ERRgeneral, NT_STATUS_UNSUCCESSFUL}, {
ERRDOS, ERRbadfunc, NT_STATUS_NOT_IMPLEMENTED}, {
ERRDOS, ERRinvlevel, NT_STATUS_INVALID_INFO_CLASS}, {
ERRDOS, 24, NT_STATUS_INFO_LENGTH_MISMATCH}, {
ERRHRD, ERRgeneral, NT_STATUS_ACCESS_VIOLATION}, {
ERRHRD, ERRgeneral, NT_STATUS_IN_PAGE_ERROR}, {
ERRHRD, ERRgeneral, NT_STATUS_PAGEFILE_QUOTA}, {
ERRDOS, ERRbadfid, NT_STATUS_INVALID_HANDLE}, {
ERRHRD, ERRgeneral, NT_STATUS_BAD_INITIAL_STACK}, {
ERRDOS, 193, NT_STATUS_BAD_INITIAL_PC}, {
ERRDOS, 87, NT_STATUS_INVALID_CID}, {
ERRHRD, ERRgeneral, NT_STATUS_TIMER_NOT_CANCELED}, {
ERRDOS, 87, NT_STATUS_INVALID_PARAMETER}, {
ERRDOS, ERRbadfile, NT_STATUS_NO_SUCH_DEVICE}, {
ERRDOS, ERRbadfile, NT_STATUS_NO_SUCH_FILE}, {
ERRDOS, ERRbadfunc, NT_STATUS_INVALID_DEVICE_REQUEST}, {
ERRDOS, 38, NT_STATUS_END_OF_FILE}, {
ERRDOS, 34, NT_STATUS_WRONG_VOLUME}, {
ERRDOS, 21, NT_STATUS_NO_MEDIA_IN_DEVICE}, {
ERRHRD, ERRgeneral, NT_STATUS_UNRECOGNIZED_MEDIA}, {
ERRDOS, 27, NT_STATUS_NONEXISTENT_SECTOR},
/* { This NT error code was 'sqashed'
from NT_STATUS_MORE_PROCESSING_REQUIRED to NT_STATUS_OK
during the session setup } */
{
ERRDOS, ERRnomem, NT_STATUS_NO_MEMORY}, {
ERRDOS, 487, NT_STATUS_CONFLICTING_ADDRESSES}, {
ERRDOS, 487, NT_STATUS_NOT_MAPPED_VIEW}, {
ERRDOS, 87, NT_STATUS_UNABLE_TO_FREE_VM}, {
ERRDOS, 87, NT_STATUS_UNABLE_TO_DELETE_SECTION}, {
ERRDOS, 2142, NT_STATUS_INVALID_SYSTEM_SERVICE}, {
ERRHRD, ERRgeneral, NT_STATUS_ILLEGAL_INSTRUCTION}, {
ERRDOS, ERRnoaccess, NT_STATUS_INVALID_LOCK_SEQUENCE}, {
ERRDOS, ERRnoaccess, NT_STATUS_INVALID_VIEW_SIZE}, {
ERRDOS, 193, NT_STATUS_INVALID_FILE_FOR_SECTION}, {
ERRDOS, ERRnoaccess, NT_STATUS_ALREADY_COMMITTED},
/* { This NT error code was 'sqashed'
from NT_STATUS_ACCESS_DENIED to NT_STATUS_TRUSTED_RELATIONSHIP_FAILURE
during the session setup } */
{
ERRDOS, ERRnoaccess, NT_STATUS_ACCESS_DENIED}, {
ERRDOS, 111, NT_STATUS_BUFFER_TOO_SMALL}, {
ERRDOS, ERRbadfid, NT_STATUS_OBJECT_TYPE_MISMATCH}, {
ERRHRD, ERRgeneral, NT_STATUS_NONCONTINUABLE_EXCEPTION}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_DISPOSITION}, {
ERRHRD, ERRgeneral, NT_STATUS_UNWIND}, {
ERRHRD, ERRgeneral, NT_STATUS_BAD_STACK}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_UNWIND_TARGET}, {
ERRDOS, 158, NT_STATUS_NOT_LOCKED}, {
ERRHRD, ERRgeneral, NT_STATUS_PARITY_ERROR}, {
ERRDOS, 487, NT_STATUS_UNABLE_TO_DECOMMIT_VM}, {
ERRDOS, 487, NT_STATUS_NOT_COMMITTED}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_PORT_ATTRIBUTES}, {
ERRHRD, ERRgeneral, NT_STATUS_PORT_MESSAGE_TOO_LONG}, {
ERRDOS, 87, NT_STATUS_INVALID_PARAMETER_MIX}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_QUOTA_LOWER}, {
ERRHRD, ERRgeneral, NT_STATUS_DISK_CORRUPT_ERROR}, {
/* mapping changed since shell does lookup on * expects FileNotFound */
ERRDOS, ERRbadfile, NT_STATUS_OBJECT_NAME_INVALID}, {
ERRDOS, ERRbadfile, NT_STATUS_OBJECT_NAME_NOT_FOUND}, {
ERRDOS, ERRalreadyexists, NT_STATUS_OBJECT_NAME_COLLISION}, {
ERRHRD, ERRgeneral, NT_STATUS_HANDLE_NOT_WAITABLE}, {
ERRDOS, ERRbadfid, NT_STATUS_PORT_DISCONNECTED}, {
ERRHRD, ERRgeneral, NT_STATUS_DEVICE_ALREADY_ATTACHED}, {
ERRDOS, 161, NT_STATUS_OBJECT_PATH_INVALID}, {
ERRDOS, ERRbadpath, NT_STATUS_OBJECT_PATH_NOT_FOUND}, {
ERRDOS, 161, NT_STATUS_OBJECT_PATH_SYNTAX_BAD}, {
ERRHRD, ERRgeneral, NT_STATUS_DATA_OVERRUN}, {
ERRHRD, ERRgeneral, NT_STATUS_DATA_LATE_ERROR}, {
ERRDOS, 23, NT_STATUS_DATA_ERROR}, {
ERRDOS, 23, NT_STATUS_CRC_ERROR}, {
ERRDOS, ERRnomem, NT_STATUS_SECTION_TOO_BIG}, {
ERRDOS, ERRnoaccess, NT_STATUS_PORT_CONNECTION_REFUSED}, {
ERRDOS, ERRbadfid, NT_STATUS_INVALID_PORT_HANDLE}, {
ERRDOS, ERRbadshare, NT_STATUS_SHARING_VIOLATION}, {
ERRHRD, ERRgeneral, NT_STATUS_QUOTA_EXCEEDED}, {
ERRDOS, 87, NT_STATUS_INVALID_PAGE_PROTECTION}, {
ERRDOS, 288, NT_STATUS_MUTANT_NOT_OWNED}, {
ERRDOS, 298, NT_STATUS_SEMAPHORE_LIMIT_EXCEEDED}, {
ERRDOS, 87, NT_STATUS_PORT_ALREADY_SET}, {
ERRDOS, 87, NT_STATUS_SECTION_NOT_IMAGE}, {
ERRDOS, 156, NT_STATUS_SUSPEND_COUNT_EXCEEDED}, {
ERRDOS, ERRnoaccess, NT_STATUS_THREAD_IS_TERMINATING}, {
ERRDOS, 87, NT_STATUS_BAD_WORKING_SET_LIMIT}, {
ERRDOS, 87, NT_STATUS_INCOMPATIBLE_FILE_MAP}, {
ERRDOS, 87, NT_STATUS_SECTION_PROTECTION}, {
ERRDOS, ERReasnotsupported, NT_STATUS_EAS_NOT_SUPPORTED}, {
ERRDOS, 255, NT_STATUS_EA_TOO_LARGE}, {
ERRHRD, ERRgeneral, NT_STATUS_NONEXISTENT_EA_ENTRY}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_EAS_ON_FILE}, {
ERRHRD, ERRgeneral, NT_STATUS_EA_CORRUPT_ERROR}, {
ERRDOS, ERRlock, NT_STATUS_FILE_LOCK_CONFLICT}, {
ERRDOS, ERRlock, NT_STATUS_LOCK_NOT_GRANTED}, {
ERRDOS, ERRbadfile, NT_STATUS_DELETE_PENDING}, {
ERRDOS, ERRunsup, NT_STATUS_CTL_FILE_NOT_SUPPORTED}, {
ERRHRD, ERRgeneral, NT_STATUS_UNKNOWN_REVISION}, {
ERRHRD, ERRgeneral, NT_STATUS_REVISION_MISMATCH}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_OWNER}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_PRIMARY_GROUP}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_IMPERSONATION_TOKEN}, {
ERRHRD, ERRgeneral, NT_STATUS_CANT_DISABLE_MANDATORY}, {
ERRDOS, 2215, NT_STATUS_NO_LOGON_SERVERS}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_SUCH_LOGON_SESSION}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_SUCH_PRIVILEGE}, {
ERRDOS, ERRnoaccess, NT_STATUS_PRIVILEGE_NOT_HELD}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_ACCOUNT_NAME}, {
ERRHRD, ERRgeneral, NT_STATUS_USER_EXISTS},
/* { This NT error code was 'sqashed'
from NT_STATUS_NO_SUCH_USER to NT_STATUS_LOGON_FAILURE
during the session setup } */
{
ERRDOS, ERRnoaccess, NT_STATUS_NO_SUCH_USER}, { /* could map to 2238 */
ERRHRD, ERRgeneral, NT_STATUS_GROUP_EXISTS}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_SUCH_GROUP}, {
ERRHRD, ERRgeneral, NT_STATUS_MEMBER_IN_GROUP}, {
ERRHRD, ERRgeneral, NT_STATUS_MEMBER_NOT_IN_GROUP}, {
ERRHRD, ERRgeneral, NT_STATUS_LAST_ADMIN},
/* { This NT error code was 'sqashed'
from NT_STATUS_WRONG_PASSWORD to NT_STATUS_LOGON_FAILURE
during the session setup } */
{
ERRSRV, ERRbadpw, NT_STATUS_WRONG_PASSWORD}, {
ERRHRD, ERRgeneral, NT_STATUS_ILL_FORMED_PASSWORD}, {
ERRHRD, ERRgeneral, NT_STATUS_PASSWORD_RESTRICTION}, {
ERRDOS, ERRnoaccess, NT_STATUS_LOGON_FAILURE}, {
ERRHRD, ERRgeneral, NT_STATUS_ACCOUNT_RESTRICTION}, {
ERRSRV, ERRbadLogonTime, NT_STATUS_INVALID_LOGON_HOURS}, {
ERRSRV, ERRbadclient, NT_STATUS_INVALID_WORKSTATION}, {
ERRSRV, ERRpasswordExpired, NT_STATUS_PASSWORD_EXPIRED}, {
ERRSRV, ERRaccountexpired, NT_STATUS_ACCOUNT_DISABLED}, {
ERRHRD, ERRgeneral, NT_STATUS_NONE_MAPPED}, {
ERRHRD, ERRgeneral, NT_STATUS_TOO_MANY_LUIDS_REQUESTED}, {
ERRHRD, ERRgeneral, NT_STATUS_LUIDS_EXHAUSTED}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_SUB_AUTHORITY}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_ACL}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_SID}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_SECURITY_DESCR}, {
ERRDOS, 127, NT_STATUS_PROCEDURE_NOT_FOUND}, {
ERRDOS, 193, NT_STATUS_INVALID_IMAGE_FORMAT}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_TOKEN}, {
ERRHRD, ERRgeneral, NT_STATUS_BAD_INHERITANCE_ACL}, {
ERRDOS, 158, NT_STATUS_RANGE_NOT_LOCKED}, {
ERRDOS, 112, NT_STATUS_DISK_FULL}, {
ERRHRD, ERRgeneral, NT_STATUS_SERVER_DISABLED}, {
ERRHRD, ERRgeneral, NT_STATUS_SERVER_NOT_DISABLED}, {
ERRDOS, 68, NT_STATUS_TOO_MANY_GUIDS_REQUESTED}, {
ERRDOS, 259, NT_STATUS_GUIDS_EXHAUSTED}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_ID_AUTHORITY}, {
ERRDOS, 259, NT_STATUS_AGENTS_EXHAUSTED}, {
ERRDOS, 154, NT_STATUS_INVALID_VOLUME_LABEL}, {
ERRDOS, 14, NT_STATUS_SECTION_NOT_EXTENDED}, {
ERRDOS, 487, NT_STATUS_NOT_MAPPED_DATA}, {
ERRHRD, ERRgeneral, NT_STATUS_RESOURCE_DATA_NOT_FOUND}, {
ERRHRD, ERRgeneral, NT_STATUS_RESOURCE_TYPE_NOT_FOUND}, {
ERRHRD, ERRgeneral, NT_STATUS_RESOURCE_NAME_NOT_FOUND}, {
ERRHRD, ERRgeneral, NT_STATUS_ARRAY_BOUNDS_EXCEEDED}, {
ERRHRD, ERRgeneral, NT_STATUS_FLOAT_DENORMAL_OPERAND}, {
ERRHRD, ERRgeneral, NT_STATUS_FLOAT_DIVIDE_BY_ZERO}, {
ERRHRD, ERRgeneral, NT_STATUS_FLOAT_INEXACT_RESULT}, {
ERRHRD, ERRgeneral, NT_STATUS_FLOAT_INVALID_OPERATION}, {
ERRHRD, ERRgeneral, NT_STATUS_FLOAT_OVERFLOW}, {
ERRHRD, ERRgeneral, NT_STATUS_FLOAT_STACK_CHECK}, {
ERRHRD, ERRgeneral, NT_STATUS_FLOAT_UNDERFLOW}, {
ERRHRD, ERRgeneral, NT_STATUS_INTEGER_DIVIDE_BY_ZERO}, {
ERRDOS, 534, NT_STATUS_INTEGER_OVERFLOW}, {
ERRHRD, ERRgeneral, NT_STATUS_PRIVILEGED_INSTRUCTION}, {
ERRDOS, ERRnomem, NT_STATUS_TOO_MANY_PAGING_FILES}, {
ERRHRD, ERRgeneral, NT_STATUS_FILE_INVALID}, {
ERRHRD, ERRgeneral, NT_STATUS_ALLOTTED_SPACE_EXCEEDED},
/* { This NT error code was 'sqashed'
from NT_STATUS_INSUFFICIENT_RESOURCES to
NT_STATUS_INSUFF_SERVER_RESOURCES during the session setup } */
{
ERRDOS, ERRnomem, NT_STATUS_INSUFFICIENT_RESOURCES}, {
ERRDOS, ERRbadpath, NT_STATUS_DFS_EXIT_PATH_FOUND}, {
ERRDOS, 23, NT_STATUS_DEVICE_DATA_ERROR}, {
ERRHRD, ERRgeneral, NT_STATUS_DEVICE_NOT_CONNECTED}, {
ERRDOS, 21, NT_STATUS_DEVICE_POWER_FAILURE}, {
ERRDOS, 487, NT_STATUS_FREE_VM_NOT_AT_BASE}, {
ERRDOS, 487, NT_STATUS_MEMORY_NOT_ALLOCATED}, {
ERRHRD, ERRgeneral, NT_STATUS_WORKING_SET_QUOTA}, {
ERRDOS, 19, NT_STATUS_MEDIA_WRITE_PROTECTED}, {
ERRDOS, 21, NT_STATUS_DEVICE_NOT_READY}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_GROUP_ATTRIBUTES}, {
ERRHRD, ERRgeneral, NT_STATUS_BAD_IMPERSONATION_LEVEL}, {
ERRHRD, ERRgeneral, NT_STATUS_CANT_OPEN_ANONYMOUS}, {
ERRHRD, ERRgeneral, NT_STATUS_BAD_VALIDATION_CLASS}, {
ERRHRD, ERRgeneral, NT_STATUS_BAD_TOKEN_TYPE}, {
ERRDOS, 87, NT_STATUS_BAD_MASTER_BOOT_RECORD}, {
ERRHRD, ERRgeneral, NT_STATUS_INSTRUCTION_MISALIGNMENT}, {
ERRDOS, ERRpipebusy, NT_STATUS_INSTANCE_NOT_AVAILABLE}, {
ERRDOS, ERRpipebusy, NT_STATUS_PIPE_NOT_AVAILABLE}, {
ERRDOS, ERRbadpipe, NT_STATUS_INVALID_PIPE_STATE}, {
ERRDOS, ERRpipebusy, NT_STATUS_PIPE_BUSY}, {
ERRDOS, ERRbadfunc, NT_STATUS_ILLEGAL_FUNCTION}, {
ERRDOS, ERRnotconnected, NT_STATUS_PIPE_DISCONNECTED}, {
ERRDOS, ERRpipeclosing, NT_STATUS_PIPE_CLOSING}, {
ERRHRD, ERRgeneral, NT_STATUS_PIPE_CONNECTED}, {
ERRHRD, ERRgeneral, NT_STATUS_PIPE_LISTENING}, {
ERRDOS, ERRbadpipe, NT_STATUS_INVALID_READ_MODE}, {
ERRDOS, 121, NT_STATUS_IO_TIMEOUT}, {
ERRDOS, 38, NT_STATUS_FILE_FORCED_CLOSED}, {
ERRHRD, ERRgeneral, NT_STATUS_PROFILING_NOT_STARTED}, {
ERRHRD, ERRgeneral, NT_STATUS_PROFILING_NOT_STOPPED}, {
ERRHRD, ERRgeneral, NT_STATUS_COULD_NOT_INTERPRET}, {
ERRDOS, ERRnoaccess, NT_STATUS_FILE_IS_A_DIRECTORY}, {
ERRDOS, ERRunsup, NT_STATUS_NOT_SUPPORTED}, {
ERRDOS, 51, NT_STATUS_REMOTE_NOT_LISTENING}, {
ERRDOS, 52, NT_STATUS_DUPLICATE_NAME}, {
ERRDOS, 53, NT_STATUS_BAD_NETWORK_PATH}, {
ERRDOS, 54, NT_STATUS_NETWORK_BUSY}, {
ERRDOS, 55, NT_STATUS_DEVICE_DOES_NOT_EXIST}, {
ERRDOS, 56, NT_STATUS_TOO_MANY_COMMANDS}, {
ERRDOS, 57, NT_STATUS_ADAPTER_HARDWARE_ERROR}, {
ERRDOS, 58, NT_STATUS_INVALID_NETWORK_RESPONSE}, {
ERRDOS, 59, NT_STATUS_UNEXPECTED_NETWORK_ERROR}, {
ERRDOS, 60, NT_STATUS_BAD_REMOTE_ADAPTER}, {
ERRDOS, 61, NT_STATUS_PRINT_QUEUE_FULL}, {
ERRDOS, 62, NT_STATUS_NO_SPOOL_SPACE}, {
ERRDOS, 63, NT_STATUS_PRINT_CANCELLED}, {
ERRDOS, 64, NT_STATUS_NETWORK_NAME_DELETED}, {
ERRDOS, 65, NT_STATUS_NETWORK_ACCESS_DENIED}, {
ERRDOS, 66, NT_STATUS_BAD_DEVICE_TYPE}, {
ERRDOS, ERRnosuchshare, NT_STATUS_BAD_NETWORK_NAME}, {
ERRDOS, 68, NT_STATUS_TOO_MANY_NAMES}, {
ERRDOS, 69, NT_STATUS_TOO_MANY_SESSIONS}, {
ERRDOS, 70, NT_STATUS_SHARING_PAUSED}, {
ERRDOS, 71, NT_STATUS_REQUEST_NOT_ACCEPTED}, {
ERRDOS, 72, NT_STATUS_REDIRECTOR_PAUSED}, {
ERRDOS, 88, NT_STATUS_NET_WRITE_FAULT}, {
ERRHRD, ERRgeneral, NT_STATUS_PROFILING_AT_LIMIT}, {
ERRDOS, ERRdiffdevice, NT_STATUS_NOT_SAME_DEVICE}, {
ERRDOS, ERRnoaccess, NT_STATUS_FILE_RENAMED}, {
ERRDOS, 240, NT_STATUS_VIRTUAL_CIRCUIT_CLOSED}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_SECURITY_ON_OBJECT}, {
ERRHRD, ERRgeneral, NT_STATUS_CANT_WAIT}, {
ERRDOS, ERRpipeclosing, NT_STATUS_PIPE_EMPTY}, {
ERRHRD, ERRgeneral, NT_STATUS_CANT_ACCESS_DOMAIN_INFO}, {
ERRHRD, ERRgeneral, NT_STATUS_CANT_TERMINATE_SELF}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_SERVER_STATE}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_DOMAIN_STATE}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_DOMAIN_ROLE}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_SUCH_DOMAIN}, {
ERRHRD, ERRgeneral, NT_STATUS_DOMAIN_EXISTS}, {
ERRHRD, ERRgeneral, NT_STATUS_DOMAIN_LIMIT_EXCEEDED}, {
ERRDOS, 300, NT_STATUS_OPLOCK_NOT_GRANTED}, {
ERRDOS, 301, NT_STATUS_INVALID_OPLOCK_PROTOCOL}, {
ERRHRD, ERRgeneral, NT_STATUS_INTERNAL_DB_CORRUPTION}, {
ERRHRD, ERRgeneral, NT_STATUS_INTERNAL_ERROR}, {
ERRHRD, ERRgeneral, NT_STATUS_GENERIC_NOT_MAPPED}, {
ERRHRD, ERRgeneral, NT_STATUS_BAD_DESCRIPTOR_FORMAT}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_USER_BUFFER}, {
ERRHRD, ERRgeneral, NT_STATUS_UNEXPECTED_IO_ERROR}, {
ERRHRD, ERRgeneral, NT_STATUS_UNEXPECTED_MM_CREATE_ERR}, {
ERRHRD, ERRgeneral, NT_STATUS_UNEXPECTED_MM_MAP_ERROR}, {
ERRHRD, ERRgeneral, NT_STATUS_UNEXPECTED_MM_EXTEND_ERR}, {
ERRHRD, ERRgeneral, NT_STATUS_NOT_LOGON_PROCESS}, {
ERRHRD, ERRgeneral, NT_STATUS_LOGON_SESSION_EXISTS}, {
ERRDOS, 87, NT_STATUS_INVALID_PARAMETER_1}, {
ERRDOS, 87, NT_STATUS_INVALID_PARAMETER_2}, {
ERRDOS, 87, NT_STATUS_INVALID_PARAMETER_3}, {
ERRDOS, 87, NT_STATUS_INVALID_PARAMETER_4}, {
ERRDOS, 87, NT_STATUS_INVALID_PARAMETER_5}, {
ERRDOS, 87, NT_STATUS_INVALID_PARAMETER_6}, {
ERRDOS, 87, NT_STATUS_INVALID_PARAMETER_7}, {
ERRDOS, 87, NT_STATUS_INVALID_PARAMETER_8}, {
ERRDOS, 87, NT_STATUS_INVALID_PARAMETER_9}, {
ERRDOS, 87, NT_STATUS_INVALID_PARAMETER_10}, {
ERRDOS, 87, NT_STATUS_INVALID_PARAMETER_11}, {
ERRDOS, 87, NT_STATUS_INVALID_PARAMETER_12}, {
ERRDOS, ERRbadpath, NT_STATUS_REDIRECTOR_NOT_STARTED}, {
ERRHRD, ERRgeneral, NT_STATUS_REDIRECTOR_STARTED}, {
ERRHRD, ERRgeneral, NT_STATUS_STACK_OVERFLOW}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_SUCH_PACKAGE}, {
ERRHRD, ERRgeneral, NT_STATUS_BAD_FUNCTION_TABLE}, {
ERRDOS, 203, 0xc0000100}, {
ERRDOS, 145, NT_STATUS_DIRECTORY_NOT_EMPTY}, {
ERRHRD, ERRgeneral, NT_STATUS_FILE_CORRUPT_ERROR}, {
ERRDOS, 267, NT_STATUS_NOT_A_DIRECTORY}, {
ERRHRD, ERRgeneral, NT_STATUS_BAD_LOGON_SESSION_STATE}, {
ERRHRD, ERRgeneral, NT_STATUS_LOGON_SESSION_COLLISION}, {
ERRDOS, 206, NT_STATUS_NAME_TOO_LONG}, {
ERRDOS, 2401, NT_STATUS_FILES_OPEN}, {
ERRDOS, 2404, NT_STATUS_CONNECTION_IN_USE}, {
ERRHRD, ERRgeneral, NT_STATUS_MESSAGE_NOT_FOUND}, {
ERRDOS, ERRnoaccess, NT_STATUS_PROCESS_IS_TERMINATING}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_LOGON_TYPE}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_GUID_TRANSLATION}, {
ERRHRD, ERRgeneral, NT_STATUS_CANNOT_IMPERSONATE}, {
ERRHRD, ERRgeneral, NT_STATUS_IMAGE_ALREADY_LOADED}, {
ERRHRD, ERRgeneral, NT_STATUS_ABIOS_NOT_PRESENT}, {
ERRHRD, ERRgeneral, NT_STATUS_ABIOS_LID_NOT_EXIST}, {
ERRHRD, ERRgeneral, NT_STATUS_ABIOS_LID_ALREADY_OWNED}, {
ERRHRD, ERRgeneral, NT_STATUS_ABIOS_NOT_LID_OWNER}, {
ERRHRD, ERRgeneral, NT_STATUS_ABIOS_INVALID_COMMAND}, {
ERRHRD, ERRgeneral, NT_STATUS_ABIOS_INVALID_LID}, {
ERRHRD, ERRgeneral, NT_STATUS_ABIOS_SELECTOR_NOT_AVAILABLE}, {
ERRHRD, ERRgeneral, NT_STATUS_ABIOS_INVALID_SELECTOR}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_LDT}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_LDT_SIZE}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_LDT_OFFSET}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_LDT_DESCRIPTOR}, {
ERRDOS, 193, NT_STATUS_INVALID_IMAGE_NE_FORMAT}, {
ERRHRD, ERRgeneral, NT_STATUS_RXACT_INVALID_STATE}, {
ERRHRD, ERRgeneral, NT_STATUS_RXACT_COMMIT_FAILURE}, {
ERRHRD, ERRgeneral, NT_STATUS_MAPPED_FILE_SIZE_ZERO}, {
ERRDOS, ERRnofids, NT_STATUS_TOO_MANY_OPENED_FILES}, {
ERRHRD, ERRgeneral, NT_STATUS_CANCELLED}, {
ERRDOS, ERRnoaccess, NT_STATUS_CANNOT_DELETE}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_COMPUTER_NAME}, {
ERRDOS, ERRnoaccess, NT_STATUS_FILE_DELETED}, {
ERRHRD, ERRgeneral, NT_STATUS_SPECIAL_ACCOUNT}, {
ERRHRD, ERRgeneral, NT_STATUS_SPECIAL_GROUP}, {
ERRHRD, ERRgeneral, NT_STATUS_SPECIAL_USER}, {
ERRHRD, ERRgeneral, NT_STATUS_MEMBERS_PRIMARY_GROUP}, {
ERRDOS, ERRbadfid, NT_STATUS_FILE_CLOSED}, {
ERRHRD, ERRgeneral, NT_STATUS_TOO_MANY_THREADS}, {
ERRHRD, ERRgeneral, NT_STATUS_THREAD_NOT_IN_PROCESS}, {
ERRHRD, ERRgeneral, NT_STATUS_TOKEN_ALREADY_IN_USE}, {
ERRHRD, ERRgeneral, NT_STATUS_PAGEFILE_QUOTA_EXCEEDED}, {
ERRHRD, ERRgeneral, NT_STATUS_COMMITMENT_LIMIT}, {
ERRDOS, 193, NT_STATUS_INVALID_IMAGE_LE_FORMAT}, {
ERRDOS, 193, NT_STATUS_INVALID_IMAGE_NOT_MZ}, {
ERRDOS, 193, NT_STATUS_INVALID_IMAGE_PROTECT}, {
ERRDOS, 193, NT_STATUS_INVALID_IMAGE_WIN_16}, {
ERRHRD, ERRgeneral, NT_STATUS_LOGON_SERVER_CONFLICT}, {
ERRHRD, ERRgeneral, NT_STATUS_TIME_DIFFERENCE_AT_DC}, {
ERRHRD, ERRgeneral, NT_STATUS_SYNCHRONIZATION_REQUIRED}, {
ERRDOS, 126, NT_STATUS_DLL_NOT_FOUND}, {
ERRHRD, ERRgeneral, NT_STATUS_OPEN_FAILED}, {
ERRHRD, ERRgeneral, NT_STATUS_IO_PRIVILEGE_FAILED}, {
ERRDOS, 182, NT_STATUS_ORDINAL_NOT_FOUND}, {
ERRDOS, 127, NT_STATUS_ENTRYPOINT_NOT_FOUND}, {
ERRHRD, ERRgeneral, NT_STATUS_CONTROL_C_EXIT}, {
ERRDOS, 64, NT_STATUS_LOCAL_DISCONNECT}, {
ERRDOS, 64, NT_STATUS_REMOTE_DISCONNECT}, {
ERRDOS, 51, NT_STATUS_REMOTE_RESOURCES}, {
ERRDOS, 59, NT_STATUS_LINK_FAILED}, {
ERRDOS, 59, NT_STATUS_LINK_TIMEOUT}, {
ERRDOS, 59, NT_STATUS_INVALID_CONNECTION}, {
ERRDOS, 59, NT_STATUS_INVALID_ADDRESS}, {
ERRHRD, ERRgeneral, NT_STATUS_DLL_INIT_FAILED}, {
ERRHRD, ERRgeneral, NT_STATUS_MISSING_SYSTEMFILE}, {
ERRHRD, ERRgeneral, NT_STATUS_UNHANDLED_EXCEPTION}, {
ERRHRD, ERRgeneral, NT_STATUS_APP_INIT_FAILURE}, {
ERRHRD, ERRgeneral, NT_STATUS_PAGEFILE_CREATE_FAILED}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_PAGEFILE}, {
ERRDOS, 124, NT_STATUS_INVALID_LEVEL}, {
ERRDOS, 86, NT_STATUS_WRONG_PASSWORD_CORE}, {
ERRHRD, ERRgeneral, NT_STATUS_ILLEGAL_FLOAT_CONTEXT}, {
ERRDOS, 109, NT_STATUS_PIPE_BROKEN}, {
ERRHRD, ERRgeneral, NT_STATUS_REGISTRY_CORRUPT}, {
ERRHRD, ERRgeneral, NT_STATUS_REGISTRY_IO_FAILED}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_EVENT_PAIR}, {
ERRHRD, ERRgeneral, NT_STATUS_UNRECOGNIZED_VOLUME}, {
ERRHRD, ERRgeneral, NT_STATUS_SERIAL_NO_DEVICE_INITED}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_SUCH_ALIAS}, {
ERRHRD, ERRgeneral, NT_STATUS_MEMBER_NOT_IN_ALIAS}, {
ERRHRD, ERRgeneral, NT_STATUS_MEMBER_IN_ALIAS}, {
ERRHRD, ERRgeneral, NT_STATUS_ALIAS_EXISTS}, {
ERRHRD, ERRgeneral, NT_STATUS_LOGON_NOT_GRANTED}, {
ERRHRD, ERRgeneral, NT_STATUS_TOO_MANY_SECRETS}, {
ERRHRD, ERRgeneral, NT_STATUS_SECRET_TOO_LONG}, {
ERRHRD, ERRgeneral, NT_STATUS_INTERNAL_DB_ERROR}, {
ERRHRD, ERRgeneral, NT_STATUS_FULLSCREEN_MODE}, {
ERRHRD, ERRgeneral, NT_STATUS_TOO_MANY_CONTEXT_IDS}, {
ERRDOS, ERRnoaccess, NT_STATUS_LOGON_TYPE_NOT_GRANTED}, {
ERRHRD, ERRgeneral, NT_STATUS_NOT_REGISTRY_FILE}, {
ERRHRD, ERRgeneral, NT_STATUS_NT_CROSS_ENCRYPTION_REQUIRED}, {
ERRHRD, ERRgeneral, NT_STATUS_DOMAIN_CTRLR_CONFIG_ERROR}, {
ERRHRD, ERRgeneral, NT_STATUS_FT_MISSING_MEMBER}, {
ERRHRD, ERRgeneral, NT_STATUS_ILL_FORMED_SERVICE_ENTRY}, {
ERRHRD, ERRgeneral, NT_STATUS_ILLEGAL_CHARACTER}, {
ERRHRD, ERRgeneral, NT_STATUS_UNMAPPABLE_CHARACTER}, {
ERRHRD, ERRgeneral, NT_STATUS_UNDEFINED_CHARACTER}, {
ERRHRD, ERRgeneral, NT_STATUS_FLOPPY_VOLUME}, {
ERRHRD, ERRgeneral, NT_STATUS_FLOPPY_ID_MARK_NOT_FOUND}, {
ERRHRD, ERRgeneral, NT_STATUS_FLOPPY_WRONG_CYLINDER}, {
ERRHRD, ERRgeneral, NT_STATUS_FLOPPY_UNKNOWN_ERROR}, {
ERRHRD, ERRgeneral, NT_STATUS_FLOPPY_BAD_REGISTERS}, {
ERRHRD, ERRgeneral, NT_STATUS_DISK_RECALIBRATE_FAILED}, {
ERRHRD, ERRgeneral, NT_STATUS_DISK_OPERATION_FAILED}, {
ERRHRD, ERRgeneral, NT_STATUS_DISK_RESET_FAILED}, {
ERRHRD, ERRgeneral, NT_STATUS_SHARED_IRQ_BUSY}, {
ERRHRD, ERRgeneral, NT_STATUS_FT_ORPHANING}, {
ERRHRD, ERRgeneral, 0xc000016e}, {
ERRHRD, ERRgeneral, 0xc000016f}, {
ERRHRD, ERRgeneral, 0xc0000170}, {
ERRHRD, ERRgeneral, 0xc0000171}, {
ERRHRD, ERRgeneral, NT_STATUS_PARTITION_FAILURE}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_BLOCK_LENGTH}, {
ERRHRD, ERRgeneral, NT_STATUS_DEVICE_NOT_PARTITIONED}, {
ERRHRD, ERRgeneral, NT_STATUS_UNABLE_TO_LOCK_MEDIA}, {
ERRHRD, ERRgeneral, NT_STATUS_UNABLE_TO_UNLOAD_MEDIA}, {
ERRHRD, ERRgeneral, NT_STATUS_EOM_OVERFLOW}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_MEDIA}, {
ERRHRD, ERRgeneral, 0xc0000179}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_SUCH_MEMBER}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_MEMBER}, {
ERRHRD, ERRgeneral, NT_STATUS_KEY_DELETED}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_LOG_SPACE}, {
ERRHRD, ERRgeneral, NT_STATUS_TOO_MANY_SIDS}, {
ERRHRD, ERRgeneral, NT_STATUS_LM_CROSS_ENCRYPTION_REQUIRED}, {
ERRHRD, ERRgeneral, NT_STATUS_KEY_HAS_CHILDREN}, {
ERRHRD, ERRgeneral, NT_STATUS_CHILD_MUST_BE_VOLATILE}, {
ERRDOS, 87, NT_STATUS_DEVICE_CONFIGURATION_ERROR}, {
ERRHRD, ERRgeneral, NT_STATUS_DRIVER_INTERNAL_ERROR}, {
ERRDOS, 22, NT_STATUS_INVALID_DEVICE_STATE}, {
ERRHRD, ERRgeneral, NT_STATUS_IO_DEVICE_ERROR}, {
ERRHRD, ERRgeneral, NT_STATUS_DEVICE_PROTOCOL_ERROR}, {
ERRHRD, ERRgeneral, NT_STATUS_BACKUP_CONTROLLER}, {
ERRHRD, ERRgeneral, NT_STATUS_LOG_FILE_FULL}, {
ERRDOS, 19, NT_STATUS_TOO_LATE}, {
ERRDOS, ERRnoaccess, NT_STATUS_NO_TRUST_LSA_SECRET},
/* { This NT error code was 'sqashed'
from NT_STATUS_NO_TRUST_SAM_ACCOUNT to
NT_STATUS_TRUSTED_RELATIONSHIP_FAILURE during the session setup } */
{
ERRDOS, ERRnoaccess, NT_STATUS_NO_TRUST_SAM_ACCOUNT}, {
ERRDOS, ERRnoaccess, NT_STATUS_TRUSTED_DOMAIN_FAILURE}, {
ERRDOS, ERRnoaccess, NT_STATUS_TRUSTED_RELATIONSHIP_FAILURE}, {
ERRHRD, ERRgeneral, NT_STATUS_EVENTLOG_FILE_CORRUPT}, {
ERRHRD, ERRgeneral, NT_STATUS_EVENTLOG_CANT_START}, {
ERRDOS, ERRnoaccess, NT_STATUS_TRUST_FAILURE}, {
ERRHRD, ERRgeneral, NT_STATUS_MUTANT_LIMIT_EXCEEDED}, {
ERRDOS, ERRnetlogonNotStarted, NT_STATUS_NETLOGON_NOT_STARTED}, {
ERRSRV, ERRaccountexpired, NT_STATUS_ACCOUNT_EXPIRED}, {
ERRHRD, ERRgeneral, NT_STATUS_POSSIBLE_DEADLOCK}, {
ERRHRD, ERRgeneral, NT_STATUS_NETWORK_CREDENTIAL_CONFLICT}, {
ERRHRD, ERRgeneral, NT_STATUS_REMOTE_SESSION_LIMIT}, {
ERRHRD, ERRgeneral, NT_STATUS_EVENTLOG_FILE_CHANGED}, {
ERRDOS, ERRnoaccess, NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT}, {
ERRDOS, ERRnoaccess, NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT}, {
ERRDOS, ERRnoaccess, NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT},
/* { This NT error code was 'sqashed'
from NT_STATUS_DOMAIN_TRUST_INCONSISTENT to NT_STATUS_LOGON_FAILURE
during the session setup } */
{
ERRDOS, ERRnoaccess, NT_STATUS_DOMAIN_TRUST_INCONSISTENT}, {
ERRHRD, ERRgeneral, NT_STATUS_FS_DRIVER_REQUIRED}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_USER_SESSION_KEY}, {
ERRDOS, 59, NT_STATUS_USER_SESSION_DELETED}, {
ERRHRD, ERRgeneral, NT_STATUS_RESOURCE_LANG_NOT_FOUND}, {
ERRDOS, ERRnomem, NT_STATUS_INSUFF_SERVER_RESOURCES}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_BUFFER_SIZE}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_ADDRESS_COMPONENT}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_ADDRESS_WILDCARD}, {
ERRDOS, 68, NT_STATUS_TOO_MANY_ADDRESSES}, {
ERRDOS, 52, NT_STATUS_ADDRESS_ALREADY_EXISTS}, {
ERRDOS, 64, NT_STATUS_ADDRESS_CLOSED}, {
ERRDOS, 64, NT_STATUS_CONNECTION_DISCONNECTED}, {
ERRDOS, 64, NT_STATUS_CONNECTION_RESET}, {
ERRDOS, 68, NT_STATUS_TOO_MANY_NODES}, {
ERRDOS, 59, NT_STATUS_TRANSACTION_ABORTED}, {
ERRDOS, 59, NT_STATUS_TRANSACTION_TIMED_OUT}, {
ERRDOS, 59, NT_STATUS_TRANSACTION_NO_RELEASE}, {
ERRDOS, 59, NT_STATUS_TRANSACTION_NO_MATCH}, {
ERRDOS, 59, NT_STATUS_TRANSACTION_RESPONDED}, {
ERRDOS, 59, NT_STATUS_TRANSACTION_INVALID_ID}, {
ERRDOS, 59, NT_STATUS_TRANSACTION_INVALID_TYPE}, {
ERRDOS, ERRunsup, NT_STATUS_NOT_SERVER_SESSION}, {
ERRDOS, ERRunsup, NT_STATUS_NOT_CLIENT_SESSION}, {
ERRHRD, ERRgeneral, NT_STATUS_CANNOT_LOAD_REGISTRY_FILE}, {
ERRHRD, ERRgeneral, NT_STATUS_DEBUG_ATTACH_FAILED}, {
ERRHRD, ERRgeneral, NT_STATUS_SYSTEM_PROCESS_TERMINATED}, {
ERRHRD, ERRgeneral, NT_STATUS_DATA_NOT_ACCEPTED}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_BROWSER_SERVERS_FOUND}, {
ERRHRD, ERRgeneral, NT_STATUS_VDM_HARD_ERROR}, {
ERRHRD, ERRgeneral, NT_STATUS_DRIVER_CANCEL_TIMEOUT}, {
ERRHRD, ERRgeneral, NT_STATUS_REPLY_MESSAGE_MISMATCH}, {
ERRHRD, ERRgeneral, NT_STATUS_MAPPED_ALIGNMENT}, {
ERRDOS, 193, NT_STATUS_IMAGE_CHECKSUM_MISMATCH}, {
ERRHRD, ERRgeneral, NT_STATUS_LOST_WRITEBEHIND_DATA}, {
ERRHRD, ERRgeneral, NT_STATUS_CLIENT_SERVER_PARAMETERS_INVALID}, {
ERRSRV, ERRpasswordExpired, NT_STATUS_PASSWORD_MUST_CHANGE}, {
ERRHRD, ERRgeneral, NT_STATUS_NOT_FOUND}, {
ERRHRD, ERRgeneral, NT_STATUS_NOT_TINY_STREAM}, {
ERRHRD, ERRgeneral, NT_STATUS_RECOVERY_FAILURE}, {
ERRHRD, ERRgeneral, NT_STATUS_STACK_OVERFLOW_READ}, {
ERRHRD, ERRgeneral, NT_STATUS_FAIL_CHECK}, {
ERRHRD, ERRgeneral, NT_STATUS_DUPLICATE_OBJECTID}, {
ERRHRD, ERRgeneral, NT_STATUS_OBJECTID_EXISTS}, {
ERRHRD, ERRgeneral, NT_STATUS_CONVERT_TO_LARGE}, {
ERRHRD, ERRgeneral, NT_STATUS_RETRY}, {
ERRHRD, ERRgeneral, NT_STATUS_FOUND_OUT_OF_SCOPE}, {
ERRHRD, ERRgeneral, NT_STATUS_ALLOCATE_BUCKET}, {
ERRHRD, ERRgeneral, NT_STATUS_PROPSET_NOT_FOUND}, {
ERRHRD, ERRgeneral, NT_STATUS_MARSHALL_OVERFLOW}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_VARIANT}, {
ERRHRD, ERRgeneral, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND}, {
ERRDOS, ERRnoaccess, NT_STATUS_ACCOUNT_LOCKED_OUT}, {
ERRDOS, ERRbadfid, NT_STATUS_HANDLE_NOT_CLOSABLE}, {
ERRHRD, ERRgeneral, NT_STATUS_CONNECTION_REFUSED}, {
ERRHRD, ERRgeneral, NT_STATUS_GRACEFUL_DISCONNECT}, {
ERRHRD, ERRgeneral, NT_STATUS_ADDRESS_ALREADY_ASSOCIATED}, {
ERRHRD, ERRgeneral, NT_STATUS_ADDRESS_NOT_ASSOCIATED}, {
ERRHRD, ERRgeneral, NT_STATUS_CONNECTION_INVALID}, {
ERRHRD, ERRgeneral, NT_STATUS_CONNECTION_ACTIVE}, {
ERRHRD, ERRgeneral, NT_STATUS_NETWORK_UNREACHABLE}, {
ERRHRD, ERRgeneral, NT_STATUS_HOST_UNREACHABLE}, {
ERRHRD, ERRgeneral, NT_STATUS_PROTOCOL_UNREACHABLE}, {
ERRHRD, ERRgeneral, NT_STATUS_PORT_UNREACHABLE}, {
ERRHRD, ERRgeneral, NT_STATUS_REQUEST_ABORTED}, {
ERRHRD, ERRgeneral, NT_STATUS_CONNECTION_ABORTED}, {
ERRHRD, ERRgeneral, NT_STATUS_BAD_COMPRESSION_BUFFER}, {
ERRHRD, ERRgeneral, NT_STATUS_USER_MAPPED_FILE}, {
ERRHRD, ERRgeneral, NT_STATUS_AUDIT_FAILED}, {
ERRHRD, ERRgeneral, NT_STATUS_TIMER_RESOLUTION_NOT_SET}, {
ERRHRD, ERRgeneral, NT_STATUS_CONNECTION_COUNT_LIMIT}, {
ERRHRD, ERRgeneral, NT_STATUS_LOGIN_TIME_RESTRICTION}, {
ERRHRD, ERRgeneral, NT_STATUS_LOGIN_WKSTA_RESTRICTION}, {
ERRDOS, 193, NT_STATUS_IMAGE_MP_UP_MISMATCH}, {
ERRHRD, ERRgeneral, 0xc000024a}, {
ERRHRD, ERRgeneral, 0xc000024b}, {
ERRHRD, ERRgeneral, 0xc000024c}, {
ERRHRD, ERRgeneral, 0xc000024d}, {
ERRHRD, ERRgeneral, 0xc000024e}, {
ERRHRD, ERRgeneral, 0xc000024f}, {
ERRHRD, ERRgeneral, NT_STATUS_INSUFFICIENT_LOGON_INFO}, {
ERRHRD, ERRgeneral, NT_STATUS_BAD_DLL_ENTRYPOINT}, {
ERRHRD, ERRgeneral, NT_STATUS_BAD_SERVICE_ENTRYPOINT}, {
ERRHRD, ERRgeneral, NT_STATUS_LPC_REPLY_LOST}, {
ERRHRD, ERRgeneral, NT_STATUS_IP_ADDRESS_CONFLICT1}, {
ERRHRD, ERRgeneral, NT_STATUS_IP_ADDRESS_CONFLICT2}, {
ERRHRD, ERRgeneral, NT_STATUS_REGISTRY_QUOTA_LIMIT}, {
ERRSRV, 3, NT_STATUS_PATH_NOT_COVERED}, {
ERRHRD, ERRgeneral, NT_STATUS_NO_CALLBACK_ACTIVE}, {
ERRHRD, ERRgeneral, NT_STATUS_LICENSE_QUOTA_EXCEEDED}, {
ERRHRD, ERRgeneral, NT_STATUS_PWD_TOO_SHORT}, {
ERRHRD, ERRgeneral, NT_STATUS_PWD_TOO_RECENT}, {
ERRHRD, ERRgeneral, NT_STATUS_PWD_HISTORY_CONFLICT}, {
ERRHRD, ERRgeneral, 0xc000025d}, {
ERRHRD, ERRgeneral, NT_STATUS_PLUGPLAY_NO_DEVICE}, {
ERRHRD, ERRgeneral, NT_STATUS_UNSUPPORTED_COMPRESSION}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_HW_PROFILE}, {
ERRHRD, ERRgeneral, NT_STATUS_INVALID_PLUGPLAY_DEVICE_PATH}, {
ERRDOS, 182, NT_STATUS_DRIVER_ORDINAL_NOT_FOUND}, {
ERRDOS, 127, NT_STATUS_DRIVER_ENTRYPOINT_NOT_FOUND}, {
ERRDOS, 288, NT_STATUS_RESOURCE_NOT_OWNED}, {
ERRDOS, ErrTooManyLinks, NT_STATUS_TOO_MANY_LINKS}, {
ERRHRD, ERRgeneral, NT_STATUS_QUOTA_LIST_INCONSISTENT}, {
ERRHRD, ERRgeneral, NT_STATUS_FILE_IS_OFFLINE}, {
ERRDOS, 21, 0xc000026e}, {
ERRDOS, 161, 0xc0000281}, {
ERRDOS, ERRnoaccess, 0xc000028a}, {
ERRDOS, ERRnoaccess, 0xc000028b}, {
ERRHRD, ERRgeneral, 0xc000028c}, {
ERRDOS, ERRnoaccess, 0xc000028d}, {
ERRDOS, ERRnoaccess, 0xc000028e}, {
ERRDOS, ERRnoaccess, 0xc000028f}, {
ERRDOS, ERRnoaccess, 0xc0000290}, {
ERRDOS, ERRbadfunc, 0xc000029c}, {
ERRDOS, ERRsymlink, NT_STATUS_STOPPED_ON_SYMLINK}, {
ERRDOS, ERRinvlevel, 0x007c0001}, };
/*****************************************************************************
Print an error message from the status code
*****************************************************************************/
static void
cifs_print_status(__u32 status_code)
{
int idx = 0;
while (nt_errs[idx].nt_errstr != NULL) {
if (((nt_errs[idx].nt_errcode) & 0xFFFFFF) ==
(status_code & 0xFFFFFF)) {
printk(KERN_NOTICE "Status code returned 0x%08x %s\n",
status_code, nt_errs[idx].nt_errstr);
}
idx++;
}
return;
}
static void
ntstatus_to_dos(__u32 ntstatus, __u8 *eclass, __u16 *ecode)
{
int i;
if (ntstatus == 0) {
*eclass = 0;
*ecode = 0;
return;
}
for (i = 0; ntstatus_to_dos_map[i].ntstatus; i++) {
if (ntstatus == ntstatus_to_dos_map[i].ntstatus) {
*eclass = ntstatus_to_dos_map[i].dos_class;
*ecode = ntstatus_to_dos_map[i].dos_code;
return;
}
}
*eclass = ERRHRD;
*ecode = ERRgeneral;
}
int
map_smb_to_linux_error(char *buf, bool logErr)
{
struct smb_hdr *smb = (struct smb_hdr *)buf;
unsigned int i;
int rc = -EIO; /* if transport error smb error may not be set */
__u8 smberrclass;
__u16 smberrcode;
/* BB if NT Status codes - map NT BB */
/* old style smb error codes */
if (smb->Status.CifsError == 0)
return 0;
if (smb->Flags2 & SMBFLG2_ERR_STATUS) {
/* translate the newer STATUS codes to old style SMB errors
* and then to POSIX errors */
__u32 err = le32_to_cpu(smb->Status.CifsError);
if (logErr && (err != (NT_STATUS_MORE_PROCESSING_REQUIRED)))
cifs_print_status(err);
else if (cifsFYI & CIFS_RC)
cifs_print_status(err);
ntstatus_to_dos(err, &smberrclass, &smberrcode);
} else {
smberrclass = smb->Status.DosError.ErrorClass;
smberrcode = le16_to_cpu(smb->Status.DosError.Error);
}
/* old style errors */
/* DOS class smb error codes - map DOS */
if (smberrclass == ERRDOS) {
/* 1 byte field no need to byte reverse */
for (i = 0;
i <
sizeof(mapping_table_ERRDOS) /
sizeof(struct smb_to_posix_error); i++) {
if (mapping_table_ERRDOS[i].smb_err == 0)
break;
else if (mapping_table_ERRDOS[i].smb_err ==
smberrcode) {
rc = mapping_table_ERRDOS[i].posix_code;
break;
}
/* else try next error mapping one to see if match */
}
} else if (smberrclass == ERRSRV) {
/* server class of error codes */
for (i = 0;
i <
sizeof(mapping_table_ERRSRV) /
sizeof(struct smb_to_posix_error); i++) {
if (mapping_table_ERRSRV[i].smb_err == 0)
break;
else if (mapping_table_ERRSRV[i].smb_err ==
smberrcode) {
rc = mapping_table_ERRSRV[i].posix_code;
break;
}
/* else try next error mapping to see if match */
}
}
/* else ERRHRD class errors or junk - return EIO */
cFYI(1, "Mapping smb error code 0x%x to POSIX err %d",
le32_to_cpu(smb->Status.CifsError), rc);
/* generic corrective action e.g. reconnect SMB session on
* ERRbaduid could be added */
return rc;
}
/*
* calculate the size of the SMB message based on the fixed header
* portion, the number of word parameters and the data portion of the message
*/
unsigned int
smbCalcSize(struct smb_hdr *ptr)
{
return (sizeof(struct smb_hdr) + (2 * ptr->WordCount) +
2 /* size of the bcc field */ + get_bcc(ptr));
}
/* The following are taken from fs/ntfs/util.c */
#define NTFS_TIME_OFFSET ((u64)(369*365 + 89) * 24 * 3600 * 10000000)
/*
* Convert the NT UTC (based 1601-01-01, in hundred nanosecond units)
* into Unix UTC (based 1970-01-01, in seconds).
*/
struct timespec
cifs_NTtimeToUnix(__le64 ntutc)
{
struct timespec ts;
/* BB what about the timezone? BB */
/* Subtract the NTFS time offset, then convert to 1s intervals. */
u64 t;
t = le64_to_cpu(ntutc) - NTFS_TIME_OFFSET;
ts.tv_nsec = do_div(t, 10000000) * 100;
ts.tv_sec = t;
return ts;
}
/* Convert the Unix UTC into NT UTC. */
u64
cifs_UnixTimeToNT(struct timespec t)
{
/* Convert to 100ns intervals and then add the NTFS time offset. */
return (u64) t.tv_sec * 10000000 + t.tv_nsec/100 + NTFS_TIME_OFFSET;
}
static int total_days_of_prev_months[] =
{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
struct timespec cnvrtDosUnixTm(__le16 le_date, __le16 le_time, int offset)
{
struct timespec ts;
int sec, min, days, month, year;
u16 date = le16_to_cpu(le_date);
u16 time = le16_to_cpu(le_time);
SMB_TIME *st = (SMB_TIME *)&time;
SMB_DATE *sd = (SMB_DATE *)&date;
cFYI(1, "date %d time %d", date, time);
sec = 2 * st->TwoSeconds;
min = st->Minutes;
if ((sec > 59) || (min > 59))
cERROR(1, "illegal time min %d sec %d", min, sec);
sec += (min * 60);
sec += 60 * 60 * st->Hours;
if (st->Hours > 24)
cERROR(1, "illegal hours %d", st->Hours);
days = sd->Day;
month = sd->Month;
if ((days > 31) || (month > 12)) {
cERROR(1, "illegal date, month %d day: %d", month, days);
if (month > 12)
month = 12;
}
month -= 1;
days += total_days_of_prev_months[month];
days += 3652; /* account for difference in days between 1980 and 1970 */
year = sd->Year;
days += year * 365;
days += (year/4); /* leap year */
/* generalized leap year calculation is more complex, ie no leap year
for years/100 except for years/400, but since the maximum number for DOS
year is 2**7, the last year is 1980+127, which means we need only
consider 2 special case years, ie the years 2000 and 2100, and only
adjust for the lack of leap year for the year 2100, as 2000 was a
leap year (divisable by 400) */
if (year >= 120) /* the year 2100 */
days = days - 1; /* do not count leap year for the year 2100 */
/* adjust for leap year where we are still before leap day */
if (year != 120)
days -= ((year & 0x03) == 0) && (month < 2 ? 1 : 0);
sec += 24 * 60 * 60 * days;
ts.tv_sec = sec + offset;
/* cFYI(1, "sec after cnvrt dos to unix time %d",sec); */
ts.tv_nsec = 0;
return ts;
}
| gpl-2.0 |
Mrcl1450/caf | arch/x86/kernel/amd_gart_64.c | 4967 | 22818 | /*
* Dynamic DMA mapping support for AMD Hammer.
*
* Use the integrated AGP GART in the Hammer northbridge as an IOMMU for PCI.
* This allows to use PCI devices that only support 32bit addresses on systems
* with more than 4GB.
*
* See Documentation/DMA-API-HOWTO.txt for the interface specification.
*
* Copyright 2002 Andi Kleen, SuSE Labs.
* Subject to the GNU General Public License v2 only.
*/
#include <linux/types.h>
#include <linux/ctype.h>
#include <linux/agp_backend.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/string.h>
#include <linux/spinlock.h>
#include <linux/pci.h>
#include <linux/module.h>
#include <linux/topology.h>
#include <linux/interrupt.h>
#include <linux/bitmap.h>
#include <linux/kdebug.h>
#include <linux/scatterlist.h>
#include <linux/iommu-helper.h>
#include <linux/syscore_ops.h>
#include <linux/io.h>
#include <linux/gfp.h>
#include <linux/atomic.h>
#include <asm/mtrr.h>
#include <asm/pgtable.h>
#include <asm/proto.h>
#include <asm/iommu.h>
#include <asm/gart.h>
#include <asm/cacheflush.h>
#include <asm/swiotlb.h>
#include <asm/dma.h>
#include <asm/amd_nb.h>
#include <asm/x86_init.h>
#include <asm/iommu_table.h>
static unsigned long iommu_bus_base; /* GART remapping area (physical) */
static unsigned long iommu_size; /* size of remapping area bytes */
static unsigned long iommu_pages; /* .. and in pages */
static u32 *iommu_gatt_base; /* Remapping table */
static dma_addr_t bad_dma_addr;
/*
* If this is disabled the IOMMU will use an optimized flushing strategy
* of only flushing when an mapping is reused. With it true the GART is
* flushed for every mapping. Problem is that doing the lazy flush seems
* to trigger bugs with some popular PCI cards, in particular 3ware (but
* has been also also seen with Qlogic at least).
*/
static int iommu_fullflush = 1;
/* Allocation bitmap for the remapping area: */
static DEFINE_SPINLOCK(iommu_bitmap_lock);
/* Guarded by iommu_bitmap_lock: */
static unsigned long *iommu_gart_bitmap;
static u32 gart_unmapped_entry;
#define GPTE_VALID 1
#define GPTE_COHERENT 2
#define GPTE_ENCODE(x) \
(((x) & 0xfffff000) | (((x) >> 32) << 4) | GPTE_VALID | GPTE_COHERENT)
#define GPTE_DECODE(x) (((x) & 0xfffff000) | (((u64)(x) & 0xff0) << 28))
#define EMERGENCY_PAGES 32 /* = 128KB */
#ifdef CONFIG_AGP
#define AGPEXTERN extern
#else
#define AGPEXTERN
#endif
/* GART can only remap to physical addresses < 1TB */
#define GART_MAX_PHYS_ADDR (1ULL << 40)
/* backdoor interface to AGP driver */
AGPEXTERN int agp_memory_reserved;
AGPEXTERN __u32 *agp_gatt_table;
static unsigned long next_bit; /* protected by iommu_bitmap_lock */
static bool need_flush; /* global flush state. set for each gart wrap */
static unsigned long alloc_iommu(struct device *dev, int size,
unsigned long align_mask)
{
unsigned long offset, flags;
unsigned long boundary_size;
unsigned long base_index;
base_index = ALIGN(iommu_bus_base & dma_get_seg_boundary(dev),
PAGE_SIZE) >> PAGE_SHIFT;
boundary_size = ALIGN((u64)dma_get_seg_boundary(dev) + 1,
PAGE_SIZE) >> PAGE_SHIFT;
spin_lock_irqsave(&iommu_bitmap_lock, flags);
offset = iommu_area_alloc(iommu_gart_bitmap, iommu_pages, next_bit,
size, base_index, boundary_size, align_mask);
if (offset == -1) {
need_flush = true;
offset = iommu_area_alloc(iommu_gart_bitmap, iommu_pages, 0,
size, base_index, boundary_size,
align_mask);
}
if (offset != -1) {
next_bit = offset+size;
if (next_bit >= iommu_pages) {
next_bit = 0;
need_flush = true;
}
}
if (iommu_fullflush)
need_flush = true;
spin_unlock_irqrestore(&iommu_bitmap_lock, flags);
return offset;
}
static void free_iommu(unsigned long offset, int size)
{
unsigned long flags;
spin_lock_irqsave(&iommu_bitmap_lock, flags);
bitmap_clear(iommu_gart_bitmap, offset, size);
if (offset >= next_bit)
next_bit = offset + size;
spin_unlock_irqrestore(&iommu_bitmap_lock, flags);
}
/*
* Use global flush state to avoid races with multiple flushers.
*/
static void flush_gart(void)
{
unsigned long flags;
spin_lock_irqsave(&iommu_bitmap_lock, flags);
if (need_flush) {
amd_flush_garts();
need_flush = false;
}
spin_unlock_irqrestore(&iommu_bitmap_lock, flags);
}
#ifdef CONFIG_IOMMU_LEAK
/* Debugging aid for drivers that don't free their IOMMU tables */
static int leak_trace;
static int iommu_leak_pages = 20;
static void dump_leak(void)
{
static int dump;
if (dump)
return;
dump = 1;
show_stack(NULL, NULL);
debug_dma_dump_mappings(NULL);
}
#endif
static void iommu_full(struct device *dev, size_t size, int dir)
{
/*
* Ran out of IOMMU space for this operation. This is very bad.
* Unfortunately the drivers cannot handle this operation properly.
* Return some non mapped prereserved space in the aperture and
* let the Northbridge deal with it. This will result in garbage
* in the IO operation. When the size exceeds the prereserved space
* memory corruption will occur or random memory will be DMAed
* out. Hopefully no network devices use single mappings that big.
*/
dev_err(dev, "PCI-DMA: Out of IOMMU space for %lu bytes\n", size);
if (size > PAGE_SIZE*EMERGENCY_PAGES) {
if (dir == PCI_DMA_FROMDEVICE || dir == PCI_DMA_BIDIRECTIONAL)
panic("PCI-DMA: Memory would be corrupted\n");
if (dir == PCI_DMA_TODEVICE || dir == PCI_DMA_BIDIRECTIONAL)
panic(KERN_ERR
"PCI-DMA: Random memory would be DMAed\n");
}
#ifdef CONFIG_IOMMU_LEAK
dump_leak();
#endif
}
static inline int
need_iommu(struct device *dev, unsigned long addr, size_t size)
{
return force_iommu || !dma_capable(dev, addr, size);
}
static inline int
nonforced_iommu(struct device *dev, unsigned long addr, size_t size)
{
return !dma_capable(dev, addr, size);
}
/* Map a single continuous physical area into the IOMMU.
* Caller needs to check if the iommu is needed and flush.
*/
static dma_addr_t dma_map_area(struct device *dev, dma_addr_t phys_mem,
size_t size, int dir, unsigned long align_mask)
{
unsigned long npages = iommu_num_pages(phys_mem, size, PAGE_SIZE);
unsigned long iommu_page;
int i;
if (unlikely(phys_mem + size > GART_MAX_PHYS_ADDR))
return bad_dma_addr;
iommu_page = alloc_iommu(dev, npages, align_mask);
if (iommu_page == -1) {
if (!nonforced_iommu(dev, phys_mem, size))
return phys_mem;
if (panic_on_overflow)
panic("dma_map_area overflow %lu bytes\n", size);
iommu_full(dev, size, dir);
return bad_dma_addr;
}
for (i = 0; i < npages; i++) {
iommu_gatt_base[iommu_page + i] = GPTE_ENCODE(phys_mem);
phys_mem += PAGE_SIZE;
}
return iommu_bus_base + iommu_page*PAGE_SIZE + (phys_mem & ~PAGE_MASK);
}
/* Map a single area into the IOMMU */
static dma_addr_t gart_map_page(struct device *dev, struct page *page,
unsigned long offset, size_t size,
enum dma_data_direction dir,
struct dma_attrs *attrs)
{
unsigned long bus;
phys_addr_t paddr = page_to_phys(page) + offset;
if (!dev)
dev = &x86_dma_fallback_dev;
if (!need_iommu(dev, paddr, size))
return paddr;
bus = dma_map_area(dev, paddr, size, dir, 0);
flush_gart();
return bus;
}
/*
* Free a DMA mapping.
*/
static void gart_unmap_page(struct device *dev, dma_addr_t dma_addr,
size_t size, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
unsigned long iommu_page;
int npages;
int i;
if (dma_addr < iommu_bus_base + EMERGENCY_PAGES*PAGE_SIZE ||
dma_addr >= iommu_bus_base + iommu_size)
return;
iommu_page = (dma_addr - iommu_bus_base)>>PAGE_SHIFT;
npages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
for (i = 0; i < npages; i++) {
iommu_gatt_base[iommu_page + i] = gart_unmapped_entry;
}
free_iommu(iommu_page, npages);
}
/*
* Wrapper for pci_unmap_single working with scatterlists.
*/
static void gart_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
enum dma_data_direction dir, struct dma_attrs *attrs)
{
struct scatterlist *s;
int i;
for_each_sg(sg, s, nents, i) {
if (!s->dma_length || !s->length)
break;
gart_unmap_page(dev, s->dma_address, s->dma_length, dir, NULL);
}
}
/* Fallback for dma_map_sg in case of overflow */
static int dma_map_sg_nonforce(struct device *dev, struct scatterlist *sg,
int nents, int dir)
{
struct scatterlist *s;
int i;
#ifdef CONFIG_IOMMU_DEBUG
pr_debug("dma_map_sg overflow\n");
#endif
for_each_sg(sg, s, nents, i) {
unsigned long addr = sg_phys(s);
if (nonforced_iommu(dev, addr, s->length)) {
addr = dma_map_area(dev, addr, s->length, dir, 0);
if (addr == bad_dma_addr) {
if (i > 0)
gart_unmap_sg(dev, sg, i, dir, NULL);
nents = 0;
sg[0].dma_length = 0;
break;
}
}
s->dma_address = addr;
s->dma_length = s->length;
}
flush_gart();
return nents;
}
/* Map multiple scatterlist entries continuous into the first. */
static int __dma_map_cont(struct device *dev, struct scatterlist *start,
int nelems, struct scatterlist *sout,
unsigned long pages)
{
unsigned long iommu_start = alloc_iommu(dev, pages, 0);
unsigned long iommu_page = iommu_start;
struct scatterlist *s;
int i;
if (iommu_start == -1)
return -1;
for_each_sg(start, s, nelems, i) {
unsigned long pages, addr;
unsigned long phys_addr = s->dma_address;
BUG_ON(s != start && s->offset);
if (s == start) {
sout->dma_address = iommu_bus_base;
sout->dma_address += iommu_page*PAGE_SIZE + s->offset;
sout->dma_length = s->length;
} else {
sout->dma_length += s->length;
}
addr = phys_addr;
pages = iommu_num_pages(s->offset, s->length, PAGE_SIZE);
while (pages--) {
iommu_gatt_base[iommu_page] = GPTE_ENCODE(addr);
addr += PAGE_SIZE;
iommu_page++;
}
}
BUG_ON(iommu_page - iommu_start != pages);
return 0;
}
static inline int
dma_map_cont(struct device *dev, struct scatterlist *start, int nelems,
struct scatterlist *sout, unsigned long pages, int need)
{
if (!need) {
BUG_ON(nelems != 1);
sout->dma_address = start->dma_address;
sout->dma_length = start->length;
return 0;
}
return __dma_map_cont(dev, start, nelems, sout, pages);
}
/*
* DMA map all entries in a scatterlist.
* Merge chunks that have page aligned sizes into a continuous mapping.
*/
static int gart_map_sg(struct device *dev, struct scatterlist *sg, int nents,
enum dma_data_direction dir, struct dma_attrs *attrs)
{
struct scatterlist *s, *ps, *start_sg, *sgmap;
int need = 0, nextneed, i, out, start;
unsigned long pages = 0;
unsigned int seg_size;
unsigned int max_seg_size;
if (nents == 0)
return 0;
if (!dev)
dev = &x86_dma_fallback_dev;
out = 0;
start = 0;
start_sg = sg;
sgmap = sg;
seg_size = 0;
max_seg_size = dma_get_max_seg_size(dev);
ps = NULL; /* shut up gcc */
for_each_sg(sg, s, nents, i) {
dma_addr_t addr = sg_phys(s);
s->dma_address = addr;
BUG_ON(s->length == 0);
nextneed = need_iommu(dev, addr, s->length);
/* Handle the previous not yet processed entries */
if (i > start) {
/*
* Can only merge when the last chunk ends on a
* page boundary and the new one doesn't have an
* offset.
*/
if (!iommu_merge || !nextneed || !need || s->offset ||
(s->length + seg_size > max_seg_size) ||
(ps->offset + ps->length) % PAGE_SIZE) {
if (dma_map_cont(dev, start_sg, i - start,
sgmap, pages, need) < 0)
goto error;
out++;
seg_size = 0;
sgmap = sg_next(sgmap);
pages = 0;
start = i;
start_sg = s;
}
}
seg_size += s->length;
need = nextneed;
pages += iommu_num_pages(s->offset, s->length, PAGE_SIZE);
ps = s;
}
if (dma_map_cont(dev, start_sg, i - start, sgmap, pages, need) < 0)
goto error;
out++;
flush_gart();
if (out < nents) {
sgmap = sg_next(sgmap);
sgmap->dma_length = 0;
}
return out;
error:
flush_gart();
gart_unmap_sg(dev, sg, out, dir, NULL);
/* When it was forced or merged try again in a dumb way */
if (force_iommu || iommu_merge) {
out = dma_map_sg_nonforce(dev, sg, nents, dir);
if (out > 0)
return out;
}
if (panic_on_overflow)
panic("dma_map_sg: overflow on %lu pages\n", pages);
iommu_full(dev, pages << PAGE_SHIFT, dir);
for_each_sg(sg, s, nents, i)
s->dma_address = bad_dma_addr;
return 0;
}
/* allocate and map a coherent mapping */
static void *
gart_alloc_coherent(struct device *dev, size_t size, dma_addr_t *dma_addr,
gfp_t flag, struct dma_attrs *attrs)
{
dma_addr_t paddr;
unsigned long align_mask;
struct page *page;
if (force_iommu && !(flag & GFP_DMA)) {
flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
page = alloc_pages(flag | __GFP_ZERO, get_order(size));
if (!page)
return NULL;
align_mask = (1UL << get_order(size)) - 1;
paddr = dma_map_area(dev, page_to_phys(page), size,
DMA_BIDIRECTIONAL, align_mask);
flush_gart();
if (paddr != bad_dma_addr) {
*dma_addr = paddr;
return page_address(page);
}
__free_pages(page, get_order(size));
} else
return dma_generic_alloc_coherent(dev, size, dma_addr, flag,
attrs);
return NULL;
}
/* free a coherent mapping */
static void
gart_free_coherent(struct device *dev, size_t size, void *vaddr,
dma_addr_t dma_addr, struct dma_attrs *attrs)
{
gart_unmap_page(dev, dma_addr, size, DMA_BIDIRECTIONAL, NULL);
free_pages((unsigned long)vaddr, get_order(size));
}
static int gart_mapping_error(struct device *dev, dma_addr_t dma_addr)
{
return (dma_addr == bad_dma_addr);
}
static int no_agp;
static __init unsigned long check_iommu_size(unsigned long aper, u64 aper_size)
{
unsigned long a;
if (!iommu_size) {
iommu_size = aper_size;
if (!no_agp)
iommu_size /= 2;
}
a = aper + iommu_size;
iommu_size -= round_up(a, PMD_PAGE_SIZE) - a;
if (iommu_size < 64*1024*1024) {
pr_warning(
"PCI-DMA: Warning: Small IOMMU %luMB."
" Consider increasing the AGP aperture in BIOS\n",
iommu_size >> 20);
}
return iommu_size;
}
static __init unsigned read_aperture(struct pci_dev *dev, u32 *size)
{
unsigned aper_size = 0, aper_base_32, aper_order;
u64 aper_base;
pci_read_config_dword(dev, AMD64_GARTAPERTUREBASE, &aper_base_32);
pci_read_config_dword(dev, AMD64_GARTAPERTURECTL, &aper_order);
aper_order = (aper_order >> 1) & 7;
aper_base = aper_base_32 & 0x7fff;
aper_base <<= 25;
aper_size = (32 * 1024 * 1024) << aper_order;
if (aper_base + aper_size > 0x100000000UL || !aper_size)
aper_base = 0;
*size = aper_size;
return aper_base;
}
static void enable_gart_translations(void)
{
int i;
if (!amd_nb_has_feature(AMD_NB_GART))
return;
for (i = 0; i < amd_nb_num(); i++) {
struct pci_dev *dev = node_to_amd_nb(i)->misc;
enable_gart_translation(dev, __pa(agp_gatt_table));
}
/* Flush the GART-TLB to remove stale entries */
amd_flush_garts();
}
/*
* If fix_up_north_bridges is set, the north bridges have to be fixed up on
* resume in the same way as they are handled in gart_iommu_hole_init().
*/
static bool fix_up_north_bridges;
static u32 aperture_order;
static u32 aperture_alloc;
void set_up_gart_resume(u32 aper_order, u32 aper_alloc)
{
fix_up_north_bridges = true;
aperture_order = aper_order;
aperture_alloc = aper_alloc;
}
static void gart_fixup_northbridges(void)
{
int i;
if (!fix_up_north_bridges)
return;
if (!amd_nb_has_feature(AMD_NB_GART))
return;
pr_info("PCI-DMA: Restoring GART aperture settings\n");
for (i = 0; i < amd_nb_num(); i++) {
struct pci_dev *dev = node_to_amd_nb(i)->misc;
/*
* Don't enable translations just yet. That is the next
* step. Restore the pre-suspend aperture settings.
*/
gart_set_size_and_enable(dev, aperture_order);
pci_write_config_dword(dev, AMD64_GARTAPERTUREBASE, aperture_alloc >> 25);
}
}
static void gart_resume(void)
{
pr_info("PCI-DMA: Resuming GART IOMMU\n");
gart_fixup_northbridges();
enable_gart_translations();
}
static struct syscore_ops gart_syscore_ops = {
.resume = gart_resume,
};
/*
* Private Northbridge GATT initialization in case we cannot use the
* AGP driver for some reason.
*/
static __init int init_amd_gatt(struct agp_kern_info *info)
{
unsigned aper_size, gatt_size, new_aper_size;
unsigned aper_base, new_aper_base;
struct pci_dev *dev;
void *gatt;
int i;
pr_info("PCI-DMA: Disabling AGP.\n");
aper_size = aper_base = info->aper_size = 0;
dev = NULL;
for (i = 0; i < amd_nb_num(); i++) {
dev = node_to_amd_nb(i)->misc;
new_aper_base = read_aperture(dev, &new_aper_size);
if (!new_aper_base)
goto nommu;
if (!aper_base) {
aper_size = new_aper_size;
aper_base = new_aper_base;
}
if (aper_size != new_aper_size || aper_base != new_aper_base)
goto nommu;
}
if (!aper_base)
goto nommu;
info->aper_base = aper_base;
info->aper_size = aper_size >> 20;
gatt_size = (aper_size >> PAGE_SHIFT) * sizeof(u32);
gatt = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
get_order(gatt_size));
if (!gatt)
panic("Cannot allocate GATT table");
if (set_memory_uc((unsigned long)gatt, gatt_size >> PAGE_SHIFT))
panic("Could not set GART PTEs to uncacheable pages");
agp_gatt_table = gatt;
register_syscore_ops(&gart_syscore_ops);
flush_gart();
pr_info("PCI-DMA: aperture base @ %x size %u KB\n",
aper_base, aper_size>>10);
return 0;
nommu:
/* Should not happen anymore */
pr_warning("PCI-DMA: More than 4GB of RAM and no IOMMU\n"
"falling back to iommu=soft.\n");
return -1;
}
static struct dma_map_ops gart_dma_ops = {
.map_sg = gart_map_sg,
.unmap_sg = gart_unmap_sg,
.map_page = gart_map_page,
.unmap_page = gart_unmap_page,
.alloc = gart_alloc_coherent,
.free = gart_free_coherent,
.mapping_error = gart_mapping_error,
};
static void gart_iommu_shutdown(void)
{
struct pci_dev *dev;
int i;
/* don't shutdown it if there is AGP installed */
if (!no_agp)
return;
if (!amd_nb_has_feature(AMD_NB_GART))
return;
for (i = 0; i < amd_nb_num(); i++) {
u32 ctl;
dev = node_to_amd_nb(i)->misc;
pci_read_config_dword(dev, AMD64_GARTAPERTURECTL, &ctl);
ctl &= ~GARTEN;
pci_write_config_dword(dev, AMD64_GARTAPERTURECTL, ctl);
}
}
int __init gart_iommu_init(void)
{
struct agp_kern_info info;
unsigned long iommu_start;
unsigned long aper_base, aper_size;
unsigned long start_pfn, end_pfn;
unsigned long scratch;
long i;
if (!amd_nb_has_feature(AMD_NB_GART))
return 0;
#ifndef CONFIG_AGP_AMD64
no_agp = 1;
#else
/* Makefile puts PCI initialization via subsys_initcall first. */
/* Add other AMD AGP bridge drivers here */
no_agp = no_agp ||
(agp_amd64_init() < 0) ||
(agp_copy_info(agp_bridge, &info) < 0);
#endif
if (no_iommu ||
(!force_iommu && max_pfn <= MAX_DMA32_PFN) ||
!gart_iommu_aperture ||
(no_agp && init_amd_gatt(&info) < 0)) {
if (max_pfn > MAX_DMA32_PFN) {
pr_warning("More than 4GB of memory but GART IOMMU not available.\n");
pr_warning("falling back to iommu=soft.\n");
}
return 0;
}
/* need to map that range */
aper_size = info.aper_size << 20;
aper_base = info.aper_base;
end_pfn = (aper_base>>PAGE_SHIFT) + (aper_size>>PAGE_SHIFT);
if (end_pfn > max_low_pfn_mapped) {
start_pfn = (aper_base>>PAGE_SHIFT);
init_memory_mapping(start_pfn<<PAGE_SHIFT, end_pfn<<PAGE_SHIFT);
}
pr_info("PCI-DMA: using GART IOMMU.\n");
iommu_size = check_iommu_size(info.aper_base, aper_size);
iommu_pages = iommu_size >> PAGE_SHIFT;
iommu_gart_bitmap = (void *) __get_free_pages(GFP_KERNEL | __GFP_ZERO,
get_order(iommu_pages/8));
if (!iommu_gart_bitmap)
panic("Cannot allocate iommu bitmap\n");
#ifdef CONFIG_IOMMU_LEAK
if (leak_trace) {
int ret;
ret = dma_debug_resize_entries(iommu_pages);
if (ret)
pr_debug("PCI-DMA: Cannot trace all the entries\n");
}
#endif
/*
* Out of IOMMU space handling.
* Reserve some invalid pages at the beginning of the GART.
*/
bitmap_set(iommu_gart_bitmap, 0, EMERGENCY_PAGES);
pr_info("PCI-DMA: Reserving %luMB of IOMMU area in the AGP aperture\n",
iommu_size >> 20);
agp_memory_reserved = iommu_size;
iommu_start = aper_size - iommu_size;
iommu_bus_base = info.aper_base + iommu_start;
bad_dma_addr = iommu_bus_base;
iommu_gatt_base = agp_gatt_table + (iommu_start>>PAGE_SHIFT);
/*
* Unmap the IOMMU part of the GART. The alias of the page is
* always mapped with cache enabled and there is no full cache
* coherency across the GART remapping. The unmapping avoids
* automatic prefetches from the CPU allocating cache lines in
* there. All CPU accesses are done via the direct mapping to
* the backing memory. The GART address is only used by PCI
* devices.
*/
set_memory_np((unsigned long)__va(iommu_bus_base),
iommu_size >> PAGE_SHIFT);
/*
* Tricky. The GART table remaps the physical memory range,
* so the CPU wont notice potential aliases and if the memory
* is remapped to UC later on, we might surprise the PCI devices
* with a stray writeout of a cacheline. So play it sure and
* do an explicit, full-scale wbinvd() _after_ having marked all
* the pages as Not-Present:
*/
wbinvd();
/*
* Now all caches are flushed and we can safely enable
* GART hardware. Doing it early leaves the possibility
* of stale cache entries that can lead to GART PTE
* errors.
*/
enable_gart_translations();
/*
* Try to workaround a bug (thanks to BenH):
* Set unmapped entries to a scratch page instead of 0.
* Any prefetches that hit unmapped entries won't get an bus abort
* then. (P2P bridge may be prefetching on DMA reads).
*/
scratch = get_zeroed_page(GFP_KERNEL);
if (!scratch)
panic("Cannot allocate iommu scratch page");
gart_unmapped_entry = GPTE_ENCODE(__pa(scratch));
for (i = EMERGENCY_PAGES; i < iommu_pages; i++)
iommu_gatt_base[i] = gart_unmapped_entry;
flush_gart();
dma_ops = &gart_dma_ops;
x86_platform.iommu_shutdown = gart_iommu_shutdown;
swiotlb = 0;
return 0;
}
void __init gart_parse_options(char *p)
{
int arg;
#ifdef CONFIG_IOMMU_LEAK
if (!strncmp(p, "leak", 4)) {
leak_trace = 1;
p += 4;
if (*p == '=')
++p;
if (isdigit(*p) && get_option(&p, &arg))
iommu_leak_pages = arg;
}
#endif
if (isdigit(*p) && get_option(&p, &arg))
iommu_size = arg;
if (!strncmp(p, "fullflush", 9))
iommu_fullflush = 1;
if (!strncmp(p, "nofullflush", 11))
iommu_fullflush = 0;
if (!strncmp(p, "noagp", 5))
no_agp = 1;
if (!strncmp(p, "noaperture", 10))
fix_aperture = 0;
/* duplicated from pci-dma.c */
if (!strncmp(p, "force", 5))
gart_iommu_aperture_allowed = 1;
if (!strncmp(p, "allowed", 7))
gart_iommu_aperture_allowed = 1;
if (!strncmp(p, "memaper", 7)) {
fallback_aper_force = 1;
p += 7;
if (*p == '=') {
++p;
if (get_option(&p, &arg))
fallback_aper_order = arg;
}
}
}
IOMMU_INIT_POST(gart_iommu_hole_init);
| gpl-2.0 |
wangenau/samsung-kernel-msm7x30 | fs/hfsplus/unicode.c | 5735 | 9490 | /*
* linux/fs/hfsplus/unicode.c
*
* Copyright (C) 2001
* Brad Boyer (flar@allandria.com)
* (C) 2003 Ardis Technologies <roman@ardistech.com>
*
* Handler routines for unicode strings
*/
#include <linux/types.h>
#include <linux/nls.h>
#include "hfsplus_fs.h"
#include "hfsplus_raw.h"
/* Fold the case of a unicode char, given the 16 bit value */
/* Returns folded char, or 0 if ignorable */
static inline u16 case_fold(u16 c)
{
u16 tmp;
tmp = hfsplus_case_fold_table[c >> 8];
if (tmp)
tmp = hfsplus_case_fold_table[tmp + (c & 0xff)];
else
tmp = c;
return tmp;
}
/* Compare unicode strings, return values like normal strcmp */
int hfsplus_strcasecmp(const struct hfsplus_unistr *s1,
const struct hfsplus_unistr *s2)
{
u16 len1, len2, c1, c2;
const hfsplus_unichr *p1, *p2;
len1 = be16_to_cpu(s1->length);
len2 = be16_to_cpu(s2->length);
p1 = s1->unicode;
p2 = s2->unicode;
while (1) {
c1 = c2 = 0;
while (len1 && !c1) {
c1 = case_fold(be16_to_cpu(*p1));
p1++;
len1--;
}
while (len2 && !c2) {
c2 = case_fold(be16_to_cpu(*p2));
p2++;
len2--;
}
if (c1 != c2)
return (c1 < c2) ? -1 : 1;
if (!c1 && !c2)
return 0;
}
}
/* Compare names as a sequence of 16-bit unsigned integers */
int hfsplus_strcmp(const struct hfsplus_unistr *s1,
const struct hfsplus_unistr *s2)
{
u16 len1, len2, c1, c2;
const hfsplus_unichr *p1, *p2;
int len;
len1 = be16_to_cpu(s1->length);
len2 = be16_to_cpu(s2->length);
p1 = s1->unicode;
p2 = s2->unicode;
for (len = min(len1, len2); len > 0; len--) {
c1 = be16_to_cpu(*p1);
c2 = be16_to_cpu(*p2);
if (c1 != c2)
return c1 < c2 ? -1 : 1;
p1++;
p2++;
}
return len1 < len2 ? -1 :
len1 > len2 ? 1 : 0;
}
#define Hangul_SBase 0xac00
#define Hangul_LBase 0x1100
#define Hangul_VBase 0x1161
#define Hangul_TBase 0x11a7
#define Hangul_SCount 11172
#define Hangul_LCount 19
#define Hangul_VCount 21
#define Hangul_TCount 28
#define Hangul_NCount (Hangul_VCount * Hangul_TCount)
static u16 *hfsplus_compose_lookup(u16 *p, u16 cc)
{
int i, s, e;
s = 1;
e = p[1];
if (!e || cc < p[s * 2] || cc > p[e * 2])
return NULL;
do {
i = (s + e) / 2;
if (cc > p[i * 2])
s = i + 1;
else if (cc < p[i * 2])
e = i - 1;
else
return hfsplus_compose_table + p[i * 2 + 1];
} while (s <= e);
return NULL;
}
int hfsplus_uni2asc(struct super_block *sb,
const struct hfsplus_unistr *ustr,
char *astr, int *len_p)
{
const hfsplus_unichr *ip;
struct nls_table *nls = HFSPLUS_SB(sb)->nls;
u8 *op;
u16 cc, c0, c1;
u16 *ce1, *ce2;
int i, len, ustrlen, res, compose;
op = astr;
ip = ustr->unicode;
ustrlen = be16_to_cpu(ustr->length);
len = *len_p;
ce1 = NULL;
compose = !test_bit(HFSPLUS_SB_NODECOMPOSE, &HFSPLUS_SB(sb)->flags);
while (ustrlen > 0) {
c0 = be16_to_cpu(*ip++);
ustrlen--;
/* search for single decomposed char */
if (likely(compose))
ce1 = hfsplus_compose_lookup(hfsplus_compose_table, c0);
if (ce1)
cc = ce1[0];
else
cc = 0;
if (cc) {
/* start of a possibly decomposed Hangul char */
if (cc != 0xffff)
goto done;
if (!ustrlen)
goto same;
c1 = be16_to_cpu(*ip) - Hangul_VBase;
if (c1 < Hangul_VCount) {
/* compose the Hangul char */
cc = (c0 - Hangul_LBase) * Hangul_VCount;
cc = (cc + c1) * Hangul_TCount;
cc += Hangul_SBase;
ip++;
ustrlen--;
if (!ustrlen)
goto done;
c1 = be16_to_cpu(*ip) - Hangul_TBase;
if (c1 > 0 && c1 < Hangul_TCount) {
cc += c1;
ip++;
ustrlen--;
}
goto done;
}
}
while (1) {
/* main loop for common case of not composed chars */
if (!ustrlen)
goto same;
c1 = be16_to_cpu(*ip);
if (likely(compose))
ce1 = hfsplus_compose_lookup(
hfsplus_compose_table, c1);
if (ce1)
break;
switch (c0) {
case 0:
c0 = 0x2400;
break;
case '/':
c0 = ':';
break;
}
res = nls->uni2char(c0, op, len);
if (res < 0) {
if (res == -ENAMETOOLONG)
goto out;
*op = '?';
res = 1;
}
op += res;
len -= res;
c0 = c1;
ip++;
ustrlen--;
}
ce2 = hfsplus_compose_lookup(ce1, c0);
if (ce2) {
i = 1;
while (i < ustrlen) {
ce1 = hfsplus_compose_lookup(ce2,
be16_to_cpu(ip[i]));
if (!ce1)
break;
i++;
ce2 = ce1;
}
cc = ce2[0];
if (cc) {
ip += i;
ustrlen -= i;
goto done;
}
}
same:
switch (c0) {
case 0:
cc = 0x2400;
break;
case '/':
cc = ':';
break;
default:
cc = c0;
}
done:
res = nls->uni2char(cc, op, len);
if (res < 0) {
if (res == -ENAMETOOLONG)
goto out;
*op = '?';
res = 1;
}
op += res;
len -= res;
}
res = 0;
out:
*len_p = (char *)op - astr;
return res;
}
/*
* Convert one or more ASCII characters into a single unicode character.
* Returns the number of ASCII characters corresponding to the unicode char.
*/
static inline int asc2unichar(struct super_block *sb, const char *astr, int len,
wchar_t *uc)
{
int size = HFSPLUS_SB(sb)->nls->char2uni(astr, len, uc);
if (size <= 0) {
*uc = '?';
size = 1;
}
switch (*uc) {
case 0x2400:
*uc = 0;
break;
case ':':
*uc = '/';
break;
}
return size;
}
/* Decomposes a single unicode character. */
static inline u16 *decompose_unichar(wchar_t uc, int *size)
{
int off;
off = hfsplus_decompose_table[(uc >> 12) & 0xf];
if (off == 0 || off == 0xffff)
return NULL;
off = hfsplus_decompose_table[off + ((uc >> 8) & 0xf)];
if (!off)
return NULL;
off = hfsplus_decompose_table[off + ((uc >> 4) & 0xf)];
if (!off)
return NULL;
off = hfsplus_decompose_table[off + (uc & 0xf)];
*size = off & 3;
if (*size == 0)
return NULL;
return hfsplus_decompose_table + (off / 4);
}
int hfsplus_asc2uni(struct super_block *sb, struct hfsplus_unistr *ustr,
const char *astr, int len)
{
int size, dsize, decompose;
u16 *dstr, outlen = 0;
wchar_t c;
decompose = !test_bit(HFSPLUS_SB_NODECOMPOSE, &HFSPLUS_SB(sb)->flags);
while (outlen < HFSPLUS_MAX_STRLEN && len > 0) {
size = asc2unichar(sb, astr, len, &c);
if (decompose)
dstr = decompose_unichar(c, &dsize);
else
dstr = NULL;
if (dstr) {
if (outlen + dsize > HFSPLUS_MAX_STRLEN)
break;
do {
ustr->unicode[outlen++] = cpu_to_be16(*dstr++);
} while (--dsize > 0);
} else
ustr->unicode[outlen++] = cpu_to_be16(c);
astr += size;
len -= size;
}
ustr->length = cpu_to_be16(outlen);
if (len > 0)
return -ENAMETOOLONG;
return 0;
}
/*
* Hash a string to an integer as appropriate for the HFS+ filesystem.
* Composed unicode characters are decomposed and case-folding is performed
* if the appropriate bits are (un)set on the superblock.
*/
int hfsplus_hash_dentry(const struct dentry *dentry, const struct inode *inode,
struct qstr *str)
{
struct super_block *sb = dentry->d_sb;
const char *astr;
const u16 *dstr;
int casefold, decompose, size, len;
unsigned long hash;
wchar_t c;
u16 c2;
casefold = test_bit(HFSPLUS_SB_CASEFOLD, &HFSPLUS_SB(sb)->flags);
decompose = !test_bit(HFSPLUS_SB_NODECOMPOSE, &HFSPLUS_SB(sb)->flags);
hash = init_name_hash();
astr = str->name;
len = str->len;
while (len > 0) {
int uninitialized_var(dsize);
size = asc2unichar(sb, astr, len, &c);
astr += size;
len -= size;
if (decompose)
dstr = decompose_unichar(c, &dsize);
else
dstr = NULL;
if (dstr) {
do {
c2 = *dstr++;
if (casefold)
c2 = case_fold(c2);
if (!casefold || c2)
hash = partial_name_hash(c2, hash);
} while (--dsize > 0);
} else {
c2 = c;
if (casefold)
c2 = case_fold(c2);
if (!casefold || c2)
hash = partial_name_hash(c2, hash);
}
}
str->hash = end_name_hash(hash);
return 0;
}
/*
* Compare strings with HFS+ filename ordering.
* Composed unicode characters are decomposed and case-folding is performed
* if the appropriate bits are (un)set on the superblock.
*/
int hfsplus_compare_dentry(const struct dentry *parent,
const struct inode *pinode,
const struct dentry *dentry, const struct inode *inode,
unsigned int len, const char *str, const struct qstr *name)
{
struct super_block *sb = parent->d_sb;
int casefold, decompose, size;
int dsize1, dsize2, len1, len2;
const u16 *dstr1, *dstr2;
const char *astr1, *astr2;
u16 c1, c2;
wchar_t c;
casefold = test_bit(HFSPLUS_SB_CASEFOLD, &HFSPLUS_SB(sb)->flags);
decompose = !test_bit(HFSPLUS_SB_NODECOMPOSE, &HFSPLUS_SB(sb)->flags);
astr1 = str;
len1 = len;
astr2 = name->name;
len2 = name->len;
dsize1 = dsize2 = 0;
dstr1 = dstr2 = NULL;
while (len1 > 0 && len2 > 0) {
if (!dsize1) {
size = asc2unichar(sb, astr1, len1, &c);
astr1 += size;
len1 -= size;
if (decompose)
dstr1 = decompose_unichar(c, &dsize1);
if (!decompose || !dstr1) {
c1 = c;
dstr1 = &c1;
dsize1 = 1;
}
}
if (!dsize2) {
size = asc2unichar(sb, astr2, len2, &c);
astr2 += size;
len2 -= size;
if (decompose)
dstr2 = decompose_unichar(c, &dsize2);
if (!decompose || !dstr2) {
c2 = c;
dstr2 = &c2;
dsize2 = 1;
}
}
c1 = *dstr1;
c2 = *dstr2;
if (casefold) {
c1 = case_fold(c1);
if (!c1) {
dstr1++;
dsize1--;
continue;
}
c2 = case_fold(c2);
if (!c2) {
dstr2++;
dsize2--;
continue;
}
}
if (c1 < c2)
return -1;
else if (c1 > c2)
return 1;
dstr1++;
dsize1--;
dstr2++;
dsize2--;
}
if (len1 < len2)
return -1;
if (len1 > len2)
return 1;
return 0;
}
| gpl-2.0 |
nazunamoe/Oxygen_united_kernel-gproj | drivers/scsi/aacraid/dpcsup.c | 8039 | 11592 | /*
* Adaptec AAC series RAID controller driver
* (c) Copyright 2001 Red Hat Inc.
*
* based on the old aacraid driver that is..
* Adaptec aacraid device driver for Linux.
*
* Copyright (c) 2000-2010 Adaptec, Inc.
* 2010 PMC-Sierra, Inc. (aacraid@pmc-sierra.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, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Module Name:
* dpcsup.c
*
* Abstract: All DPC processing routines for the cyclone board occur here.
*
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/completion.h>
#include <linux/blkdev.h>
#include <linux/semaphore.h>
#include "aacraid.h"
/**
* aac_response_normal - Handle command replies
* @q: Queue to read from
*
* This DPC routine will be run when the adapter interrupts us to let us
* know there is a response on our normal priority queue. We will pull off
* all QE there are and wake up all the waiters before exiting. We will
* take a spinlock out on the queue before operating on it.
*/
unsigned int aac_response_normal(struct aac_queue * q)
{
struct aac_dev * dev = q->dev;
struct aac_entry *entry;
struct hw_fib * hwfib;
struct fib * fib;
int consumed = 0;
unsigned long flags, mflags;
spin_lock_irqsave(q->lock, flags);
/*
* Keep pulling response QEs off the response queue and waking
* up the waiters until there are no more QEs. We then return
* back to the system. If no response was requesed we just
* deallocate the Fib here and continue.
*/
while(aac_consumer_get(dev, q, &entry))
{
int fast;
u32 index = le32_to_cpu(entry->addr);
fast = index & 0x01;
fib = &dev->fibs[index >> 2];
hwfib = fib->hw_fib_va;
aac_consumer_free(dev, q, HostNormRespQueue);
/*
* Remove this fib from the Outstanding I/O queue.
* But only if it has not already been timed out.
*
* If the fib has been timed out already, then just
* continue. The caller has already been notified that
* the fib timed out.
*/
dev->queues->queue[AdapNormCmdQueue].numpending--;
if (unlikely(fib->flags & FIB_CONTEXT_FLAG_TIMED_OUT)) {
spin_unlock_irqrestore(q->lock, flags);
aac_fib_complete(fib);
aac_fib_free(fib);
spin_lock_irqsave(q->lock, flags);
continue;
}
spin_unlock_irqrestore(q->lock, flags);
if (fast) {
/*
* Doctor the fib
*/
*(__le32 *)hwfib->data = cpu_to_le32(ST_OK);
hwfib->header.XferState |= cpu_to_le32(AdapterProcessed);
}
FIB_COUNTER_INCREMENT(aac_config.FibRecved);
if (hwfib->header.Command == cpu_to_le16(NuFileSystem))
{
__le32 *pstatus = (__le32 *)hwfib->data;
if (*pstatus & cpu_to_le32(0xffff0000))
*pstatus = cpu_to_le32(ST_OK);
}
if (hwfib->header.XferState & cpu_to_le32(NoResponseExpected | Async))
{
if (hwfib->header.XferState & cpu_to_le32(NoResponseExpected))
FIB_COUNTER_INCREMENT(aac_config.NoResponseRecved);
else
FIB_COUNTER_INCREMENT(aac_config.AsyncRecved);
/*
* NOTE: we cannot touch the fib after this
* call, because it may have been deallocated.
*/
fib->flags = 0;
fib->callback(fib->callback_data, fib);
} else {
unsigned long flagv;
spin_lock_irqsave(&fib->event_lock, flagv);
if (!fib->done) {
fib->done = 1;
up(&fib->event_wait);
}
spin_unlock_irqrestore(&fib->event_lock, flagv);
spin_lock_irqsave(&dev->manage_lock, mflags);
dev->management_fib_count--;
spin_unlock_irqrestore(&dev->manage_lock, mflags);
FIB_COUNTER_INCREMENT(aac_config.NormalRecved);
if (fib->done == 2) {
spin_lock_irqsave(&fib->event_lock, flagv);
fib->done = 0;
spin_unlock_irqrestore(&fib->event_lock, flagv);
aac_fib_complete(fib);
aac_fib_free(fib);
}
}
consumed++;
spin_lock_irqsave(q->lock, flags);
}
if (consumed > aac_config.peak_fibs)
aac_config.peak_fibs = consumed;
if (consumed == 0)
aac_config.zero_fibs++;
spin_unlock_irqrestore(q->lock, flags);
return 0;
}
/**
* aac_command_normal - handle commands
* @q: queue to process
*
* This DPC routine will be queued when the adapter interrupts us to
* let us know there is a command on our normal priority queue. We will
* pull off all QE there are and wake up all the waiters before exiting.
* We will take a spinlock out on the queue before operating on it.
*/
unsigned int aac_command_normal(struct aac_queue *q)
{
struct aac_dev * dev = q->dev;
struct aac_entry *entry;
unsigned long flags;
spin_lock_irqsave(q->lock, flags);
/*
* Keep pulling response QEs off the response queue and waking
* up the waiters until there are no more QEs. We then return
* back to the system.
*/
while(aac_consumer_get(dev, q, &entry))
{
struct fib fibctx;
struct hw_fib * hw_fib;
u32 index;
struct fib *fib = &fibctx;
index = le32_to_cpu(entry->addr) / sizeof(struct hw_fib);
hw_fib = &dev->aif_base_va[index];
/*
* Allocate a FIB at all costs. For non queued stuff
* we can just use the stack so we are happy. We need
* a fib object in order to manage the linked lists
*/
if (dev->aif_thread)
if((fib = kmalloc(sizeof(struct fib), GFP_ATOMIC)) == NULL)
fib = &fibctx;
memset(fib, 0, sizeof(struct fib));
INIT_LIST_HEAD(&fib->fiblink);
fib->type = FSAFS_NTC_FIB_CONTEXT;
fib->size = sizeof(struct fib);
fib->hw_fib_va = hw_fib;
fib->data = hw_fib->data;
fib->dev = dev;
if (dev->aif_thread && fib != &fibctx) {
list_add_tail(&fib->fiblink, &q->cmdq);
aac_consumer_free(dev, q, HostNormCmdQueue);
wake_up_interruptible(&q->cmdready);
} else {
aac_consumer_free(dev, q, HostNormCmdQueue);
spin_unlock_irqrestore(q->lock, flags);
/*
* Set the status of this FIB
*/
*(__le32 *)hw_fib->data = cpu_to_le32(ST_OK);
aac_fib_adapter_complete(fib, sizeof(u32));
spin_lock_irqsave(q->lock, flags);
}
}
spin_unlock_irqrestore(q->lock, flags);
return 0;
}
/*
*
* aac_aif_callback
* @context: the context set in the fib - here it is scsi cmd
* @fibptr: pointer to the fib
*
* Handles the AIFs - new method (SRC)
*
*/
static void aac_aif_callback(void *context, struct fib * fibptr)
{
struct fib *fibctx;
struct aac_dev *dev;
struct aac_aifcmd *cmd;
int status;
fibctx = (struct fib *)context;
BUG_ON(fibptr == NULL);
dev = fibptr->dev;
if (fibptr->hw_fib_va->header.XferState &
cpu_to_le32(NoMoreAifDataAvailable)) {
aac_fib_complete(fibptr);
aac_fib_free(fibptr);
return;
}
aac_intr_normal(dev, 0, 1, 0, fibptr->hw_fib_va);
aac_fib_init(fibctx);
cmd = (struct aac_aifcmd *) fib_data(fibctx);
cmd->command = cpu_to_le32(AifReqEvent);
status = aac_fib_send(AifRequest,
fibctx,
sizeof(struct hw_fib)-sizeof(struct aac_fibhdr),
FsaNormal,
0, 1,
(fib_callback)aac_aif_callback, fibctx);
}
/**
* aac_intr_normal - Handle command replies
* @dev: Device
* @index: completion reference
*
* This DPC routine will be run when the adapter interrupts us to let us
* know there is a response on our normal priority queue. We will pull off
* all QE there are and wake up all the waiters before exiting.
*/
unsigned int aac_intr_normal(struct aac_dev *dev, u32 index,
int isAif, int isFastResponse, struct hw_fib *aif_fib)
{
unsigned long mflags;
dprintk((KERN_INFO "aac_intr_normal(%p,%x)\n", dev, index));
if (isAif == 1) { /* AIF - common */
struct hw_fib * hw_fib;
struct fib * fib;
struct aac_queue *q = &dev->queues->queue[HostNormCmdQueue];
unsigned long flags;
/*
* Allocate a FIB. For non queued stuff we can just use
* the stack so we are happy. We need a fib object in order to
* manage the linked lists.
*/
if ((!dev->aif_thread)
|| (!(fib = kzalloc(sizeof(struct fib),GFP_ATOMIC))))
return 1;
if (!(hw_fib = kzalloc(sizeof(struct hw_fib),GFP_ATOMIC))) {
kfree (fib);
return 1;
}
if (aif_fib != NULL) {
memcpy(hw_fib, aif_fib, sizeof(struct hw_fib));
} else {
memcpy(hw_fib,
(struct hw_fib *)(((uintptr_t)(dev->regs.sa)) +
index), sizeof(struct hw_fib));
}
INIT_LIST_HEAD(&fib->fiblink);
fib->type = FSAFS_NTC_FIB_CONTEXT;
fib->size = sizeof(struct fib);
fib->hw_fib_va = hw_fib;
fib->data = hw_fib->data;
fib->dev = dev;
spin_lock_irqsave(q->lock, flags);
list_add_tail(&fib->fiblink, &q->cmdq);
wake_up_interruptible(&q->cmdready);
spin_unlock_irqrestore(q->lock, flags);
return 1;
} else if (isAif == 2) { /* AIF - new (SRC) */
struct fib *fibctx;
struct aac_aifcmd *cmd;
fibctx = aac_fib_alloc(dev);
if (!fibctx)
return 1;
aac_fib_init(fibctx);
cmd = (struct aac_aifcmd *) fib_data(fibctx);
cmd->command = cpu_to_le32(AifReqEvent);
return aac_fib_send(AifRequest,
fibctx,
sizeof(struct hw_fib)-sizeof(struct aac_fibhdr),
FsaNormal,
0, 1,
(fib_callback)aac_aif_callback, fibctx);
} else {
struct fib *fib = &dev->fibs[index];
struct hw_fib * hwfib = fib->hw_fib_va;
/*
* Remove this fib from the Outstanding I/O queue.
* But only if it has not already been timed out.
*
* If the fib has been timed out already, then just
* continue. The caller has already been notified that
* the fib timed out.
*/
dev->queues->queue[AdapNormCmdQueue].numpending--;
if (unlikely(fib->flags & FIB_CONTEXT_FLAG_TIMED_OUT)) {
aac_fib_complete(fib);
aac_fib_free(fib);
return 0;
}
if (isFastResponse) {
/*
* Doctor the fib
*/
*(__le32 *)hwfib->data = cpu_to_le32(ST_OK);
hwfib->header.XferState |= cpu_to_le32(AdapterProcessed);
}
FIB_COUNTER_INCREMENT(aac_config.FibRecved);
if (hwfib->header.Command == cpu_to_le16(NuFileSystem))
{
__le32 *pstatus = (__le32 *)hwfib->data;
if (*pstatus & cpu_to_le32(0xffff0000))
*pstatus = cpu_to_le32(ST_OK);
}
if (hwfib->header.XferState & cpu_to_le32(NoResponseExpected | Async))
{
if (hwfib->header.XferState & cpu_to_le32(NoResponseExpected))
FIB_COUNTER_INCREMENT(aac_config.NoResponseRecved);
else
FIB_COUNTER_INCREMENT(aac_config.AsyncRecved);
/*
* NOTE: we cannot touch the fib after this
* call, because it may have been deallocated.
*/
fib->flags = 0;
fib->callback(fib->callback_data, fib);
} else {
unsigned long flagv;
dprintk((KERN_INFO "event_wait up\n"));
spin_lock_irqsave(&fib->event_lock, flagv);
if (!fib->done) {
fib->done = 1;
up(&fib->event_wait);
}
spin_unlock_irqrestore(&fib->event_lock, flagv);
spin_lock_irqsave(&dev->manage_lock, mflags);
dev->management_fib_count--;
spin_unlock_irqrestore(&dev->manage_lock, mflags);
FIB_COUNTER_INCREMENT(aac_config.NormalRecved);
if (fib->done == 2) {
spin_lock_irqsave(&fib->event_lock, flagv);
fib->done = 0;
spin_unlock_irqrestore(&fib->event_lock, flagv);
aac_fib_complete(fib);
aac_fib_free(fib);
}
}
return 0;
}
}
| gpl-2.0 |
varigit/VAR-SOM-AM33-SDK7-Kernel | arch/powerpc/platforms/40x/ep405.c | 8039 | 3169 | /*
* Architecture- / platform-specific boot-time initialization code for
* IBM PowerPC 4xx based boards. Adapted from original
* code by Gary Thomas, Cort Dougan <cort@fsmlabs.com>, and Dan Malek
* <dan@net4x.com>.
*
* Copyright(c) 1999-2000 Grant Erickson <grant@lcse.umn.edu>
*
* Rewritten and ported to the merged powerpc tree:
* Copyright 2007 IBM Corporation
* Josh Boyer <jwboyer@linux.vnet.ibm.com>
*
* Adapted to EP405 by Ben. Herrenschmidt <benh@kernel.crashing.org>
*
* TODO: Wire up the PCI IRQ mux and the southbridge interrupts
*
* 2002 (c) MontaVista, Software, Inc. This file is licensed under
* the terms of the GNU General Public License version 2. This program
* is licensed "as is" without any warranty of any kind, whether express
* or implied.
*/
#include <linux/init.h>
#include <linux/of_platform.h>
#include <asm/machdep.h>
#include <asm/prom.h>
#include <asm/udbg.h>
#include <asm/time.h>
#include <asm/uic.h>
#include <asm/pci-bridge.h>
#include <asm/ppc4xx.h>
static struct device_node *bcsr_node;
static void __iomem *bcsr_regs;
/* BCSR registers */
#define BCSR_ID 0
#define BCSR_PCI_CTRL 1
#define BCSR_FLASH_NV_POR_CTRL 2
#define BCSR_FENET_UART_CTRL 3
#define BCSR_PCI_IRQ 4
#define BCSR_XIRQ_SELECT 5
#define BCSR_XIRQ_ROUTING 6
#define BCSR_XIRQ_STATUS 7
#define BCSR_XIRQ_STATUS2 8
#define BCSR_SW_STAT_LED_CTRL 9
#define BCSR_GPIO_IRQ_PAR_CTRL 10
/* there's more, can't be bothered typing them tho */
static __initdata struct of_device_id ep405_of_bus[] = {
{ .compatible = "ibm,plb3", },
{ .compatible = "ibm,opb", },
{ .compatible = "ibm,ebc", },
{},
};
static int __init ep405_device_probe(void)
{
of_platform_bus_probe(NULL, ep405_of_bus, NULL);
return 0;
}
machine_device_initcall(ep405, ep405_device_probe);
static void __init ep405_init_bcsr(void)
{
const u8 *irq_routing;
int i;
/* Find the bloody thing & map it */
bcsr_node = of_find_compatible_node(NULL, NULL, "ep405-bcsr");
if (bcsr_node == NULL) {
printk(KERN_ERR "EP405 BCSR not found !\n");
return;
}
bcsr_regs = of_iomap(bcsr_node, 0);
if (bcsr_regs == NULL) {
printk(KERN_ERR "EP405 BCSR failed to map !\n");
return;
}
/* Get the irq-routing property and apply the routing to the CPLD */
irq_routing = of_get_property(bcsr_node, "irq-routing", NULL);
if (irq_routing == NULL)
return;
for (i = 0; i < 16; i++) {
u8 irq = irq_routing[i];
out_8(bcsr_regs + BCSR_XIRQ_SELECT, i);
out_8(bcsr_regs + BCSR_XIRQ_ROUTING, irq);
}
in_8(bcsr_regs + BCSR_XIRQ_SELECT);
mb();
out_8(bcsr_regs + BCSR_GPIO_IRQ_PAR_CTRL, 0xfe);
}
static void __init ep405_setup_arch(void)
{
/* Find & init the BCSR CPLD */
ep405_init_bcsr();
pci_set_flags(PCI_REASSIGN_ALL_RSRC);
}
static int __init ep405_probe(void)
{
unsigned long root = of_get_flat_dt_root();
if (!of_flat_dt_is_compatible(root, "ep405"))
return 0;
return 1;
}
define_machine(ep405) {
.name = "EP405",
.probe = ep405_probe,
.setup_arch = ep405_setup_arch,
.progress = udbg_progress,
.init_IRQ = uic_init_tree,
.get_irq = uic_get_irq,
.restart = ppc4xx_reset_system,
.calibrate_decr = generic_calibrate_decr,
};
| gpl-2.0 |
MingquanLiang/linux | drivers/watchdog/imx2_wdt.c | 104 | 8984 | /*
* Watchdog driver for IMX2 and later processors
*
* Copyright (C) 2010 Wolfram Sang, Pengutronix e.K. <w.sang@pengutronix.de>
* Copyright (C) 2014 Freescale Semiconductor, Inc.
*
* some parts adapted by similar drivers from Darius Augulis and Vladimir
* Zapolskiy, additional improvements by Wim Van Sebroeck.
*
* 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.
*
* NOTE: MX1 has a slightly different Watchdog than MX2 and later:
*
* MX1: MX2+:
* ---- -----
* Registers: 32-bit 16-bit
* Stopable timer: Yes No
* Need to enable clk: No Yes
* Halt on suspend: Manual Can be automatic
*/
#include <linux/clk.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/of_address.h>
#include <linux/platform_device.h>
#include <linux/regmap.h>
#include <linux/timer.h>
#include <linux/watchdog.h>
#define DRIVER_NAME "imx2-wdt"
#define IMX2_WDT_WCR 0x00 /* Control Register */
#define IMX2_WDT_WCR_WT (0xFF << 8) /* -> Watchdog Timeout Field */
#define IMX2_WDT_WCR_WRE (1 << 3) /* -> WDOG Reset Enable */
#define IMX2_WDT_WCR_WDE (1 << 2) /* -> Watchdog Enable */
#define IMX2_WDT_WCR_WDZST (1 << 0) /* -> Watchdog timer Suspend */
#define IMX2_WDT_WSR 0x02 /* Service Register */
#define IMX2_WDT_SEQ1 0x5555 /* -> service sequence 1 */
#define IMX2_WDT_SEQ2 0xAAAA /* -> service sequence 2 */
#define IMX2_WDT_WRSR 0x04 /* Reset Status Register */
#define IMX2_WDT_WRSR_TOUT (1 << 1) /* -> Reset due to Timeout */
#define IMX2_WDT_MAX_TIME 128
#define IMX2_WDT_DEFAULT_TIME 60 /* in seconds */
#define WDOG_SEC_TO_COUNT(s) ((s * 2 - 1) << 8)
struct imx2_wdt_device {
struct clk *clk;
struct regmap *regmap;
struct timer_list timer; /* Pings the watchdog when closed */
struct watchdog_device wdog;
};
static bool nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default="
__MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
static unsigned timeout = IMX2_WDT_DEFAULT_TIME;
module_param(timeout, uint, 0);
MODULE_PARM_DESC(timeout, "Watchdog timeout in seconds (default="
__MODULE_STRING(IMX2_WDT_DEFAULT_TIME) ")");
static const struct watchdog_info imx2_wdt_info = {
.identity = "imx2+ watchdog",
.options = WDIOF_KEEPALIVEPING | WDIOF_SETTIMEOUT | WDIOF_MAGICCLOSE,
};
static inline void imx2_wdt_setup(struct watchdog_device *wdog)
{
struct imx2_wdt_device *wdev = watchdog_get_drvdata(wdog);
u32 val;
regmap_read(wdev->regmap, IMX2_WDT_WCR, &val);
/* Suspend timer in low power mode, write once-only */
val |= IMX2_WDT_WCR_WDZST;
/* Strip the old watchdog Time-Out value */
val &= ~IMX2_WDT_WCR_WT;
/* Generate reset if WDOG times out */
val &= ~IMX2_WDT_WCR_WRE;
/* Keep Watchdog Disabled */
val &= ~IMX2_WDT_WCR_WDE;
/* Set the watchdog's Time-Out value */
val |= WDOG_SEC_TO_COUNT(wdog->timeout);
regmap_write(wdev->regmap, IMX2_WDT_WCR, val);
/* enable the watchdog */
val |= IMX2_WDT_WCR_WDE;
regmap_write(wdev->regmap, IMX2_WDT_WCR, val);
}
static inline bool imx2_wdt_is_running(struct imx2_wdt_device *wdev)
{
u32 val;
regmap_read(wdev->regmap, IMX2_WDT_WCR, &val);
return val & IMX2_WDT_WCR_WDE;
}
static int imx2_wdt_ping(struct watchdog_device *wdog)
{
struct imx2_wdt_device *wdev = watchdog_get_drvdata(wdog);
regmap_write(wdev->regmap, IMX2_WDT_WSR, IMX2_WDT_SEQ1);
regmap_write(wdev->regmap, IMX2_WDT_WSR, IMX2_WDT_SEQ2);
return 0;
}
static void imx2_wdt_timer_ping(unsigned long arg)
{
struct watchdog_device *wdog = (struct watchdog_device *)arg;
struct imx2_wdt_device *wdev = watchdog_get_drvdata(wdog);
/* ping it every wdog->timeout / 2 seconds to prevent reboot */
imx2_wdt_ping(wdog);
mod_timer(&wdev->timer, jiffies + wdog->timeout * HZ / 2);
}
static int imx2_wdt_set_timeout(struct watchdog_device *wdog,
unsigned int new_timeout)
{
struct imx2_wdt_device *wdev = watchdog_get_drvdata(wdog);
regmap_update_bits(wdev->regmap, IMX2_WDT_WCR, IMX2_WDT_WCR_WT,
WDOG_SEC_TO_COUNT(new_timeout));
return 0;
}
static int imx2_wdt_start(struct watchdog_device *wdog)
{
struct imx2_wdt_device *wdev = watchdog_get_drvdata(wdog);
if (imx2_wdt_is_running(wdev)) {
/* delete the timer that pings the watchdog after close */
del_timer_sync(&wdev->timer);
imx2_wdt_set_timeout(wdog, wdog->timeout);
} else
imx2_wdt_setup(wdog);
return imx2_wdt_ping(wdog);
}
static int imx2_wdt_stop(struct watchdog_device *wdog)
{
/*
* We don't need a clk_disable, it cannot be disabled once started.
* We use a timer to ping the watchdog while /dev/watchdog is closed
*/
imx2_wdt_timer_ping((unsigned long)wdog);
return 0;
}
static inline void imx2_wdt_ping_if_active(struct watchdog_device *wdog)
{
struct imx2_wdt_device *wdev = watchdog_get_drvdata(wdog);
if (imx2_wdt_is_running(wdev)) {
imx2_wdt_set_timeout(wdog, wdog->timeout);
imx2_wdt_timer_ping((unsigned long)wdog);
}
}
static struct watchdog_ops imx2_wdt_ops = {
.owner = THIS_MODULE,
.start = imx2_wdt_start,
.stop = imx2_wdt_stop,
.ping = imx2_wdt_ping,
.set_timeout = imx2_wdt_set_timeout,
};
static struct regmap_config imx2_wdt_regmap_config = {
.reg_bits = 16,
.reg_stride = 2,
.val_bits = 16,
.max_register = 0x8,
};
static int __init imx2_wdt_probe(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
struct imx2_wdt_device *wdev;
struct watchdog_device *wdog;
struct resource *res;
void __iomem *base;
bool big_endian;
int ret;
u32 val;
wdev = devm_kzalloc(&pdev->dev, sizeof(*wdev), GFP_KERNEL);
if (!wdev)
return -ENOMEM;
big_endian = of_property_read_bool(np, "big-endian");
if (big_endian)
imx2_wdt_regmap_config.val_format_endian = REGMAP_ENDIAN_BIG;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(base))
return PTR_ERR(base);
wdev->regmap = devm_regmap_init_mmio_clk(&pdev->dev, NULL, base,
&imx2_wdt_regmap_config);
if (IS_ERR(wdev->regmap)) {
dev_err(&pdev->dev, "regmap init failed\n");
return PTR_ERR(wdev->regmap);
}
wdev->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(wdev->clk)) {
dev_err(&pdev->dev, "can't get Watchdog clock\n");
return PTR_ERR(wdev->clk);
}
wdog = &wdev->wdog;
wdog->info = &imx2_wdt_info;
wdog->ops = &imx2_wdt_ops;
wdog->min_timeout = 1;
wdog->max_timeout = IMX2_WDT_MAX_TIME;
clk_prepare_enable(wdev->clk);
regmap_read(wdev->regmap, IMX2_WDT_WRSR, &val);
wdog->bootstatus = val & IMX2_WDT_WRSR_TOUT ? WDIOF_CARDRESET : 0;
wdog->timeout = clamp_t(unsigned, timeout, 1, IMX2_WDT_MAX_TIME);
if (wdog->timeout != timeout)
dev_warn(&pdev->dev, "Initial timeout out of range! Clamped from %u to %u\n",
timeout, wdog->timeout);
platform_set_drvdata(pdev, wdog);
watchdog_set_drvdata(wdog, wdev);
watchdog_set_nowayout(wdog, nowayout);
watchdog_init_timeout(wdog, timeout, &pdev->dev);
setup_timer(&wdev->timer, imx2_wdt_timer_ping, (unsigned long)wdog);
imx2_wdt_ping_if_active(wdog);
ret = watchdog_register_device(wdog);
if (ret) {
dev_err(&pdev->dev, "cannot register watchdog device\n");
return ret;
}
dev_info(&pdev->dev, "timeout %d sec (nowayout=%d)\n",
wdog->timeout, nowayout);
return 0;
}
static int __exit imx2_wdt_remove(struct platform_device *pdev)
{
struct watchdog_device *wdog = platform_get_drvdata(pdev);
struct imx2_wdt_device *wdev = watchdog_get_drvdata(wdog);
watchdog_unregister_device(wdog);
if (imx2_wdt_is_running(wdev)) {
del_timer_sync(&wdev->timer);
imx2_wdt_ping(wdog);
dev_crit(&pdev->dev, "Device removed: Expect reboot!\n");
}
return 0;
}
static void imx2_wdt_shutdown(struct platform_device *pdev)
{
struct watchdog_device *wdog = platform_get_drvdata(pdev);
struct imx2_wdt_device *wdev = watchdog_get_drvdata(wdog);
if (imx2_wdt_is_running(wdev)) {
/*
* We are running, we need to delete the timer but will
* give max timeout before reboot will take place
*/
del_timer_sync(&wdev->timer);
imx2_wdt_set_timeout(wdog, IMX2_WDT_MAX_TIME);
imx2_wdt_ping(wdog);
dev_crit(&pdev->dev, "Device shutdown: Expect reboot!\n");
}
}
static const struct of_device_id imx2_wdt_dt_ids[] = {
{ .compatible = "fsl,imx21-wdt", },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, imx2_wdt_dt_ids);
static struct platform_driver imx2_wdt_driver = {
.remove = __exit_p(imx2_wdt_remove),
.shutdown = imx2_wdt_shutdown,
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
.of_match_table = imx2_wdt_dt_ids,
},
};
module_platform_driver_probe(imx2_wdt_driver, imx2_wdt_probe);
MODULE_AUTHOR("Wolfram Sang");
MODULE_DESCRIPTION("Watchdog driver for IMX2 and later");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:" DRIVER_NAME);
| gpl-2.0 |
zarboz/m8wlv | drivers/media/platform/msm/camera_v2/isp/msm_buf_mgr.c | 104 | 23998 | /* Copyright (c) 2013-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/workqueue.h>
#include <linux/delay.h>
#include <linux/types.h>
#include <linux/list.h>
#include <linux/ioctl.h>
#include <linux/spinlock.h>
#include <linux/videodev2.h>
#include <linux/proc_fs.h>
#include <linux/videodev2.h>
#include <linux/vmalloc.h>
#include <media/v4l2-dev.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-device.h>
#include <media/videobuf2-core.h>
#include <media/msm_camera.h>
#include <media/msm_isp.h>
#include <mach/iommu.h>
#include "msm.h"
#include "msm_buf_mgr.h"
#undef CDBG
#ifdef CONFIG_MSM_ISP_DBG
#define CDBG(fmt, args...) pr_err(fmt, ##args)
#else
#define CDBG(fmt, args...) do { } while (0)
#endif
static struct msm_isp_bufq *msm_isp_get_bufq(
struct msm_isp_buf_mgr *buf_mgr,
uint32_t bufq_handle)
{
struct msm_isp_bufq *bufq = NULL;
uint32_t bufq_index = bufq_handle & 0xFF;
if (bufq_index > buf_mgr->num_buf_q)
return bufq;
bufq = &buf_mgr->bufq[bufq_index];
if (bufq->bufq_handle == bufq_handle)
return bufq;
return NULL;
}
static struct msm_isp_buffer *msm_isp_get_buf_ptr(
struct msm_isp_buf_mgr *buf_mgr,
uint32_t bufq_handle, uint32_t buf_index)
{
struct msm_isp_bufq *bufq = NULL;
struct msm_isp_buffer *buf_info = NULL;
bufq = msm_isp_get_bufq(buf_mgr, bufq_handle);
if (!bufq) {
pr_err("%s: Invalid bufq\n", __func__);
return buf_info;
}
if (bufq->num_bufs <= buf_index) {
pr_err("%s: Invalid buf index\n", __func__);
return buf_info;
}
buf_info = &bufq->bufs[buf_index];
return buf_info;
}
static uint32_t msm_isp_get_buf_handle(
struct msm_isp_buf_mgr *buf_mgr,
uint32_t session_id, uint32_t stream_id)
{
int i;
if ((buf_mgr->buf_handle_cnt << 8) == 0)
buf_mgr->buf_handle_cnt++;
for (i = 0; i < buf_mgr->num_buf_q; i++) {
if (buf_mgr->bufq[i].session_id == session_id &&
buf_mgr->bufq[i].stream_id == stream_id)
return 0;
}
for (i = 0; i < buf_mgr->num_buf_q; i++) {
if (buf_mgr->bufq[i].bufq_handle == 0) {
memset(&buf_mgr->bufq[i],
0, sizeof(struct msm_isp_bufq));
buf_mgr->bufq[i].bufq_handle =
(++buf_mgr->buf_handle_cnt) << 8 | i;
return buf_mgr->bufq[i].bufq_handle;
}
}
return 0;
}
static int msm_isp_free_buf_handle(struct msm_isp_buf_mgr *buf_mgr,
uint32_t bufq_handle)
{
struct msm_isp_bufq *bufq =
msm_isp_get_bufq(buf_mgr, bufq_handle);
if (!bufq)
return -EINVAL;
memset(bufq, 0, sizeof(struct msm_isp_bufq));
return 0;
}
static int msm_isp_prepare_v4l2_buf(struct msm_isp_buf_mgr *buf_mgr,
struct msm_isp_buffer *buf_info,
struct v4l2_buffer *v4l2_buf)
{
int i, rc = -1;
struct msm_isp_buffer_mapped_info *mapped_info;
struct buffer_cmd *buf_pending = NULL;
for (i = 0; i < v4l2_buf->length; i++) {
mapped_info = &buf_info->mapped_info[i];
mapped_info->handle =
ion_import_dma_buf(buf_mgr->client,
v4l2_buf->m.planes[i].m.userptr);
if (IS_ERR_OR_NULL(mapped_info->handle)) {
pr_err("%s: buf has null/error ION handle %p\n",
__func__, mapped_info->handle);
goto ion_map_error;
}
if (ion_map_iommu(buf_mgr->client, mapped_info->handle,
buf_mgr->iommu_domain_num, 0, SZ_4K,
0, &(mapped_info->paddr),
&(mapped_info->len), 0, 0) < 0) {
rc = -EINVAL;
pr_err("%s: cannot map address", __func__);
ion_free(buf_mgr->client, mapped_info->handle);
goto ion_map_error;
}
mapped_info->paddr += v4l2_buf->m.planes[i].data_offset;
CDBG("%s: plane: %d addr:%lu\n",
__func__, i, mapped_info->paddr);
buf_pending = kzalloc(sizeof(struct buffer_cmd), GFP_ATOMIC);
if (!buf_pending) {
pr_err("No free memory for buf_pending\n");
return rc;
}
buf_pending->mapped_info = mapped_info;
list_add_tail(&buf_pending->list, &buf_mgr->buffer_q);
}
buf_info->num_planes = v4l2_buf->length;
return 0;
ion_map_error:
for (--i; i >= 0; i--) {
mapped_info = &buf_info->mapped_info[i];
ion_unmap_iommu(buf_mgr->client, mapped_info->handle,
buf_mgr->iommu_domain_num, 0);
ion_free(buf_mgr->client, mapped_info->handle);
}
return rc;
}
static void msm_isp_unprepare_v4l2_buf(
struct msm_isp_buf_mgr *buf_mgr,
struct msm_isp_buffer *buf_info)
{
int i;
struct msm_isp_buffer_mapped_info *mapped_info;
struct buffer_cmd *buf_pending = NULL;
for (i = 0; i < buf_info->num_planes; i++) {
mapped_info = &buf_info->mapped_info[i];
list_for_each_entry(buf_pending, &buf_mgr->buffer_q, list) {
if (!buf_pending)
break;
if (buf_pending->mapped_info == mapped_info) {
ion_unmap_iommu(buf_mgr->client,
mapped_info->handle,
buf_mgr->iommu_domain_num, 0);
ion_free(buf_mgr->client, mapped_info->handle);
list_del_init(&buf_pending->list);
kfree(buf_pending);
break;
}
}
}
return;
}
static int msm_isp_buf_prepare(struct msm_isp_buf_mgr *buf_mgr,
struct msm_isp_qbuf_info *info, struct vb2_buffer *vb2_buf)
{
int rc = -1;
unsigned long flags;
struct msm_isp_bufq *bufq = NULL;
struct msm_isp_buffer *buf_info = NULL;
struct v4l2_buffer *buf = NULL;
struct v4l2_plane *plane = NULL;
buf_info = msm_isp_get_buf_ptr(buf_mgr,
info->handle, info->buf_idx);
if (!buf_info) {
pr_err("Invalid buffer prepare\n");
return rc;
}
bufq = msm_isp_get_bufq(buf_mgr, buf_info->bufq_handle);
if (!bufq) {
pr_err("%s: Invalid bufq\n", __func__);
return rc;
}
spin_lock_irqsave(&bufq->bufq_lock, flags);
if (buf_info->state == MSM_ISP_BUFFER_STATE_DIVERTED) {
rc = buf_info->state;
spin_unlock_irqrestore(&bufq->bufq_lock, flags);
return rc;
}
if (buf_info->state != MSM_ISP_BUFFER_STATE_INITIALIZED) {
pr_err("%s: Invalid buffer state: %d\n",
__func__, buf_info->state);
spin_unlock_irqrestore(&bufq->bufq_lock, flags);
return rc;
}
spin_unlock_irqrestore(&bufq->bufq_lock, flags);
if (vb2_buf) {
buf = &vb2_buf->v4l2_buf;
buf_info->vb2_buf = vb2_buf;
} else {
buf = &info->buffer;
plane =
kzalloc(sizeof(struct v4l2_plane) * buf->length,
GFP_KERNEL);
if (!plane) {
pr_err("%s: Cannot alloc plane: %d\n",
__func__, buf_info->state);
return rc;
}
if (copy_from_user(plane,
(void __user *)(buf->m.planes),
sizeof(struct v4l2_plane) * buf->length)) {
kfree(plane);
return rc;
}
buf->m.planes = plane;
}
rc = msm_isp_prepare_v4l2_buf(buf_mgr, buf_info, buf);
if (rc < 0) {
pr_err("%s: Prepare buffer error\n", __func__);
kfree(plane);
return rc;
}
spin_lock_irqsave(&bufq->bufq_lock, flags);
buf_info->state = MSM_ISP_BUFFER_STATE_PREPARED;
spin_unlock_irqrestore(&bufq->bufq_lock, flags);
kfree(plane);
return rc;
}
static int msm_isp_buf_unprepare(struct msm_isp_buf_mgr *buf_mgr,
uint32_t buf_handle)
{
int rc = -1, i;
struct msm_isp_bufq *bufq = NULL;
struct msm_isp_buffer *buf_info = NULL;
bufq = msm_isp_get_bufq(buf_mgr, buf_handle);
if (!bufq) {
pr_err("%s: Invalid bufq\n", __func__);
return rc;
}
for (i = 0; i < bufq->num_bufs; i++) {
buf_info = msm_isp_get_buf_ptr(buf_mgr, buf_handle, i);
if (buf_info == NULL) {
pr_err("%s: buf_info is NULL\n", __func__);
return rc;
}
if (buf_info->state == MSM_ISP_BUFFER_STATE_UNUSED ||
buf_info->state ==
MSM_ISP_BUFFER_STATE_INITIALIZED)
continue;
if (!BUF_SRC(bufq->stream_id)) {
if (buf_info->state == MSM_ISP_BUFFER_STATE_DEQUEUED ||
buf_info->state == MSM_ISP_BUFFER_STATE_DIVERTED)
buf_mgr->vb2_ops->put_buf(buf_info->vb2_buf,
bufq->session_id, bufq->stream_id);
}
msm_isp_unprepare_v4l2_buf(buf_mgr, buf_info);
}
return 0;
}
static int msm_isp_get_buf(struct msm_isp_buf_mgr *buf_mgr, uint32_t id,
uint32_t bufq_handle, struct msm_isp_buffer **buf_info)
{
int rc = -1;
unsigned long flags;
struct msm_isp_buffer *temp_buf_info;
struct msm_isp_bufq *bufq = NULL;
struct vb2_buffer *vb2_buf = NULL;
struct buffer_cmd *buf_pending = NULL;
struct msm_isp_buffer_mapped_info *mped_info_tmp1;
struct msm_isp_buffer_mapped_info *mped_info_tmp2;
bufq = msm_isp_get_bufq(buf_mgr, bufq_handle);
if (!bufq) {
pr_err("%s: Invalid bufq\n", __func__);
return rc;
}
if (!bufq->bufq_handle) {
pr_err("%s: Invalid bufq handle\n", __func__);
return rc;
}
*buf_info = NULL;
spin_lock_irqsave(&bufq->bufq_lock, flags);
if (bufq->buf_type == ISP_SHARE_BUF) {
list_for_each_entry(temp_buf_info,
&bufq->share_head, share_list) {
if (!temp_buf_info->buf_used[id]) {
temp_buf_info->buf_used[id] = 1;
temp_buf_info->buf_get_count++;
if (temp_buf_info->buf_get_count ==
bufq->buf_client_count)
list_del_init(
&temp_buf_info->share_list);
if (temp_buf_info->buf_reuse_flag) {
kfree(temp_buf_info);
} else {
*buf_info = temp_buf_info;
rc = 0;
}
spin_unlock_irqrestore(
&bufq->bufq_lock, flags);
return rc;
}
}
}
if (BUF_SRC(bufq->stream_id)) {
list_for_each_entry(temp_buf_info, &bufq->head, list) {
if (temp_buf_info->state ==
MSM_ISP_BUFFER_STATE_QUEUED) {
list_for_each_entry(buf_pending, &buf_mgr->buffer_q, list) {
if (!buf_pending)
break;
mped_info_tmp1 = buf_pending->mapped_info;
mped_info_tmp2 = &temp_buf_info->mapped_info[0];
if (mped_info_tmp1 == mped_info_tmp2
&& (mped_info_tmp1->len == mped_info_tmp2->len)
&& (mped_info_tmp1->paddr == mped_info_tmp2->paddr)) {
list_del_init(&temp_buf_info->list);
*buf_info = temp_buf_info;
break;
}
}
break;
}
}
} else {
vb2_buf = buf_mgr->vb2_ops->get_buf(
bufq->session_id, bufq->stream_id);
if (vb2_buf) {
if (vb2_buf->v4l2_buf.index < bufq->num_bufs) {
list_for_each_entry(buf_pending, &buf_mgr->buffer_q, list) {
if (!buf_pending)
break;
mped_info_tmp1 = buf_pending->mapped_info;
mped_info_tmp2 =
&bufq->bufs[vb2_buf->v4l2_buf.index].mapped_info[0];
if (mped_info_tmp1 == mped_info_tmp2
&& (mped_info_tmp1->len == mped_info_tmp2->len)
&& (mped_info_tmp1->paddr == mped_info_tmp2->paddr)) {
*buf_info = &bufq->bufs[vb2_buf->v4l2_buf.index];
(*buf_info)->vb2_buf = vb2_buf;
break;
}
}
} else {
pr_err("%s: Incorrect buf index %d\n",
__func__, vb2_buf->v4l2_buf.index);
rc = -EINVAL;
}
}
}
if (!(*buf_info)) {
if (bufq->buf_type == ISP_SHARE_BUF) {
temp_buf_info = kzalloc(
sizeof(struct msm_isp_buffer), GFP_ATOMIC);
if (temp_buf_info) {
temp_buf_info->buf_reuse_flag = 1;
temp_buf_info->buf_used[id] = 1;
temp_buf_info->buf_get_count = 1;
list_add_tail(&temp_buf_info->share_list,
&bufq->share_head);
} else
rc = -ENOMEM;
}
} else {
(*buf_info)->state = MSM_ISP_BUFFER_STATE_DEQUEUED;
if (bufq->buf_type == ISP_SHARE_BUF) {
memset((*buf_info)->buf_used, 0,
sizeof(uint8_t) * bufq->buf_client_count);
(*buf_info)->buf_used[id] = 1;
(*buf_info)->buf_get_count = 1;
(*buf_info)->buf_put_count = 0;
(*buf_info)->buf_reuse_flag = 0;
list_add_tail(&(*buf_info)->share_list,
&bufq->share_head);
}
rc = 0;
}
spin_unlock_irqrestore(&bufq->bufq_lock, flags);
return rc;
}
static int msm_isp_put_buf(struct msm_isp_buf_mgr *buf_mgr,
uint32_t bufq_handle, uint32_t buf_index)
{
int rc = -1;
unsigned long flags;
struct msm_isp_bufq *bufq = NULL;
struct msm_isp_buffer *buf_info = NULL;
bufq = msm_isp_get_bufq(buf_mgr, bufq_handle);
if (!bufq) {
pr_err("%s: Invalid bufq\n", __func__);
return rc;
}
buf_info = msm_isp_get_buf_ptr(buf_mgr, bufq_handle, buf_index);
if (!buf_info) {
pr_err("%s: buf not found\n", __func__);
return rc;
}
spin_lock_irqsave(&bufq->bufq_lock, flags);
switch (buf_info->state) {
case MSM_ISP_BUFFER_STATE_PREPARED:
case MSM_ISP_BUFFER_STATE_DEQUEUED:
case MSM_ISP_BUFFER_STATE_DIVERTED:
if (BUF_SRC(bufq->stream_id))
list_add_tail(&buf_info->list, &bufq->head);
else
buf_mgr->vb2_ops->put_buf(buf_info->vb2_buf,
bufq->session_id, bufq->stream_id);
buf_info->state = MSM_ISP_BUFFER_STATE_QUEUED;
rc = 0;
break;
case MSM_ISP_BUFFER_STATE_DISPATCHED:
buf_info->state = MSM_ISP_BUFFER_STATE_QUEUED;
rc = 0;
break;
case MSM_ISP_BUFFER_STATE_QUEUED:
rc = 0;
break;
default:
pr_err("%s: incorrect state = %d",
__func__, buf_info->state);
break;
}
spin_unlock_irqrestore(&bufq->bufq_lock, flags);
return rc;
}
static int msm_isp_buf_done(struct msm_isp_buf_mgr *buf_mgr,
uint32_t bufq_handle, uint32_t buf_index,
struct timeval *tv, uint32_t frame_id, uint32_t output_format)
{
int rc = -1;
unsigned long flags;
struct msm_isp_bufq *bufq = NULL;
struct msm_isp_buffer *buf_info = NULL;
enum msm_isp_buffer_state state;
bufq = msm_isp_get_bufq(buf_mgr, bufq_handle);
if (!bufq) {
pr_err("Invalid bufq\n");
return rc;
}
buf_info = msm_isp_get_buf_ptr(buf_mgr, bufq_handle, buf_index);
if (!buf_info) {
pr_err("%s: buf not found\n", __func__);
return rc;
}
spin_lock_irqsave(&bufq->bufq_lock, flags);
state = buf_info->state;
spin_unlock_irqrestore(&bufq->bufq_lock, flags);
if (state == MSM_ISP_BUFFER_STATE_DEQUEUED ||
state == MSM_ISP_BUFFER_STATE_DIVERTED) {
spin_lock_irqsave(&bufq->bufq_lock, flags);
if (bufq->buf_type == ISP_SHARE_BUF) {
buf_info->buf_put_count++;
if (buf_info->buf_put_count != ISP_SHARE_BUF_CLIENT) {
rc = buf_info->buf_put_count;
spin_unlock_irqrestore(&bufq->bufq_lock, flags);
return rc;
}
}
buf_info->state = MSM_ISP_BUFFER_STATE_DISPATCHED;
if ((BUF_SRC(bufq->stream_id))) {
spin_unlock_irqrestore(&bufq->bufq_lock, flags);
rc = msm_isp_put_buf(buf_mgr, buf_info->bufq_handle,
buf_info->buf_idx);
if (rc < 0) {
pr_err("%s: Buf put failed\n", __func__);
return rc;
}
} else {
buf_info->vb2_buf->v4l2_buf.timestamp = *tv;
buf_info->vb2_buf->v4l2_buf.sequence = frame_id;
buf_info->vb2_buf->v4l2_buf.reserved = output_format;
spin_unlock_irqrestore(&bufq->bufq_lock, flags);
buf_mgr->vb2_ops->buf_done(buf_info->vb2_buf,
bufq->session_id, bufq->stream_id);
}
}
return 0;
}
static int msm_isp_flush_buf(struct msm_isp_buf_mgr *buf_mgr,
uint32_t bufq_handle, enum msm_isp_buffer_flush_t flush_type)
{
int rc = -1, i;
unsigned long flags;
struct msm_isp_bufq *bufq = NULL;
struct msm_isp_buffer *buf_info = NULL;
bufq = msm_isp_get_bufq(buf_mgr, bufq_handle);
if (!bufq) {
pr_err("Invalid bufq\n");
return rc;
}
pr_err("%s: CAMD bufqh:%d flush_type:%d\n", __func__, bufq_handle, flush_type);
for (i = 0; i < bufq->num_bufs; i++) {
buf_info = msm_isp_get_buf_ptr(buf_mgr, bufq_handle, i);
if (!buf_info) {
pr_err("%s: buf not found\n", __func__);
continue;
}
spin_lock_irqsave(&bufq->bufq_lock, flags);
if (flush_type == MSM_ISP_BUFFER_FLUSH_DIVERTED &&
buf_info->state == MSM_ISP_BUFFER_STATE_DIVERTED) {
buf_info->state = MSM_ISP_BUFFER_STATE_QUEUED;
} else if (flush_type == MSM_ISP_BUFFER_FLUSH_ALL &&
(buf_info->state == MSM_ISP_BUFFER_STATE_DEQUEUED ||
buf_info->state == MSM_ISP_BUFFER_STATE_DIVERTED ||
buf_info->state == MSM_ISP_BUFFER_STATE_DISPATCHED)) {
buf_info->state = MSM_ISP_BUFFER_STATE_QUEUED;
}
spin_unlock_irqrestore(&bufq->bufq_lock, flags);
}
return 0;
}
static int msm_isp_buf_divert(struct msm_isp_buf_mgr *buf_mgr,
uint32_t bufq_handle, uint32_t buf_index,
struct timeval *tv, uint32_t frame_id)
{
int rc = -1;
unsigned long flags;
struct msm_isp_bufq *bufq = NULL;
struct msm_isp_buffer *buf_info = NULL;
bufq = msm_isp_get_bufq(buf_mgr, bufq_handle);
if (!bufq) {
pr_err("Invalid bufq\n");
return rc;
}
buf_info = msm_isp_get_buf_ptr(buf_mgr, bufq_handle, buf_index);
if (!buf_info) {
pr_err("%s: buf not found\n", __func__);
return rc;
}
spin_lock_irqsave(&bufq->bufq_lock, flags);
if (bufq->buf_type == ISP_SHARE_BUF) {
buf_info->buf_put_count++;
if (buf_info->buf_put_count != ISP_SHARE_BUF_CLIENT) {
rc = buf_info->buf_put_count;
spin_unlock_irqrestore(&bufq->bufq_lock, flags);
return rc;
}
}
if (buf_info->state == MSM_ISP_BUFFER_STATE_DEQUEUED) {
buf_info->state = MSM_ISP_BUFFER_STATE_DIVERTED;
buf_info->tv = tv;
buf_info->frame_id = frame_id;
}
spin_unlock_irqrestore(&bufq->bufq_lock, flags);
return 0;
}
static int msm_isp_buf_enqueue(struct msm_isp_buf_mgr *buf_mgr,
struct msm_isp_qbuf_info *info)
{
int rc = -1, buf_state;
struct msm_isp_bufq *bufq = NULL;
struct msm_isp_buffer *buf_info = NULL;
buf_state = msm_isp_buf_prepare(buf_mgr, info, NULL);
if (buf_state < 0) {
pr_err("%s: Buf prepare failed\n", __func__);
return -EINVAL;
}
if (buf_state == MSM_ISP_BUFFER_STATE_DIVERTED) {
buf_info = msm_isp_get_buf_ptr(buf_mgr,
info->handle, info->buf_idx);
if (buf_info == NULL) {
pr_err("%s: buf_info is NULL\n", __func__);
return rc;
}
if (info->dirty_buf) {
rc = msm_isp_put_buf(buf_mgr,
info->handle, info->buf_idx);
} else {
bufq = msm_isp_get_bufq(buf_mgr, info->handle);
if (!bufq) {
pr_err("%s: Invalid bufq\n", __func__);
return rc;
}
if (BUF_SRC(bufq->stream_id))
pr_err("%s: Invalid native buffer state\n",
__func__);
else
rc = msm_isp_buf_done(buf_mgr,
info->handle, info->buf_idx,
buf_info->tv, buf_info->frame_id, 0);
}
} else {
bufq = msm_isp_get_bufq(buf_mgr, info->handle);
if (bufq && BUF_SRC(bufq->stream_id)) {
rc = msm_isp_put_buf(buf_mgr,
info->handle, info->buf_idx);
if (rc < 0) {
pr_err("%s: Buf put failed\n", __func__);
return rc;
}
}
}
return rc;
}
static int msm_isp_get_bufq_handle(struct msm_isp_buf_mgr *buf_mgr,
uint32_t session_id, uint32_t stream_id)
{
int i;
for (i = 0; i < buf_mgr->num_buf_q; i++) {
if (buf_mgr->bufq[i].session_id == session_id &&
buf_mgr->bufq[i].stream_id == stream_id) {
return buf_mgr->bufq[i].bufq_handle;
}
}
return 0;
}
static int msm_isp_request_bufq(struct msm_isp_buf_mgr *buf_mgr,
struct msm_isp_buf_request *buf_request)
{
int rc = -1, i;
struct msm_isp_bufq *bufq = NULL;
CDBG("%s: E\n", __func__);
if (!buf_request->num_buf || buf_request->num_buf > VIDEO_MAX_FRAME) {
pr_err("Invalid buffer request\n");
return rc;
}
buf_request->handle = msm_isp_get_buf_handle(buf_mgr,
buf_request->session_id, buf_request->stream_id);
if (!buf_request->handle) {
pr_err("Invalid buffer handle\n");
return rc;
}
bufq = msm_isp_get_bufq(buf_mgr, buf_request->handle);
if (!bufq) {
pr_err("Invalid buffer queue\n");
return rc;
}
bufq->bufs = kzalloc(sizeof(struct msm_isp_buffer) *
buf_request->num_buf, GFP_KERNEL);
if (!bufq->bufs) {
pr_err("No free memory for buf info\n");
msm_isp_free_buf_handle(buf_mgr, buf_request->handle);
return rc;
}
spin_lock_init(&bufq->bufq_lock);
bufq->bufq_handle = buf_request->handle;
bufq->session_id = buf_request->session_id;
bufq->stream_id = buf_request->stream_id;
bufq->num_bufs = buf_request->num_buf;
bufq->buf_type = buf_request->buf_type;
if (bufq->buf_type == ISP_SHARE_BUF)
bufq->buf_client_count = ISP_SHARE_BUF_CLIENT;
INIT_LIST_HEAD(&bufq->head);
INIT_LIST_HEAD(&bufq->share_head);
for (i = 0; i < buf_request->num_buf; i++) {
bufq->bufs[i].state = MSM_ISP_BUFFER_STATE_INITIALIZED;
bufq->bufs[i].bufq_handle = bufq->bufq_handle;
bufq->bufs[i].buf_idx = i;
}
return 0;
}
static int msm_isp_release_bufq(struct msm_isp_buf_mgr *buf_mgr,
uint32_t bufq_handle)
{
struct msm_isp_bufq *bufq = NULL;
int rc = -1;
bufq = msm_isp_get_bufq(buf_mgr, bufq_handle);
if (!bufq) {
pr_err("Invalid bufq release\n");
return rc;
}
msm_isp_buf_unprepare(buf_mgr, bufq_handle);
kfree(bufq->bufs);
msm_isp_free_buf_handle(buf_mgr, bufq_handle);
return 0;
}
static void msm_isp_release_all_bufq(
struct msm_isp_buf_mgr *buf_mgr)
{
struct msm_isp_bufq *bufq = NULL;
int i;
for (i = 0; i < buf_mgr->num_buf_q; i++) {
bufq = &buf_mgr->bufq[i];
if (!bufq->bufq_handle)
continue;
msm_isp_buf_unprepare(buf_mgr, bufq->bufq_handle);
kfree(bufq->bufs);
msm_isp_free_buf_handle(buf_mgr, bufq->bufq_handle);
}
}
static void msm_isp_register_ctx(struct msm_isp_buf_mgr *buf_mgr,
struct device **iommu_ctx, int num_iommu_ctx)
{
int i;
buf_mgr->num_iommu_ctx = num_iommu_ctx;
for (i = 0; i < num_iommu_ctx; i++)
buf_mgr->iommu_ctx[i] = iommu_ctx[i];
}
static int msm_isp_attach_ctx(struct msm_isp_buf_mgr *buf_mgr)
{
int rc, i;
for (i = 0; i < buf_mgr->num_iommu_ctx; i++) {
rc = iommu_attach_device(buf_mgr->iommu_domain,
buf_mgr->iommu_ctx[i]);
if (rc) {
pr_err("%s: Iommu attach error\n", __func__);
return -EINVAL;
}
}
return 0;
}
static void msm_isp_detach_ctx(struct msm_isp_buf_mgr *buf_mgr)
{
int i;
for (i = 0; i < buf_mgr->num_iommu_ctx; i++)
iommu_detach_device(buf_mgr->iommu_domain,
buf_mgr->iommu_ctx[i]);
}
static int msm_isp_init_isp_buf_mgr(
struct msm_isp_buf_mgr *buf_mgr,
const char *ctx_name, uint16_t num_buf_q)
{
int rc = -1;
if (buf_mgr->open_count++)
return 0;
if (!num_buf_q) {
pr_err("Invalid buffer queue number\n");
return rc;
}
CDBG("%s: E\n", __func__);
msm_isp_attach_ctx(buf_mgr);
INIT_LIST_HEAD(&buf_mgr->buffer_q);
buf_mgr->num_buf_q = num_buf_q;
buf_mgr->bufq =
kzalloc(sizeof(struct msm_isp_bufq) * num_buf_q,
GFP_KERNEL);
if (!buf_mgr->bufq) {
pr_err("Bufq malloc error\n");
goto bufq_error;
}
buf_mgr->client = msm_ion_client_create(-1, ctx_name);
buf_mgr->buf_handle_cnt = 0;
return 0;
bufq_error:
return rc;
}
static int msm_isp_deinit_isp_buf_mgr(
struct msm_isp_buf_mgr *buf_mgr)
{
if (--buf_mgr->open_count)
return 0;
msm_isp_release_all_bufq(buf_mgr);
ion_client_destroy(buf_mgr->client);
kfree(buf_mgr->bufq);
buf_mgr->num_buf_q = 0;
msm_isp_detach_ctx(buf_mgr);
return 0;
}
int msm_isp_proc_buf_cmd(struct msm_isp_buf_mgr *buf_mgr,
unsigned int cmd, void *arg)
{
switch (cmd) {
case VIDIOC_MSM_ISP_REQUEST_BUF: {
struct msm_isp_buf_request *buf_req = arg;
buf_mgr->ops->request_buf(buf_mgr, buf_req);
break;
}
case VIDIOC_MSM_ISP_ENQUEUE_BUF: {
struct msm_isp_qbuf_info *qbuf_info = arg;
buf_mgr->ops->enqueue_buf(buf_mgr, qbuf_info);
break;
}
case VIDIOC_MSM_ISP_RELEASE_BUF: {
struct msm_isp_buf_request *buf_req = arg;
buf_mgr->ops->release_buf(buf_mgr, buf_req->handle);
break;
}
}
return 0;
}
static struct msm_isp_buf_ops isp_buf_ops = {
.request_buf = msm_isp_request_bufq,
.enqueue_buf = msm_isp_buf_enqueue,
.release_buf = msm_isp_release_bufq,
.get_bufq_handle = msm_isp_get_bufq_handle,
.get_buf = msm_isp_get_buf,
.put_buf = msm_isp_put_buf,
.flush_buf = msm_isp_flush_buf,
.buf_done = msm_isp_buf_done,
.buf_divert = msm_isp_buf_divert,
.register_ctx = msm_isp_register_ctx,
.buf_mgr_init = msm_isp_init_isp_buf_mgr,
.buf_mgr_deinit = msm_isp_deinit_isp_buf_mgr,
};
int msm_isp_create_isp_buf_mgr(
struct msm_isp_buf_mgr *buf_mgr,
struct msm_sd_req_vb2_q *vb2_ops,
struct msm_iova_layout *iova_layout)
{
int rc = 0;
if (buf_mgr->init_done)
return rc;
buf_mgr->iommu_domain_num = msm_register_domain(iova_layout);
if (buf_mgr->iommu_domain_num < 0) {
pr_err("%s: Invalid iommu domain number\n", __func__);
rc = -1;
goto iommu_domain_error;
}
buf_mgr->iommu_domain = msm_get_iommu_domain(
buf_mgr->iommu_domain_num);
if (!buf_mgr->iommu_domain) {
pr_err("%s: Invalid iommu domain\n", __func__);
rc = -1;
goto iommu_domain_error;
}
buf_mgr->ops = &isp_buf_ops;
buf_mgr->vb2_ops = vb2_ops;
buf_mgr->init_done = 1;
buf_mgr->open_count = 0;
return 0;
iommu_domain_error:
return rc;
}
| gpl-2.0 |
pengus77/kowalski | drivers/video/tegra/host/t20/t20.c | 104 | 7728 | /*
* drivers/video/tegra/host/t20/t20.c
*
* Tegra Graphics Init for T20 Architecture Chips
*
* Copyright (c) 2011-2012, NVIDIA Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/nvhost_ioctl.h>
#include <mach/powergate.h>
#include <mach/iomap.h>
#include "t20.h"
#include "gr3d/gr3d_t20.h"
#include "mpe/mpe.h"
#include "host1x/host1x.h"
#include "nvhost_channel.h"
#include "nvhost_memmgr.h"
#include "host1x/host1x01_hardware.h"
#include "host1x/host1x_syncpt.h"
#include "chip_support.h"
#define NVMODMUTEX_2D_FULL (1)
#define NVMODMUTEX_2D_SIMPLE (2)
#define NVMODMUTEX_2D_SB_A (3)
#define NVMODMUTEX_2D_SB_B (4)
#define NVMODMUTEX_3D (5)
#define NVMODMUTEX_DISPLAYA (6)
#define NVMODMUTEX_DISPLAYB (7)
#define NVMODMUTEX_VI (8)
#define NVMODMUTEX_DSI (9)
static int t20_num_alloc_channels = 0;
static struct resource tegra_host1x01_resources[] = {
{
.start = TEGRA_HOST1X_BASE,
.end = TEGRA_HOST1X_BASE + TEGRA_HOST1X_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_SYNCPT_THRESH_BASE,
.end = INT_SYNCPT_THRESH_BASE + INT_SYNCPT_THRESH_NR - 1,
.flags = IORESOURCE_IRQ,
},
{
.start = INT_HOST1X_MPCORE_GENERAL,
.end = INT_HOST1X_MPCORE_GENERAL,
.flags = IORESOURCE_IRQ,
},
};
static const char *s_syncpt_names[32] = {
"gfx_host",
"", "", "", "", "", "", "",
"disp0_a", "disp1_a", "avp_0",
"csi_vi_0", "csi_vi_1",
"vi_isp_0", "vi_isp_1", "vi_isp_2", "vi_isp_3", "vi_isp_4",
"2d_0", "2d_1",
"disp0_b", "disp1_b",
"3d",
"mpe",
"disp0_c", "disp1_c",
"vblank0", "vblank1",
"mpe_ebm_eof", "mpe_wr_safe",
"2d_tinyblt",
"dsi"
};
static struct host1x_device_info host1x01_info = {
.nb_channels = 8,
.nb_pts = 32,
.nb_mlocks = 16,
.nb_bases = 8,
.syncpt_names = s_syncpt_names,
.client_managed = NVSYNCPTS_CLIENT_MANAGED,
};
static struct nvhost_device tegra_host1x01_device = {
.dev = {.platform_data = &host1x01_info},
.name = "host1x",
.id = -1,
.resource = tegra_host1x01_resources,
.num_resources = ARRAY_SIZE(tegra_host1x01_resources),
.clocks = {{"host1x", UINT_MAX}, {} },
NVHOST_MODULE_NO_POWERGATE_IDS,
};
static struct nvhost_device tegra_display01_device = {
.name = "display",
.id = -1,
.index = 0,
.syncpts = BIT(NVSYNCPT_DISP0_A) | BIT(NVSYNCPT_DISP1_A) |
BIT(NVSYNCPT_DISP0_B) | BIT(NVSYNCPT_DISP1_B) |
BIT(NVSYNCPT_DISP0_C) | BIT(NVSYNCPT_DISP1_C) |
BIT(NVSYNCPT_VBLANK0) | BIT(NVSYNCPT_VBLANK1),
.modulemutexes = BIT(NVMODMUTEX_DISPLAYA) | BIT(NVMODMUTEX_DISPLAYB),
NVHOST_MODULE_NO_POWERGATE_IDS,
NVHOST_DEFAULT_CLOCKGATE_DELAY,
.moduleid = NVHOST_MODULE_NONE,
};
static struct nvhost_device tegra_gr3d01_device = {
.name = "gr3d",
.version = 1,
.id = -1,
.index = 1,
.syncpts = BIT(NVSYNCPT_3D),
.waitbases = BIT(NVWAITBASE_3D),
.modulemutexes = BIT(NVMODMUTEX_3D),
.class = NV_GRAPHICS_3D_CLASS_ID,
.clocks = {{"gr3d", UINT_MAX}, {"emc", UINT_MAX}, {} },
.powergate_ids = {TEGRA_POWERGATE_3D, -1},
NVHOST_DEFAULT_CLOCKGATE_DELAY,
.moduleid = NVHOST_MODULE_NONE,
};
static struct nvhost_device tegra_gr2d01_device = {
.name = "gr2d",
.id = -1,
.index = 2,
.syncpts = BIT(NVSYNCPT_2D_0) | BIT(NVSYNCPT_2D_1),
.waitbases = BIT(NVWAITBASE_2D_0) | BIT(NVWAITBASE_2D_1),
.modulemutexes = BIT(NVMODMUTEX_2D_FULL) | BIT(NVMODMUTEX_2D_SIMPLE) |
BIT(NVMODMUTEX_2D_SB_A) | BIT(NVMODMUTEX_2D_SB_B),
.clocks = { {"gr2d", UINT_MAX},
{"epp", UINT_MAX},
{"emc", UINT_MAX} },
NVHOST_MODULE_NO_POWERGATE_IDS,
.clockgate_delay = 0,
.moduleid = NVHOST_MODULE_NONE,
.serialize = true,
};
static struct resource isp_resources_t20[] = {
{
.name = "regs",
.start = TEGRA_ISP_BASE,
.end = TEGRA_ISP_BASE + TEGRA_ISP_SIZE - 1,
.flags = IORESOURCE_MEM,
}
};
static struct nvhost_device tegra_isp01_device = {
.name = "isp",
.id = -1,
.resource = isp_resources_t20,
.num_resources = ARRAY_SIZE(isp_resources_t20),
.index = 3,
.syncpts = 0,
NVHOST_MODULE_NO_POWERGATE_IDS,
NVHOST_DEFAULT_CLOCKGATE_DELAY,
.moduleid = NVHOST_MODULE_ISP,
};
static struct resource vi_resources[] = {
{
.name = "regs",
.start = TEGRA_VI_BASE,
.end = TEGRA_VI_BASE + TEGRA_VI_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
static struct nvhost_device tegra_vi01_device = {
.name = "vi",
.resource = vi_resources,
.num_resources = ARRAY_SIZE(vi_resources),
.id = -1,
.index = 4,
.syncpts = BIT(NVSYNCPT_CSI_VI_0) | BIT(NVSYNCPT_CSI_VI_1) |
BIT(NVSYNCPT_VI_ISP_0) | BIT(NVSYNCPT_VI_ISP_1) |
BIT(NVSYNCPT_VI_ISP_2) | BIT(NVSYNCPT_VI_ISP_3) |
BIT(NVSYNCPT_VI_ISP_4),
.modulemutexes = BIT(NVMODMUTEX_VI),
.exclusive = true,
NVHOST_MODULE_NO_POWERGATE_IDS,
NVHOST_DEFAULT_CLOCKGATE_DELAY,
.moduleid = NVHOST_MODULE_VI,
};
static struct resource tegra_mpe01_resources[] = {
{
.name = "regs",
.start = TEGRA_MPE_BASE,
.end = TEGRA_MPE_BASE + TEGRA_MPE_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
static struct nvhost_device tegra_mpe01_device = {
.name = "mpe",
.version = 1,
.id = -1,
.resource = tegra_mpe01_resources,
.num_resources = ARRAY_SIZE(tegra_mpe01_resources),
.index = 5,
.syncpts = BIT(NVSYNCPT_MPE) | BIT(NVSYNCPT_MPE_EBM_EOF) |
BIT(NVSYNCPT_MPE_WR_SAFE),
.waitbases = BIT(NVWAITBASE_MPE),
.class = NV_VIDEO_ENCODE_MPEG_CLASS_ID,
.waitbasesync = true,
.keepalive = true,
.clocks = { {"mpe", UINT_MAX},
{"emc", UINT_MAX} },
.powergate_ids = {TEGRA_POWERGATE_MPE, -1},
NVHOST_DEFAULT_CLOCKGATE_DELAY,
.moduleid = NVHOST_MODULE_MPE,
};
static struct nvhost_device tegra_dsi01_device = {
.name = "dsi",
.id = -1,
.index = 6,
.syncpts = BIT(NVSYNCPT_DSI),
.modulemutexes = BIT(NVMODMUTEX_DSI),
NVHOST_MODULE_NO_POWERGATE_IDS,
NVHOST_DEFAULT_CLOCKGATE_DELAY,
.moduleid = NVHOST_MODULE_NONE,
};
static struct nvhost_device *t20_devices[] = {
&tegra_host1x01_device,
&tegra_display01_device,
&tegra_gr3d01_device,
&tegra_gr2d01_device,
&tegra_isp01_device,
&tegra_vi01_device,
&tegra_mpe01_device,
&tegra_dsi01_device,
};
int tegra2_register_host1x_devices(void)
{
return nvhost_add_devices(t20_devices, ARRAY_SIZE(t20_devices));
}
static void t20_free_nvhost_channel(struct nvhost_channel *ch)
{
nvhost_free_channel_internal(ch, &t20_num_alloc_channels);
}
static struct nvhost_channel *t20_alloc_nvhost_channel(
struct nvhost_device *dev)
{
return nvhost_alloc_channel_internal(dev->index,
nvhost_get_host(dev)->info.nb_channels,
&t20_num_alloc_channels);
}
#include "host1x/host1x_channel.c"
#include "host1x/host1x_cdma.c"
#include "host1x/host1x_debug.c"
#include "host1x/host1x_syncpt.c"
#include "host1x/host1x_intr.c"
int nvhost_init_t20_support(struct nvhost_master *host,
struct nvhost_chip_support *op)
{
int err;
op->channel = host1x_channel_ops;
op->cdma = host1x_cdma_ops;
op->push_buffer = host1x_pushbuffer_ops;
op->debug = host1x_debug_ops;
host->sync_aperture = host->aperture + HOST1X_CHANNEL_SYNC_REG_BASE;
op->syncpt = host1x_syncpt_ops;
op->intr = host1x_intr_ops;
err = nvhost_memmgr_init(op);
if (err)
return err;
op->nvhost_dev.alloc_nvhost_channel = t20_alloc_nvhost_channel;
op->nvhost_dev.free_nvhost_channel = t20_free_nvhost_channel;
return 0;
}
| gpl-2.0 |
Webee-IOT/webee210-linux-kernel-3.8 | drivers/media/usb/tm6000/tm6000-video.c | 104 | 45097 | /*
* tm6000-video.c - driver for TM5600/TM6000/TM6010 USB video capture devices
*
* Copyright (C) 2006-2007 Mauro Carvalho Chehab <mchehab@infradead.org>
*
* Copyright (C) 2007 Michel Ludwig <michel.ludwig@gmail.com>
* - Fixed module load/unload
*
* 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
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/random.h>
#include <linux/usb.h>
#include <linux/videodev2.h>
#include <media/v4l2-ioctl.h>
#include <media/tuner.h>
#include <linux/interrupt.h>
#include <linux/kthread.h>
#include <linux/highmem.h>
#include <linux/freezer.h>
#include "tm6000-regs.h"
#include "tm6000.h"
#define BUFFER_TIMEOUT msecs_to_jiffies(2000) /* 2 seconds */
/* Limits minimum and default number of buffers */
#define TM6000_MIN_BUF 4
#define TM6000_DEF_BUF 8
#define TM6000_MAX_ISO_PACKETS 46 /* Max number of ISO packets */
/* Declare static vars that will be used as parameters */
static unsigned int vid_limit = 16; /* Video memory limit, in Mb */
static int video_nr = -1; /* /dev/videoN, -1 for autodetect */
static int radio_nr = -1; /* /dev/radioN, -1 for autodetect */
/* Debug level */
int tm6000_debug;
EXPORT_SYMBOL_GPL(tm6000_debug);
static const struct v4l2_queryctrl no_ctrl = {
.name = "42",
.flags = V4L2_CTRL_FLAG_DISABLED,
};
/* supported controls */
static struct v4l2_queryctrl tm6000_qctrl[] = {
{
.id = V4L2_CID_BRIGHTNESS,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Brightness",
.minimum = 0,
.maximum = 255,
.step = 1,
.default_value = 54,
.flags = 0,
}, {
.id = V4L2_CID_CONTRAST,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Contrast",
.minimum = 0,
.maximum = 255,
.step = 0x1,
.default_value = 119,
.flags = 0,
}, {
.id = V4L2_CID_SATURATION,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Saturation",
.minimum = 0,
.maximum = 255,
.step = 0x1,
.default_value = 112,
.flags = 0,
}, {
.id = V4L2_CID_HUE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Hue",
.minimum = -128,
.maximum = 127,
.step = 0x1,
.default_value = 0,
.flags = 0,
},
/* --- audio --- */
{
.id = V4L2_CID_AUDIO_MUTE,
.name = "Mute",
.minimum = 0,
.maximum = 1,
.type = V4L2_CTRL_TYPE_BOOLEAN,
}, {
.id = V4L2_CID_AUDIO_VOLUME,
.name = "Volume",
.minimum = -15,
.maximum = 15,
.step = 1,
.default_value = 0,
.type = V4L2_CTRL_TYPE_INTEGER,
}
};
static const unsigned int CTRLS = ARRAY_SIZE(tm6000_qctrl);
static int qctl_regs[ARRAY_SIZE(tm6000_qctrl)];
static struct tm6000_fmt format[] = {
{
.name = "4:2:2, packed, YVY2",
.fourcc = V4L2_PIX_FMT_YUYV,
.depth = 16,
}, {
.name = "4:2:2, packed, UYVY",
.fourcc = V4L2_PIX_FMT_UYVY,
.depth = 16,
}, {
.name = "A/V + VBI mux packet",
.fourcc = V4L2_PIX_FMT_TM6000,
.depth = 16,
}
};
static const struct v4l2_queryctrl *ctrl_by_id(unsigned int id)
{
unsigned int i;
for (i = 0; i < CTRLS; i++)
if (tm6000_qctrl[i].id == id)
return tm6000_qctrl+i;
return NULL;
}
/* ------------------------------------------------------------------
* DMA and thread functions
* ------------------------------------------------------------------
*/
#define norm_maxw(a) 720
#define norm_maxh(a) 576
#define norm_minw(a) norm_maxw(a)
#define norm_minh(a) norm_maxh(a)
/*
* video-buf generic routine to get the next available buffer
*/
static inline void get_next_buf(struct tm6000_dmaqueue *dma_q,
struct tm6000_buffer **buf)
{
struct tm6000_core *dev = container_of(dma_q, struct tm6000_core, vidq);
if (list_empty(&dma_q->active)) {
dprintk(dev, V4L2_DEBUG_QUEUE, "No active queue to serve\n");
*buf = NULL;
return;
}
*buf = list_entry(dma_q->active.next,
struct tm6000_buffer, vb.queue);
}
/*
* Announces that a buffer were filled and request the next
*/
static inline void buffer_filled(struct tm6000_core *dev,
struct tm6000_dmaqueue *dma_q,
struct tm6000_buffer *buf)
{
/* Advice that buffer was filled */
dprintk(dev, V4L2_DEBUG_ISOC, "[%p/%d] wakeup\n", buf, buf->vb.i);
buf->vb.state = VIDEOBUF_DONE;
buf->vb.field_count++;
do_gettimeofday(&buf->vb.ts);
list_del(&buf->vb.queue);
wake_up(&buf->vb.done);
}
/*
* Identify the tm5600/6000 buffer header type and properly handles
*/
static int copy_streams(u8 *data, unsigned long len,
struct urb *urb)
{
struct tm6000_dmaqueue *dma_q = urb->context;
struct tm6000_core *dev = container_of(dma_q, struct tm6000_core, vidq);
u8 *ptr = data, *endp = data+len;
unsigned long header = 0;
int rc = 0;
unsigned int cmd, cpysize, pktsize, size, field, block, line, pos = 0;
struct tm6000_buffer *vbuf = NULL;
char *voutp = NULL;
unsigned int linewidth;
if (!dev->radio) {
/* get video buffer */
get_next_buf(dma_q, &vbuf);
if (!vbuf)
return rc;
voutp = videobuf_to_vmalloc(&vbuf->vb);
if (!voutp)
return 0;
}
for (ptr = data; ptr < endp;) {
if (!dev->isoc_ctl.cmd) {
/* Header */
if (dev->isoc_ctl.tmp_buf_len > 0) {
/* from last urb or packet */
header = dev->isoc_ctl.tmp_buf;
if (4 - dev->isoc_ctl.tmp_buf_len > 0) {
memcpy((u8 *)&header +
dev->isoc_ctl.tmp_buf_len,
ptr,
4 - dev->isoc_ctl.tmp_buf_len);
ptr += 4 - dev->isoc_ctl.tmp_buf_len;
}
dev->isoc_ctl.tmp_buf_len = 0;
} else {
if (ptr + 3 >= endp) {
/* have incomplete header */
dev->isoc_ctl.tmp_buf_len = endp - ptr;
memcpy(&dev->isoc_ctl.tmp_buf, ptr,
dev->isoc_ctl.tmp_buf_len);
return rc;
}
/* Seek for sync */
for (; ptr < endp - 3; ptr++) {
if (*(ptr + 3) == 0x47)
break;
}
/* Get message header */
header = *(unsigned long *)ptr;
ptr += 4;
}
/* split the header fields */
size = ((header & 0x7e) << 1);
if (size > 0)
size -= 4;
block = (header >> 7) & 0xf;
field = (header >> 11) & 0x1;
line = (header >> 12) & 0x1ff;
cmd = (header >> 21) & 0x7;
/* Validates haeder fields */
if (size > TM6000_URB_MSG_LEN)
size = TM6000_URB_MSG_LEN;
pktsize = TM6000_URB_MSG_LEN;
/*
* calculate position in buffer and change the buffer
*/
switch (cmd) {
case TM6000_URB_MSG_VIDEO:
if (!dev->radio) {
if ((dev->isoc_ctl.vfield != field) &&
(field == 1)) {
/*
* Announces that a new buffer
* were filled
*/
buffer_filled(dev, dma_q, vbuf);
dprintk(dev, V4L2_DEBUG_ISOC,
"new buffer filled\n");
get_next_buf(dma_q, &vbuf);
if (!vbuf)
return rc;
voutp = videobuf_to_vmalloc(&vbuf->vb);
if (!voutp)
return rc;
memset(voutp, 0, vbuf->vb.size);
}
linewidth = vbuf->vb.width << 1;
pos = ((line << 1) - field - 1) *
linewidth + block * TM6000_URB_MSG_LEN;
/* Don't allow to write out of the buffer */
if (pos + size > vbuf->vb.size)
cmd = TM6000_URB_MSG_ERR;
dev->isoc_ctl.vfield = field;
}
break;
case TM6000_URB_MSG_VBI:
break;
case TM6000_URB_MSG_AUDIO:
case TM6000_URB_MSG_PTS:
size = pktsize; /* Size is always 180 bytes */
break;
}
} else {
/* Continue the last copy */
cmd = dev->isoc_ctl.cmd;
size = dev->isoc_ctl.size;
pos = dev->isoc_ctl.pos;
pktsize = dev->isoc_ctl.pktsize;
field = dev->isoc_ctl.field;
}
cpysize = (endp - ptr > size) ? size : endp - ptr;
if (cpysize) {
/* copy data in different buffers */
switch (cmd) {
case TM6000_URB_MSG_VIDEO:
/* Fills video buffer */
if (vbuf)
memcpy(&voutp[pos], ptr, cpysize);
break;
case TM6000_URB_MSG_AUDIO: {
int i;
for (i = 0; i < cpysize; i += 2)
swab16s((u16 *)(ptr + i));
tm6000_call_fillbuf(dev, TM6000_AUDIO, ptr, cpysize);
break;
}
case TM6000_URB_MSG_VBI:
/* Need some code to copy vbi buffer */
break;
case TM6000_URB_MSG_PTS: {
/* Need some code to copy pts */
u32 pts;
pts = *(u32 *)ptr;
dprintk(dev, V4L2_DEBUG_ISOC, "field %d, PTS %x",
field, pts);
break;
}
}
}
if (ptr + pktsize > endp) {
/*
* End of URB packet, but cmd processing is not
* complete. Preserve the state for a next packet
*/
dev->isoc_ctl.pos = pos + cpysize;
dev->isoc_ctl.size = size - cpysize;
dev->isoc_ctl.cmd = cmd;
dev->isoc_ctl.field = field;
dev->isoc_ctl.pktsize = pktsize - (endp - ptr);
ptr += endp - ptr;
} else {
dev->isoc_ctl.cmd = 0;
ptr += pktsize;
}
}
return 0;
}
/*
* Identify the tm5600/6000 buffer header type and properly handles
*/
static int copy_multiplexed(u8 *ptr, unsigned long len,
struct urb *urb)
{
struct tm6000_dmaqueue *dma_q = urb->context;
struct tm6000_core *dev = container_of(dma_q, struct tm6000_core, vidq);
unsigned int pos = dev->isoc_ctl.pos, cpysize;
int rc = 1;
struct tm6000_buffer *buf;
char *outp = NULL;
get_next_buf(dma_q, &buf);
if (buf)
outp = videobuf_to_vmalloc(&buf->vb);
if (!outp)
return 0;
while (len > 0) {
cpysize = min(len, buf->vb.size-pos);
memcpy(&outp[pos], ptr, cpysize);
pos += cpysize;
ptr += cpysize;
len -= cpysize;
if (pos >= buf->vb.size) {
pos = 0;
/* Announces that a new buffer were filled */
buffer_filled(dev, dma_q, buf);
dprintk(dev, V4L2_DEBUG_ISOC, "new buffer filled\n");
get_next_buf(dma_q, &buf);
if (!buf)
break;
outp = videobuf_to_vmalloc(&(buf->vb));
if (!outp)
return rc;
pos = 0;
}
}
dev->isoc_ctl.pos = pos;
return rc;
}
static inline void print_err_status(struct tm6000_core *dev,
int packet, int status)
{
char *errmsg = "Unknown";
switch (status) {
case -ENOENT:
errmsg = "unlinked synchronuously";
break;
case -ECONNRESET:
errmsg = "unlinked asynchronuously";
break;
case -ENOSR:
errmsg = "Buffer error (overrun)";
break;
case -EPIPE:
errmsg = "Stalled (device not responding)";
break;
case -EOVERFLOW:
errmsg = "Babble (bad cable?)";
break;
case -EPROTO:
errmsg = "Bit-stuff error (bad cable?)";
break;
case -EILSEQ:
errmsg = "CRC/Timeout (could be anything)";
break;
case -ETIME:
errmsg = "Device does not respond";
break;
}
if (packet < 0) {
dprintk(dev, V4L2_DEBUG_QUEUE, "URB status %d [%s].\n",
status, errmsg);
} else {
dprintk(dev, V4L2_DEBUG_QUEUE, "URB packet %d, status %d [%s].\n",
packet, status, errmsg);
}
}
/*
* Controls the isoc copy of each urb packet
*/
static inline int tm6000_isoc_copy(struct urb *urb)
{
struct tm6000_dmaqueue *dma_q = urb->context;
struct tm6000_core *dev = container_of(dma_q, struct tm6000_core, vidq);
int i, len = 0, rc = 1, status;
char *p;
if (urb->status < 0) {
print_err_status(dev, -1, urb->status);
return 0;
}
for (i = 0; i < urb->number_of_packets; i++) {
status = urb->iso_frame_desc[i].status;
if (status < 0) {
print_err_status(dev, i, status);
continue;
}
len = urb->iso_frame_desc[i].actual_length;
if (len > 0) {
p = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
if (!urb->iso_frame_desc[i].status) {
if ((dev->fourcc) == V4L2_PIX_FMT_TM6000) {
rc = copy_multiplexed(p, len, urb);
if (rc <= 0)
return rc;
} else {
copy_streams(p, len, urb);
}
}
}
}
return rc;
}
/* ------------------------------------------------------------------
* URB control
* ------------------------------------------------------------------
*/
/*
* IRQ callback, called by URB callback
*/
static void tm6000_irq_callback(struct urb *urb)
{
struct tm6000_dmaqueue *dma_q = urb->context;
struct tm6000_core *dev = container_of(dma_q, struct tm6000_core, vidq);
int i;
switch (urb->status) {
case 0:
case -ETIMEDOUT:
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
return;
default:
tm6000_err("urb completion error %d.\n", urb->status);
break;
}
spin_lock(&dev->slock);
tm6000_isoc_copy(urb);
spin_unlock(&dev->slock);
/* Reset urb buffers */
for (i = 0; i < urb->number_of_packets; i++) {
urb->iso_frame_desc[i].status = 0;
urb->iso_frame_desc[i].actual_length = 0;
}
urb->status = usb_submit_urb(urb, GFP_ATOMIC);
if (urb->status)
tm6000_err("urb resubmit failed (error=%i)\n",
urb->status);
}
/*
* Stop and Deallocate URBs
*/
static void tm6000_uninit_isoc(struct tm6000_core *dev)
{
struct urb *urb;
int i;
dev->isoc_ctl.buf = NULL;
for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
urb = dev->isoc_ctl.urb[i];
if (urb) {
usb_kill_urb(urb);
usb_unlink_urb(urb);
if (dev->isoc_ctl.transfer_buffer[i]) {
usb_free_coherent(dev->udev,
urb->transfer_buffer_length,
dev->isoc_ctl.transfer_buffer[i],
urb->transfer_dma);
}
usb_free_urb(urb);
dev->isoc_ctl.urb[i] = NULL;
}
dev->isoc_ctl.transfer_buffer[i] = NULL;
}
kfree(dev->isoc_ctl.urb);
kfree(dev->isoc_ctl.transfer_buffer);
dev->isoc_ctl.urb = NULL;
dev->isoc_ctl.transfer_buffer = NULL;
dev->isoc_ctl.num_bufs = 0;
}
/*
* Allocate URBs and start IRQ
*/
static int tm6000_prepare_isoc(struct tm6000_core *dev)
{
struct tm6000_dmaqueue *dma_q = &dev->vidq;
int i, j, sb_size, pipe, size, max_packets, num_bufs = 8;
struct urb *urb;
/* De-allocates all pending stuff */
tm6000_uninit_isoc(dev);
/* Stop interrupt USB pipe */
tm6000_ir_int_stop(dev);
usb_set_interface(dev->udev,
dev->isoc_in.bInterfaceNumber,
dev->isoc_in.bAlternateSetting);
/* Start interrupt USB pipe */
tm6000_ir_int_start(dev);
pipe = usb_rcvisocpipe(dev->udev,
dev->isoc_in.endp->desc.bEndpointAddress &
USB_ENDPOINT_NUMBER_MASK);
size = usb_maxpacket(dev->udev, pipe, usb_pipeout(pipe));
if (size > dev->isoc_in.maxsize)
size = dev->isoc_in.maxsize;
dev->isoc_ctl.max_pkt_size = size;
max_packets = TM6000_MAX_ISO_PACKETS;
sb_size = max_packets * size;
dev->isoc_ctl.num_bufs = num_bufs;
dev->isoc_ctl.urb = kmalloc(sizeof(void *)*num_bufs, GFP_KERNEL);
if (!dev->isoc_ctl.urb) {
tm6000_err("cannot alloc memory for usb buffers\n");
return -ENOMEM;
}
dev->isoc_ctl.transfer_buffer = kmalloc(sizeof(void *)*num_bufs,
GFP_KERNEL);
if (!dev->isoc_ctl.transfer_buffer) {
tm6000_err("cannot allocate memory for usbtransfer\n");
kfree(dev->isoc_ctl.urb);
return -ENOMEM;
}
dprintk(dev, V4L2_DEBUG_QUEUE, "Allocating %d x %d packets"
" (%d bytes) of %d bytes each to handle %u size\n",
max_packets, num_bufs, sb_size,
dev->isoc_in.maxsize, size);
/* allocate urbs and transfer buffers */
for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
urb = usb_alloc_urb(max_packets, GFP_KERNEL);
if (!urb) {
tm6000_err("cannot alloc isoc_ctl.urb %i\n", i);
tm6000_uninit_isoc(dev);
usb_free_urb(urb);
return -ENOMEM;
}
dev->isoc_ctl.urb[i] = urb;
dev->isoc_ctl.transfer_buffer[i] = usb_alloc_coherent(dev->udev,
sb_size, GFP_KERNEL, &urb->transfer_dma);
if (!dev->isoc_ctl.transfer_buffer[i]) {
tm6000_err("unable to allocate %i bytes for transfer"
" buffer %i%s\n",
sb_size, i,
in_interrupt() ? " while in int" : "");
tm6000_uninit_isoc(dev);
return -ENOMEM;
}
memset(dev->isoc_ctl.transfer_buffer[i], 0, sb_size);
usb_fill_bulk_urb(urb, dev->udev, pipe,
dev->isoc_ctl.transfer_buffer[i], sb_size,
tm6000_irq_callback, dma_q);
urb->interval = dev->isoc_in.endp->desc.bInterval;
urb->number_of_packets = max_packets;
urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
for (j = 0; j < max_packets; j++) {
urb->iso_frame_desc[j].offset = size * j;
urb->iso_frame_desc[j].length = size;
}
}
return 0;
}
static int tm6000_start_thread(struct tm6000_core *dev)
{
struct tm6000_dmaqueue *dma_q = &dev->vidq;
int i;
dma_q->frame = 0;
dma_q->ini_jiffies = jiffies;
init_waitqueue_head(&dma_q->wq);
/* submit urbs and enables IRQ */
for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
int rc = usb_submit_urb(dev->isoc_ctl.urb[i], GFP_ATOMIC);
if (rc) {
tm6000_err("submit of urb %i failed (error=%i)\n", i,
rc);
tm6000_uninit_isoc(dev);
return rc;
}
}
return 0;
}
/* ------------------------------------------------------------------
* Videobuf operations
* ------------------------------------------------------------------
*/
static int
buffer_setup(struct videobuf_queue *vq, unsigned int *count, unsigned int *size)
{
struct tm6000_fh *fh = vq->priv_data;
*size = fh->fmt->depth * fh->width * fh->height >> 3;
if (0 == *count)
*count = TM6000_DEF_BUF;
if (*count < TM6000_MIN_BUF)
*count = TM6000_MIN_BUF;
while (*size * *count > vid_limit * 1024 * 1024)
(*count)--;
return 0;
}
static void free_buffer(struct videobuf_queue *vq, struct tm6000_buffer *buf)
{
struct tm6000_fh *fh = vq->priv_data;
struct tm6000_core *dev = fh->dev;
unsigned long flags;
if (in_interrupt())
BUG();
/* We used to wait for the buffer to finish here, but this didn't work
because, as we were keeping the state as VIDEOBUF_QUEUED,
videobuf_queue_cancel marked it as finished for us.
(Also, it could wedge forever if the hardware was misconfigured.)
This should be safe; by the time we get here, the buffer isn't
queued anymore. If we ever start marking the buffers as
VIDEOBUF_ACTIVE, it won't be, though.
*/
spin_lock_irqsave(&dev->slock, flags);
if (dev->isoc_ctl.buf == buf)
dev->isoc_ctl.buf = NULL;
spin_unlock_irqrestore(&dev->slock, flags);
videobuf_vmalloc_free(&buf->vb);
buf->vb.state = VIDEOBUF_NEEDS_INIT;
}
static int
buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
enum v4l2_field field)
{
struct tm6000_fh *fh = vq->priv_data;
struct tm6000_buffer *buf = container_of(vb, struct tm6000_buffer, vb);
struct tm6000_core *dev = fh->dev;
int rc = 0;
BUG_ON(NULL == fh->fmt);
/* FIXME: It assumes depth=2 */
/* The only currently supported format is 16 bits/pixel */
buf->vb.size = fh->fmt->depth*fh->width*fh->height >> 3;
if (0 != buf->vb.baddr && buf->vb.bsize < buf->vb.size)
return -EINVAL;
if (buf->fmt != fh->fmt ||
buf->vb.width != fh->width ||
buf->vb.height != fh->height ||
buf->vb.field != field) {
buf->fmt = fh->fmt;
buf->vb.width = fh->width;
buf->vb.height = fh->height;
buf->vb.field = field;
buf->vb.state = VIDEOBUF_NEEDS_INIT;
}
if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
rc = videobuf_iolock(vq, &buf->vb, NULL);
if (rc != 0)
goto fail;
}
if (!dev->isoc_ctl.num_bufs) {
rc = tm6000_prepare_isoc(dev);
if (rc < 0)
goto fail;
rc = tm6000_start_thread(dev);
if (rc < 0)
goto fail;
}
buf->vb.state = VIDEOBUF_PREPARED;
return 0;
fail:
free_buffer(vq, buf);
return rc;
}
static void
buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
{
struct tm6000_buffer *buf = container_of(vb, struct tm6000_buffer, vb);
struct tm6000_fh *fh = vq->priv_data;
struct tm6000_core *dev = fh->dev;
struct tm6000_dmaqueue *vidq = &dev->vidq;
buf->vb.state = VIDEOBUF_QUEUED;
list_add_tail(&buf->vb.queue, &vidq->active);
}
static void buffer_release(struct videobuf_queue *vq, struct videobuf_buffer *vb)
{
struct tm6000_buffer *buf = container_of(vb, struct tm6000_buffer, vb);
free_buffer(vq, buf);
}
static struct videobuf_queue_ops tm6000_video_qops = {
.buf_setup = buffer_setup,
.buf_prepare = buffer_prepare,
.buf_queue = buffer_queue,
.buf_release = buffer_release,
};
/* ------------------------------------------------------------------
* IOCTL handling
* ------------------------------------------------------------------
*/
static bool is_res_read(struct tm6000_core *dev, struct tm6000_fh *fh)
{
/* Is the current fh handling it? if so, that's OK */
if (dev->resources == fh && dev->is_res_read)
return true;
return false;
}
static bool is_res_streaming(struct tm6000_core *dev, struct tm6000_fh *fh)
{
/* Is the current fh handling it? if so, that's OK */
if (dev->resources == fh)
return true;
return false;
}
static bool res_get(struct tm6000_core *dev, struct tm6000_fh *fh,
bool is_res_read)
{
/* Is the current fh handling it? if so, that's OK */
if (dev->resources == fh && dev->is_res_read == is_res_read)
return true;
/* is it free? */
if (dev->resources)
return false;
/* grab it */
dev->resources = fh;
dev->is_res_read = is_res_read;
dprintk(dev, V4L2_DEBUG_RES_LOCK, "res: get\n");
return true;
}
static void res_free(struct tm6000_core *dev, struct tm6000_fh *fh)
{
/* Is the current fh handling it? if so, that's OK */
if (dev->resources != fh)
return;
dev->resources = NULL;
dprintk(dev, V4L2_DEBUG_RES_LOCK, "res: put\n");
}
/* ------------------------------------------------------------------
* IOCTL vidioc handling
* ------------------------------------------------------------------
*/
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct tm6000_core *dev = ((struct tm6000_fh *)priv)->dev;
strlcpy(cap->driver, "tm6000", sizeof(cap->driver));
strlcpy(cap->card, "Trident TVMaster TM5600/6000/6010", sizeof(cap->card));
cap->capabilities = V4L2_CAP_VIDEO_CAPTURE |
V4L2_CAP_STREAMING |
V4L2_CAP_AUDIO |
V4L2_CAP_READWRITE;
if (dev->tuner_type != TUNER_ABSENT)
cap->capabilities |= V4L2_CAP_TUNER;
return 0;
}
static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
if (unlikely(f->index >= ARRAY_SIZE(format)))
return -EINVAL;
strlcpy(f->description, format[f->index].name, sizeof(f->description));
f->pixelformat = format[f->index].fourcc;
return 0;
}
static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct tm6000_fh *fh = priv;
f->fmt.pix.width = fh->width;
f->fmt.pix.height = fh->height;
f->fmt.pix.field = fh->vb_vidq.field;
f->fmt.pix.pixelformat = fh->fmt->fourcc;
f->fmt.pix.bytesperline =
(f->fmt.pix.width * fh->fmt->depth) >> 3;
f->fmt.pix.sizeimage =
f->fmt.pix.height * f->fmt.pix.bytesperline;
return 0;
}
static struct tm6000_fmt *format_by_fourcc(unsigned int fourcc)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(format); i++)
if (format[i].fourcc == fourcc)
return format+i;
return NULL;
}
static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct tm6000_core *dev = ((struct tm6000_fh *)priv)->dev;
struct tm6000_fmt *fmt;
enum v4l2_field field;
fmt = format_by_fourcc(f->fmt.pix.pixelformat);
if (NULL == fmt) {
dprintk(dev, V4L2_DEBUG_IOCTL_ARG, "Fourcc format (0x%08x)"
" invalid.\n", f->fmt.pix.pixelformat);
return -EINVAL;
}
field = f->fmt.pix.field;
if (field == V4L2_FIELD_ANY)
field = V4L2_FIELD_SEQ_TB;
else if (V4L2_FIELD_INTERLACED != field) {
dprintk(dev, V4L2_DEBUG_IOCTL_ARG, "Field type invalid.\n");
return -EINVAL;
}
tm6000_get_std_res(dev);
f->fmt.pix.width = dev->width;
f->fmt.pix.height = dev->height;
f->fmt.pix.width &= ~0x01;
f->fmt.pix.field = field;
f->fmt.pix.bytesperline =
(f->fmt.pix.width * fmt->depth) >> 3;
f->fmt.pix.sizeimage =
f->fmt.pix.height * f->fmt.pix.bytesperline;
return 0;
}
/*FIXME: This seems to be generic enough to be at videodev2 */
static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct tm6000_fh *fh = priv;
struct tm6000_core *dev = fh->dev;
int ret = vidioc_try_fmt_vid_cap(file, fh, f);
if (ret < 0)
return ret;
fh->fmt = format_by_fourcc(f->fmt.pix.pixelformat);
fh->width = f->fmt.pix.width;
fh->height = f->fmt.pix.height;
fh->vb_vidq.field = f->fmt.pix.field;
fh->type = f->type;
dev->fourcc = f->fmt.pix.pixelformat;
tm6000_set_fourcc_format(dev);
return 0;
}
static int vidioc_reqbufs(struct file *file, void *priv,
struct v4l2_requestbuffers *p)
{
struct tm6000_fh *fh = priv;
return videobuf_reqbufs(&fh->vb_vidq, p);
}
static int vidioc_querybuf(struct file *file, void *priv,
struct v4l2_buffer *p)
{
struct tm6000_fh *fh = priv;
return videobuf_querybuf(&fh->vb_vidq, p);
}
static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
struct tm6000_fh *fh = priv;
return videobuf_qbuf(&fh->vb_vidq, p);
}
static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
struct tm6000_fh *fh = priv;
return videobuf_dqbuf(&fh->vb_vidq, p,
file->f_flags & O_NONBLOCK);
}
static int vidioc_streamon(struct file *file, void *priv, enum v4l2_buf_type i)
{
struct tm6000_fh *fh = priv;
struct tm6000_core *dev = fh->dev;
if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
if (i != fh->type)
return -EINVAL;
if (!res_get(dev, fh, false))
return -EBUSY;
return videobuf_streamon(&fh->vb_vidq);
}
static int vidioc_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
{
struct tm6000_fh *fh = priv;
struct tm6000_core *dev = fh->dev;
if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
if (i != fh->type)
return -EINVAL;
videobuf_streamoff(&fh->vb_vidq);
res_free(dev, fh);
return 0;
}
static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id *norm)
{
int rc = 0;
struct tm6000_fh *fh = priv;
struct tm6000_core *dev = fh->dev;
dev->norm = *norm;
rc = tm6000_init_analog_mode(dev);
fh->width = dev->width;
fh->height = dev->height;
if (rc < 0)
return rc;
v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_std, dev->norm);
return 0;
}
static const char *iname[] = {
[TM6000_INPUT_TV] = "Television",
[TM6000_INPUT_COMPOSITE1] = "Composite 1",
[TM6000_INPUT_COMPOSITE2] = "Composite 2",
[TM6000_INPUT_SVIDEO] = "S-Video",
};
static int vidioc_enum_input(struct file *file, void *priv,
struct v4l2_input *i)
{
struct tm6000_fh *fh = priv;
struct tm6000_core *dev = fh->dev;
unsigned int n;
n = i->index;
if (n >= 3)
return -EINVAL;
if (!dev->vinput[n].type)
return -EINVAL;
i->index = n;
if (dev->vinput[n].type == TM6000_INPUT_TV)
i->type = V4L2_INPUT_TYPE_TUNER;
else
i->type = V4L2_INPUT_TYPE_CAMERA;
strcpy(i->name, iname[dev->vinput[n].type]);
i->std = TM6000_STD;
return 0;
}
static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
{
struct tm6000_fh *fh = priv;
struct tm6000_core *dev = fh->dev;
*i = dev->input;
return 0;
}
static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
{
struct tm6000_fh *fh = priv;
struct tm6000_core *dev = fh->dev;
int rc = 0;
if (i >= 3)
return -EINVAL;
if (!dev->vinput[i].type)
return -EINVAL;
dev->input = i;
rc = vidioc_s_std(file, priv, &dev->vfd->current_norm);
return rc;
}
/* --- controls ---------------------------------------------- */
static int vidioc_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *qc)
{
int i;
for (i = 0; i < ARRAY_SIZE(tm6000_qctrl); i++)
if (qc->id && qc->id == tm6000_qctrl[i].id) {
memcpy(qc, &(tm6000_qctrl[i]),
sizeof(*qc));
return 0;
}
return -EINVAL;
}
static int vidioc_g_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct tm6000_fh *fh = priv;
struct tm6000_core *dev = fh->dev;
int val;
/* FIXME: Probably, those won't work! Maybe we need shadow regs */
switch (ctrl->id) {
case V4L2_CID_CONTRAST:
val = tm6000_get_reg(dev, TM6010_REQ07_R08_LUMA_CONTRAST_ADJ, 0);
break;
case V4L2_CID_BRIGHTNESS:
val = tm6000_get_reg(dev, TM6010_REQ07_R09_LUMA_BRIGHTNESS_ADJ, 0);
return 0;
case V4L2_CID_SATURATION:
val = tm6000_get_reg(dev, TM6010_REQ07_R0A_CHROMA_SATURATION_ADJ, 0);
return 0;
case V4L2_CID_HUE:
val = tm6000_get_reg(dev, TM6010_REQ07_R0B_CHROMA_HUE_PHASE_ADJ, 0);
return 0;
case V4L2_CID_AUDIO_MUTE:
val = dev->ctl_mute;
return 0;
case V4L2_CID_AUDIO_VOLUME:
val = dev->ctl_volume;
return 0;
default:
return -EINVAL;
}
if (val < 0)
return val;
ctrl->value = val;
return 0;
}
static int vidioc_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct tm6000_fh *fh = priv;
struct tm6000_core *dev = fh->dev;
u8 val = ctrl->value;
switch (ctrl->id) {
case V4L2_CID_CONTRAST:
tm6000_set_reg(dev, TM6010_REQ07_R08_LUMA_CONTRAST_ADJ, val);
return 0;
case V4L2_CID_BRIGHTNESS:
tm6000_set_reg(dev, TM6010_REQ07_R09_LUMA_BRIGHTNESS_ADJ, val);
return 0;
case V4L2_CID_SATURATION:
tm6000_set_reg(dev, TM6010_REQ07_R0A_CHROMA_SATURATION_ADJ, val);
return 0;
case V4L2_CID_HUE:
tm6000_set_reg(dev, TM6010_REQ07_R0B_CHROMA_HUE_PHASE_ADJ, val);
return 0;
case V4L2_CID_AUDIO_MUTE:
dev->ctl_mute = val;
tm6000_tvaudio_set_mute(dev, val);
return 0;
case V4L2_CID_AUDIO_VOLUME:
dev->ctl_volume = val;
tm6000_set_volume(dev, val);
return 0;
}
return -EINVAL;
}
static int vidioc_g_tuner(struct file *file, void *priv,
struct v4l2_tuner *t)
{
struct tm6000_fh *fh = priv;
struct tm6000_core *dev = fh->dev;
if (unlikely(UNSET == dev->tuner_type))
return -EINVAL;
if (0 != t->index)
return -EINVAL;
strcpy(t->name, "Television");
t->type = V4L2_TUNER_ANALOG_TV;
t->capability = V4L2_TUNER_CAP_NORM;
t->rangehigh = 0xffffffffUL;
t->rxsubchans = V4L2_TUNER_SUB_STEREO;
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, g_tuner, t);
t->audmode = dev->amode;
return 0;
}
static int vidioc_s_tuner(struct file *file, void *priv,
struct v4l2_tuner *t)
{
struct tm6000_fh *fh = priv;
struct tm6000_core *dev = fh->dev;
if (UNSET == dev->tuner_type)
return -EINVAL;
if (0 != t->index)
return -EINVAL;
dev->amode = t->audmode;
dprintk(dev, 3, "audio mode: %x\n", t->audmode);
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_tuner, t);
return 0;
}
static int vidioc_g_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct tm6000_fh *fh = priv;
struct tm6000_core *dev = fh->dev;
if (unlikely(UNSET == dev->tuner_type))
return -EINVAL;
f->type = fh->radio ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV;
f->frequency = dev->freq;
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, g_frequency, f);
return 0;
}
static int vidioc_s_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct tm6000_fh *fh = priv;
struct tm6000_core *dev = fh->dev;
if (unlikely(UNSET == dev->tuner_type))
return -EINVAL;
if (unlikely(f->tuner != 0))
return -EINVAL;
if (0 == fh->radio && V4L2_TUNER_ANALOG_TV != f->type)
return -EINVAL;
if (1 == fh->radio && V4L2_TUNER_RADIO != f->type)
return -EINVAL;
dev->freq = f->frequency;
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_frequency, f);
return 0;
}
static int radio_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct tm6000_fh *fh = file->private_data;
struct tm6000_core *dev = fh->dev;
strcpy(cap->driver, "tm6000");
strlcpy(cap->card, dev->name, sizeof(dev->name));
sprintf(cap->bus_info, "USB%04x:%04x",
le16_to_cpu(dev->udev->descriptor.idVendor),
le16_to_cpu(dev->udev->descriptor.idProduct));
cap->version = dev->dev_type;
cap->capabilities = V4L2_CAP_TUNER |
V4L2_CAP_AUDIO |
V4L2_CAP_RADIO |
V4L2_CAP_READWRITE |
V4L2_CAP_STREAMING;
return 0;
}
static int radio_g_tuner(struct file *file, void *priv,
struct v4l2_tuner *t)
{
struct tm6000_fh *fh = file->private_data;
struct tm6000_core *dev = fh->dev;
if (0 != t->index)
return -EINVAL;
memset(t, 0, sizeof(*t));
strcpy(t->name, "Radio");
t->type = V4L2_TUNER_RADIO;
t->rxsubchans = V4L2_TUNER_SUB_STEREO;
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, g_tuner, t);
return 0;
}
static int radio_s_tuner(struct file *file, void *priv,
struct v4l2_tuner *t)
{
struct tm6000_fh *fh = file->private_data;
struct tm6000_core *dev = fh->dev;
if (0 != t->index)
return -EINVAL;
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_tuner, t);
return 0;
}
static int radio_enum_input(struct file *file, void *priv,
struct v4l2_input *i)
{
struct tm6000_fh *fh = priv;
struct tm6000_core *dev = fh->dev;
if (i->index != 0)
return -EINVAL;
if (!dev->rinput.type)
return -EINVAL;
strcpy(i->name, "Radio");
i->type = V4L2_INPUT_TYPE_TUNER;
return 0;
}
static int radio_g_input(struct file *filp, void *priv, unsigned int *i)
{
struct tm6000_fh *fh = priv;
struct tm6000_core *dev = fh->dev;
if (dev->input != 5)
return -EINVAL;
*i = dev->input - 5;
return 0;
}
static int radio_g_audio(struct file *file, void *priv,
struct v4l2_audio *a)
{
memset(a, 0, sizeof(*a));
strcpy(a->name, "Radio");
return 0;
}
static int radio_s_audio(struct file *file, void *priv,
const struct v4l2_audio *a)
{
return 0;
}
static int radio_s_input(struct file *filp, void *priv, unsigned int i)
{
struct tm6000_fh *fh = priv;
struct tm6000_core *dev = fh->dev;
if (i)
return -EINVAL;
if (!dev->rinput.type)
return -EINVAL;
dev->input = i + 5;
return 0;
}
static int radio_s_std(struct file *file, void *fh, v4l2_std_id *norm)
{
return 0;
}
static int radio_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *c)
{
const struct v4l2_queryctrl *ctrl;
if (c->id < V4L2_CID_BASE ||
c->id >= V4L2_CID_LASTP1)
return -EINVAL;
if (c->id == V4L2_CID_AUDIO_MUTE) {
ctrl = ctrl_by_id(c->id);
*c = *ctrl;
} else
*c = no_ctrl;
return 0;
}
/* ------------------------------------------------------------------
File operations for the device
------------------------------------------------------------------*/
static int __tm6000_open(struct file *file)
{
struct video_device *vdev = video_devdata(file);
struct tm6000_core *dev = video_drvdata(file);
struct tm6000_fh *fh;
enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
int i, rc;
int radio = 0;
dprintk(dev, V4L2_DEBUG_OPEN, "tm6000: open called (dev=%s)\n",
video_device_node_name(vdev));
switch (vdev->vfl_type) {
case VFL_TYPE_GRABBER:
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
break;
case VFL_TYPE_VBI:
type = V4L2_BUF_TYPE_VBI_CAPTURE;
break;
case VFL_TYPE_RADIO:
radio = 1;
break;
}
/* If more than one user, mutex should be added */
dev->users++;
dprintk(dev, V4L2_DEBUG_OPEN, "open dev=%s type=%s users=%d\n",
video_device_node_name(vdev), v4l2_type_names[type],
dev->users);
/* allocate + initialize per filehandle data */
fh = kzalloc(sizeof(*fh), GFP_KERNEL);
if (NULL == fh) {
dev->users--;
return -ENOMEM;
}
file->private_data = fh;
fh->dev = dev;
fh->radio = radio;
dev->radio = radio;
fh->type = type;
dev->fourcc = format[0].fourcc;
fh->fmt = format_by_fourcc(dev->fourcc);
tm6000_get_std_res(dev);
fh->width = dev->width;
fh->height = dev->height;
dprintk(dev, V4L2_DEBUG_OPEN, "Open: fh=0x%08lx, dev=0x%08lx, "
"dev->vidq=0x%08lx\n",
(unsigned long)fh, (unsigned long)dev,
(unsigned long)&dev->vidq);
dprintk(dev, V4L2_DEBUG_OPEN, "Open: list_empty "
"queued=%d\n", list_empty(&dev->vidq.queued));
dprintk(dev, V4L2_DEBUG_OPEN, "Open: list_empty "
"active=%d\n", list_empty(&dev->vidq.active));
/* initialize hardware on analog mode */
rc = tm6000_init_analog_mode(dev);
if (rc < 0)
return rc;
if (dev->mode != TM6000_MODE_ANALOG) {
/* Put all controls at a sane state */
for (i = 0; i < ARRAY_SIZE(tm6000_qctrl); i++)
qctl_regs[i] = tm6000_qctrl[i].default_value;
dev->mode = TM6000_MODE_ANALOG;
}
if (!fh->radio) {
videobuf_queue_vmalloc_init(&fh->vb_vidq, &tm6000_video_qops,
NULL, &dev->slock,
fh->type,
V4L2_FIELD_INTERLACED,
sizeof(struct tm6000_buffer), fh, &dev->lock);
} else {
dprintk(dev, V4L2_DEBUG_OPEN, "video_open: setting radio device\n");
dev->input = 5;
tm6000_set_audio_rinput(dev);
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_radio);
tm6000_prepare_isoc(dev);
tm6000_start_thread(dev);
}
return 0;
}
static int tm6000_open(struct file *file)
{
struct video_device *vdev = video_devdata(file);
int res;
mutex_lock(vdev->lock);
res = __tm6000_open(file);
mutex_unlock(vdev->lock);
return res;
}
static ssize_t
tm6000_read(struct file *file, char __user *data, size_t count, loff_t *pos)
{
struct tm6000_fh *fh = file->private_data;
struct tm6000_core *dev = fh->dev;
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
int res;
if (!res_get(fh->dev, fh, true))
return -EBUSY;
if (mutex_lock_interruptible(&dev->lock))
return -ERESTARTSYS;
res = videobuf_read_stream(&fh->vb_vidq, data, count, pos, 0,
file->f_flags & O_NONBLOCK);
mutex_unlock(&dev->lock);
return res;
}
return 0;
}
static unsigned int
__tm6000_poll(struct file *file, struct poll_table_struct *wait)
{
struct tm6000_fh *fh = file->private_data;
struct tm6000_buffer *buf;
if (V4L2_BUF_TYPE_VIDEO_CAPTURE != fh->type)
return POLLERR;
if (!!is_res_streaming(fh->dev, fh))
return POLLERR;
if (!is_res_read(fh->dev, fh)) {
/* streaming capture */
if (list_empty(&fh->vb_vidq.stream))
return POLLERR;
buf = list_entry(fh->vb_vidq.stream.next, struct tm6000_buffer, vb.stream);
} else {
/* read() capture */
return videobuf_poll_stream(file, &fh->vb_vidq, wait);
}
poll_wait(file, &buf->vb.done, wait);
if (buf->vb.state == VIDEOBUF_DONE ||
buf->vb.state == VIDEOBUF_ERROR)
return POLLIN | POLLRDNORM;
return 0;
}
static unsigned int tm6000_poll(struct file *file, struct poll_table_struct *wait)
{
struct tm6000_fh *fh = file->private_data;
struct tm6000_core *dev = fh->dev;
unsigned int res;
mutex_lock(&dev->lock);
res = __tm6000_poll(file, wait);
mutex_unlock(&dev->lock);
return res;
}
static int tm6000_release(struct file *file)
{
struct tm6000_fh *fh = file->private_data;
struct tm6000_core *dev = fh->dev;
struct video_device *vdev = video_devdata(file);
dprintk(dev, V4L2_DEBUG_OPEN, "tm6000: close called (dev=%s, users=%d)\n",
video_device_node_name(vdev), dev->users);
mutex_lock(&dev->lock);
dev->users--;
res_free(dev, fh);
if (!dev->users) {
tm6000_uninit_isoc(dev);
/* Stop interrupt USB pipe */
tm6000_ir_int_stop(dev);
usb_reset_configuration(dev->udev);
if (dev->int_in.endp)
usb_set_interface(dev->udev,
dev->isoc_in.bInterfaceNumber, 2);
else
usb_set_interface(dev->udev,
dev->isoc_in.bInterfaceNumber, 0);
/* Start interrupt USB pipe */
tm6000_ir_int_start(dev);
if (!fh->radio)
videobuf_mmap_free(&fh->vb_vidq);
}
kfree(fh);
mutex_unlock(&dev->lock);
return 0;
}
static int tm6000_mmap(struct file *file, struct vm_area_struct * vma)
{
struct tm6000_fh *fh = file->private_data;
struct tm6000_core *dev = fh->dev;
int res;
if (mutex_lock_interruptible(&dev->lock))
return -ERESTARTSYS;
res = videobuf_mmap_mapper(&fh->vb_vidq, vma);
mutex_unlock(&dev->lock);
return res;
}
static struct v4l2_file_operations tm6000_fops = {
.owner = THIS_MODULE,
.open = tm6000_open,
.release = tm6000_release,
.unlocked_ioctl = video_ioctl2, /* V4L2 ioctl handler */
.read = tm6000_read,
.poll = tm6000_poll,
.mmap = tm6000_mmap,
};
static const struct v4l2_ioctl_ops video_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
.vidioc_s_std = vidioc_s_std,
.vidioc_enum_input = vidioc_enum_input,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
.vidioc_queryctrl = vidioc_queryctrl,
.vidioc_g_ctrl = vidioc_g_ctrl,
.vidioc_s_ctrl = vidioc_s_ctrl,
.vidioc_g_tuner = vidioc_g_tuner,
.vidioc_s_tuner = vidioc_s_tuner,
.vidioc_g_frequency = vidioc_g_frequency,
.vidioc_s_frequency = vidioc_s_frequency,
.vidioc_streamon = vidioc_streamon,
.vidioc_streamoff = vidioc_streamoff,
.vidioc_reqbufs = vidioc_reqbufs,
.vidioc_querybuf = vidioc_querybuf,
.vidioc_qbuf = vidioc_qbuf,
.vidioc_dqbuf = vidioc_dqbuf,
};
static struct video_device tm6000_template = {
.name = "tm6000",
.fops = &tm6000_fops,
.ioctl_ops = &video_ioctl_ops,
.release = video_device_release,
.tvnorms = TM6000_STD,
.current_norm = V4L2_STD_NTSC_M,
};
static const struct v4l2_file_operations radio_fops = {
.owner = THIS_MODULE,
.open = tm6000_open,
.release = tm6000_release,
.unlocked_ioctl = video_ioctl2,
};
static const struct v4l2_ioctl_ops radio_ioctl_ops = {
.vidioc_querycap = radio_querycap,
.vidioc_g_tuner = radio_g_tuner,
.vidioc_enum_input = radio_enum_input,
.vidioc_g_audio = radio_g_audio,
.vidioc_s_tuner = radio_s_tuner,
.vidioc_s_audio = radio_s_audio,
.vidioc_s_input = radio_s_input,
.vidioc_s_std = radio_s_std,
.vidioc_queryctrl = radio_queryctrl,
.vidioc_g_input = radio_g_input,
.vidioc_g_ctrl = vidioc_g_ctrl,
.vidioc_s_ctrl = vidioc_s_ctrl,
.vidioc_g_frequency = vidioc_g_frequency,
.vidioc_s_frequency = vidioc_s_frequency,
};
static struct video_device tm6000_radio_template = {
.name = "tm6000",
.fops = &radio_fops,
.ioctl_ops = &radio_ioctl_ops,
};
/* -----------------------------------------------------------------
* Initialization and module stuff
* ------------------------------------------------------------------
*/
static struct video_device *vdev_init(struct tm6000_core *dev,
const struct video_device
*template, const char *type_name)
{
struct video_device *vfd;
vfd = video_device_alloc();
if (NULL == vfd)
return NULL;
*vfd = *template;
vfd->v4l2_dev = &dev->v4l2_dev;
vfd->release = video_device_release;
vfd->debug = tm6000_debug;
vfd->lock = &dev->lock;
snprintf(vfd->name, sizeof(vfd->name), "%s %s", dev->name, type_name);
video_set_drvdata(vfd, dev);
return vfd;
}
int tm6000_v4l2_register(struct tm6000_core *dev)
{
int ret = -1;
dev->vfd = vdev_init(dev, &tm6000_template, "video");
if (!dev->vfd) {
printk(KERN_INFO "%s: can't register video device\n",
dev->name);
return -ENOMEM;
}
/* init video dma queues */
INIT_LIST_HEAD(&dev->vidq.active);
INIT_LIST_HEAD(&dev->vidq.queued);
ret = video_register_device(dev->vfd, VFL_TYPE_GRABBER, video_nr);
if (ret < 0) {
printk(KERN_INFO "%s: can't register video device\n",
dev->name);
return ret;
}
printk(KERN_INFO "%s: registered device %s\n",
dev->name, video_device_node_name(dev->vfd));
if (dev->caps.has_radio) {
dev->radio_dev = vdev_init(dev, &tm6000_radio_template,
"radio");
if (!dev->radio_dev) {
printk(KERN_INFO "%s: can't register radio device\n",
dev->name);
ret = -ENXIO;
return ret; /* FIXME release resource */
}
ret = video_register_device(dev->radio_dev, VFL_TYPE_RADIO,
radio_nr);
if (ret < 0) {
printk(KERN_INFO "%s: can't register radio device\n",
dev->name);
return ret; /* FIXME release resource */
}
printk(KERN_INFO "%s: registered device %s\n",
dev->name, video_device_node_name(dev->radio_dev));
}
printk(KERN_INFO "Trident TVMaster TM5600/TM6000/TM6010 USB2 board (Load status: %d)\n", ret);
return ret;
}
int tm6000_v4l2_unregister(struct tm6000_core *dev)
{
video_unregister_device(dev->vfd);
if (dev->radio_dev) {
if (video_is_registered(dev->radio_dev))
video_unregister_device(dev->radio_dev);
else
video_device_release(dev->radio_dev);
dev->radio_dev = NULL;
}
return 0;
}
int tm6000_v4l2_exit(void)
{
return 0;
}
module_param(video_nr, int, 0);
MODULE_PARM_DESC(video_nr, "Allow changing video device number");
module_param_named(debug, tm6000_debug, int, 0444);
MODULE_PARM_DESC(debug, "activates debug info");
module_param(vid_limit, int, 0644);
MODULE_PARM_DESC(vid_limit, "capture memory limit in megabytes");
| gpl-2.0 |
NAM-IL/ARM_Linux_Kernel_12b | kernel/printk/printk.c | 104 | 78528 | /*
* linux/kernel/printk.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Modified to make sys_syslog() more flexible: added commands to
* return the last 4k of kernel messages, regardless of whether
* they've been read or not. Added option to suppress kernel printk's
* to the console. Added hook for sending the console messages
* elsewhere, in preparation for a serial line console (someday).
* Ted Ts'o, 2/11/93.
* Modified for sysctl support, 1/8/97, Chris Horn.
* Fixed SMP synchronization, 08/08/99, Manfred Spraul
* manfred@colorfullife.com
* Rewrote bits to get rid of console_lock
* 01Mar01 Andrew Morton
*/
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/console.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <linux/nmi.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/interrupt.h> /* For in_interrupt() */
#include <linux/delay.h>
#include <linux/smp.h>
#include <linux/security.h>
#include <linux/bootmem.h>
#include <linux/memblock.h>
#include <linux/aio.h>
#include <linux/syscalls.h>
#include <linux/kexec.h>
#include <linux/kdb.h>
#include <linux/ratelimit.h>
#include <linux/kmsg_dump.h>
#include <linux/syslog.h>
#include <linux/cpu.h>
#include <linux/notifier.h>
#include <linux/rculist.h>
#include <linux/poll.h>
#include <linux/irq_work.h>
#include <linux/utsname.h>
#include <linux/ctype.h>
#include <asm/uaccess.h>
#define CREATE_TRACE_POINTS
#include <trace/events/printk.h>
#include "console_cmdline.h"
#include "braille.h"
int console_printk[4] = {
CONSOLE_LOGLEVEL_DEFAULT, /* console_loglevel */
MESSAGE_LOGLEVEL_DEFAULT, /* default_message_loglevel */
CONSOLE_LOGLEVEL_MIN, /* minimum_console_loglevel */
CONSOLE_LOGLEVEL_DEFAULT, /* default_console_loglevel */
};
/*
* Low level drivers may need that to know if they can schedule in
* their unblank() callback or not. So let's export it.
*/
int oops_in_progress;
EXPORT_SYMBOL(oops_in_progress);
/*
* console_sem protects the console_drivers list, and also
* provides serialisation for access to the entire console
* driver system.
*/
static DEFINE_SEMAPHORE(console_sem);
struct console *console_drivers;
EXPORT_SYMBOL_GPL(console_drivers);
#ifdef CONFIG_LOCKDEP
static struct lockdep_map console_lock_dep_map = {
.name = "console_lock"
};
#endif
/*
* Helper macros to handle lockdep when locking/unlocking console_sem. We use
* macros instead of functions so that _RET_IP_ contains useful information.
*/
#define down_console_sem() do { \
down(&console_sem);\
mutex_acquire(&console_lock_dep_map, 0, 0, _RET_IP_);\
} while (0)
static int __down_trylock_console_sem(unsigned long ip)
{
if (down_trylock(&console_sem))
return 1;
mutex_acquire(&console_lock_dep_map, 0, 1, ip);
return 0;
}
#define down_trylock_console_sem() __down_trylock_console_sem(_RET_IP_)
#define up_console_sem() do { \
mutex_release(&console_lock_dep_map, 1, _RET_IP_);\
up(&console_sem);\
} while (0)
/*
* This is used for debugging the mess that is the VT code by
* keeping track if we have the console semaphore held. It's
* definitely not the perfect debug tool (we don't know if _WE_
* hold it and are racing, but it helps tracking those weird code
* paths in the console code where we end up in places I want
* locked without the console sempahore held).
*/
static int console_locked, console_suspended;
/*
* If exclusive_console is non-NULL then only this console is to be printed to.
*/
static struct console *exclusive_console;
/*
* Array of consoles built from command line options (console=)
*/
#define MAX_CMDLINECONSOLES 8
static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
static int selected_console = -1;
static int preferred_console = -1;
int console_set_on_cmdline;
EXPORT_SYMBOL(console_set_on_cmdline);
/* Flag: console code may call schedule() */
static int console_may_schedule;
/*
* The printk log buffer consists of a chain of concatenated variable
* length records. Every record starts with a record header, containing
* the overall length of the record.
*
* The heads to the first and last entry in the buffer, as well as the
* sequence numbers of these entries are maintained when messages are
* stored.
*
* If the heads indicate available messages, the length in the header
* tells the start next message. A length == 0 for the next message
* indicates a wrap-around to the beginning of the buffer.
*
* Every record carries the monotonic timestamp in microseconds, as well as
* the standard userspace syslog level and syslog facility. The usual
* kernel messages use LOG_KERN; userspace-injected messages always carry
* a matching syslog facility, by default LOG_USER. The origin of every
* message can be reliably determined that way.
*
* The human readable log message directly follows the message header. The
* length of the message text is stored in the header, the stored message
* is not terminated.
*
* Optionally, a message can carry a dictionary of properties (key/value pairs),
* to provide userspace with a machine-readable message context.
*
* Examples for well-defined, commonly used property names are:
* DEVICE=b12:8 device identifier
* b12:8 block dev_t
* c127:3 char dev_t
* n8 netdev ifindex
* +sound:card0 subsystem:devname
* SUBSYSTEM=pci driver-core subsystem name
*
* Valid characters in property names are [a-zA-Z0-9.-_]. The plain text value
* follows directly after a '=' character. Every property is terminated by
* a '\0' character. The last property is not terminated.
*
* Example of a message structure:
* 0000 ff 8f 00 00 00 00 00 00 monotonic time in nsec
* 0008 34 00 record is 52 bytes long
* 000a 0b 00 text is 11 bytes long
* 000c 1f 00 dictionary is 23 bytes long
* 000e 03 00 LOG_KERN (facility) LOG_ERR (level)
* 0010 69 74 27 73 20 61 20 6c "it's a l"
* 69 6e 65 "ine"
* 001b 44 45 56 49 43 "DEVIC"
* 45 3d 62 38 3a 32 00 44 "E=b8:2\0D"
* 52 49 56 45 52 3d 62 75 "RIVER=bu"
* 67 "g"
* 0032 00 00 00 padding to next message header
*
* The 'struct printk_log' buffer header must never be directly exported to
* userspace, it is a kernel-private implementation detail that might
* need to be changed in the future, when the requirements change.
*
* /dev/kmsg exports the structured data in the following line format:
* "level,sequnum,timestamp;<message text>\n"
*
* The optional key/value pairs are attached as continuation lines starting
* with a space character and terminated by a newline. All possible
* non-prinatable characters are escaped in the "\xff" notation.
*
* Users of the export format should ignore possible additional values
* separated by ',', and find the message after the ';' character.
*/
enum log_flags {
LOG_NOCONS = 1, /* already flushed, do not print to console */
LOG_NEWLINE = 2, /* text ended with a newline */
LOG_PREFIX = 4, /* text started with a prefix */
LOG_CONT = 8, /* text is a fragment of a continuation line */
};
struct printk_log {
u64 ts_nsec; /* timestamp in nanoseconds */
u16 len; /* length of entire record */
u16 text_len; /* length of text buffer */
u16 dict_len; /* length of dictionary buffer */
u8 facility; /* syslog facility */
u8 flags:5; /* internal record flags */
u8 level:3; /* syslog level */
};
/*
* The logbuf_lock protects kmsg buffer, indices, counters. This can be taken
* within the scheduler's rq lock. It must be released before calling
* console_unlock() or anything else that might wake up a process.
*/
static DEFINE_RAW_SPINLOCK(logbuf_lock);
#ifdef CONFIG_PRINTK
DECLARE_WAIT_QUEUE_HEAD(log_wait);
/* the next printk record to read by syslog(READ) or /proc/kmsg */
static u64 syslog_seq;
static u32 syslog_idx;
static enum log_flags syslog_prev;
static size_t syslog_partial;
/* index and sequence number of the first record stored in the buffer */
static u64 log_first_seq;
static u32 log_first_idx;
/* index and sequence number of the next record to store in the buffer */
static u64 log_next_seq;
static u32 log_next_idx;
/* the next printk record to write to the console */
static u64 console_seq;
static u32 console_idx;
static enum log_flags console_prev;
/* the next printk record to read after the last 'clear' command */
static u64 clear_seq;
static u32 clear_idx;
#define PREFIX_MAX 32
#define LOG_LINE_MAX (1024 - PREFIX_MAX)
/* record buffer */
#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
#define LOG_ALIGN 4
#else
#define LOG_ALIGN __alignof__(struct printk_log)
#endif
#define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN);
static char *log_buf = __log_buf;
static u32 log_buf_len = __LOG_BUF_LEN;
/* Return log buffer address */
char *log_buf_addr_get(void)
{
return log_buf;
}
/* Return log buffer size */
u32 log_buf_len_get(void)
{
return log_buf_len;
}
/* human readable text of the record */
static char *log_text(const struct printk_log *msg)
{
return (char *)msg + sizeof(struct printk_log);
}
/* optional key/value pair dictionary attached to the record */
static char *log_dict(const struct printk_log *msg)
{
return (char *)msg + sizeof(struct printk_log) + msg->text_len;
}
/* get record by index; idx must point to valid msg */
static struct printk_log *log_from_idx(u32 idx)
{
struct printk_log *msg = (struct printk_log *)(log_buf + idx);
/*
* A length == 0 record is the end of buffer marker. Wrap around and
* read the message at the start of the buffer.
*/
if (!msg->len)
return (struct printk_log *)log_buf;
return msg;
}
/* get next record; idx must point to valid msg */
static u32 log_next(u32 idx)
{
struct printk_log *msg = (struct printk_log *)(log_buf + idx);
/* length == 0 indicates the end of the buffer; wrap */
/*
* A length == 0 record is the end of buffer marker. Wrap around and
* read the message at the start of the buffer as *this* one, and
* return the one after that.
*/
if (!msg->len) {
msg = (struct printk_log *)log_buf;
return msg->len;
}
return idx + msg->len;
}
/*
* Check whether there is enough free space for the given message.
*
* The same values of first_idx and next_idx mean that the buffer
* is either empty or full.
*
* If the buffer is empty, we must respect the position of the indexes.
* They cannot be reset to the beginning of the buffer.
*/
static int logbuf_has_space(u32 msg_size, bool empty)
{
u32 free;
if (log_next_idx > log_first_idx || empty)
free = max(log_buf_len - log_next_idx, log_first_idx);
else
free = log_first_idx - log_next_idx;
/*
* We need space also for an empty header that signalizes wrapping
* of the buffer.
*/
return free >= msg_size + sizeof(struct printk_log);
}
static int log_make_free_space(u32 msg_size)
{
while (log_first_seq < log_next_seq) {
if (logbuf_has_space(msg_size, false))
return 0;
/* drop old messages until we have enough contiguous space */
log_first_idx = log_next(log_first_idx);
log_first_seq++;
}
/* sequence numbers are equal, so the log buffer is empty */
if (logbuf_has_space(msg_size, true))
return 0;
return -ENOMEM;
}
/* compute the message size including the padding bytes */
static u32 msg_used_size(u16 text_len, u16 dict_len, u32 *pad_len)
{
u32 size;
size = sizeof(struct printk_log) + text_len + dict_len;
*pad_len = (-size) & (LOG_ALIGN - 1);
size += *pad_len;
return size;
}
/*
* Define how much of the log buffer we could take at maximum. The value
* must be greater than two. Note that only half of the buffer is available
* when the index points to the middle.
*/
#define MAX_LOG_TAKE_PART 4
static const char trunc_msg[] = "<truncated>";
static u32 truncate_msg(u16 *text_len, u16 *trunc_msg_len,
u16 *dict_len, u32 *pad_len)
{
/*
* The message should not take the whole buffer. Otherwise, it might
* get removed too soon.
*/
u32 max_text_len = log_buf_len / MAX_LOG_TAKE_PART;
if (*text_len > max_text_len)
*text_len = max_text_len;
/* enable the warning message */
*trunc_msg_len = strlen(trunc_msg);
/* disable the "dict" completely */
*dict_len = 0;
/* compute the size again, count also the warning message */
return msg_used_size(*text_len + *trunc_msg_len, 0, pad_len);
}
/* insert record into the buffer, discard old ones, update heads */
static int log_store(int facility, int level,
enum log_flags flags, u64 ts_nsec,
const char *dict, u16 dict_len,
const char *text, u16 text_len)
{
struct printk_log *msg;
u32 size, pad_len;
u16 trunc_msg_len = 0;
/* number of '\0' padding bytes to next message */
size = msg_used_size(text_len, dict_len, &pad_len);
if (log_make_free_space(size)) {
/* truncate the message if it is too long for empty buffer */
size = truncate_msg(&text_len, &trunc_msg_len,
&dict_len, &pad_len);
/* survive when the log buffer is too small for trunc_msg */
if (log_make_free_space(size))
return 0;
}
if (log_next_idx + size + sizeof(struct printk_log) > log_buf_len) {
/*
* This message + an additional empty header does not fit
* at the end of the buffer. Add an empty header with len == 0
* to signify a wrap around.
*/
memset(log_buf + log_next_idx, 0, sizeof(struct printk_log));
log_next_idx = 0;
}
/* fill message */
msg = (struct printk_log *)(log_buf + log_next_idx);
memcpy(log_text(msg), text, text_len);
msg->text_len = text_len;
if (trunc_msg_len) {
memcpy(log_text(msg) + text_len, trunc_msg, trunc_msg_len);
msg->text_len += trunc_msg_len;
}
memcpy(log_dict(msg), dict, dict_len);
msg->dict_len = dict_len;
msg->facility = facility;
msg->level = level & 7;
msg->flags = flags & 0x1f;
if (ts_nsec > 0)
msg->ts_nsec = ts_nsec;
else
msg->ts_nsec = local_clock();
memset(log_dict(msg) + dict_len, 0, pad_len);
msg->len = size;
/* insert message */
log_next_idx += msg->len;
log_next_seq++;
return msg->text_len;
}
int dmesg_restrict = IS_ENABLED(CONFIG_SECURITY_DMESG_RESTRICT);
static int syslog_action_restricted(int type)
{
if (dmesg_restrict)
return 1;
/*
* Unless restricted, we allow "read all" and "get buffer size"
* for everybody.
*/
return type != SYSLOG_ACTION_READ_ALL &&
type != SYSLOG_ACTION_SIZE_BUFFER;
}
int check_syslog_permissions(int type, bool from_file)
{
/*
* If this is from /proc/kmsg and we've already opened it, then we've
* already done the capabilities checks at open time.
*/
if (from_file && type != SYSLOG_ACTION_OPEN)
return 0;
if (syslog_action_restricted(type)) {
if (capable(CAP_SYSLOG))
return 0;
/*
* For historical reasons, accept CAP_SYS_ADMIN too, with
* a warning.
*/
if (capable(CAP_SYS_ADMIN)) {
pr_warn_once("%s (%d): Attempt to access syslog with "
"CAP_SYS_ADMIN but no CAP_SYSLOG "
"(deprecated).\n",
current->comm, task_pid_nr(current));
return 0;
}
return -EPERM;
}
return security_syslog(type);
}
/* /dev/kmsg - userspace message inject/listen interface */
struct devkmsg_user {
u64 seq;
u32 idx;
enum log_flags prev;
struct mutex lock;
char buf[8192];
};
static ssize_t devkmsg_write(struct kiocb *iocb, struct iov_iter *from)
{
char *buf, *line;
int i;
int level = default_message_loglevel;
int facility = 1; /* LOG_USER */
size_t len = iocb->ki_nbytes;
ssize_t ret = len;
if (len > LOG_LINE_MAX)
return -EINVAL;
buf = kmalloc(len+1, GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
buf[len] = '\0';
if (copy_from_iter(buf, len, from) != len) {
kfree(buf);
return -EFAULT;
}
/*
* Extract and skip the syslog prefix <[0-9]*>. Coming from userspace
* the decimal value represents 32bit, the lower 3 bit are the log
* level, the rest are the log facility.
*
* If no prefix or no userspace facility is specified, we
* enforce LOG_USER, to be able to reliably distinguish
* kernel-generated messages from userspace-injected ones.
*/
line = buf;
if (line[0] == '<') {
char *endp = NULL;
i = simple_strtoul(line+1, &endp, 10);
if (endp && endp[0] == '>') {
level = i & 7;
if (i >> 3)
facility = i >> 3;
endp++;
len -= endp - line;
line = endp;
}
}
printk_emit(facility, level, NULL, 0, "%s", line);
kfree(buf);
return ret;
}
static ssize_t devkmsg_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct devkmsg_user *user = file->private_data;
struct printk_log *msg;
u64 ts_usec;
size_t i;
char cont = '-';
size_t len;
ssize_t ret;
if (!user)
return -EBADF;
ret = mutex_lock_interruptible(&user->lock);
if (ret)
return ret;
raw_spin_lock_irq(&logbuf_lock);
while (user->seq == log_next_seq) {
if (file->f_flags & O_NONBLOCK) {
ret = -EAGAIN;
raw_spin_unlock_irq(&logbuf_lock);
goto out;
}
raw_spin_unlock_irq(&logbuf_lock);
ret = wait_event_interruptible(log_wait,
user->seq != log_next_seq);
if (ret)
goto out;
raw_spin_lock_irq(&logbuf_lock);
}
if (user->seq < log_first_seq) {
/* our last seen message is gone, return error and reset */
user->idx = log_first_idx;
user->seq = log_first_seq;
ret = -EPIPE;
raw_spin_unlock_irq(&logbuf_lock);
goto out;
}
msg = log_from_idx(user->idx);
ts_usec = msg->ts_nsec;
do_div(ts_usec, 1000);
/*
* If we couldn't merge continuation line fragments during the print,
* export the stored flags to allow an optional external merge of the
* records. Merging the records isn't always neccessarily correct, like
* when we hit a race during printing. In most cases though, it produces
* better readable output. 'c' in the record flags mark the first
* fragment of a line, '+' the following.
*/
if (msg->flags & LOG_CONT && !(user->prev & LOG_CONT))
cont = 'c';
else if ((msg->flags & LOG_CONT) ||
((user->prev & LOG_CONT) && !(msg->flags & LOG_PREFIX)))
cont = '+';
len = sprintf(user->buf, "%u,%llu,%llu,%c;",
(msg->facility << 3) | msg->level,
user->seq, ts_usec, cont);
user->prev = msg->flags;
/* escape non-printable characters */
for (i = 0; i < msg->text_len; i++) {
unsigned char c = log_text(msg)[i];
if (c < ' ' || c >= 127 || c == '\\')
len += sprintf(user->buf + len, "\\x%02x", c);
else
user->buf[len++] = c;
}
user->buf[len++] = '\n';
if (msg->dict_len) {
bool line = true;
for (i = 0; i < msg->dict_len; i++) {
unsigned char c = log_dict(msg)[i];
if (line) {
user->buf[len++] = ' ';
line = false;
}
if (c == '\0') {
user->buf[len++] = '\n';
line = true;
continue;
}
if (c < ' ' || c >= 127 || c == '\\') {
len += sprintf(user->buf + len, "\\x%02x", c);
continue;
}
user->buf[len++] = c;
}
user->buf[len++] = '\n';
}
user->idx = log_next(user->idx);
user->seq++;
raw_spin_unlock_irq(&logbuf_lock);
if (len > count) {
ret = -EINVAL;
goto out;
}
if (copy_to_user(buf, user->buf, len)) {
ret = -EFAULT;
goto out;
}
ret = len;
out:
mutex_unlock(&user->lock);
return ret;
}
static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
{
struct devkmsg_user *user = file->private_data;
loff_t ret = 0;
if (!user)
return -EBADF;
if (offset)
return -ESPIPE;
raw_spin_lock_irq(&logbuf_lock);
switch (whence) {
case SEEK_SET:
/* the first record */
user->idx = log_first_idx;
user->seq = log_first_seq;
break;
case SEEK_DATA:
/*
* The first record after the last SYSLOG_ACTION_CLEAR,
* like issued by 'dmesg -c'. Reading /dev/kmsg itself
* changes no global state, and does not clear anything.
*/
user->idx = clear_idx;
user->seq = clear_seq;
break;
case SEEK_END:
/* after the last record */
user->idx = log_next_idx;
user->seq = log_next_seq;
break;
default:
ret = -EINVAL;
}
raw_spin_unlock_irq(&logbuf_lock);
return ret;
}
static unsigned int devkmsg_poll(struct file *file, poll_table *wait)
{
struct devkmsg_user *user = file->private_data;
int ret = 0;
if (!user)
return POLLERR|POLLNVAL;
poll_wait(file, &log_wait, wait);
raw_spin_lock_irq(&logbuf_lock);
if (user->seq < log_next_seq) {
/* return error when data has vanished underneath us */
if (user->seq < log_first_seq)
ret = POLLIN|POLLRDNORM|POLLERR|POLLPRI;
else
ret = POLLIN|POLLRDNORM;
}
raw_spin_unlock_irq(&logbuf_lock);
return ret;
}
static int devkmsg_open(struct inode *inode, struct file *file)
{
struct devkmsg_user *user;
int err;
/* write-only does not need any file context */
if ((file->f_flags & O_ACCMODE) == O_WRONLY)
return 0;
err = check_syslog_permissions(SYSLOG_ACTION_READ_ALL,
SYSLOG_FROM_READER);
if (err)
return err;
user = kmalloc(sizeof(struct devkmsg_user), GFP_KERNEL);
if (!user)
return -ENOMEM;
mutex_init(&user->lock);
raw_spin_lock_irq(&logbuf_lock);
user->idx = log_first_idx;
user->seq = log_first_seq;
raw_spin_unlock_irq(&logbuf_lock);
file->private_data = user;
return 0;
}
static int devkmsg_release(struct inode *inode, struct file *file)
{
struct devkmsg_user *user = file->private_data;
if (!user)
return 0;
mutex_destroy(&user->lock);
kfree(user);
return 0;
}
const struct file_operations kmsg_fops = {
.open = devkmsg_open,
.read = devkmsg_read,
.write_iter = devkmsg_write,
.llseek = devkmsg_llseek,
.poll = devkmsg_poll,
.release = devkmsg_release,
};
#ifdef CONFIG_KEXEC
/*
* This appends the listed symbols to /proc/vmcore
*
* /proc/vmcore is used by various utilities, like crash and makedumpfile to
* obtain access to symbols that are otherwise very difficult to locate. These
* symbols are specifically used so that utilities can access and extract the
* dmesg log from a vmcore file after a crash.
*/
void log_buf_kexec_setup(void)
{
VMCOREINFO_SYMBOL(log_buf);
VMCOREINFO_SYMBOL(log_buf_len);
VMCOREINFO_SYMBOL(log_first_idx);
VMCOREINFO_SYMBOL(log_next_idx);
/*
* Export struct printk_log size and field offsets. User space tools can
* parse it and detect any changes to structure down the line.
*/
VMCOREINFO_STRUCT_SIZE(printk_log);
VMCOREINFO_OFFSET(printk_log, ts_nsec);
VMCOREINFO_OFFSET(printk_log, len);
VMCOREINFO_OFFSET(printk_log, text_len);
VMCOREINFO_OFFSET(printk_log, dict_len);
}
#endif
/* requested log_buf_len from kernel cmdline */
static unsigned long __initdata new_log_buf_len;
/* we practice scaling the ring buffer by powers of 2 */
static void __init log_buf_len_update(unsigned size)
{
if (size)
size = roundup_pow_of_two(size);
if (size > log_buf_len)
new_log_buf_len = size;
}
/* save requested log_buf_len since it's too early to process it */
static int __init log_buf_len_setup(char *str)
{
unsigned size = memparse(str, &str);
log_buf_len_update(size);
return 0;
}
early_param("log_buf_len", log_buf_len_setup);
#ifdef CONFIG_SMP
#define __LOG_CPU_MAX_BUF_LEN (1 << CONFIG_LOG_CPU_MAX_BUF_SHIFT)
static void __init log_buf_add_cpu(void)
{
unsigned int cpu_extra;
/*
* archs should set up cpu_possible_bits properly with
* set_cpu_possible() after setup_arch() but just in
* case lets ensure this is valid.
*/
if (num_possible_cpus() == 1)
return;
cpu_extra = (num_possible_cpus() - 1) * __LOG_CPU_MAX_BUF_LEN;
/* by default this will only continue through for large > 64 CPUs */
if (cpu_extra <= __LOG_BUF_LEN / 2)
return;
pr_info("log_buf_len individual max cpu contribution: %d bytes\n",
__LOG_CPU_MAX_BUF_LEN);
pr_info("log_buf_len total cpu_extra contributions: %d bytes\n",
cpu_extra);
pr_info("log_buf_len min size: %d bytes\n", __LOG_BUF_LEN);
log_buf_len_update(cpu_extra + __LOG_BUF_LEN);
}
#else /* !CONFIG_SMP */
static inline void log_buf_add_cpu(void) {}
#endif /* CONFIG_SMP */
void __init setup_log_buf(int early)
{
unsigned long flags;
char *new_log_buf;
int free;
if (log_buf != __log_buf)
return;
if (!early && !new_log_buf_len)
log_buf_add_cpu();
if (!new_log_buf_len)
return;
if (early) {
new_log_buf =
memblock_virt_alloc(new_log_buf_len, LOG_ALIGN);
} else {
new_log_buf = memblock_virt_alloc_nopanic(new_log_buf_len,
LOG_ALIGN);
}
if (unlikely(!new_log_buf)) {
pr_err("log_buf_len: %ld bytes not available\n",
new_log_buf_len);
return;
}
raw_spin_lock_irqsave(&logbuf_lock, flags);
log_buf_len = new_log_buf_len;
log_buf = new_log_buf;
new_log_buf_len = 0;
free = __LOG_BUF_LEN - log_next_idx;
memcpy(log_buf, __log_buf, __LOG_BUF_LEN);
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
pr_info("log_buf_len: %d bytes\n", log_buf_len);
pr_info("early log buf free: %d(%d%%)\n",
free, (free * 100) / __LOG_BUF_LEN);
}
static bool __read_mostly ignore_loglevel;
static int __init ignore_loglevel_setup(char *str)
{
ignore_loglevel = true;
pr_info("debug: ignoring loglevel setting.\n");
return 0;
}
early_param("ignore_loglevel", ignore_loglevel_setup);
module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(ignore_loglevel,
"ignore loglevel setting (prints all kernel messages to the console)");
#ifdef CONFIG_BOOT_PRINTK_DELAY
static int boot_delay; /* msecs delay after each printk during bootup */
static unsigned long long loops_per_msec; /* based on boot_delay */
static int __init boot_delay_setup(char *str)
{
unsigned long lpj;
lpj = preset_lpj ? preset_lpj : 1000000; /* some guess */
loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
get_option(&str, &boot_delay);
if (boot_delay > 10 * 1000)
boot_delay = 0;
pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
"HZ: %d, loops_per_msec: %llu\n",
boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
return 0;
}
early_param("boot_delay", boot_delay_setup);
static void boot_delay_msec(int level)
{
unsigned long long k;
unsigned long timeout;
if ((boot_delay == 0 || system_state != SYSTEM_BOOTING)
|| (level >= console_loglevel && !ignore_loglevel)) {
return;
}
k = (unsigned long long)loops_per_msec * boot_delay;
timeout = jiffies + msecs_to_jiffies(boot_delay);
while (k) {
k--;
cpu_relax();
/*
* use (volatile) jiffies to prevent
* compiler reduction; loop termination via jiffies
* is secondary and may or may not happen.
*/
if (time_after(jiffies, timeout))
break;
touch_nmi_watchdog();
}
}
#else
static inline void boot_delay_msec(int level)
{
}
#endif
static bool printk_time = IS_ENABLED(CONFIG_PRINTK_TIME);
module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
static size_t print_time(u64 ts, char *buf)
{
unsigned long rem_nsec;
if (!printk_time)
return 0;
rem_nsec = do_div(ts, 1000000000);
if (!buf)
return snprintf(NULL, 0, "[%5lu.000000] ", (unsigned long)ts);
return sprintf(buf, "[%5lu.%06lu] ",
(unsigned long)ts, rem_nsec / 1000);
}
static size_t print_prefix(const struct printk_log *msg, bool syslog, char *buf)
{
size_t len = 0;
unsigned int prefix = (msg->facility << 3) | msg->level;
if (syslog) {
if (buf) {
len += sprintf(buf, "<%u>", prefix);
} else {
len += 3;
if (prefix > 999)
len += 3;
else if (prefix > 99)
len += 2;
else if (prefix > 9)
len++;
}
}
len += print_time(msg->ts_nsec, buf ? buf + len : NULL);
return len;
}
static size_t msg_print_text(const struct printk_log *msg, enum log_flags prev,
bool syslog, char *buf, size_t size)
{
const char *text = log_text(msg);
size_t text_size = msg->text_len;
bool prefix = true;
bool newline = true;
size_t len = 0;
if ((prev & LOG_CONT) && !(msg->flags & LOG_PREFIX))
prefix = false;
if (msg->flags & LOG_CONT) {
if ((prev & LOG_CONT) && !(prev & LOG_NEWLINE))
prefix = false;
if (!(msg->flags & LOG_NEWLINE))
newline = false;
}
do {
const char *next = memchr(text, '\n', text_size);
size_t text_len;
if (next) {
text_len = next - text;
next++;
text_size -= next - text;
} else {
text_len = text_size;
}
if (buf) {
if (print_prefix(msg, syslog, NULL) +
text_len + 1 >= size - len)
break;
if (prefix)
len += print_prefix(msg, syslog, buf + len);
memcpy(buf + len, text, text_len);
len += text_len;
if (next || newline)
buf[len++] = '\n';
} else {
/* SYSLOG_ACTION_* buffer size only calculation */
if (prefix)
len += print_prefix(msg, syslog, NULL);
len += text_len;
if (next || newline)
len++;
}
prefix = true;
text = next;
} while (text);
return len;
}
static int syslog_print(char __user *buf, int size)
{
char *text;
struct printk_log *msg;
int len = 0;
text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
if (!text)
return -ENOMEM;
while (size > 0) {
size_t n;
size_t skip;
raw_spin_lock_irq(&logbuf_lock);
if (syslog_seq < log_first_seq) {
/* messages are gone, move to first one */
syslog_seq = log_first_seq;
syslog_idx = log_first_idx;
syslog_prev = 0;
syslog_partial = 0;
}
if (syslog_seq == log_next_seq) {
raw_spin_unlock_irq(&logbuf_lock);
break;
}
skip = syslog_partial;
msg = log_from_idx(syslog_idx);
n = msg_print_text(msg, syslog_prev, true, text,
LOG_LINE_MAX + PREFIX_MAX);
if (n - syslog_partial <= size) {
/* message fits into buffer, move forward */
syslog_idx = log_next(syslog_idx);
syslog_seq++;
syslog_prev = msg->flags;
n -= syslog_partial;
syslog_partial = 0;
} else if (!len){
/* partial read(), remember position */
n = size;
syslog_partial += n;
} else
n = 0;
raw_spin_unlock_irq(&logbuf_lock);
if (!n)
break;
if (copy_to_user(buf, text + skip, n)) {
if (!len)
len = -EFAULT;
break;
}
len += n;
size -= n;
buf += n;
}
kfree(text);
return len;
}
static int syslog_print_all(char __user *buf, int size, bool clear)
{
char *text;
int len = 0;
text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
if (!text)
return -ENOMEM;
raw_spin_lock_irq(&logbuf_lock);
if (buf) {
u64 next_seq;
u64 seq;
u32 idx;
enum log_flags prev;
if (clear_seq < log_first_seq) {
/* messages are gone, move to first available one */
clear_seq = log_first_seq;
clear_idx = log_first_idx;
}
/*
* Find first record that fits, including all following records,
* into the user-provided buffer for this dump.
*/
seq = clear_seq;
idx = clear_idx;
prev = 0;
while (seq < log_next_seq) {
struct printk_log *msg = log_from_idx(idx);
len += msg_print_text(msg, prev, true, NULL, 0);
prev = msg->flags;
idx = log_next(idx);
seq++;
}
/* move first record forward until length fits into the buffer */
seq = clear_seq;
idx = clear_idx;
prev = 0;
while (len > size && seq < log_next_seq) {
struct printk_log *msg = log_from_idx(idx);
len -= msg_print_text(msg, prev, true, NULL, 0);
prev = msg->flags;
idx = log_next(idx);
seq++;
}
/* last message fitting into this dump */
next_seq = log_next_seq;
len = 0;
while (len >= 0 && seq < next_seq) {
struct printk_log *msg = log_from_idx(idx);
int textlen;
textlen = msg_print_text(msg, prev, true, text,
LOG_LINE_MAX + PREFIX_MAX);
if (textlen < 0) {
len = textlen;
break;
}
idx = log_next(idx);
seq++;
prev = msg->flags;
raw_spin_unlock_irq(&logbuf_lock);
if (copy_to_user(buf + len, text, textlen))
len = -EFAULT;
else
len += textlen;
raw_spin_lock_irq(&logbuf_lock);
if (seq < log_first_seq) {
/* messages are gone, move to next one */
seq = log_first_seq;
idx = log_first_idx;
prev = 0;
}
}
}
if (clear) {
clear_seq = log_next_seq;
clear_idx = log_next_idx;
}
raw_spin_unlock_irq(&logbuf_lock);
kfree(text);
return len;
}
int do_syslog(int type, char __user *buf, int len, bool from_file)
{
bool clear = false;
static int saved_console_loglevel = LOGLEVEL_DEFAULT;
int error;
error = check_syslog_permissions(type, from_file);
if (error)
goto out;
error = security_syslog(type);
if (error)
return error;
switch (type) {
case SYSLOG_ACTION_CLOSE: /* Close log */
break;
case SYSLOG_ACTION_OPEN: /* Open log */
break;
case SYSLOG_ACTION_READ: /* Read from log */
error = -EINVAL;
if (!buf || len < 0)
goto out;
error = 0;
if (!len)
goto out;
if (!access_ok(VERIFY_WRITE, buf, len)) {
error = -EFAULT;
goto out;
}
error = wait_event_interruptible(log_wait,
syslog_seq != log_next_seq);
if (error)
goto out;
error = syslog_print(buf, len);
break;
/* Read/clear last kernel messages */
case SYSLOG_ACTION_READ_CLEAR:
clear = true;
/* FALL THRU */
/* Read last kernel messages */
case SYSLOG_ACTION_READ_ALL:
error = -EINVAL;
if (!buf || len < 0)
goto out;
error = 0;
if (!len)
goto out;
if (!access_ok(VERIFY_WRITE, buf, len)) {
error = -EFAULT;
goto out;
}
error = syslog_print_all(buf, len, clear);
break;
/* Clear ring buffer */
case SYSLOG_ACTION_CLEAR:
syslog_print_all(NULL, 0, true);
break;
/* Disable logging to console */
case SYSLOG_ACTION_CONSOLE_OFF:
if (saved_console_loglevel == LOGLEVEL_DEFAULT)
saved_console_loglevel = console_loglevel;
console_loglevel = minimum_console_loglevel;
break;
/* Enable logging to console */
case SYSLOG_ACTION_CONSOLE_ON:
if (saved_console_loglevel != LOGLEVEL_DEFAULT) {
console_loglevel = saved_console_loglevel;
saved_console_loglevel = LOGLEVEL_DEFAULT;
}
break;
/* Set level of messages printed to console */
case SYSLOG_ACTION_CONSOLE_LEVEL:
error = -EINVAL;
if (len < 1 || len > 8)
goto out;
if (len < minimum_console_loglevel)
len = minimum_console_loglevel;
console_loglevel = len;
/* Implicitly re-enable logging to console */
saved_console_loglevel = LOGLEVEL_DEFAULT;
error = 0;
break;
/* Number of chars in the log buffer */
case SYSLOG_ACTION_SIZE_UNREAD:
raw_spin_lock_irq(&logbuf_lock);
if (syslog_seq < log_first_seq) {
/* messages are gone, move to first one */
syslog_seq = log_first_seq;
syslog_idx = log_first_idx;
syslog_prev = 0;
syslog_partial = 0;
}
if (from_file) {
/*
* Short-cut for poll(/"proc/kmsg") which simply checks
* for pending data, not the size; return the count of
* records, not the length.
*/
error = log_next_seq - syslog_seq;
} else {
u64 seq = syslog_seq;
u32 idx = syslog_idx;
enum log_flags prev = syslog_prev;
error = 0;
while (seq < log_next_seq) {
struct printk_log *msg = log_from_idx(idx);
error += msg_print_text(msg, prev, true, NULL, 0);
idx = log_next(idx);
seq++;
prev = msg->flags;
}
error -= syslog_partial;
}
raw_spin_unlock_irq(&logbuf_lock);
break;
/* Size of the log buffer */
case SYSLOG_ACTION_SIZE_BUFFER:
error = log_buf_len;
break;
default:
error = -EINVAL;
break;
}
out:
return error;
}
SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
{
return do_syslog(type, buf, len, SYSLOG_FROM_READER);
}
/*
* Call the console drivers, asking them to write out
* log_buf[start] to log_buf[end - 1].
* The console_lock must be held.
*/
static void call_console_drivers(int level, const char *text, size_t len)
{
struct console *con;
trace_console(text, len);
if (level >= console_loglevel && !ignore_loglevel)
return;
if (!console_drivers)
return;
for_each_console(con) {
if (exclusive_console && con != exclusive_console)
continue;
if (!(con->flags & CON_ENABLED))
continue;
if (!con->write)
continue;
if (!cpu_online(smp_processor_id()) &&
!(con->flags & CON_ANYTIME))
continue;
con->write(con, text, len);
}
}
/*
* Zap console related locks when oopsing.
* To leave time for slow consoles to print a full oops,
* only zap at most once every 30 seconds.
*/
static void zap_locks(void)
{
static unsigned long oops_timestamp;
if (time_after_eq(jiffies, oops_timestamp) &&
!time_after(jiffies, oops_timestamp + 30 * HZ))
return;
oops_timestamp = jiffies;
debug_locks_off();
/* If a crash is occurring, make sure we can't deadlock */
raw_spin_lock_init(&logbuf_lock);
/* And make sure that we print immediately */
sema_init(&console_sem, 1);
}
/*
* Check if we have any console that is capable of printing while cpu is
* booting or shutting down. Requires console_sem.
*/
static int have_callable_console(void)
{
struct console *con;
for_each_console(con)
if (con->flags & CON_ANYTIME)
return 1;
return 0;
}
/*
* Can we actually use the console at this time on this cpu?
*
* Console drivers may assume that per-cpu resources have been allocated. So
* unless they're explicitly marked as being able to cope (CON_ANYTIME) don't
* call them until this CPU is officially up.
*/
static inline int can_use_console(unsigned int cpu)
{
return cpu_online(cpu) || have_callable_console();
}
/*
* Try to get console ownership to actually show the kernel
* messages from a 'printk'. Return true (and with the
* console_lock held, and 'console_locked' set) if it
* is successful, false otherwise.
*/
static int console_trylock_for_printk(void)
{
unsigned int cpu = smp_processor_id();
if (!console_trylock())
return 0;
/*
* If we can't use the console, we need to release the console
* semaphore by hand to avoid flushing the buffer. We need to hold the
* console semaphore in order to do this test safely.
*/
if (!can_use_console(cpu)) {
console_locked = 0;
up_console_sem();
return 0;
}
return 1;
}
int printk_delay_msec __read_mostly;
static inline void printk_delay(void)
{
if (unlikely(printk_delay_msec)) {
int m = printk_delay_msec;
while (m--) {
mdelay(1);
touch_nmi_watchdog();
}
}
}
/*
* Continuation lines are buffered, and not committed to the record buffer
* until the line is complete, or a race forces it. The line fragments
* though, are printed immediately to the consoles to ensure everything has
* reached the console in case of a kernel crash.
*/
static struct cont {
char buf[LOG_LINE_MAX];
size_t len; /* length == 0 means unused buffer */
size_t cons; /* bytes written to console */
struct task_struct *owner; /* task of first print*/
u64 ts_nsec; /* time of first print */
u8 level; /* log level of first message */
u8 facility; /* log facility of first message */
enum log_flags flags; /* prefix, newline flags */
bool flushed:1; /* buffer sealed and committed */
} cont;
static void cont_flush(enum log_flags flags)
{
if (cont.flushed)
return;
if (cont.len == 0)
return;
if (cont.cons) {
/*
* If a fragment of this line was directly flushed to the
* console; wait for the console to pick up the rest of the
* line. LOG_NOCONS suppresses a duplicated output.
*/
log_store(cont.facility, cont.level, flags | LOG_NOCONS,
cont.ts_nsec, NULL, 0, cont.buf, cont.len);
cont.flags = flags;
cont.flushed = true;
} else {
/*
* If no fragment of this line ever reached the console,
* just submit it to the store and free the buffer.
*/
log_store(cont.facility, cont.level, flags, 0,
NULL, 0, cont.buf, cont.len);
cont.len = 0;
}
}
static bool cont_add(int facility, int level, const char *text, size_t len)
{
if (cont.len && cont.flushed)
return false;
if (cont.len + len > sizeof(cont.buf)) {
/* the line gets too long, split it up in separate records */
cont_flush(LOG_CONT);
return false;
}
if (!cont.len) {
cont.facility = facility;
cont.level = level;
cont.owner = current;
cont.ts_nsec = local_clock();
cont.flags = 0;
cont.cons = 0;
cont.flushed = false;
}
memcpy(cont.buf + cont.len, text, len);
cont.len += len;
if (cont.len > (sizeof(cont.buf) * 80) / 100)
cont_flush(LOG_CONT);
return true;
}
static size_t cont_print_text(char *text, size_t size)
{
size_t textlen = 0;
size_t len;
if (cont.cons == 0 && (console_prev & LOG_NEWLINE)) {
textlen += print_time(cont.ts_nsec, text);
size -= textlen;
}
len = cont.len - cont.cons;
if (len > 0) {
if (len+1 > size)
len = size-1;
memcpy(text + textlen, cont.buf + cont.cons, len);
textlen += len;
cont.cons = cont.len;
}
if (cont.flushed) {
if (cont.flags & LOG_NEWLINE)
text[textlen++] = '\n';
/* got everything, release buffer */
cont.len = 0;
}
return textlen;
}
asmlinkage int vprintk_emit(int facility, int level,
const char *dict, size_t dictlen,
const char *fmt, va_list args)
{
static int recursion_bug;
static char textbuf[LOG_LINE_MAX];
char *text = textbuf;
size_t text_len = 0;
enum log_flags lflags = 0;
unsigned long flags;
int this_cpu;
int printed_len = 0;
bool in_sched = false;
/* cpu currently holding logbuf_lock in this function */
static unsigned int logbuf_cpu = UINT_MAX;
if (level == LOGLEVEL_SCHED) {
level = LOGLEVEL_DEFAULT;
in_sched = true;
}
boot_delay_msec(level);
printk_delay();
/* This stops the holder of console_sem just where we want him */
local_irq_save(flags);
this_cpu = smp_processor_id();
/*
* Ouch, printk recursed into itself!
*/
if (unlikely(logbuf_cpu == this_cpu)) {
/*
* If a crash is occurring during printk() on this CPU,
* then try to get the crash message out but make sure
* we can't deadlock. Otherwise just return to avoid the
* recursion and return - but flag the recursion so that
* it can be printed at the next appropriate moment:
*/
if (!oops_in_progress && !lockdep_recursing(current)) {
recursion_bug = 1;
local_irq_restore(flags);
return 0;
}
zap_locks();
}
lockdep_off();
raw_spin_lock(&logbuf_lock);
logbuf_cpu = this_cpu;
if (unlikely(recursion_bug)) {
static const char recursion_msg[] =
"BUG: recent printk recursion!";
recursion_bug = 0;
/* emit KERN_CRIT message */
printed_len += log_store(0, 2, LOG_PREFIX|LOG_NEWLINE, 0,
NULL, 0, recursion_msg,
strlen(recursion_msg));
}
/*
* The printf needs to come first; we need the syslog
* prefix which might be passed-in as a parameter.
*/
text_len = vscnprintf(text, sizeof(textbuf), fmt, args);
/* mark and strip a trailing newline */
if (text_len && text[text_len-1] == '\n') {
text_len--;
lflags |= LOG_NEWLINE;
}
/* strip kernel syslog prefix and extract log level or control flags */
if (facility == 0) {
int kern_level = printk_get_level(text);
if (kern_level) {
const char *end_of_header = printk_skip_level(text);
switch (kern_level) {
case '0' ... '7':
if (level == LOGLEVEL_DEFAULT)
level = kern_level - '0';
/* fallthrough */
case 'd': /* KERN_DEFAULT */
lflags |= LOG_PREFIX;
}
/*
* No need to check length here because vscnprintf
* put '\0' at the end of the string. Only valid and
* newly printed level is detected.
*/
text_len -= end_of_header - text;
text = (char *)end_of_header;
}
}
if (level == LOGLEVEL_DEFAULT)
level = default_message_loglevel;
if (dict)
lflags |= LOG_PREFIX|LOG_NEWLINE;
if (!(lflags & LOG_NEWLINE)) {
/*
* Flush the conflicting buffer. An earlier newline was missing,
* or another task also prints continuation lines.
*/
if (cont.len && (lflags & LOG_PREFIX || cont.owner != current))
cont_flush(LOG_NEWLINE);
/* buffer line if possible, otherwise store it right away */
if (cont_add(facility, level, text, text_len))
printed_len += text_len;
else
printed_len += log_store(facility, level,
lflags | LOG_CONT, 0,
dict, dictlen, text, text_len);
} else {
bool stored = false;
/*
* If an earlier newline was missing and it was the same task,
* either merge it with the current buffer and flush, or if
* there was a race with interrupts (prefix == true) then just
* flush it out and store this line separately.
* If the preceding printk was from a different task and missed
* a newline, flush and append the newline.
*/
if (cont.len) {
if (cont.owner == current && !(lflags & LOG_PREFIX))
stored = cont_add(facility, level, text,
text_len);
cont_flush(LOG_NEWLINE);
}
if (stored)
printed_len += text_len;
else
printed_len += log_store(facility, level, lflags, 0,
dict, dictlen, text, text_len);
}
logbuf_cpu = UINT_MAX;
raw_spin_unlock(&logbuf_lock);
lockdep_on();
local_irq_restore(flags);
/* If called from the scheduler, we can not call up(). */
if (!in_sched) {
lockdep_off();
/*
* Disable preemption to avoid being preempted while holding
* console_sem which would prevent anyone from printing to
* console
*/
preempt_disable();
/*
* Try to acquire and then immediately release the console
* semaphore. The release will print out buffers and wake up
* /dev/kmsg and syslog() users.
*/
if (console_trylock_for_printk())
console_unlock();
preempt_enable();
lockdep_on();
}
return printed_len;
}
EXPORT_SYMBOL(vprintk_emit);
asmlinkage int vprintk(const char *fmt, va_list args)
{
return vprintk_emit(0, LOGLEVEL_DEFAULT, NULL, 0, fmt, args);
}
EXPORT_SYMBOL(vprintk);
asmlinkage int printk_emit(int facility, int level,
const char *dict, size_t dictlen,
const char *fmt, ...)
{
va_list args;
int r;
va_start(args, fmt);
r = vprintk_emit(facility, level, dict, dictlen, fmt, args);
va_end(args);
return r;
}
EXPORT_SYMBOL(printk_emit);
int vprintk_default(const char *fmt, va_list args)
{
int r;
#ifdef CONFIG_KGDB_KDB
if (unlikely(kdb_trap_printk)) {
r = vkdb_printf(KDB_MSGSRC_PRINTK, fmt, args);
return r;
}
#endif
r = vprintk_emit(0, LOGLEVEL_DEFAULT, NULL, 0, fmt, args);
return r;
}
EXPORT_SYMBOL_GPL(vprintk_default);
/*
* This allows printk to be diverted to another function per cpu.
* This is useful for calling printk functions from within NMI
* without worrying about race conditions that can lock up the
* box.
*/
DEFINE_PER_CPU(printk_func_t, printk_func) = vprintk_default;
/**
* printk - print a kernel message
* @fmt: format string
*
* This is printk(). It can be called from any context. We want it to work.
*
* We try to grab the console_lock. If we succeed, it's easy - we log the
* output and call the console drivers. If we fail to get the semaphore, we
* place the output into the log buffer and return. The current holder of
* the console_sem will notice the new output in console_unlock(); and will
* send it to the consoles before releasing the lock.
*
* One effect of this deferred printing is that code which calls printk() and
* then changes console_loglevel may break. This is because console_loglevel
* is inspected when the actual printing occurs.
*
* See also:
* printf(3)
*
* See the vsnprintf() documentation for format string extensions over C99.
*/
asmlinkage __visible int printk(const char *fmt, ...)
{
printk_func_t vprintk_func;
va_list args;
int r;
va_start(args, fmt);
/*
* If a caller overrides the per_cpu printk_func, then it needs
* to disable preemption when calling printk(). Otherwise
* the printk_func should be set to the default. No need to
* disable preemption here.
*/
vprintk_func = this_cpu_read(printk_func);
r = vprintk_func(fmt, args);
va_end(args);
return r;
}
EXPORT_SYMBOL(printk);
#else /* CONFIG_PRINTK */
#define LOG_LINE_MAX 0
#define PREFIX_MAX 0
static u64 syslog_seq;
static u32 syslog_idx;
static u64 console_seq;
static u32 console_idx;
static enum log_flags syslog_prev;
static u64 log_first_seq;
static u32 log_first_idx;
static u64 log_next_seq;
static enum log_flags console_prev;
static struct cont {
size_t len;
size_t cons;
u8 level;
bool flushed:1;
} cont;
static struct printk_log *log_from_idx(u32 idx) { return NULL; }
static u32 log_next(u32 idx) { return 0; }
static void call_console_drivers(int level, const char *text, size_t len) {}
static size_t msg_print_text(const struct printk_log *msg, enum log_flags prev,
bool syslog, char *buf, size_t size) { return 0; }
static size_t cont_print_text(char *text, size_t size) { return 0; }
/* Still needs to be defined for users */
DEFINE_PER_CPU(printk_func_t, printk_func);
#endif /* CONFIG_PRINTK */
#ifdef CONFIG_EARLY_PRINTK
struct console *early_console;
asmlinkage __visible void early_printk(const char *fmt, ...)
{
va_list ap;
char buf[512];
int n;
if (!early_console)
return;
va_start(ap, fmt);
n = vscnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
early_console->write(early_console, buf, n);
}
#endif
static int __add_preferred_console(char *name, int idx, char *options,
char *brl_options)
{
struct console_cmdline *c;
int i;
/*
* See if this tty is not yet registered, and
* if we have a slot free.
*/
for (i = 0, c = console_cmdline;
i < MAX_CMDLINECONSOLES && c->name[0];
i++, c++) {
if (strcmp(c->name, name) == 0 && c->index == idx) {
if (!brl_options)
selected_console = i;
return 0;
}
}
if (i == MAX_CMDLINECONSOLES)
return -E2BIG;
if (!brl_options)
selected_console = i;
strlcpy(c->name, name, sizeof(c->name));
c->options = options;
braille_set_options(c, brl_options);
c->index = idx;
return 0;
}
/*
* Set up a console. Called via do_early_param() in init/main.c
* for each "console=" parameter in the boot command line.
*/
static int __init console_setup(char *str)
{
char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for "ttyS" */
char *s, *options, *brl_options = NULL;
int idx;
if (_braille_console_setup(&str, &brl_options))
return 1;
/*
* Decode str into name, index, options.
*/
if (str[0] >= '0' && str[0] <= '9') {
strcpy(buf, "ttyS");
strncpy(buf + 4, str, sizeof(buf) - 5);
} else {
strncpy(buf, str, sizeof(buf) - 1);
}
buf[sizeof(buf) - 1] = 0;
options = strchr(str, ',');
if (options)
*(options++) = 0;
#ifdef __sparc__
if (!strcmp(str, "ttya"))
strcpy(buf, "ttyS0");
if (!strcmp(str, "ttyb"))
strcpy(buf, "ttyS1");
#endif
for (s = buf; *s; s++)
if (isdigit(*s) || *s == ',')
break;
idx = simple_strtoul(s, NULL, 10);
*s = 0;
__add_preferred_console(buf, idx, options, brl_options);
console_set_on_cmdline = 1;
return 1;
}
__setup("console=", console_setup);
/**
* add_preferred_console - add a device to the list of preferred consoles.
* @name: device name
* @idx: device index
* @options: options for this console
*
* The last preferred console added will be used for kernel messages
* and stdin/out/err for init. Normally this is used by console_setup
* above to handle user-supplied console arguments; however it can also
* be used by arch-specific code either to override the user or more
* commonly to provide a default console (ie from PROM variables) when
* the user has not supplied one.
*/
int add_preferred_console(char *name, int idx, char *options)
{
return __add_preferred_console(name, idx, options, NULL);
}
int update_console_cmdline(char *name, int idx, char *name_new, int idx_new, char *options)
{
struct console_cmdline *c;
int i;
for (i = 0, c = console_cmdline;
i < MAX_CMDLINECONSOLES && c->name[0];
i++, c++)
if (strcmp(c->name, name) == 0 && c->index == idx) {
strlcpy(c->name, name_new, sizeof(c->name));
c->options = options;
c->index = idx_new;
return i;
}
/* not found */
return -1;
}
bool console_suspend_enabled = true;
EXPORT_SYMBOL(console_suspend_enabled);
static int __init console_suspend_disable(char *str)
{
console_suspend_enabled = false;
return 1;
}
__setup("no_console_suspend", console_suspend_disable);
module_param_named(console_suspend, console_suspend_enabled,
bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
" and hibernate operations");
/**
* suspend_console - suspend the console subsystem
*
* This disables printk() while we go into suspend states
*/
void suspend_console(void)
{
if (!console_suspend_enabled)
return;
printk("Suspending console(s) (use no_console_suspend to debug)\n");
console_lock();
console_suspended = 1;
up_console_sem();
}
void resume_console(void)
{
if (!console_suspend_enabled)
return;
down_console_sem();
console_suspended = 0;
console_unlock();
}
/**
* console_cpu_notify - print deferred console messages after CPU hotplug
* @self: notifier struct
* @action: CPU hotplug event
* @hcpu: unused
*
* If printk() is called from a CPU that is not online yet, the messages
* will be spooled but will not show up on the console. This function is
* called when a new CPU comes online (or fails to come up), and ensures
* that any such output gets printed.
*/
static int console_cpu_notify(struct notifier_block *self,
unsigned long action, void *hcpu)
{
switch (action) {
case CPU_ONLINE:
case CPU_DEAD:
case CPU_DOWN_FAILED:
case CPU_UP_CANCELED:
console_lock();
console_unlock();
}
return NOTIFY_OK;
}
/**
* console_lock - lock the console system for exclusive use.
*
* Acquires a lock which guarantees that the caller has
* exclusive access to the console system and the console_drivers list.
*
* Can sleep, returns nothing.
*/
void console_lock(void)
{
might_sleep();
down_console_sem();
if (console_suspended)
return;
console_locked = 1;
console_may_schedule = 1;
}
EXPORT_SYMBOL(console_lock);
/**
* console_trylock - try to lock the console system for exclusive use.
*
* Try to acquire a lock which guarantees that the caller has exclusive
* access to the console system and the console_drivers list.
*
* returns 1 on success, and 0 on failure to acquire the lock.
*/
int console_trylock(void)
{
if (down_trylock_console_sem())
return 0;
if (console_suspended) {
up_console_sem();
return 0;
}
console_locked = 1;
console_may_schedule = 0;
return 1;
}
EXPORT_SYMBOL(console_trylock);
int is_console_locked(void)
{
return console_locked;
}
static void console_cont_flush(char *text, size_t size)
{
unsigned long flags;
size_t len;
raw_spin_lock_irqsave(&logbuf_lock, flags);
if (!cont.len)
goto out;
/*
* We still queue earlier records, likely because the console was
* busy. The earlier ones need to be printed before this one, we
* did not flush any fragment so far, so just let it queue up.
*/
if (console_seq < log_next_seq && !cont.cons)
goto out;
len = cont_print_text(text, size);
raw_spin_unlock(&logbuf_lock);
stop_critical_timings();
call_console_drivers(cont.level, text, len);
start_critical_timings();
local_irq_restore(flags);
return;
out:
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
}
/**
* console_unlock - unlock the console system
*
* Releases the console_lock which the caller holds on the console system
* and the console driver list.
*
* While the console_lock was held, console output may have been buffered
* by printk(). If this is the case, console_unlock(); emits
* the output prior to releasing the lock.
*
* If there is output waiting, we wake /dev/kmsg and syslog() users.
*
* console_unlock(); may be called from any context.
*/
void console_unlock(void)
{
static char text[LOG_LINE_MAX + PREFIX_MAX];
static u64 seen_seq;
unsigned long flags;
bool wake_klogd = false;
bool retry;
if (console_suspended) {
up_console_sem();
return;
}
console_may_schedule = 0;
/* flush buffered message fragment immediately to console */
console_cont_flush(text, sizeof(text));
again:
for (;;) {
struct printk_log *msg;
size_t len;
int level;
raw_spin_lock_irqsave(&logbuf_lock, flags);
if (seen_seq != log_next_seq) {
wake_klogd = true;
seen_seq = log_next_seq;
}
if (console_seq < log_first_seq) {
len = sprintf(text, "** %u printk messages dropped ** ",
(unsigned)(log_first_seq - console_seq));
/* messages are gone, move to first one */
console_seq = log_first_seq;
console_idx = log_first_idx;
console_prev = 0;
} else {
len = 0;
}
skip:
if (console_seq == log_next_seq)
break;
msg = log_from_idx(console_idx);
if (msg->flags & LOG_NOCONS) {
/*
* Skip record we have buffered and already printed
* directly to the console when we received it.
*/
console_idx = log_next(console_idx);
console_seq++;
/*
* We will get here again when we register a new
* CON_PRINTBUFFER console. Clear the flag so we
* will properly dump everything later.
*/
msg->flags &= ~LOG_NOCONS;
console_prev = msg->flags;
goto skip;
}
level = msg->level;
len += msg_print_text(msg, console_prev, false,
text + len, sizeof(text) - len);
console_idx = log_next(console_idx);
console_seq++;
console_prev = msg->flags;
raw_spin_unlock(&logbuf_lock);
stop_critical_timings(); /* don't trace print latency */
call_console_drivers(level, text, len);
start_critical_timings();
local_irq_restore(flags);
}
console_locked = 0;
/* Release the exclusive_console once it is used */
if (unlikely(exclusive_console))
exclusive_console = NULL;
raw_spin_unlock(&logbuf_lock);
up_console_sem();
/*
* Someone could have filled up the buffer again, so re-check if there's
* something to flush. In case we cannot trylock the console_sem again,
* there's a new owner and the console_unlock() from them will do the
* flush, no worries.
*/
raw_spin_lock(&logbuf_lock);
retry = console_seq != log_next_seq;
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
if (retry && console_trylock())
goto again;
if (wake_klogd)
wake_up_klogd();
}
EXPORT_SYMBOL(console_unlock);
/**
* console_conditional_schedule - yield the CPU if required
*
* If the console code is currently allowed to sleep, and
* if this CPU should yield the CPU to another task, do
* so here.
*
* Must be called within console_lock();.
*/
void __sched console_conditional_schedule(void)
{
if (console_may_schedule)
cond_resched();
}
EXPORT_SYMBOL(console_conditional_schedule);
void console_unblank(void)
{
struct console *c;
/*
* console_unblank can no longer be called in interrupt context unless
* oops_in_progress is set to 1..
*/
if (oops_in_progress) {
if (down_trylock_console_sem() != 0)
return;
} else
console_lock();
console_locked = 1;
console_may_schedule = 0;
for_each_console(c)
if ((c->flags & CON_ENABLED) && c->unblank)
c->unblank();
console_unlock();
}
/*
* Return the console tty driver structure and its associated index
*/
struct tty_driver *console_device(int *index)
{
struct console *c;
struct tty_driver *driver = NULL;
console_lock();
for_each_console(c) {
if (!c->device)
continue;
driver = c->device(c, index);
if (driver)
break;
}
console_unlock();
return driver;
}
/*
* Prevent further output on the passed console device so that (for example)
* serial drivers can disable console output before suspending a port, and can
* re-enable output afterwards.
*/
void console_stop(struct console *console)
{
console_lock();
console->flags &= ~CON_ENABLED;
console_unlock();
}
EXPORT_SYMBOL(console_stop);
void console_start(struct console *console)
{
console_lock();
console->flags |= CON_ENABLED;
console_unlock();
}
EXPORT_SYMBOL(console_start);
static int __read_mostly keep_bootcon;
static int __init keep_bootcon_setup(char *str)
{
keep_bootcon = 1;
pr_info("debug: skip boot console de-registration.\n");
return 0;
}
early_param("keep_bootcon", keep_bootcon_setup);
/*
* The console driver calls this routine during kernel initialization
* to register the console printing procedure with printk() and to
* print any messages that were printed by the kernel before the
* console driver was initialized.
*
* This can happen pretty early during the boot process (because of
* early_printk) - sometimes before setup_arch() completes - be careful
* of what kernel features are used - they may not be initialised yet.
*
* There are two types of consoles - bootconsoles (early_printk) and
* "real" consoles (everything which is not a bootconsole) which are
* handled differently.
* - Any number of bootconsoles can be registered at any time.
* - As soon as a "real" console is registered, all bootconsoles
* will be unregistered automatically.
* - Once a "real" console is registered, any attempt to register a
* bootconsoles will be rejected
*/
void register_console(struct console *newcon)
{
int i;
unsigned long flags;
struct console *bcon = NULL;
struct console_cmdline *c;
if (console_drivers)
for_each_console(bcon)
if (WARN(bcon == newcon,
"console '%s%d' already registered\n",
bcon->name, bcon->index))
return;
/*
* before we register a new CON_BOOT console, make sure we don't
* already have a valid console
*/
if (console_drivers && newcon->flags & CON_BOOT) {
/* find the last or real console */
for_each_console(bcon) {
if (!(bcon->flags & CON_BOOT)) {
pr_info("Too late to register bootconsole %s%d\n",
newcon->name, newcon->index);
return;
}
}
}
if (console_drivers && console_drivers->flags & CON_BOOT)
bcon = console_drivers;
if (preferred_console < 0 || bcon || !console_drivers)
preferred_console = selected_console;
if (newcon->early_setup)
newcon->early_setup();
/*
* See if we want to use this console driver. If we
* didn't select a console we take the first one
* that registers here.
*/
if (preferred_console < 0) {
if (newcon->index < 0)
newcon->index = 0;
if (newcon->setup == NULL ||
newcon->setup(newcon, NULL) == 0) {
newcon->flags |= CON_ENABLED;
if (newcon->device) {
newcon->flags |= CON_CONSDEV;
preferred_console = 0;
}
}
}
/*
* See if this console matches one we selected on
* the command line.
*/
for (i = 0, c = console_cmdline;
i < MAX_CMDLINECONSOLES && c->name[0];
i++, c++) {
BUILD_BUG_ON(sizeof(c->name) != sizeof(newcon->name));
if (strcmp(c->name, newcon->name) != 0)
continue;
if (newcon->index >= 0 &&
newcon->index != c->index)
continue;
if (newcon->index < 0)
newcon->index = c->index;
if (_braille_register_console(newcon, c))
return;
if (newcon->setup &&
newcon->setup(newcon, console_cmdline[i].options) != 0)
break;
newcon->flags |= CON_ENABLED;
newcon->index = c->index;
if (i == selected_console) {
newcon->flags |= CON_CONSDEV;
preferred_console = selected_console;
}
break;
}
if (!(newcon->flags & CON_ENABLED))
return;
/*
* If we have a bootconsole, and are switching to a real console,
* don't print everything out again, since when the boot console, and
* the real console are the same physical device, it's annoying to
* see the beginning boot messages twice
*/
if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV))
newcon->flags &= ~CON_PRINTBUFFER;
/*
* Put this console in the list - keep the
* preferred driver at the head of the list.
*/
console_lock();
if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
newcon->next = console_drivers;
console_drivers = newcon;
if (newcon->next)
newcon->next->flags &= ~CON_CONSDEV;
} else {
newcon->next = console_drivers->next;
console_drivers->next = newcon;
}
if (newcon->flags & CON_PRINTBUFFER) {
/*
* console_unlock(); will print out the buffered messages
* for us.
*/
raw_spin_lock_irqsave(&logbuf_lock, flags);
console_seq = syslog_seq;
console_idx = syslog_idx;
console_prev = syslog_prev;
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
/*
* We're about to replay the log buffer. Only do this to the
* just-registered console to avoid excessive message spam to
* the already-registered consoles.
*/
exclusive_console = newcon;
}
console_unlock();
console_sysfs_notify();
/*
* By unregistering the bootconsoles after we enable the real console
* we get the "console xxx enabled" message on all the consoles -
* boot consoles, real consoles, etc - this is to ensure that end
* users know there might be something in the kernel's log buffer that
* went to the bootconsole (that they do not see on the real console)
*/
pr_info("%sconsole [%s%d] enabled\n",
(newcon->flags & CON_BOOT) ? "boot" : "" ,
newcon->name, newcon->index);
if (bcon &&
((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
!keep_bootcon) {
/* We need to iterate through all boot consoles, to make
* sure we print everything out, before we unregister them.
*/
for_each_console(bcon)
if (bcon->flags & CON_BOOT)
unregister_console(bcon);
}
}
EXPORT_SYMBOL(register_console);
int unregister_console(struct console *console)
{
struct console *a, *b;
int res;
pr_info("%sconsole [%s%d] disabled\n",
(console->flags & CON_BOOT) ? "boot" : "" ,
console->name, console->index);
res = _braille_unregister_console(console);
if (res)
return res;
res = 1;
console_lock();
if (console_drivers == console) {
console_drivers=console->next;
res = 0;
} else if (console_drivers) {
for (a=console_drivers->next, b=console_drivers ;
a; b=a, a=b->next) {
if (a == console) {
b->next = a->next;
res = 0;
break;
}
}
}
/*
* If this isn't the last console and it has CON_CONSDEV set, we
* need to set it on the next preferred console.
*/
if (console_drivers != NULL && console->flags & CON_CONSDEV)
console_drivers->flags |= CON_CONSDEV;
console->flags &= ~CON_ENABLED;
console_unlock();
console_sysfs_notify();
return res;
}
EXPORT_SYMBOL(unregister_console);
static int __init printk_late_init(void)
{
struct console *con;
for_each_console(con) {
if (!keep_bootcon && con->flags & CON_BOOT) {
unregister_console(con);
}
}
hotcpu_notifier(console_cpu_notify, 0);
return 0;
}
late_initcall(printk_late_init);
#if defined CONFIG_PRINTK
/*
* Delayed printk version, for scheduler-internal messages:
*/
#define PRINTK_PENDING_WAKEUP 0x01
#define PRINTK_PENDING_OUTPUT 0x02
static DEFINE_PER_CPU(int, printk_pending);
static void wake_up_klogd_work_func(struct irq_work *irq_work)
{
int pending = __this_cpu_xchg(printk_pending, 0);
if (pending & PRINTK_PENDING_OUTPUT) {
/* If trylock fails, someone else is doing the printing */
if (console_trylock())
console_unlock();
}
if (pending & PRINTK_PENDING_WAKEUP)
wake_up_interruptible(&log_wait);
}
static DEFINE_PER_CPU(struct irq_work, wake_up_klogd_work) = {
.func = wake_up_klogd_work_func,
.flags = IRQ_WORK_LAZY,
};
void wake_up_klogd(void)
{
preempt_disable();
if (waitqueue_active(&log_wait)) {
this_cpu_or(printk_pending, PRINTK_PENDING_WAKEUP);
irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
}
preempt_enable();
}
int printk_deferred(const char *fmt, ...)
{
va_list args;
int r;
preempt_disable();
va_start(args, fmt);
r = vprintk_emit(0, LOGLEVEL_SCHED, NULL, 0, fmt, args);
va_end(args);
__this_cpu_or(printk_pending, PRINTK_PENDING_OUTPUT);
irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
preempt_enable();
return r;
}
/*
* printk rate limiting, lifted from the networking subsystem.
*
* This enforces a rate limit: not more than 10 kernel messages
* every 5s to make a denial-of-service attack impossible.
*/
DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
int __printk_ratelimit(const char *func)
{
return ___ratelimit(&printk_ratelimit_state, func);
}
EXPORT_SYMBOL(__printk_ratelimit);
/**
* printk_timed_ratelimit - caller-controlled printk ratelimiting
* @caller_jiffies: pointer to caller's state
* @interval_msecs: minimum interval between prints
*
* printk_timed_ratelimit() returns true if more than @interval_msecs
* milliseconds have elapsed since the last time printk_timed_ratelimit()
* returned true.
*/
bool printk_timed_ratelimit(unsigned long *caller_jiffies,
unsigned int interval_msecs)
{
unsigned long elapsed = jiffies - *caller_jiffies;
if (*caller_jiffies && elapsed <= msecs_to_jiffies(interval_msecs))
return false;
*caller_jiffies = jiffies;
return true;
}
EXPORT_SYMBOL(printk_timed_ratelimit);
static DEFINE_SPINLOCK(dump_list_lock);
static LIST_HEAD(dump_list);
/**
* kmsg_dump_register - register a kernel log dumper.
* @dumper: pointer to the kmsg_dumper structure
*
* Adds a kernel log dumper to the system. The dump callback in the
* structure will be called when the kernel oopses or panics and must be
* set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
*/
int kmsg_dump_register(struct kmsg_dumper *dumper)
{
unsigned long flags;
int err = -EBUSY;
/* The dump callback needs to be set */
if (!dumper->dump)
return -EINVAL;
spin_lock_irqsave(&dump_list_lock, flags);
/* Don't allow registering multiple times */
if (!dumper->registered) {
dumper->registered = 1;
list_add_tail_rcu(&dumper->list, &dump_list);
err = 0;
}
spin_unlock_irqrestore(&dump_list_lock, flags);
return err;
}
EXPORT_SYMBOL_GPL(kmsg_dump_register);
/**
* kmsg_dump_unregister - unregister a kmsg dumper.
* @dumper: pointer to the kmsg_dumper structure
*
* Removes a dump device from the system. Returns zero on success and
* %-EINVAL otherwise.
*/
int kmsg_dump_unregister(struct kmsg_dumper *dumper)
{
unsigned long flags;
int err = -EINVAL;
spin_lock_irqsave(&dump_list_lock, flags);
if (dumper->registered) {
dumper->registered = 0;
list_del_rcu(&dumper->list);
err = 0;
}
spin_unlock_irqrestore(&dump_list_lock, flags);
synchronize_rcu();
return err;
}
EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
static bool always_kmsg_dump;
module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
/**
* kmsg_dump - dump kernel log to kernel message dumpers.
* @reason: the reason (oops, panic etc) for dumping
*
* Call each of the registered dumper's dump() callback, which can
* retrieve the kmsg records with kmsg_dump_get_line() or
* kmsg_dump_get_buffer().
*/
void kmsg_dump(enum kmsg_dump_reason reason)
{
struct kmsg_dumper *dumper;
unsigned long flags;
if ((reason > KMSG_DUMP_OOPS) && !always_kmsg_dump)
return;
rcu_read_lock();
list_for_each_entry_rcu(dumper, &dump_list, list) {
if (dumper->max_reason && reason > dumper->max_reason)
continue;
/* initialize iterator with data about the stored records */
dumper->active = true;
raw_spin_lock_irqsave(&logbuf_lock, flags);
dumper->cur_seq = clear_seq;
dumper->cur_idx = clear_idx;
dumper->next_seq = log_next_seq;
dumper->next_idx = log_next_idx;
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
/* invoke dumper which will iterate over records */
dumper->dump(dumper, reason);
/* reset iterator */
dumper->active = false;
}
rcu_read_unlock();
}
/**
* kmsg_dump_get_line_nolock - retrieve one kmsg log line (unlocked version)
* @dumper: registered kmsg dumper
* @syslog: include the "<4>" prefixes
* @line: buffer to copy the line to
* @size: maximum size of the buffer
* @len: length of line placed into buffer
*
* Start at the beginning of the kmsg buffer, with the oldest kmsg
* record, and copy one record into the provided buffer.
*
* Consecutive calls will return the next available record moving
* towards the end of the buffer with the youngest messages.
*
* A return value of FALSE indicates that there are no more records to
* read.
*
* The function is similar to kmsg_dump_get_line(), but grabs no locks.
*/
bool kmsg_dump_get_line_nolock(struct kmsg_dumper *dumper, bool syslog,
char *line, size_t size, size_t *len)
{
struct printk_log *msg;
size_t l = 0;
bool ret = false;
if (!dumper->active)
goto out;
if (dumper->cur_seq < log_first_seq) {
/* messages are gone, move to first available one */
dumper->cur_seq = log_first_seq;
dumper->cur_idx = log_first_idx;
}
/* last entry */
if (dumper->cur_seq >= log_next_seq)
goto out;
msg = log_from_idx(dumper->cur_idx);
l = msg_print_text(msg, 0, syslog, line, size);
dumper->cur_idx = log_next(dumper->cur_idx);
dumper->cur_seq++;
ret = true;
out:
if (len)
*len = l;
return ret;
}
/**
* kmsg_dump_get_line - retrieve one kmsg log line
* @dumper: registered kmsg dumper
* @syslog: include the "<4>" prefixes
* @line: buffer to copy the line to
* @size: maximum size of the buffer
* @len: length of line placed into buffer
*
* Start at the beginning of the kmsg buffer, with the oldest kmsg
* record, and copy one record into the provided buffer.
*
* Consecutive calls will return the next available record moving
* towards the end of the buffer with the youngest messages.
*
* A return value of FALSE indicates that there are no more records to
* read.
*/
bool kmsg_dump_get_line(struct kmsg_dumper *dumper, bool syslog,
char *line, size_t size, size_t *len)
{
unsigned long flags;
bool ret;
raw_spin_lock_irqsave(&logbuf_lock, flags);
ret = kmsg_dump_get_line_nolock(dumper, syslog, line, size, len);
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
return ret;
}
EXPORT_SYMBOL_GPL(kmsg_dump_get_line);
/**
* kmsg_dump_get_buffer - copy kmsg log lines
* @dumper: registered kmsg dumper
* @syslog: include the "<4>" prefixes
* @buf: buffer to copy the line to
* @size: maximum size of the buffer
* @len: length of line placed into buffer
*
* Start at the end of the kmsg buffer and fill the provided buffer
* with as many of the the *youngest* kmsg records that fit into it.
* If the buffer is large enough, all available kmsg records will be
* copied with a single call.
*
* Consecutive calls will fill the buffer with the next block of
* available older records, not including the earlier retrieved ones.
*
* A return value of FALSE indicates that there are no more records to
* read.
*/
bool kmsg_dump_get_buffer(struct kmsg_dumper *dumper, bool syslog,
char *buf, size_t size, size_t *len)
{
unsigned long flags;
u64 seq;
u32 idx;
u64 next_seq;
u32 next_idx;
enum log_flags prev;
size_t l = 0;
bool ret = false;
if (!dumper->active)
goto out;
raw_spin_lock_irqsave(&logbuf_lock, flags);
if (dumper->cur_seq < log_first_seq) {
/* messages are gone, move to first available one */
dumper->cur_seq = log_first_seq;
dumper->cur_idx = log_first_idx;
}
/* last entry */
if (dumper->cur_seq >= dumper->next_seq) {
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
goto out;
}
/* calculate length of entire buffer */
seq = dumper->cur_seq;
idx = dumper->cur_idx;
prev = 0;
while (seq < dumper->next_seq) {
struct printk_log *msg = log_from_idx(idx);
l += msg_print_text(msg, prev, true, NULL, 0);
idx = log_next(idx);
seq++;
prev = msg->flags;
}
/* move first record forward until length fits into the buffer */
seq = dumper->cur_seq;
idx = dumper->cur_idx;
prev = 0;
while (l > size && seq < dumper->next_seq) {
struct printk_log *msg = log_from_idx(idx);
l -= msg_print_text(msg, prev, true, NULL, 0);
idx = log_next(idx);
seq++;
prev = msg->flags;
}
/* last message in next interation */
next_seq = seq;
next_idx = idx;
l = 0;
while (seq < dumper->next_seq) {
struct printk_log *msg = log_from_idx(idx);
l += msg_print_text(msg, prev, syslog, buf + l, size - l);
idx = log_next(idx);
seq++;
prev = msg->flags;
}
dumper->next_seq = next_seq;
dumper->next_idx = next_idx;
ret = true;
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
out:
if (len)
*len = l;
return ret;
}
EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
/**
* kmsg_dump_rewind_nolock - reset the interator (unlocked version)
* @dumper: registered kmsg dumper
*
* Reset the dumper's iterator so that kmsg_dump_get_line() and
* kmsg_dump_get_buffer() can be called again and used multiple
* times within the same dumper.dump() callback.
*
* The function is similar to kmsg_dump_rewind(), but grabs no locks.
*/
void kmsg_dump_rewind_nolock(struct kmsg_dumper *dumper)
{
dumper->cur_seq = clear_seq;
dumper->cur_idx = clear_idx;
dumper->next_seq = log_next_seq;
dumper->next_idx = log_next_idx;
}
/**
* kmsg_dump_rewind - reset the interator
* @dumper: registered kmsg dumper
*
* Reset the dumper's iterator so that kmsg_dump_get_line() and
* kmsg_dump_get_buffer() can be called again and used multiple
* times within the same dumper.dump() callback.
*/
void kmsg_dump_rewind(struct kmsg_dumper *dumper)
{
unsigned long flags;
raw_spin_lock_irqsave(&logbuf_lock, flags);
kmsg_dump_rewind_nolock(dumper);
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
}
EXPORT_SYMBOL_GPL(kmsg_dump_rewind);
static char dump_stack_arch_desc_str[128];
/**
* dump_stack_set_arch_desc - set arch-specific str to show with task dumps
* @fmt: printf-style format string
* @...: arguments for the format string
*
* The configured string will be printed right after utsname during task
* dumps. Usually used to add arch-specific system identifiers. If an
* arch wants to make use of such an ID string, it should initialize this
* as soon as possible during boot.
*/
void __init dump_stack_set_arch_desc(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vsnprintf(dump_stack_arch_desc_str, sizeof(dump_stack_arch_desc_str),
fmt, args);
va_end(args);
}
/**
* dump_stack_print_info - print generic debug info for dump_stack()
* @log_lvl: log level
*
* Arch-specific dump_stack() implementations can use this function to
* print out the same debug information as the generic dump_stack().
*/
void dump_stack_print_info(const char *log_lvl)
{
printk("%sCPU: %d PID: %d Comm: %.20s %s %s %.*s\n",
log_lvl, raw_smp_processor_id(), current->pid, current->comm,
print_tainted(), init_utsname()->release,
(int)strcspn(init_utsname()->version, " "),
init_utsname()->version);
if (dump_stack_arch_desc_str[0] != '\0')
printk("%sHardware name: %s\n",
log_lvl, dump_stack_arch_desc_str);
print_worker_info(log_lvl, current);
}
/**
* show_regs_print_info - print generic debug info for show_regs()
* @log_lvl: log level
*
* show_regs() implementations can use this function to print out generic
* debug information.
*/
void show_regs_print_info(const char *log_lvl)
{
dump_stack_print_info(log_lvl);
printk("%stask: %p ti: %p task.ti: %p\n",
log_lvl, current, current_thread_info(),
task_thread_info(current));
}
#endif
| gpl-2.0 |
kamma/ace_kernel | sound/isa/sb/es968.c | 616 | 6612 |
/*
card-es968.c - driver for ESS AudioDrive ES968 based soundcards.
Copyright (C) 1999 by Massimo Piccioni <dafastidio@libero.it>
Thanks to Pierfrancesco 'qM2' Passerini.
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/init.h>
#include <linux/time.h>
#include <linux/pnp.h>
#include <linux/moduleparam.h>
#include <sound/core.h>
#include <sound/initval.h>
#include <sound/sb.h>
#define PFX "es968: "
MODULE_AUTHOR("Massimo Piccioni <dafastidio@libero.it>");
MODULE_DESCRIPTION("ESS AudioDrive ES968");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{ESS,AudioDrive ES968}}");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_ISAPNP; /* Enable this card */
static long port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */
static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* Pnp setup */
static int dma8[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* PnP setup */
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for es968 based soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for es968 based soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable es968 based soundcard.");
struct snd_card_es968 {
struct pnp_dev *dev;
struct snd_sb *chip;
};
static struct pnp_card_device_id snd_es968_pnpids[] = {
{ .id = "ESS0968", .devs = { { "@@@0968" }, } },
{ .id = "", } /* end */
};
MODULE_DEVICE_TABLE(pnp_card, snd_es968_pnpids);
#define DRIVER_NAME "snd-card-es968"
static irqreturn_t snd_card_es968_interrupt(int irq, void *dev_id)
{
struct snd_sb *chip = dev_id;
if (chip->open & SB_OPEN_PCM) {
return snd_sb8dsp_interrupt(chip);
} else {
return snd_sb8dsp_midi_interrupt(chip);
}
}
static int __devinit snd_card_es968_pnp(int dev, struct snd_card_es968 *acard,
struct pnp_card_link *card,
const struct pnp_card_device_id *id)
{
struct pnp_dev *pdev;
int err;
acard->dev = pnp_request_card_device(card, id->devs[0].id, NULL);
if (acard->dev == NULL)
return -ENODEV;
pdev = acard->dev;
err = pnp_activate_dev(pdev);
if (err < 0) {
snd_printk(KERN_ERR PFX "AUDIO pnp configure failure\n");
return err;
}
port[dev] = pnp_port_start(pdev, 0);
dma8[dev] = pnp_dma(pdev, 1);
irq[dev] = pnp_irq(pdev, 0);
return 0;
}
static int __devinit snd_card_es968_probe(int dev,
struct pnp_card_link *pcard,
const struct pnp_card_device_id *pid)
{
int error;
struct snd_sb *chip;
struct snd_card *card;
struct snd_card_es968 *acard;
error = snd_card_create(index[dev], id[dev], THIS_MODULE,
sizeof(struct snd_card_es968), &card);
if (error < 0)
return error;
acard = card->private_data;
if ((error = snd_card_es968_pnp(dev, acard, pcard, pid))) {
snd_card_free(card);
return error;
}
snd_card_set_dev(card, &pcard->card->dev);
if ((error = snd_sbdsp_create(card, port[dev],
irq[dev],
snd_card_es968_interrupt,
dma8[dev],
-1,
SB_HW_AUTO, &chip)) < 0) {
snd_card_free(card);
return error;
}
acard->chip = chip;
if ((error = snd_sb8dsp_pcm(chip, 0, NULL)) < 0) {
snd_card_free(card);
return error;
}
if ((error = snd_sbmixer_new(chip)) < 0) {
snd_card_free(card);
return error;
}
if ((error = snd_sb8dsp_midi(chip, 0, NULL)) < 0) {
snd_card_free(card);
return error;
}
strcpy(card->driver, "ES968");
strcpy(card->shortname, "ESS ES968");
sprintf(card->longname, "%s soundcard, %s at 0x%lx, irq %d, dma %d",
card->shortname, chip->name, chip->port, irq[dev], dma8[dev]);
if ((error = snd_card_register(card)) < 0) {
snd_card_free(card);
return error;
}
pnp_set_card_drvdata(pcard, card);
return 0;
}
static unsigned int __devinitdata es968_devices;
static int __devinit snd_es968_pnp_detect(struct pnp_card_link *card,
const struct pnp_card_device_id *id)
{
static int dev;
int res;
for ( ; dev < SNDRV_CARDS; dev++) {
if (!enable[dev])
continue;
res = snd_card_es968_probe(dev, card, id);
if (res < 0)
return res;
dev++;
es968_devices++;
return 0;
}
return -ENODEV;
}
static void __devexit snd_es968_pnp_remove(struct pnp_card_link * pcard)
{
snd_card_free(pnp_get_card_drvdata(pcard));
pnp_set_card_drvdata(pcard, NULL);
}
#ifdef CONFIG_PM
static int snd_es968_pnp_suspend(struct pnp_card_link *pcard, pm_message_t state)
{
struct snd_card *card = pnp_get_card_drvdata(pcard);
struct snd_card_es968 *acard = card->private_data;
struct snd_sb *chip = acard->chip;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
snd_pcm_suspend_all(chip->pcm);
snd_sbmixer_suspend(chip);
return 0;
}
static int snd_es968_pnp_resume(struct pnp_card_link *pcard)
{
struct snd_card *card = pnp_get_card_drvdata(pcard);
struct snd_card_es968 *acard = card->private_data;
struct snd_sb *chip = acard->chip;
snd_sbdsp_reset(chip);
snd_sbmixer_resume(chip);
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif
static struct pnp_card_driver es968_pnpc_driver = {
.flags = PNP_DRIVER_RES_DISABLE,
.name = "es968",
.id_table = snd_es968_pnpids,
.probe = snd_es968_pnp_detect,
.remove = __devexit_p(snd_es968_pnp_remove),
#ifdef CONFIG_PM
.suspend = snd_es968_pnp_suspend,
.resume = snd_es968_pnp_resume,
#endif
};
static int __init alsa_card_es968_init(void)
{
int err = pnp_register_card_driver(&es968_pnpc_driver);
if (err)
return err;
if (!es968_devices) {
pnp_unregister_card_driver(&es968_pnpc_driver);
#ifdef MODULE
snd_printk(KERN_ERR "no ES968 based soundcards found\n");
#endif
return -ENODEV;
}
return 0;
}
static void __exit alsa_card_es968_exit(void)
{
pnp_unregister_card_driver(&es968_pnpc_driver);
}
module_init(alsa_card_es968_init)
module_exit(alsa_card_es968_exit)
| gpl-2.0 |
BenRomer/unisys | arch/arm/mach-omap2/powerdomains54xx_data.c | 1896 | 9334 | /*
* OMAP54XX Power domains framework
*
* Copyright (C) 2013 Texas Instruments, Inc.
*
* Abhijit Pagare (abhijitpagare@ti.com)
* Benoit Cousson (b-cousson@ti.com)
* Paul Walmsley (paul@pwsan.com)
*
* This file is automatically generated from the OMAP hardware databases.
* We respectfully ask that any modifications to this file be coordinated
* with the public linux-omap@vger.kernel.org mailing list and the
* authors above to ensure that the autogeneration scripts are kept
* up-to-date with the file contents.
*
* 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 "powerdomain.h"
#include "prcm-common.h"
#include "prcm44xx.h"
#include "prm54xx.h"
#include "prcm_mpu54xx.h"
/* core_54xx_pwrdm: CORE power domain */
static struct powerdomain core_54xx_pwrdm = {
.name = "core_pwrdm",
.voltdm = { .name = "core" },
.prcm_offs = OMAP54XX_PRM_CORE_INST,
.prcm_partition = OMAP54XX_PRM_PARTITION,
.pwrsts = PWRSTS_RET_ON,
.pwrsts_logic_ret = PWRSTS_RET,
.banks = 5,
.pwrsts_mem_ret = {
[0] = PWRSTS_OFF_RET, /* core_nret_bank */
[1] = PWRSTS_OFF_RET, /* core_ocmram */
[2] = PWRSTS_OFF_RET, /* core_other_bank */
[3] = PWRSTS_OFF_RET, /* ipu_l2ram */
[4] = PWRSTS_OFF_RET, /* ipu_unicache */
},
.pwrsts_mem_on = {
[0] = PWRSTS_OFF_RET, /* core_nret_bank */
[1] = PWRSTS_OFF_RET, /* core_ocmram */
[2] = PWRSTS_OFF_RET, /* core_other_bank */
[3] = PWRSTS_OFF_RET, /* ipu_l2ram */
[4] = PWRSTS_OFF_RET, /* ipu_unicache */
},
.flags = PWRDM_HAS_LOWPOWERSTATECHANGE,
};
/* abe_54xx_pwrdm: Audio back end power domain */
static struct powerdomain abe_54xx_pwrdm = {
.name = "abe_pwrdm",
.voltdm = { .name = "core" },
.prcm_offs = OMAP54XX_PRM_ABE_INST,
.prcm_partition = OMAP54XX_PRM_PARTITION,
.pwrsts = PWRSTS_OFF_RET_ON,
.pwrsts_logic_ret = PWRSTS_OFF,
.banks = 2,
.pwrsts_mem_ret = {
[0] = PWRSTS_OFF_RET, /* aessmem */
[1] = PWRSTS_OFF_RET, /* periphmem */
},
.pwrsts_mem_on = {
[0] = PWRSTS_OFF_RET, /* aessmem */
[1] = PWRSTS_OFF_RET, /* periphmem */
},
.flags = PWRDM_HAS_LOWPOWERSTATECHANGE,
};
/* coreaon_54xx_pwrdm: Always ON logic that sits in VDD_CORE voltage domain */
static struct powerdomain coreaon_54xx_pwrdm = {
.name = "coreaon_pwrdm",
.voltdm = { .name = "core" },
.prcm_offs = OMAP54XX_PRM_COREAON_INST,
.prcm_partition = OMAP54XX_PRM_PARTITION,
.pwrsts = PWRSTS_ON,
};
/* dss_54xx_pwrdm: Display subsystem power domain */
static struct powerdomain dss_54xx_pwrdm = {
.name = "dss_pwrdm",
.voltdm = { .name = "core" },
.prcm_offs = OMAP54XX_PRM_DSS_INST,
.prcm_partition = OMAP54XX_PRM_PARTITION,
.pwrsts = PWRSTS_OFF_RET_ON,
.pwrsts_logic_ret = PWRSTS_OFF,
.banks = 1,
.pwrsts_mem_ret = {
[0] = PWRSTS_OFF_RET, /* dss_mem */
},
.pwrsts_mem_on = {
[0] = PWRSTS_OFF_RET, /* dss_mem */
},
.flags = PWRDM_HAS_LOWPOWERSTATECHANGE,
};
/* cpu0_54xx_pwrdm: MPU0 processor and Neon coprocessor power domain */
static struct powerdomain cpu0_54xx_pwrdm = {
.name = "cpu0_pwrdm",
.voltdm = { .name = "mpu" },
.prcm_offs = OMAP54XX_PRCM_MPU_PRM_C0_INST,
.prcm_partition = OMAP54XX_PRCM_MPU_PARTITION,
.pwrsts = PWRSTS_RET_ON,
.pwrsts_logic_ret = PWRSTS_RET,
.banks = 1,
.pwrsts_mem_ret = {
[0] = PWRSTS_OFF_RET, /* cpu0_l1 */
},
.pwrsts_mem_on = {
[0] = PWRSTS_ON, /* cpu0_l1 */
},
};
/* cpu1_54xx_pwrdm: MPU1 processor and Neon coprocessor power domain */
static struct powerdomain cpu1_54xx_pwrdm = {
.name = "cpu1_pwrdm",
.voltdm = { .name = "mpu" },
.prcm_offs = OMAP54XX_PRCM_MPU_PRM_C1_INST,
.prcm_partition = OMAP54XX_PRCM_MPU_PARTITION,
.pwrsts = PWRSTS_RET_ON,
.pwrsts_logic_ret = PWRSTS_RET,
.banks = 1,
.pwrsts_mem_ret = {
[0] = PWRSTS_OFF_RET, /* cpu1_l1 */
},
.pwrsts_mem_on = {
[0] = PWRSTS_ON, /* cpu1_l1 */
},
};
/* emu_54xx_pwrdm: Emulation power domain */
static struct powerdomain emu_54xx_pwrdm = {
.name = "emu_pwrdm",
.voltdm = { .name = "wkup" },
.prcm_offs = OMAP54XX_PRM_EMU_INST,
.prcm_partition = OMAP54XX_PRM_PARTITION,
.pwrsts = PWRSTS_OFF_ON,
.banks = 1,
.pwrsts_mem_ret = {
[0] = PWRSTS_OFF_RET, /* emu_bank */
},
.pwrsts_mem_on = {
[0] = PWRSTS_OFF_RET, /* emu_bank */
},
};
/* mpu_54xx_pwrdm: Modena processor and the Neon coprocessor power domain */
static struct powerdomain mpu_54xx_pwrdm = {
.name = "mpu_pwrdm",
.voltdm = { .name = "mpu" },
.prcm_offs = OMAP54XX_PRM_MPU_INST,
.prcm_partition = OMAP54XX_PRM_PARTITION,
.pwrsts = PWRSTS_RET_ON,
.pwrsts_logic_ret = PWRSTS_RET,
.banks = 2,
.pwrsts_mem_ret = {
[0] = PWRSTS_OFF_RET, /* mpu_l2 */
[1] = PWRSTS_RET, /* mpu_ram */
},
.pwrsts_mem_on = {
[0] = PWRSTS_OFF_RET, /* mpu_l2 */
[1] = PWRSTS_OFF_RET, /* mpu_ram */
},
};
/* custefuse_54xx_pwrdm: Customer efuse controller power domain */
static struct powerdomain custefuse_54xx_pwrdm = {
.name = "custefuse_pwrdm",
.voltdm = { .name = "core" },
.prcm_offs = OMAP54XX_PRM_CUSTEFUSE_INST,
.prcm_partition = OMAP54XX_PRM_PARTITION,
.pwrsts = PWRSTS_OFF_ON,
.flags = PWRDM_HAS_LOWPOWERSTATECHANGE,
};
/* dsp_54xx_pwrdm: Tesla processor power domain */
static struct powerdomain dsp_54xx_pwrdm = {
.name = "dsp_pwrdm",
.voltdm = { .name = "mm" },
.prcm_offs = OMAP54XX_PRM_DSP_INST,
.prcm_partition = OMAP54XX_PRM_PARTITION,
.pwrsts = PWRSTS_OFF_RET_ON,
.pwrsts_logic_ret = PWRSTS_OFF_RET,
.banks = 3,
.pwrsts_mem_ret = {
[0] = PWRSTS_OFF_RET, /* dsp_edma */
[1] = PWRSTS_OFF_RET, /* dsp_l1 */
[2] = PWRSTS_OFF_RET, /* dsp_l2 */
},
.pwrsts_mem_on = {
[0] = PWRSTS_OFF_RET, /* dsp_edma */
[1] = PWRSTS_OFF_RET, /* dsp_l1 */
[2] = PWRSTS_OFF_RET, /* dsp_l2 */
},
.flags = PWRDM_HAS_LOWPOWERSTATECHANGE,
};
/* cam_54xx_pwrdm: Camera subsystem power domain */
static struct powerdomain cam_54xx_pwrdm = {
.name = "cam_pwrdm",
.voltdm = { .name = "core" },
.prcm_offs = OMAP54XX_PRM_CAM_INST,
.prcm_partition = OMAP54XX_PRM_PARTITION,
.pwrsts = PWRSTS_OFF_ON,
.banks = 1,
.pwrsts_mem_ret = {
[0] = PWRSTS_OFF_RET, /* cam_mem */
},
.pwrsts_mem_on = {
[0] = PWRSTS_OFF_RET, /* cam_mem */
},
.flags = PWRDM_HAS_LOWPOWERSTATECHANGE,
};
/* l3init_54xx_pwrdm: L3 initators pheripherals power domain */
static struct powerdomain l3init_54xx_pwrdm = {
.name = "l3init_pwrdm",
.voltdm = { .name = "core" },
.prcm_offs = OMAP54XX_PRM_L3INIT_INST,
.prcm_partition = OMAP54XX_PRM_PARTITION,
.pwrsts = PWRSTS_RET_ON,
.pwrsts_logic_ret = PWRSTS_OFF_RET,
.banks = 2,
.pwrsts_mem_ret = {
[0] = PWRSTS_OFF_RET, /* l3init_bank1 */
[1] = PWRSTS_OFF_RET, /* l3init_bank2 */
},
.pwrsts_mem_on = {
[0] = PWRSTS_OFF_RET, /* l3init_bank1 */
[1] = PWRSTS_OFF_RET, /* l3init_bank2 */
},
.flags = PWRDM_HAS_LOWPOWERSTATECHANGE,
};
/* gpu_54xx_pwrdm: 3D accelerator power domain */
static struct powerdomain gpu_54xx_pwrdm = {
.name = "gpu_pwrdm",
.voltdm = { .name = "mm" },
.prcm_offs = OMAP54XX_PRM_GPU_INST,
.prcm_partition = OMAP54XX_PRM_PARTITION,
.pwrsts = PWRSTS_OFF_ON,
.banks = 1,
.pwrsts_mem_ret = {
[0] = PWRSTS_OFF_RET, /* gpu_mem */
},
.pwrsts_mem_on = {
[0] = PWRSTS_OFF_RET, /* gpu_mem */
},
.flags = PWRDM_HAS_LOWPOWERSTATECHANGE,
};
/* wkupaon_54xx_pwrdm: Wake-up power domain */
static struct powerdomain wkupaon_54xx_pwrdm = {
.name = "wkupaon_pwrdm",
.voltdm = { .name = "wkup" },
.prcm_offs = OMAP54XX_PRM_WKUPAON_INST,
.prcm_partition = OMAP54XX_PRM_PARTITION,
.pwrsts = PWRSTS_ON,
.banks = 1,
.pwrsts_mem_ret = {
},
.pwrsts_mem_on = {
[0] = PWRSTS_ON, /* wkup_bank */
},
};
/* iva_54xx_pwrdm: IVA-HD power domain */
static struct powerdomain iva_54xx_pwrdm = {
.name = "iva_pwrdm",
.voltdm = { .name = "mm" },
.prcm_offs = OMAP54XX_PRM_IVA_INST,
.prcm_partition = OMAP54XX_PRM_PARTITION,
.pwrsts = PWRSTS_OFF_RET_ON,
.pwrsts_logic_ret = PWRSTS_OFF,
.banks = 4,
.pwrsts_mem_ret = {
[0] = PWRSTS_OFF_RET, /* hwa_mem */
[1] = PWRSTS_OFF_RET, /* sl2_mem */
[2] = PWRSTS_OFF_RET, /* tcm1_mem */
[3] = PWRSTS_OFF_RET, /* tcm2_mem */
},
.pwrsts_mem_on = {
[0] = PWRSTS_OFF_RET, /* hwa_mem */
[1] = PWRSTS_OFF_RET, /* sl2_mem */
[2] = PWRSTS_OFF_RET, /* tcm1_mem */
[3] = PWRSTS_OFF_RET, /* tcm2_mem */
},
.flags = PWRDM_HAS_LOWPOWERSTATECHANGE,
};
/*
* The following power domains are not under SW control
*
* mpuaon
* mmaon
*/
/* As powerdomains are added or removed above, this list must also be changed */
static struct powerdomain *powerdomains_omap54xx[] __initdata = {
&core_54xx_pwrdm,
&abe_54xx_pwrdm,
&coreaon_54xx_pwrdm,
&dss_54xx_pwrdm,
&cpu0_54xx_pwrdm,
&cpu1_54xx_pwrdm,
&emu_54xx_pwrdm,
&mpu_54xx_pwrdm,
&custefuse_54xx_pwrdm,
&dsp_54xx_pwrdm,
&cam_54xx_pwrdm,
&l3init_54xx_pwrdm,
&gpu_54xx_pwrdm,
&wkupaon_54xx_pwrdm,
&iva_54xx_pwrdm,
NULL
};
void __init omap54xx_powerdomains_init(void)
{
pwrdm_register_platform_funcs(&omap4_pwrdm_operations);
pwrdm_register_pwrdms(powerdomains_omap54xx);
pwrdm_complete_init();
}
| gpl-2.0 |
vlw/android_kernel_samsung_msm8916_A3 | drivers/net/ethernet/qlogic/qlcnic/qlcnic_init.c | 2152 | 31285 | /*
* QLogic qlcnic NIC Driver
* Copyright (c) 2009-2013 QLogic Corporation
*
* See LICENSE.qlcnic for copyright and licensing details.
*/
#include "qlcnic.h"
#include "qlcnic_hw.h"
struct crb_addr_pair {
u32 addr;
u32 data;
};
#define QLCNIC_MAX_CRB_XFORM 60
static unsigned int crb_addr_xform[QLCNIC_MAX_CRB_XFORM];
#define crb_addr_transform(name) \
(crb_addr_xform[QLCNIC_HW_PX_MAP_CRB_##name] = \
QLCNIC_HW_CRB_HUB_AGT_ADR_##name << 20)
#define QLCNIC_ADDR_ERROR (0xffffffff)
static int
qlcnic_check_fw_hearbeat(struct qlcnic_adapter *adapter);
static void crb_addr_transform_setup(void)
{
crb_addr_transform(XDMA);
crb_addr_transform(TIMR);
crb_addr_transform(SRE);
crb_addr_transform(SQN3);
crb_addr_transform(SQN2);
crb_addr_transform(SQN1);
crb_addr_transform(SQN0);
crb_addr_transform(SQS3);
crb_addr_transform(SQS2);
crb_addr_transform(SQS1);
crb_addr_transform(SQS0);
crb_addr_transform(RPMX7);
crb_addr_transform(RPMX6);
crb_addr_transform(RPMX5);
crb_addr_transform(RPMX4);
crb_addr_transform(RPMX3);
crb_addr_transform(RPMX2);
crb_addr_transform(RPMX1);
crb_addr_transform(RPMX0);
crb_addr_transform(ROMUSB);
crb_addr_transform(SN);
crb_addr_transform(QMN);
crb_addr_transform(QMS);
crb_addr_transform(PGNI);
crb_addr_transform(PGND);
crb_addr_transform(PGN3);
crb_addr_transform(PGN2);
crb_addr_transform(PGN1);
crb_addr_transform(PGN0);
crb_addr_transform(PGSI);
crb_addr_transform(PGSD);
crb_addr_transform(PGS3);
crb_addr_transform(PGS2);
crb_addr_transform(PGS1);
crb_addr_transform(PGS0);
crb_addr_transform(PS);
crb_addr_transform(PH);
crb_addr_transform(NIU);
crb_addr_transform(I2Q);
crb_addr_transform(EG);
crb_addr_transform(MN);
crb_addr_transform(MS);
crb_addr_transform(CAS2);
crb_addr_transform(CAS1);
crb_addr_transform(CAS0);
crb_addr_transform(CAM);
crb_addr_transform(C2C1);
crb_addr_transform(C2C0);
crb_addr_transform(SMB);
crb_addr_transform(OCM0);
crb_addr_transform(I2C0);
}
void qlcnic_release_rx_buffers(struct qlcnic_adapter *adapter)
{
struct qlcnic_recv_context *recv_ctx;
struct qlcnic_host_rds_ring *rds_ring;
struct qlcnic_rx_buffer *rx_buf;
int i, ring;
recv_ctx = adapter->recv_ctx;
for (ring = 0; ring < adapter->max_rds_rings; ring++) {
rds_ring = &recv_ctx->rds_rings[ring];
for (i = 0; i < rds_ring->num_desc; ++i) {
rx_buf = &(rds_ring->rx_buf_arr[i]);
if (rx_buf->skb == NULL)
continue;
pci_unmap_single(adapter->pdev,
rx_buf->dma,
rds_ring->dma_size,
PCI_DMA_FROMDEVICE);
dev_kfree_skb_any(rx_buf->skb);
}
}
}
void qlcnic_reset_rx_buffers_list(struct qlcnic_adapter *adapter)
{
struct qlcnic_recv_context *recv_ctx;
struct qlcnic_host_rds_ring *rds_ring;
struct qlcnic_rx_buffer *rx_buf;
int i, ring;
recv_ctx = adapter->recv_ctx;
for (ring = 0; ring < adapter->max_rds_rings; ring++) {
rds_ring = &recv_ctx->rds_rings[ring];
INIT_LIST_HEAD(&rds_ring->free_list);
rx_buf = rds_ring->rx_buf_arr;
for (i = 0; i < rds_ring->num_desc; i++) {
list_add_tail(&rx_buf->list,
&rds_ring->free_list);
rx_buf++;
}
}
}
void qlcnic_release_tx_buffers(struct qlcnic_adapter *adapter)
{
struct qlcnic_cmd_buffer *cmd_buf;
struct qlcnic_skb_frag *buffrag;
int i, j;
struct qlcnic_host_tx_ring *tx_ring = adapter->tx_ring;
cmd_buf = tx_ring->cmd_buf_arr;
for (i = 0; i < tx_ring->num_desc; i++) {
buffrag = cmd_buf->frag_array;
if (buffrag->dma) {
pci_unmap_single(adapter->pdev, buffrag->dma,
buffrag->length, PCI_DMA_TODEVICE);
buffrag->dma = 0ULL;
}
for (j = 0; j < cmd_buf->frag_count; j++) {
buffrag++;
if (buffrag->dma) {
pci_unmap_page(adapter->pdev, buffrag->dma,
buffrag->length,
PCI_DMA_TODEVICE);
buffrag->dma = 0ULL;
}
}
if (cmd_buf->skb) {
dev_kfree_skb_any(cmd_buf->skb);
cmd_buf->skb = NULL;
}
cmd_buf++;
}
}
void qlcnic_free_sw_resources(struct qlcnic_adapter *adapter)
{
struct qlcnic_recv_context *recv_ctx;
struct qlcnic_host_rds_ring *rds_ring;
int ring;
recv_ctx = adapter->recv_ctx;
if (recv_ctx->rds_rings == NULL)
return;
for (ring = 0; ring < adapter->max_rds_rings; ring++) {
rds_ring = &recv_ctx->rds_rings[ring];
vfree(rds_ring->rx_buf_arr);
rds_ring->rx_buf_arr = NULL;
}
kfree(recv_ctx->rds_rings);
}
int qlcnic_alloc_sw_resources(struct qlcnic_adapter *adapter)
{
struct qlcnic_recv_context *recv_ctx;
struct qlcnic_host_rds_ring *rds_ring;
struct qlcnic_host_sds_ring *sds_ring;
struct qlcnic_rx_buffer *rx_buf;
int ring, i;
recv_ctx = adapter->recv_ctx;
rds_ring = kcalloc(adapter->max_rds_rings,
sizeof(struct qlcnic_host_rds_ring), GFP_KERNEL);
if (rds_ring == NULL)
goto err_out;
recv_ctx->rds_rings = rds_ring;
for (ring = 0; ring < adapter->max_rds_rings; ring++) {
rds_ring = &recv_ctx->rds_rings[ring];
switch (ring) {
case RCV_RING_NORMAL:
rds_ring->num_desc = adapter->num_rxd;
rds_ring->dma_size = QLCNIC_P3P_RX_BUF_MAX_LEN;
rds_ring->skb_size = rds_ring->dma_size + NET_IP_ALIGN;
break;
case RCV_RING_JUMBO:
rds_ring->num_desc = adapter->num_jumbo_rxd;
rds_ring->dma_size =
QLCNIC_P3P_RX_JUMBO_BUF_MAX_LEN;
if (adapter->ahw->capabilities &
QLCNIC_FW_CAPABILITY_HW_LRO)
rds_ring->dma_size += QLCNIC_LRO_BUFFER_EXTRA;
rds_ring->skb_size =
rds_ring->dma_size + NET_IP_ALIGN;
break;
}
rds_ring->rx_buf_arr = vzalloc(RCV_BUFF_RINGSIZE(rds_ring));
if (rds_ring->rx_buf_arr == NULL)
goto err_out;
INIT_LIST_HEAD(&rds_ring->free_list);
/*
* Now go through all of them, set reference handles
* and put them in the queues.
*/
rx_buf = rds_ring->rx_buf_arr;
for (i = 0; i < rds_ring->num_desc; i++) {
list_add_tail(&rx_buf->list,
&rds_ring->free_list);
rx_buf->ref_handle = i;
rx_buf++;
}
spin_lock_init(&rds_ring->lock);
}
for (ring = 0; ring < adapter->max_sds_rings; ring++) {
sds_ring = &recv_ctx->sds_rings[ring];
sds_ring->irq = adapter->msix_entries[ring].vector;
sds_ring->adapter = adapter;
sds_ring->num_desc = adapter->num_rxd;
for (i = 0; i < NUM_RCV_DESC_RINGS; i++)
INIT_LIST_HEAD(&sds_ring->free_list[i]);
}
return 0;
err_out:
qlcnic_free_sw_resources(adapter);
return -ENOMEM;
}
/*
* Utility to translate from internal Phantom CRB address
* to external PCI CRB address.
*/
static u32 qlcnic_decode_crb_addr(u32 addr)
{
int i;
u32 base_addr, offset, pci_base;
crb_addr_transform_setup();
pci_base = QLCNIC_ADDR_ERROR;
base_addr = addr & 0xfff00000;
offset = addr & 0x000fffff;
for (i = 0; i < QLCNIC_MAX_CRB_XFORM; i++) {
if (crb_addr_xform[i] == base_addr) {
pci_base = i << 20;
break;
}
}
if (pci_base == QLCNIC_ADDR_ERROR)
return pci_base;
else
return pci_base + offset;
}
#define QLCNIC_MAX_ROM_WAIT_USEC 100
static int qlcnic_wait_rom_done(struct qlcnic_adapter *adapter)
{
long timeout = 0;
long done = 0;
cond_resched();
while (done == 0) {
done = QLCRD32(adapter, QLCNIC_ROMUSB_GLB_STATUS);
done &= 2;
if (++timeout >= QLCNIC_MAX_ROM_WAIT_USEC) {
dev_err(&adapter->pdev->dev,
"Timeout reached waiting for rom done");
return -EIO;
}
udelay(1);
}
return 0;
}
static int do_rom_fast_read(struct qlcnic_adapter *adapter,
u32 addr, u32 *valp)
{
QLCWR32(adapter, QLCNIC_ROMUSB_ROM_ADDRESS, addr);
QLCWR32(adapter, QLCNIC_ROMUSB_ROM_DUMMY_BYTE_CNT, 0);
QLCWR32(adapter, QLCNIC_ROMUSB_ROM_ABYTE_CNT, 3);
QLCWR32(adapter, QLCNIC_ROMUSB_ROM_INSTR_OPCODE, 0xb);
if (qlcnic_wait_rom_done(adapter)) {
dev_err(&adapter->pdev->dev, "Error waiting for rom done\n");
return -EIO;
}
/* reset abyte_cnt and dummy_byte_cnt */
QLCWR32(adapter, QLCNIC_ROMUSB_ROM_ABYTE_CNT, 0);
udelay(10);
QLCWR32(adapter, QLCNIC_ROMUSB_ROM_DUMMY_BYTE_CNT, 0);
*valp = QLCRD32(adapter, QLCNIC_ROMUSB_ROM_RDATA);
return 0;
}
static int do_rom_fast_read_words(struct qlcnic_adapter *adapter, int addr,
u8 *bytes, size_t size)
{
int addridx;
int ret = 0;
for (addridx = addr; addridx < (addr + size); addridx += 4) {
int v;
ret = do_rom_fast_read(adapter, addridx, &v);
if (ret != 0)
break;
*(__le32 *)bytes = cpu_to_le32(v);
bytes += 4;
}
return ret;
}
int
qlcnic_rom_fast_read_words(struct qlcnic_adapter *adapter, int addr,
u8 *bytes, size_t size)
{
int ret;
ret = qlcnic_rom_lock(adapter);
if (ret < 0)
return ret;
ret = do_rom_fast_read_words(adapter, addr, bytes, size);
qlcnic_rom_unlock(adapter);
return ret;
}
int qlcnic_rom_fast_read(struct qlcnic_adapter *adapter, u32 addr, u32 *valp)
{
int ret;
if (qlcnic_rom_lock(adapter) != 0)
return -EIO;
ret = do_rom_fast_read(adapter, addr, valp);
qlcnic_rom_unlock(adapter);
return ret;
}
int qlcnic_pinit_from_rom(struct qlcnic_adapter *adapter)
{
int addr, val;
int i, n, init_delay;
struct crb_addr_pair *buf;
unsigned offset;
u32 off;
struct pci_dev *pdev = adapter->pdev;
QLC_SHARED_REG_WR32(adapter, QLCNIC_CMDPEG_STATE, 0);
QLC_SHARED_REG_WR32(adapter, QLCNIC_RCVPEG_STATE, 0);
/* Halt all the indiviual PEGs and other blocks */
/* disable all I2Q */
QLCWR32(adapter, QLCNIC_CRB_I2Q + 0x10, 0x0);
QLCWR32(adapter, QLCNIC_CRB_I2Q + 0x14, 0x0);
QLCWR32(adapter, QLCNIC_CRB_I2Q + 0x18, 0x0);
QLCWR32(adapter, QLCNIC_CRB_I2Q + 0x1c, 0x0);
QLCWR32(adapter, QLCNIC_CRB_I2Q + 0x20, 0x0);
QLCWR32(adapter, QLCNIC_CRB_I2Q + 0x24, 0x0);
/* disable all niu interrupts */
QLCWR32(adapter, QLCNIC_CRB_NIU + 0x40, 0xff);
/* disable xge rx/tx */
QLCWR32(adapter, QLCNIC_CRB_NIU + 0x70000, 0x00);
/* disable xg1 rx/tx */
QLCWR32(adapter, QLCNIC_CRB_NIU + 0x80000, 0x00);
/* disable sideband mac */
QLCWR32(adapter, QLCNIC_CRB_NIU + 0x90000, 0x00);
/* disable ap0 mac */
QLCWR32(adapter, QLCNIC_CRB_NIU + 0xa0000, 0x00);
/* disable ap1 mac */
QLCWR32(adapter, QLCNIC_CRB_NIU + 0xb0000, 0x00);
/* halt sre */
val = QLCRD32(adapter, QLCNIC_CRB_SRE + 0x1000);
QLCWR32(adapter, QLCNIC_CRB_SRE + 0x1000, val & (~(0x1)));
/* halt epg */
QLCWR32(adapter, QLCNIC_CRB_EPG + 0x1300, 0x1);
/* halt timers */
QLCWR32(adapter, QLCNIC_CRB_TIMER + 0x0, 0x0);
QLCWR32(adapter, QLCNIC_CRB_TIMER + 0x8, 0x0);
QLCWR32(adapter, QLCNIC_CRB_TIMER + 0x10, 0x0);
QLCWR32(adapter, QLCNIC_CRB_TIMER + 0x18, 0x0);
QLCWR32(adapter, QLCNIC_CRB_TIMER + 0x100, 0x0);
QLCWR32(adapter, QLCNIC_CRB_TIMER + 0x200, 0x0);
/* halt pegs */
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_0 + 0x3c, 1);
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_1 + 0x3c, 1);
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_2 + 0x3c, 1);
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_3 + 0x3c, 1);
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_4 + 0x3c, 1);
msleep(20);
qlcnic_rom_unlock(adapter);
/* big hammer don't reset CAM block on reset */
QLCWR32(adapter, QLCNIC_ROMUSB_GLB_SW_RESET, 0xfeffffff);
/* Init HW CRB block */
if (qlcnic_rom_fast_read(adapter, 0, &n) != 0 || (n != 0xcafecafe) ||
qlcnic_rom_fast_read(adapter, 4, &n) != 0) {
dev_err(&pdev->dev, "ERROR Reading crb_init area: val:%x\n", n);
return -EIO;
}
offset = n & 0xffffU;
n = (n >> 16) & 0xffffU;
if (n >= 1024) {
dev_err(&pdev->dev, "QLOGIC card flash not initialized.\n");
return -EIO;
}
buf = kcalloc(n, sizeof(struct crb_addr_pair), GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
for (i = 0; i < n; i++) {
if (qlcnic_rom_fast_read(adapter, 8*i + 4*offset, &val) != 0 ||
qlcnic_rom_fast_read(adapter, 8*i + 4*offset + 4, &addr) != 0) {
kfree(buf);
return -EIO;
}
buf[i].addr = addr;
buf[i].data = val;
}
for (i = 0; i < n; i++) {
off = qlcnic_decode_crb_addr(buf[i].addr);
if (off == QLCNIC_ADDR_ERROR) {
dev_err(&pdev->dev, "CRB init value out of range %x\n",
buf[i].addr);
continue;
}
off += QLCNIC_PCI_CRBSPACE;
if (off & 1)
continue;
/* skipping cold reboot MAGIC */
if (off == QLCNIC_CAM_RAM(0x1fc))
continue;
if (off == (QLCNIC_CRB_I2C0 + 0x1c))
continue;
if (off == (ROMUSB_GLB + 0xbc)) /* do not reset PCI */
continue;
if (off == (ROMUSB_GLB + 0xa8))
continue;
if (off == (ROMUSB_GLB + 0xc8)) /* core clock */
continue;
if (off == (ROMUSB_GLB + 0x24)) /* MN clock */
continue;
if (off == (ROMUSB_GLB + 0x1c)) /* MS clock */
continue;
if ((off & 0x0ff00000) == QLCNIC_CRB_DDR_NET)
continue;
/* skip the function enable register */
if (off == QLCNIC_PCIE_REG(PCIE_SETUP_FUNCTION))
continue;
if (off == QLCNIC_PCIE_REG(PCIE_SETUP_FUNCTION2))
continue;
if ((off & 0x0ff00000) == QLCNIC_CRB_SMB)
continue;
init_delay = 1;
/* After writing this register, HW needs time for CRB */
/* to quiet down (else crb_window returns 0xffffffff) */
if (off == QLCNIC_ROMUSB_GLB_SW_RESET)
init_delay = 1000;
QLCWR32(adapter, off, buf[i].data);
msleep(init_delay);
}
kfree(buf);
/* Initialize protocol process engine */
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_D + 0xec, 0x1e);
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_D + 0x4c, 8);
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_I + 0x4c, 8);
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_0 + 0x8, 0);
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_0 + 0xc, 0);
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_1 + 0x8, 0);
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_1 + 0xc, 0);
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_2 + 0x8, 0);
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_2 + 0xc, 0);
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_3 + 0x8, 0);
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_3 + 0xc, 0);
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_4 + 0x8, 0);
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_4 + 0xc, 0);
msleep(1);
QLC_SHARED_REG_WR32(adapter, QLCNIC_PEG_HALT_STATUS1, 0);
QLC_SHARED_REG_WR32(adapter, QLCNIC_PEG_HALT_STATUS2, 0);
return 0;
}
static int qlcnic_cmd_peg_ready(struct qlcnic_adapter *adapter)
{
u32 val;
int retries = QLCNIC_CMDPEG_CHECK_RETRY_COUNT;
do {
val = QLC_SHARED_REG_RD32(adapter, QLCNIC_CMDPEG_STATE);
switch (val) {
case PHAN_INITIALIZE_COMPLETE:
case PHAN_INITIALIZE_ACK:
return 0;
case PHAN_INITIALIZE_FAILED:
goto out_err;
default:
break;
}
msleep(QLCNIC_CMDPEG_CHECK_DELAY);
} while (--retries);
QLC_SHARED_REG_WR32(adapter, QLCNIC_CMDPEG_STATE,
PHAN_INITIALIZE_FAILED);
out_err:
dev_err(&adapter->pdev->dev, "Command Peg initialization not "
"complete, state: 0x%x.\n", val);
return -EIO;
}
static int
qlcnic_receive_peg_ready(struct qlcnic_adapter *adapter)
{
u32 val;
int retries = QLCNIC_RCVPEG_CHECK_RETRY_COUNT;
do {
val = QLC_SHARED_REG_RD32(adapter, QLCNIC_RCVPEG_STATE);
if (val == PHAN_PEG_RCV_INITIALIZED)
return 0;
msleep(QLCNIC_RCVPEG_CHECK_DELAY);
} while (--retries);
if (!retries) {
dev_err(&adapter->pdev->dev, "Receive Peg initialization not "
"complete, state: 0x%x.\n", val);
return -EIO;
}
return 0;
}
int
qlcnic_check_fw_status(struct qlcnic_adapter *adapter)
{
int err;
err = qlcnic_cmd_peg_ready(adapter);
if (err)
return err;
err = qlcnic_receive_peg_ready(adapter);
if (err)
return err;
QLC_SHARED_REG_WR32(adapter, QLCNIC_CMDPEG_STATE, PHAN_INITIALIZE_ACK);
return err;
}
int
qlcnic_setup_idc_param(struct qlcnic_adapter *adapter) {
int timeo;
u32 val;
val = QLC_SHARED_REG_RD32(adapter, QLCNIC_CRB_DEV_PARTITION_INFO);
val = QLC_DEV_GET_DRV(val, adapter->portnum);
if ((val & 0x3) != QLCNIC_TYPE_NIC) {
dev_err(&adapter->pdev->dev,
"Not an Ethernet NIC func=%u\n", val);
return -EIO;
}
adapter->ahw->physical_port = (val >> 2);
if (qlcnic_rom_fast_read(adapter, QLCNIC_ROM_DEV_INIT_TIMEOUT, &timeo))
timeo = QLCNIC_INIT_TIMEOUT_SECS;
adapter->dev_init_timeo = timeo;
if (qlcnic_rom_fast_read(adapter, QLCNIC_ROM_DRV_RESET_TIMEOUT, &timeo))
timeo = QLCNIC_RESET_TIMEOUT_SECS;
adapter->reset_ack_timeo = timeo;
return 0;
}
static int qlcnic_get_flt_entry(struct qlcnic_adapter *adapter, u8 region,
struct qlcnic_flt_entry *region_entry)
{
struct qlcnic_flt_header flt_hdr;
struct qlcnic_flt_entry *flt_entry;
int i = 0, ret;
u32 entry_size;
memset(region_entry, 0, sizeof(struct qlcnic_flt_entry));
ret = qlcnic_rom_fast_read_words(adapter, QLCNIC_FLT_LOCATION,
(u8 *)&flt_hdr,
sizeof(struct qlcnic_flt_header));
if (ret) {
dev_warn(&adapter->pdev->dev,
"error reading flash layout header\n");
return -EIO;
}
entry_size = flt_hdr.len - sizeof(struct qlcnic_flt_header);
flt_entry = vzalloc(entry_size);
if (flt_entry == NULL)
return -EIO;
ret = qlcnic_rom_fast_read_words(adapter, QLCNIC_FLT_LOCATION +
sizeof(struct qlcnic_flt_header),
(u8 *)flt_entry, entry_size);
if (ret) {
dev_warn(&adapter->pdev->dev,
"error reading flash layout entries\n");
goto err_out;
}
while (i < (entry_size/sizeof(struct qlcnic_flt_entry))) {
if (flt_entry[i].region == region)
break;
i++;
}
if (i >= (entry_size/sizeof(struct qlcnic_flt_entry))) {
dev_warn(&adapter->pdev->dev,
"region=%x not found in %d regions\n", region, i);
ret = -EIO;
goto err_out;
}
memcpy(region_entry, &flt_entry[i], sizeof(struct qlcnic_flt_entry));
err_out:
vfree(flt_entry);
return ret;
}
int
qlcnic_check_flash_fw_ver(struct qlcnic_adapter *adapter)
{
struct qlcnic_flt_entry fw_entry;
u32 ver = -1, min_ver;
int ret;
if (adapter->ahw->revision_id == QLCNIC_P3P_C0)
ret = qlcnic_get_flt_entry(adapter, QLCNIC_C0_FW_IMAGE_REGION,
&fw_entry);
else
ret = qlcnic_get_flt_entry(adapter, QLCNIC_B0_FW_IMAGE_REGION,
&fw_entry);
if (!ret)
/* 0-4:-signature, 4-8:-fw version */
qlcnic_rom_fast_read(adapter, fw_entry.start_addr + 4,
(int *)&ver);
else
qlcnic_rom_fast_read(adapter, QLCNIC_FW_VERSION_OFFSET,
(int *)&ver);
ver = QLCNIC_DECODE_VERSION(ver);
min_ver = QLCNIC_MIN_FW_VERSION;
if (ver < min_ver) {
dev_err(&adapter->pdev->dev,
"firmware version %d.%d.%d unsupported."
"Min supported version %d.%d.%d\n",
_major(ver), _minor(ver), _build(ver),
_major(min_ver), _minor(min_ver), _build(min_ver));
return -EINVAL;
}
return 0;
}
static int
qlcnic_has_mn(struct qlcnic_adapter *adapter)
{
u32 capability;
capability = 0;
capability = QLCRD32(adapter, QLCNIC_PEG_TUNE_CAPABILITY);
if (capability & QLCNIC_PEG_TUNE_MN_PRESENT)
return 1;
return 0;
}
static
struct uni_table_desc *qlcnic_get_table_desc(const u8 *unirom, int section)
{
u32 i, entries;
struct uni_table_desc *directory = (struct uni_table_desc *) &unirom[0];
entries = le32_to_cpu(directory->num_entries);
for (i = 0; i < entries; i++) {
u32 offs = le32_to_cpu(directory->findex) +
i * le32_to_cpu(directory->entry_size);
u32 tab_type = le32_to_cpu(*((__le32 *)&unirom[offs] + 8));
if (tab_type == section)
return (struct uni_table_desc *) &unirom[offs];
}
return NULL;
}
#define FILEHEADER_SIZE (14 * 4)
static int
qlcnic_validate_header(struct qlcnic_adapter *adapter)
{
const u8 *unirom = adapter->fw->data;
struct uni_table_desc *directory = (struct uni_table_desc *) &unirom[0];
u32 entries, entry_size, tab_size, fw_file_size;
fw_file_size = adapter->fw->size;
if (fw_file_size < FILEHEADER_SIZE)
return -EINVAL;
entries = le32_to_cpu(directory->num_entries);
entry_size = le32_to_cpu(directory->entry_size);
tab_size = le32_to_cpu(directory->findex) + (entries * entry_size);
if (fw_file_size < tab_size)
return -EINVAL;
return 0;
}
static int
qlcnic_validate_bootld(struct qlcnic_adapter *adapter)
{
struct uni_table_desc *tab_desc;
struct uni_data_desc *descr;
u32 offs, tab_size, data_size, idx;
const u8 *unirom = adapter->fw->data;
__le32 temp;
temp = *((__le32 *)&unirom[adapter->file_prd_off] +
QLCNIC_UNI_BOOTLD_IDX_OFF);
idx = le32_to_cpu(temp);
tab_desc = qlcnic_get_table_desc(unirom, QLCNIC_UNI_DIR_SECT_BOOTLD);
if (!tab_desc)
return -EINVAL;
tab_size = le32_to_cpu(tab_desc->findex) +
le32_to_cpu(tab_desc->entry_size) * (idx + 1);
if (adapter->fw->size < tab_size)
return -EINVAL;
offs = le32_to_cpu(tab_desc->findex) +
le32_to_cpu(tab_desc->entry_size) * idx;
descr = (struct uni_data_desc *)&unirom[offs];
data_size = le32_to_cpu(descr->findex) + le32_to_cpu(descr->size);
if (adapter->fw->size < data_size)
return -EINVAL;
return 0;
}
static int
qlcnic_validate_fw(struct qlcnic_adapter *adapter)
{
struct uni_table_desc *tab_desc;
struct uni_data_desc *descr;
const u8 *unirom = adapter->fw->data;
u32 offs, tab_size, data_size, idx;
__le32 temp;
temp = *((__le32 *)&unirom[adapter->file_prd_off] +
QLCNIC_UNI_FIRMWARE_IDX_OFF);
idx = le32_to_cpu(temp);
tab_desc = qlcnic_get_table_desc(unirom, QLCNIC_UNI_DIR_SECT_FW);
if (!tab_desc)
return -EINVAL;
tab_size = le32_to_cpu(tab_desc->findex) +
le32_to_cpu(tab_desc->entry_size) * (idx + 1);
if (adapter->fw->size < tab_size)
return -EINVAL;
offs = le32_to_cpu(tab_desc->findex) +
le32_to_cpu(tab_desc->entry_size) * idx;
descr = (struct uni_data_desc *)&unirom[offs];
data_size = le32_to_cpu(descr->findex) + le32_to_cpu(descr->size);
if (adapter->fw->size < data_size)
return -EINVAL;
return 0;
}
static int
qlcnic_validate_product_offs(struct qlcnic_adapter *adapter)
{
struct uni_table_desc *ptab_descr;
const u8 *unirom = adapter->fw->data;
int mn_present = qlcnic_has_mn(adapter);
u32 entries, entry_size, tab_size, i;
__le32 temp;
ptab_descr = qlcnic_get_table_desc(unirom,
QLCNIC_UNI_DIR_SECT_PRODUCT_TBL);
if (!ptab_descr)
return -EINVAL;
entries = le32_to_cpu(ptab_descr->num_entries);
entry_size = le32_to_cpu(ptab_descr->entry_size);
tab_size = le32_to_cpu(ptab_descr->findex) + (entries * entry_size);
if (adapter->fw->size < tab_size)
return -EINVAL;
nomn:
for (i = 0; i < entries; i++) {
u32 flags, file_chiprev, offs;
u8 chiprev = adapter->ahw->revision_id;
u32 flagbit;
offs = le32_to_cpu(ptab_descr->findex) +
i * le32_to_cpu(ptab_descr->entry_size);
temp = *((__le32 *)&unirom[offs] + QLCNIC_UNI_FLAGS_OFF);
flags = le32_to_cpu(temp);
temp = *((__le32 *)&unirom[offs] + QLCNIC_UNI_CHIP_REV_OFF);
file_chiprev = le32_to_cpu(temp);
flagbit = mn_present ? 1 : 2;
if ((chiprev == file_chiprev) &&
((1ULL << flagbit) & flags)) {
adapter->file_prd_off = offs;
return 0;
}
}
if (mn_present) {
mn_present = 0;
goto nomn;
}
return -EINVAL;
}
static int
qlcnic_validate_unified_romimage(struct qlcnic_adapter *adapter)
{
if (qlcnic_validate_header(adapter)) {
dev_err(&adapter->pdev->dev,
"unified image: header validation failed\n");
return -EINVAL;
}
if (qlcnic_validate_product_offs(adapter)) {
dev_err(&adapter->pdev->dev,
"unified image: product validation failed\n");
return -EINVAL;
}
if (qlcnic_validate_bootld(adapter)) {
dev_err(&adapter->pdev->dev,
"unified image: bootld validation failed\n");
return -EINVAL;
}
if (qlcnic_validate_fw(adapter)) {
dev_err(&adapter->pdev->dev,
"unified image: firmware validation failed\n");
return -EINVAL;
}
return 0;
}
static
struct uni_data_desc *qlcnic_get_data_desc(struct qlcnic_adapter *adapter,
u32 section, u32 idx_offset)
{
const u8 *unirom = adapter->fw->data;
struct uni_table_desc *tab_desc;
u32 offs, idx;
__le32 temp;
temp = *((__le32 *)&unirom[adapter->file_prd_off] + idx_offset);
idx = le32_to_cpu(temp);
tab_desc = qlcnic_get_table_desc(unirom, section);
if (tab_desc == NULL)
return NULL;
offs = le32_to_cpu(tab_desc->findex) +
le32_to_cpu(tab_desc->entry_size) * idx;
return (struct uni_data_desc *)&unirom[offs];
}
static u8 *
qlcnic_get_bootld_offs(struct qlcnic_adapter *adapter)
{
u32 offs = QLCNIC_BOOTLD_START;
struct uni_data_desc *data_desc;
data_desc = qlcnic_get_data_desc(adapter, QLCNIC_UNI_DIR_SECT_BOOTLD,
QLCNIC_UNI_BOOTLD_IDX_OFF);
if (adapter->ahw->fw_type == QLCNIC_UNIFIED_ROMIMAGE)
offs = le32_to_cpu(data_desc->findex);
return (u8 *)&adapter->fw->data[offs];
}
static u8 *
qlcnic_get_fw_offs(struct qlcnic_adapter *adapter)
{
u32 offs = QLCNIC_IMAGE_START;
struct uni_data_desc *data_desc;
data_desc = qlcnic_get_data_desc(adapter, QLCNIC_UNI_DIR_SECT_FW,
QLCNIC_UNI_FIRMWARE_IDX_OFF);
if (adapter->ahw->fw_type == QLCNIC_UNIFIED_ROMIMAGE)
offs = le32_to_cpu(data_desc->findex);
return (u8 *)&adapter->fw->data[offs];
}
static u32 qlcnic_get_fw_size(struct qlcnic_adapter *adapter)
{
struct uni_data_desc *data_desc;
const u8 *unirom = adapter->fw->data;
data_desc = qlcnic_get_data_desc(adapter, QLCNIC_UNI_DIR_SECT_FW,
QLCNIC_UNI_FIRMWARE_IDX_OFF);
if (adapter->ahw->fw_type == QLCNIC_UNIFIED_ROMIMAGE)
return le32_to_cpu(data_desc->size);
else
return le32_to_cpu(*(__le32 *)&unirom[QLCNIC_FW_SIZE_OFFSET]);
}
static u32 qlcnic_get_fw_version(struct qlcnic_adapter *adapter)
{
struct uni_data_desc *fw_data_desc;
const struct firmware *fw = adapter->fw;
u32 major, minor, sub;
__le32 version_offset;
const u8 *ver_str;
int i, ret;
if (adapter->ahw->fw_type != QLCNIC_UNIFIED_ROMIMAGE) {
version_offset = *(__le32 *)&fw->data[QLCNIC_FW_VERSION_OFFSET];
return le32_to_cpu(version_offset);
}
fw_data_desc = qlcnic_get_data_desc(adapter, QLCNIC_UNI_DIR_SECT_FW,
QLCNIC_UNI_FIRMWARE_IDX_OFF);
ver_str = fw->data + le32_to_cpu(fw_data_desc->findex) +
le32_to_cpu(fw_data_desc->size) - 17;
for (i = 0; i < 12; i++) {
if (!strncmp(&ver_str[i], "REV=", 4)) {
ret = sscanf(&ver_str[i+4], "%u.%u.%u ",
&major, &minor, &sub);
if (ret != 3)
return 0;
else
return major + (minor << 8) + (sub << 16);
}
}
return 0;
}
static u32 qlcnic_get_bios_version(struct qlcnic_adapter *adapter)
{
const struct firmware *fw = adapter->fw;
u32 bios_ver, prd_off = adapter->file_prd_off;
u8 *version_offset;
__le32 temp;
if (adapter->ahw->fw_type != QLCNIC_UNIFIED_ROMIMAGE) {
version_offset = (u8 *)&fw->data[QLCNIC_BIOS_VERSION_OFFSET];
return le32_to_cpu(*(__le32 *)version_offset);
}
temp = *((__le32 *)(&fw->data[prd_off]) + QLCNIC_UNI_BIOS_VERSION_OFF);
bios_ver = le32_to_cpu(temp);
return (bios_ver << 16) + ((bios_ver >> 8) & 0xff00) + (bios_ver >> 24);
}
static void qlcnic_rom_lock_recovery(struct qlcnic_adapter *adapter)
{
if (qlcnic_pcie_sem_lock(adapter, 2, QLCNIC_ROM_LOCK_ID))
dev_info(&adapter->pdev->dev, "Resetting rom_lock\n");
qlcnic_pcie_sem_unlock(adapter, 2);
}
static int
qlcnic_check_fw_hearbeat(struct qlcnic_adapter *adapter)
{
u32 heartbeat, ret = -EIO;
int retries = QLCNIC_HEARTBEAT_CHECK_RETRY_COUNT;
adapter->heartbeat = QLC_SHARED_REG_RD32(adapter,
QLCNIC_PEG_ALIVE_COUNTER);
do {
msleep(QLCNIC_HEARTBEAT_PERIOD_MSECS);
heartbeat = QLC_SHARED_REG_RD32(adapter,
QLCNIC_PEG_ALIVE_COUNTER);
if (heartbeat != adapter->heartbeat) {
ret = QLCNIC_RCODE_SUCCESS;
break;
}
} while (--retries);
return ret;
}
int
qlcnic_need_fw_reset(struct qlcnic_adapter *adapter)
{
if ((adapter->flags & QLCNIC_FW_HANG) ||
qlcnic_check_fw_hearbeat(adapter)) {
qlcnic_rom_lock_recovery(adapter);
return 1;
}
if (adapter->need_fw_reset)
return 1;
if (adapter->fw)
return 1;
return 0;
}
static const char *fw_name[] = {
QLCNIC_UNIFIED_ROMIMAGE_NAME,
QLCNIC_FLASH_ROMIMAGE_NAME,
};
int
qlcnic_load_firmware(struct qlcnic_adapter *adapter)
{
__le64 *ptr64;
u32 i, flashaddr, size;
const struct firmware *fw = adapter->fw;
struct pci_dev *pdev = adapter->pdev;
dev_info(&pdev->dev, "loading firmware from %s\n",
fw_name[adapter->ahw->fw_type]);
if (fw) {
u64 data;
size = (QLCNIC_IMAGE_START - QLCNIC_BOOTLD_START) / 8;
ptr64 = (__le64 *)qlcnic_get_bootld_offs(adapter);
flashaddr = QLCNIC_BOOTLD_START;
for (i = 0; i < size; i++) {
data = le64_to_cpu(ptr64[i]);
if (qlcnic_pci_mem_write_2M(adapter, flashaddr, data))
return -EIO;
flashaddr += 8;
}
size = qlcnic_get_fw_size(adapter) / 8;
ptr64 = (__le64 *)qlcnic_get_fw_offs(adapter);
flashaddr = QLCNIC_IMAGE_START;
for (i = 0; i < size; i++) {
data = le64_to_cpu(ptr64[i]);
if (qlcnic_pci_mem_write_2M(adapter,
flashaddr, data))
return -EIO;
flashaddr += 8;
}
size = qlcnic_get_fw_size(adapter) % 8;
if (size) {
data = le64_to_cpu(ptr64[i]);
if (qlcnic_pci_mem_write_2M(adapter,
flashaddr, data))
return -EIO;
}
} else {
u64 data;
u32 hi, lo;
int ret;
struct qlcnic_flt_entry bootld_entry;
ret = qlcnic_get_flt_entry(adapter, QLCNIC_BOOTLD_REGION,
&bootld_entry);
if (!ret) {
size = bootld_entry.size / 8;
flashaddr = bootld_entry.start_addr;
} else {
size = (QLCNIC_IMAGE_START - QLCNIC_BOOTLD_START) / 8;
flashaddr = QLCNIC_BOOTLD_START;
dev_info(&pdev->dev,
"using legacy method to get flash fw region");
}
for (i = 0; i < size; i++) {
if (qlcnic_rom_fast_read(adapter,
flashaddr, (int *)&lo) != 0)
return -EIO;
if (qlcnic_rom_fast_read(adapter,
flashaddr + 4, (int *)&hi) != 0)
return -EIO;
data = (((u64)hi << 32) | lo);
if (qlcnic_pci_mem_write_2M(adapter,
flashaddr, data))
return -EIO;
flashaddr += 8;
}
}
msleep(1);
QLCWR32(adapter, QLCNIC_CRB_PEG_NET_0 + 0x18, 0x1020);
QLCWR32(adapter, QLCNIC_ROMUSB_GLB_SW_RESET, 0x80001e);
return 0;
}
static int
qlcnic_validate_firmware(struct qlcnic_adapter *adapter)
{
u32 val;
u32 ver, bios, min_size;
struct pci_dev *pdev = adapter->pdev;
const struct firmware *fw = adapter->fw;
u8 fw_type = adapter->ahw->fw_type;
if (fw_type == QLCNIC_UNIFIED_ROMIMAGE) {
if (qlcnic_validate_unified_romimage(adapter))
return -EINVAL;
min_size = QLCNIC_UNI_FW_MIN_SIZE;
} else {
val = le32_to_cpu(*(__le32 *)&fw->data[QLCNIC_FW_MAGIC_OFFSET]);
if (val != QLCNIC_BDINFO_MAGIC)
return -EINVAL;
min_size = QLCNIC_FW_MIN_SIZE;
}
if (fw->size < min_size)
return -EINVAL;
val = qlcnic_get_fw_version(adapter);
ver = QLCNIC_DECODE_VERSION(val);
if (ver < QLCNIC_MIN_FW_VERSION) {
dev_err(&pdev->dev,
"%s: firmware version %d.%d.%d unsupported\n",
fw_name[fw_type], _major(ver), _minor(ver), _build(ver));
return -EINVAL;
}
val = qlcnic_get_bios_version(adapter);
qlcnic_rom_fast_read(adapter, QLCNIC_BIOS_VERSION_OFFSET, (int *)&bios);
if (val != bios) {
dev_err(&pdev->dev, "%s: firmware bios is incompatible\n",
fw_name[fw_type]);
return -EINVAL;
}
QLC_SHARED_REG_WR32(adapter, QLCNIC_FW_IMG_VALID, QLCNIC_BDINFO_MAGIC);
return 0;
}
static void
qlcnic_get_next_fwtype(struct qlcnic_adapter *adapter)
{
u8 fw_type;
switch (adapter->ahw->fw_type) {
case QLCNIC_UNKNOWN_ROMIMAGE:
fw_type = QLCNIC_UNIFIED_ROMIMAGE;
break;
case QLCNIC_UNIFIED_ROMIMAGE:
default:
fw_type = QLCNIC_FLASH_ROMIMAGE;
break;
}
adapter->ahw->fw_type = fw_type;
}
void qlcnic_request_firmware(struct qlcnic_adapter *adapter)
{
struct pci_dev *pdev = adapter->pdev;
int rc;
adapter->ahw->fw_type = QLCNIC_UNKNOWN_ROMIMAGE;
next:
qlcnic_get_next_fwtype(adapter);
if (adapter->ahw->fw_type == QLCNIC_FLASH_ROMIMAGE) {
adapter->fw = NULL;
} else {
rc = request_firmware(&adapter->fw,
fw_name[adapter->ahw->fw_type],
&pdev->dev);
if (rc != 0)
goto next;
rc = qlcnic_validate_firmware(adapter);
if (rc != 0) {
release_firmware(adapter->fw);
msleep(1);
goto next;
}
}
}
void
qlcnic_release_firmware(struct qlcnic_adapter *adapter)
{
release_firmware(adapter->fw);
adapter->fw = NULL;
}
| gpl-2.0 |
xenord/TrebonKernel-3.0.101 | drivers/staging/rts_pstor/rtsx_scsi.c | 2920 | 77385 | /* 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/vmalloc.h>
#include "rtsx.h"
#include "rtsx_transport.h"
#include "rtsx_sys.h"
#include "rtsx_card.h"
#include "rtsx_chip.h"
#include "rtsx_scsi.h"
#include "sd.h"
#include "ms.h"
#include "spi.h"
void scsi_show_command(struct scsi_cmnd *srb)
{
char *what = NULL;
int i, unknown_cmd = 0;
switch (srb->cmnd[0]) {
case TEST_UNIT_READY: what = "TEST_UNIT_READY"; break;
case REZERO_UNIT: what = "REZERO_UNIT"; break;
case REQUEST_SENSE: what = "REQUEST_SENSE"; break;
case FORMAT_UNIT: what = "FORMAT_UNIT"; break;
case READ_BLOCK_LIMITS: what = "READ_BLOCK_LIMITS"; break;
case REASSIGN_BLOCKS: what = "REASSIGN_BLOCKS"; break;
case READ_6: what = "READ_6"; break;
case WRITE_6: what = "WRITE_6"; break;
case SEEK_6: what = "SEEK_6"; break;
case READ_REVERSE: what = "READ_REVERSE"; break;
case WRITE_FILEMARKS: what = "WRITE_FILEMARKS"; break;
case SPACE: what = "SPACE"; break;
case INQUIRY: what = "INQUIRY"; break;
case RECOVER_BUFFERED_DATA: what = "RECOVER_BUFFERED_DATA"; break;
case MODE_SELECT: what = "MODE_SELECT"; break;
case RESERVE: what = "RESERVE"; break;
case RELEASE: what = "RELEASE"; break;
case COPY: what = "COPY"; break;
case ERASE: what = "ERASE"; break;
case MODE_SENSE: what = "MODE_SENSE"; break;
case START_STOP: what = "START_STOP"; break;
case RECEIVE_DIAGNOSTIC: what = "RECEIVE_DIAGNOSTIC"; break;
case SEND_DIAGNOSTIC: what = "SEND_DIAGNOSTIC"; break;
case ALLOW_MEDIUM_REMOVAL: what = "ALLOW_MEDIUM_REMOVAL"; break;
case SET_WINDOW: what = "SET_WINDOW"; break;
case READ_CAPACITY: what = "READ_CAPACITY"; break;
case READ_10: what = "READ_10"; break;
case WRITE_10: what = "WRITE_10"; break;
case SEEK_10: what = "SEEK_10"; break;
case WRITE_VERIFY: what = "WRITE_VERIFY"; break;
case VERIFY: what = "VERIFY"; break;
case SEARCH_HIGH: what = "SEARCH_HIGH"; break;
case SEARCH_EQUAL: what = "SEARCH_EQUAL"; break;
case SEARCH_LOW: what = "SEARCH_LOW"; break;
case SET_LIMITS: what = "SET_LIMITS"; break;
case READ_POSITION: what = "READ_POSITION"; break;
case SYNCHRONIZE_CACHE: what = "SYNCHRONIZE_CACHE"; break;
case LOCK_UNLOCK_CACHE: what = "LOCK_UNLOCK_CACHE"; break;
case READ_DEFECT_DATA: what = "READ_DEFECT_DATA"; break;
case MEDIUM_SCAN: what = "MEDIUM_SCAN"; break;
case COMPARE: what = "COMPARE"; break;
case COPY_VERIFY: what = "COPY_VERIFY"; break;
case WRITE_BUFFER: what = "WRITE_BUFFER"; break;
case READ_BUFFER: what = "READ_BUFFER"; break;
case UPDATE_BLOCK: what = "UPDATE_BLOCK"; break;
case READ_LONG: what = "READ_LONG"; break;
case WRITE_LONG: what = "WRITE_LONG"; break;
case CHANGE_DEFINITION: what = "CHANGE_DEFINITION"; break;
case WRITE_SAME: what = "WRITE_SAME"; break;
case GPCMD_READ_SUBCHANNEL: what = "READ SUBCHANNEL"; break;
case READ_TOC: what = "READ_TOC"; break;
case GPCMD_READ_HEADER: what = "READ HEADER"; break;
case GPCMD_PLAY_AUDIO_10: what = "PLAY AUDIO (10)"; break;
case GPCMD_PLAY_AUDIO_MSF: what = "PLAY AUDIO MSF"; break;
case GPCMD_GET_EVENT_STATUS_NOTIFICATION:
what = "GET EVENT/STATUS NOTIFICATION"; break;
case GPCMD_PAUSE_RESUME: what = "PAUSE/RESUME"; break;
case LOG_SELECT: what = "LOG_SELECT"; break;
case LOG_SENSE: what = "LOG_SENSE"; break;
case GPCMD_STOP_PLAY_SCAN: what = "STOP PLAY/SCAN"; break;
case GPCMD_READ_DISC_INFO: what = "READ DISC INFORMATION"; break;
case GPCMD_READ_TRACK_RZONE_INFO:
what = "READ TRACK INFORMATION"; break;
case GPCMD_RESERVE_RZONE_TRACK: what = "RESERVE TRACK"; break;
case GPCMD_SEND_OPC: what = "SEND OPC"; break;
case MODE_SELECT_10: what = "MODE_SELECT_10"; break;
case GPCMD_REPAIR_RZONE_TRACK: what = "REPAIR TRACK"; break;
case 0x59: what = "READ MASTER CUE"; break;
case MODE_SENSE_10: what = "MODE_SENSE_10"; break;
case GPCMD_CLOSE_TRACK: what = "CLOSE TRACK/SESSION"; break;
case 0x5C: what = "READ BUFFER CAPACITY"; break;
case 0x5D: what = "SEND CUE SHEET"; break;
case GPCMD_BLANK: what = "BLANK"; break;
case REPORT_LUNS: what = "REPORT LUNS"; break;
case MOVE_MEDIUM: what = "MOVE_MEDIUM or PLAY AUDIO (12)"; break;
case READ_12: what = "READ_12"; break;
case WRITE_12: what = "WRITE_12"; break;
case WRITE_VERIFY_12: what = "WRITE_VERIFY_12"; break;
case SEARCH_HIGH_12: what = "SEARCH_HIGH_12"; break;
case SEARCH_EQUAL_12: what = "SEARCH_EQUAL_12"; break;
case SEARCH_LOW_12: what = "SEARCH_LOW_12"; break;
case SEND_VOLUME_TAG: what = "SEND_VOLUME_TAG"; break;
case READ_ELEMENT_STATUS: what = "READ_ELEMENT_STATUS"; break;
case GPCMD_READ_CD_MSF: what = "READ CD MSF"; break;
case GPCMD_SCAN: what = "SCAN"; break;
case GPCMD_SET_SPEED: what = "SET CD SPEED"; break;
case GPCMD_MECHANISM_STATUS: what = "MECHANISM STATUS"; break;
case GPCMD_READ_CD: what = "READ CD"; break;
case 0xE1: what = "WRITE CONTINUE"; break;
case WRITE_LONG_2: what = "WRITE_LONG_2"; break;
case VENDOR_CMND: what = "Realtek's vendor command"; break;
default: what = "(unknown command)"; unknown_cmd = 1; break;
}
if (srb->cmnd[0] != TEST_UNIT_READY) {
RTSX_DEBUGP("Command %s (%d bytes)\n", what, srb->cmd_len);
}
if (unknown_cmd) {
RTSX_DEBUGP("");
for (i = 0; i < srb->cmd_len && i < 16; i++)
RTSX_DEBUGPN(" %02x", srb->cmnd[i]);
RTSX_DEBUGPN("\n");
}
}
void set_sense_type(struct rtsx_chip *chip, unsigned int lun, int sense_type)
{
switch (sense_type) {
case SENSE_TYPE_MEDIA_CHANGE:
set_sense_data(chip, lun, CUR_ERR, 0x06, 0, 0x28, 0, 0, 0);
break;
case SENSE_TYPE_MEDIA_NOT_PRESENT:
set_sense_data(chip, lun, CUR_ERR, 0x02, 0, 0x3A, 0, 0, 0);
break;
case SENSE_TYPE_MEDIA_LBA_OVER_RANGE:
set_sense_data(chip, lun, CUR_ERR, 0x05, 0, 0x21, 0, 0, 0);
break;
case SENSE_TYPE_MEDIA_LUN_NOT_SUPPORT:
set_sense_data(chip, lun, CUR_ERR, 0x05, 0, 0x25, 0, 0, 0);
break;
case SENSE_TYPE_MEDIA_WRITE_PROTECT:
set_sense_data(chip, lun, CUR_ERR, 0x07, 0, 0x27, 0, 0, 0);
break;
case SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR:
set_sense_data(chip, lun, CUR_ERR, 0x03, 0, 0x11, 0, 0, 0);
break;
case SENSE_TYPE_MEDIA_WRITE_ERR:
set_sense_data(chip, lun, CUR_ERR, 0x03, 0, 0x0C, 0x02, 0, 0);
break;
case SENSE_TYPE_MEDIA_INVALID_CMD_FIELD:
set_sense_data(chip, lun, CUR_ERR, ILGAL_REQ, 0,
ASC_INVLD_CDB, ASCQ_INVLD_CDB, CDB_ILLEGAL, 1);
break;
case SENSE_TYPE_FORMAT_IN_PROGRESS:
set_sense_data(chip, lun, CUR_ERR, 0x02, 0, 0x04, 0x04, 0, 0);
break;
case SENSE_TYPE_FORMAT_CMD_FAILED:
set_sense_data(chip, lun, CUR_ERR, 0x03, 0, 0x31, 0x01, 0, 0);
break;
#ifdef SUPPORT_MAGIC_GATE
case SENSE_TYPE_MG_KEY_FAIL_NOT_ESTAB:
set_sense_data(chip, lun, CUR_ERR, 0x05, 0, 0x6F, 0x02, 0, 0);
break;
case SENSE_TYPE_MG_KEY_FAIL_NOT_AUTHEN:
set_sense_data(chip, lun, CUR_ERR, 0x05, 0, 0x6F, 0x00, 0, 0);
break;
case SENSE_TYPE_MG_INCOMPATIBLE_MEDIUM:
set_sense_data(chip, lun, CUR_ERR, 0x02, 0, 0x30, 0x00, 0, 0);
break;
case SENSE_TYPE_MG_WRITE_ERR:
set_sense_data(chip, lun, CUR_ERR, 0x03, 0, 0x0C, 0x00, 0, 0);
break;
#endif
#ifdef SUPPORT_SD_LOCK
case SENSE_TYPE_MEDIA_READ_FORBIDDEN:
set_sense_data(chip, lun, CUR_ERR, 0x07, 0, 0x11, 0x13, 0, 0);
break;
#endif
case SENSE_TYPE_NO_SENSE:
default:
set_sense_data(chip, lun, CUR_ERR, 0, 0, 0, 0, 0, 0);
break;
}
}
void set_sense_data(struct rtsx_chip *chip, unsigned int lun, u8 err_code, u8 sense_key,
u32 info, u8 asc, u8 ascq, u8 sns_key_info0, u16 sns_key_info1)
{
struct sense_data_t *sense = &(chip->sense_buffer[lun]);
sense->err_code = err_code;
sense->sense_key = sense_key;
sense->info[0] = (u8)(info >> 24);
sense->info[1] = (u8)(info >> 16);
sense->info[2] = (u8)(info >> 8);
sense->info[3] = (u8)info;
sense->ad_sense_len = sizeof(struct sense_data_t) - 8;
sense->asc = asc;
sense->ascq = ascq;
if (sns_key_info0 != 0) {
sense->sns_key_info[0] = SKSV | sns_key_info0;
sense->sns_key_info[1] = (sns_key_info1 & 0xf0) >> 8;
sense->sns_key_info[2] = sns_key_info1 & 0x0f;
}
}
static int test_unit_ready(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned int lun = SCSI_LUN(srb);
if (!check_card_ready(chip, lun)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_NOT_PRESENT);
return TRANSPORT_FAILED;
}
if (!(CHK_BIT(chip->lun_mc, lun))) {
SET_BIT(chip->lun_mc, lun);
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_CHANGE);
return TRANSPORT_FAILED;
}
#ifdef SUPPORT_SD_LOCK
if (get_lun_card(chip, SCSI_LUN(srb)) == SD_CARD) {
struct sd_info *sd_card = &(chip->sd_card);
if (sd_card->sd_lock_notify) {
sd_card->sd_lock_notify = 0;
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_CHANGE);
return TRANSPORT_FAILED;
} else if (sd_card->sd_lock_status & SD_LOCKED) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_READ_FORBIDDEN);
return TRANSPORT_FAILED;
}
}
#endif
return TRANSPORT_GOOD;
}
static unsigned char formatter_inquiry_str[20] = {
'M', 'E', 'M', 'O', 'R', 'Y', 'S', 'T', 'I', 'C', 'K',
#ifdef SUPPORT_MAGIC_GATE
'-', 'M', 'G', /* Byte[47:49] */
#else
0x20, 0x20, 0x20, /* Byte[47:49] */
#endif
#ifdef SUPPORT_MAGIC_GATE
0x0B, /* Byte[50]: MG, MS, MSPro, MSXC */
#else
0x09, /* Byte[50]: MS, MSPro, MSXC */
#endif
0x00, /* Byte[51]: Category Specific Commands */
0x00, /* Byte[52]: Access Control and feature */
0x20, 0x20, 0x20, /* Byte[53:55] */
};
static int inquiry(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned int lun = SCSI_LUN(srb);
char *inquiry_default = (char *)"Generic-xD/SD/M.S. 1.00 ";
char *inquiry_sdms = (char *)"Generic-SD/MemoryStick 1.00 ";
char *inquiry_sd = (char *)"Generic-SD/MMC 1.00 ";
char *inquiry_ms = (char *)"Generic-MemoryStick 1.00 ";
char *inquiry_string;
unsigned char sendbytes;
unsigned char *buf;
u8 card = get_lun_card(chip, lun);
int pro_formatter_flag = 0;
unsigned char inquiry_buf[] = {
QULIFIRE|DRCT_ACCESS_DEV,
RMB_DISC|0x0D,
0x00,
0x01,
0x1f,
0x02,
0,
REL_ADR|WBUS_32|WBUS_16|SYNC|LINKED|CMD_QUE|SFT_RE,
};
if (CHECK_LUN_MODE(chip, SD_MS_2LUN)) {
if (chip->lun2card[lun] == SD_CARD) {
inquiry_string = inquiry_sd;
} else {
inquiry_string = inquiry_ms;
}
} else if (CHECK_LUN_MODE(chip, SD_MS_1LUN)) {
inquiry_string = inquiry_sdms;
} else {
inquiry_string = inquiry_default;
}
buf = vmalloc(scsi_bufflen(srb));
if (buf == NULL) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
#ifdef SUPPORT_MAGIC_GATE
if ((chip->mspro_formatter_enable) &&
(chip->lun2card[lun] & MS_CARD))
#else
if (chip->mspro_formatter_enable)
#endif
{
if (!card || (card == MS_CARD)) {
pro_formatter_flag = 1;
}
}
if (pro_formatter_flag) {
if (scsi_bufflen(srb) < 56) {
sendbytes = (unsigned char)(scsi_bufflen(srb));
} else {
sendbytes = 56;
}
} else {
if (scsi_bufflen(srb) < 36) {
sendbytes = (unsigned char)(scsi_bufflen(srb));
} else {
sendbytes = 36;
}
}
if (sendbytes > 8) {
memcpy(buf, inquiry_buf, 8);
memcpy(buf + 8, inquiry_string, sendbytes - 8);
if (pro_formatter_flag) {
/* Additional Length */
buf[4] = 0x33;
}
} else {
memcpy(buf, inquiry_buf, sendbytes);
}
if (pro_formatter_flag) {
if (sendbytes > 36) {
memcpy(buf + 36, formatter_inquiry_str, sendbytes - 36);
}
}
scsi_set_resid(srb, 0);
rtsx_stor_set_xfer_buf(buf, scsi_bufflen(srb), srb);
vfree(buf);
return TRANSPORT_GOOD;
}
static int start_stop_unit(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned int lun = SCSI_LUN(srb);
scsi_set_resid(srb, scsi_bufflen(srb));
if (srb->cmnd[1] == 1)
return TRANSPORT_GOOD;
switch (srb->cmnd[0x4]) {
case STOP_MEDIUM:
/* Media disabled */
return TRANSPORT_GOOD;
case UNLOAD_MEDIUM:
/* Media shall be unload */
if (check_card_ready(chip, lun))
eject_card(chip, lun);
return TRANSPORT_GOOD;
case MAKE_MEDIUM_READY:
case LOAD_MEDIUM:
if (check_card_ready(chip, lun)) {
return TRANSPORT_GOOD;
} else {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_NOT_PRESENT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
break;
}
TRACE_RET(chip, TRANSPORT_ERROR);
}
static int allow_medium_removal(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
int prevent;
prevent = srb->cmnd[4] & 0x1;
scsi_set_resid(srb, 0);
if (prevent) {
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
return TRANSPORT_GOOD;
}
static int request_sense(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
struct sense_data_t *sense;
unsigned int lun = SCSI_LUN(srb);
struct ms_info *ms_card = &(chip->ms_card);
unsigned char *tmp, *buf;
sense = &(chip->sense_buffer[lun]);
if ((get_lun_card(chip, lun) == MS_CARD) && ms_card->pro_under_formatting) {
if (ms_card->format_status == FORMAT_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_NO_SENSE);
ms_card->pro_under_formatting = 0;
ms_card->progress = 0;
} else if (ms_card->format_status == FORMAT_IN_PROGRESS) {
/* Logical Unit Not Ready Format in Progress */
set_sense_data(chip, lun, CUR_ERR, 0x02, 0, 0x04, 0x04,
0, (u16)(ms_card->progress));
} else {
/* Format Command Failed */
set_sense_type(chip, lun, SENSE_TYPE_FORMAT_CMD_FAILED);
ms_card->pro_under_formatting = 0;
ms_card->progress = 0;
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
}
buf = vmalloc(scsi_bufflen(srb));
if (buf == NULL) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
tmp = (unsigned char *)sense;
memcpy(buf, tmp, scsi_bufflen(srb));
rtsx_stor_set_xfer_buf(buf, scsi_bufflen(srb), srb);
vfree(buf);
scsi_set_resid(srb, 0);
/* Reset Sense Data */
set_sense_type(chip, lun, SENSE_TYPE_NO_SENSE);
return TRANSPORT_GOOD;
}
static void ms_mode_sense(struct rtsx_chip *chip, u8 cmd,
int lun, u8 *buf, int buf_len)
{
struct ms_info *ms_card = &(chip->ms_card);
int sys_info_offset;
int data_size = buf_len;
int support_format = 0;
int i = 0;
if (cmd == MODE_SENSE) {
sys_info_offset = 8;
if (data_size > 0x68) {
data_size = 0x68;
}
buf[i++] = 0x67; /* Mode Data Length */
} else {
sys_info_offset = 12;
if (data_size > 0x6C) {
data_size = 0x6C;
}
buf[i++] = 0x00; /* Mode Data Length (MSB) */
buf[i++] = 0x6A; /* Mode Data Length (LSB) */
}
/* Medium Type Code */
if (check_card_ready(chip, lun)) {
if (CHK_MSXC(ms_card)) {
support_format = 1;
buf[i++] = 0x40;
} else if (CHK_MSPRO(ms_card)) {
support_format = 1;
buf[i++] = 0x20;
} else {
buf[i++] = 0x10;
}
/* WP */
if (check_card_wp(chip, lun)) {
buf[i++] = 0x80;
} else {
buf[i++] = 0x00;
}
} else {
buf[i++] = 0x00; /* MediaType */
buf[i++] = 0x00; /* WP */
}
buf[i++] = 0x00; /* Reserved */
if (cmd == MODE_SENSE_10) {
buf[i++] = 0x00; /* Reserved */
buf[i++] = 0x00; /* Block descriptor length(MSB) */
buf[i++] = 0x00; /* Block descriptor length(LSB) */
/* The Following Data is the content of "Page 0x20" */
if (data_size >= 9)
buf[i++] = 0x20; /* Page Code */
if (data_size >= 10)
buf[i++] = 0x62; /* Page Length */
if (data_size >= 11)
buf[i++] = 0x00; /* No Access Control */
if (data_size >= 12) {
if (support_format) {
buf[i++] = 0xC0; /* SF, SGM */
} else {
buf[i++] = 0x00;
}
}
} else {
/* The Following Data is the content of "Page 0x20" */
if (data_size >= 5)
buf[i++] = 0x20; /* Page Code */
if (data_size >= 6)
buf[i++] = 0x62; /* Page Length */
if (data_size >= 7)
buf[i++] = 0x00; /* No Access Control */
if (data_size >= 8) {
if (support_format) {
buf[i++] = 0xC0; /* SF, SGM */
} else {
buf[i++] = 0x00;
}
}
}
if (data_size > sys_info_offset) {
/* 96 Bytes Attribute Data */
int len = data_size - sys_info_offset;
len = (len < 96) ? len : 96;
memcpy(buf + sys_info_offset, ms_card->raw_sys_info, len);
}
}
static int mode_sense(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned int lun = SCSI_LUN(srb);
unsigned int dataSize;
int status;
int pro_formatter_flag;
unsigned char pageCode, *buf;
u8 card = get_lun_card(chip, lun);
#ifndef SUPPORT_MAGIC_GATE
if (!check_card_ready(chip, lun)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_NOT_PRESENT);
scsi_set_resid(srb, scsi_bufflen(srb));
TRACE_RET(chip, TRANSPORT_FAILED);
}
#endif
pro_formatter_flag = 0;
dataSize = 8;
#ifdef SUPPORT_MAGIC_GATE
if ((chip->lun2card[lun] & MS_CARD)) {
if (!card || (card == MS_CARD)) {
dataSize = 108;
if (chip->mspro_formatter_enable) {
pro_formatter_flag = 1;
}
}
}
#else
if (card == MS_CARD) {
if (chip->mspro_formatter_enable) {
pro_formatter_flag = 1;
dataSize = 108;
}
}
#endif
buf = kmalloc(dataSize, GFP_KERNEL);
if (buf == NULL) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
pageCode = srb->cmnd[2] & 0x3f;
if ((pageCode == 0x3F) || (pageCode == 0x1C) ||
(pageCode == 0x00) ||
(pro_formatter_flag && (pageCode == 0x20))) {
if (srb->cmnd[0] == MODE_SENSE) {
if ((pageCode == 0x3F) || (pageCode == 0x20)) {
ms_mode_sense(chip, srb->cmnd[0],
lun, buf, dataSize);
} else {
dataSize = 4;
buf[0] = 0x03;
buf[1] = 0x00;
if (check_card_wp(chip, lun)) {
buf[2] = 0x80;
} else {
buf[2] = 0x00;
}
buf[3] = 0x00;
}
} else {
if ((pageCode == 0x3F) || (pageCode == 0x20)) {
ms_mode_sense(chip, srb->cmnd[0],
lun, buf, dataSize);
} else {
dataSize = 8;
buf[0] = 0x00;
buf[1] = 0x06;
buf[2] = 0x00;
if (check_card_wp(chip, lun)) {
buf[3] = 0x80;
} else {
buf[3] = 0x00;
}
buf[4] = 0x00;
buf[5] = 0x00;
buf[6] = 0x00;
buf[7] = 0x00;
}
}
status = TRANSPORT_GOOD;
} else {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
scsi_set_resid(srb, scsi_bufflen(srb));
status = TRANSPORT_FAILED;
}
if (status == TRANSPORT_GOOD) {
unsigned int len = min(scsi_bufflen(srb), dataSize);
rtsx_stor_set_xfer_buf(buf, len, srb);
scsi_set_resid(srb, scsi_bufflen(srb) - len);
}
kfree(buf);
return status;
}
static int read_write(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
#ifdef SUPPORT_SD_LOCK
struct sd_info *sd_card = &(chip->sd_card);
#endif
unsigned int lun = SCSI_LUN(srb);
int retval;
u32 start_sec;
u16 sec_cnt;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
if (!check_card_ready(chip, lun) || (get_card_size(chip, lun) == 0)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_NOT_PRESENT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if (!(CHK_BIT(chip->lun_mc, lun))) {
SET_BIT(chip->lun_mc, lun);
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_CHANGE);
return TRANSPORT_FAILED;
}
#ifdef SUPPORT_SD_LOCK
if (sd_card->sd_erase_status) {
/* Accessing to any card is forbidden
* until the erase procedure of SD is completed
*/
RTSX_DEBUGP("SD card being erased!\n");
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_READ_FORBIDDEN);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if (get_lun_card(chip, lun) == SD_CARD) {
if (sd_card->sd_lock_status & SD_LOCKED) {
RTSX_DEBUGP("SD card locked!\n");
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_READ_FORBIDDEN);
TRACE_RET(chip, TRANSPORT_FAILED);
}
}
#endif
if ((srb->cmnd[0] == READ_10) || (srb->cmnd[0] == WRITE_10)) {
start_sec = ((u32)srb->cmnd[2] << 24) | ((u32)srb->cmnd[3] << 16) |
((u32)srb->cmnd[4] << 8) | ((u32)srb->cmnd[5]);
sec_cnt = ((u16)(srb->cmnd[7]) << 8) | srb->cmnd[8];
} else if ((srb->cmnd[0] == READ_6) || (srb->cmnd[0] == WRITE_6)) {
start_sec = ((u32)(srb->cmnd[1] & 0x1F) << 16) |
((u32)srb->cmnd[2] << 8) | ((u32)srb->cmnd[3]);
sec_cnt = srb->cmnd[4];
} else if ((srb->cmnd[0] == VENDOR_CMND) && (srb->cmnd[1] == SCSI_APP_CMD) &&
((srb->cmnd[2] == PP_READ10) || (srb->cmnd[2] == PP_WRITE10))) {
start_sec = ((u32)srb->cmnd[4] << 24) | ((u32)srb->cmnd[5] << 16) |
((u32)srb->cmnd[6] << 8) | ((u32)srb->cmnd[7]);
sec_cnt = ((u16)(srb->cmnd[9]) << 8) | srb->cmnd[10];
} else {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
/* In some test, we will receive a start_sec like 0xFFFFFFFF.
* In this situation, start_sec + sec_cnt will overflow, so we
* need to judge start_sec at first
*/
if ((start_sec > get_card_size(chip, lun)) ||
((start_sec + sec_cnt) > get_card_size(chip, lun))) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_LBA_OVER_RANGE);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if (sec_cnt == 0) {
scsi_set_resid(srb, 0);
return TRANSPORT_GOOD;
}
if (chip->rw_fail_cnt[lun] == 3) {
RTSX_DEBUGP("read/write fail three times in succession\n");
if (srb->sc_data_direction == DMA_FROM_DEVICE) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
} else {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_WRITE_ERR);
}
TRACE_RET(chip, TRANSPORT_FAILED);
}
if (srb->sc_data_direction == DMA_TO_DEVICE) {
if (check_card_wp(chip, lun)) {
RTSX_DEBUGP("Write protected card!\n");
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_WRITE_PROTECT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if (CHECK_PID(chip, 0x5209) && chip->max_payload) {
u8 val = 0x10 | (chip->max_payload << 5);
retval = rtsx_write_cfg_dw(chip, 0, 0x78, 0xFF, val);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
}
}
retval = card_rw(srb, chip, start_sec, sec_cnt);
if (retval != STATUS_SUCCESS) {
if (chip->need_release & chip->lun2card[lun]) {
chip->rw_fail_cnt[lun] = 0;
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_NOT_PRESENT);
} else {
chip->rw_fail_cnt[lun]++;
if (srb->sc_data_direction == DMA_FROM_DEVICE) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
} else {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_WRITE_ERR);
}
}
retval = TRANSPORT_FAILED;
TRACE_GOTO(chip, Exit);
} else {
chip->rw_fail_cnt[lun] = 0;
retval = TRANSPORT_GOOD;
}
scsi_set_resid(srb, 0);
Exit:
if (srb->sc_data_direction == DMA_TO_DEVICE) {
if (CHECK_PID(chip, 0x5209) && chip->max_payload) {
retval = rtsx_write_cfg_dw(chip, 0, 0x78, 0xFF, 0x10);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
}
}
return retval;
}
static int read_format_capacity(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned char *buf;
unsigned int lun = SCSI_LUN(srb);
unsigned int buf_len;
u8 card = get_lun_card(chip, lun);
u32 card_size;
int desc_cnt;
int i = 0;
if (!check_card_ready(chip, lun)) {
if (!chip->mspro_formatter_enable) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_NOT_PRESENT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
}
buf_len = (scsi_bufflen(srb) > 12) ? 0x14 : 12;
buf = kmalloc(buf_len, GFP_KERNEL);
if (buf == NULL) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
buf[i++] = 0;
buf[i++] = 0;
buf[i++] = 0;
/* Capacity List Length */
if ((buf_len > 12) && chip->mspro_formatter_enable &&
(chip->lun2card[lun] & MS_CARD) &&
(!card || (card == MS_CARD))) {
buf[i++] = 0x10;
desc_cnt = 2;
} else {
buf[i++] = 0x08;
desc_cnt = 1;
}
while (desc_cnt) {
if (check_card_ready(chip, lun)) {
card_size = get_card_size(chip, lun);
buf[i++] = (unsigned char)(card_size >> 24);
buf[i++] = (unsigned char)(card_size >> 16);
buf[i++] = (unsigned char)(card_size >> 8);
buf[i++] = (unsigned char)card_size;
if (desc_cnt == 2) {
buf[i++] = 2;
} else {
buf[i++] = 0;
}
} else {
buf[i++] = 0xFF;
buf[i++] = 0xFF;
buf[i++] = 0xFF;
buf[i++] = 0xFF;
if (desc_cnt == 2) {
buf[i++] = 3;
} else {
buf[i++] = 0;
}
}
buf[i++] = 0x00;
buf[i++] = 0x02;
buf[i++] = 0x00;
desc_cnt--;
}
buf_len = min(scsi_bufflen(srb), buf_len);
rtsx_stor_set_xfer_buf(buf, buf_len, srb);
kfree(buf);
scsi_set_resid(srb, scsi_bufflen(srb) - buf_len);
return TRANSPORT_GOOD;
}
static int read_capacity(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned char *buf;
unsigned int lun = SCSI_LUN(srb);
u32 card_size;
if (!check_card_ready(chip, lun)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_NOT_PRESENT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if (!(CHK_BIT(chip->lun_mc, lun))) {
SET_BIT(chip->lun_mc, lun);
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_CHANGE);
return TRANSPORT_FAILED;
}
buf = kmalloc(8, GFP_KERNEL);
if (buf == NULL) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
card_size = get_card_size(chip, lun);
buf[0] = (unsigned char)((card_size - 1) >> 24);
buf[1] = (unsigned char)((card_size - 1) >> 16);
buf[2] = (unsigned char)((card_size - 1) >> 8);
buf[3] = (unsigned char)(card_size - 1);
buf[4] = 0x00;
buf[5] = 0x00;
buf[6] = 0x02;
buf[7] = 0x00;
rtsx_stor_set_xfer_buf(buf, scsi_bufflen(srb), srb);
kfree(buf);
scsi_set_resid(srb, 0);
return TRANSPORT_GOOD;
}
static int read_eeprom(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned short len, i;
int retval;
u8 *buf;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
len = ((u16)srb->cmnd[4] << 8) | srb->cmnd[5];
buf = (u8 *)vmalloc(len);
if (!buf) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
retval = rtsx_force_power_on(chip, SSC_PDCTL);
if (retval != STATUS_SUCCESS) {
vfree(buf);
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
for (i = 0; i < len; i++) {
retval = spi_read_eeprom(chip, i, buf + i);
if (retval != STATUS_SUCCESS) {
vfree(buf);
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
}
len = (unsigned short)min(scsi_bufflen(srb), (unsigned int)len);
rtsx_stor_set_xfer_buf(buf, len, srb);
scsi_set_resid(srb, scsi_bufflen(srb) - len);
vfree(buf);
return TRANSPORT_GOOD;
}
static int write_eeprom(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned short len, i;
int retval;
u8 *buf;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
len = ((u16)srb->cmnd[4] << 8) | srb->cmnd[5];
retval = rtsx_force_power_on(chip, SSC_PDCTL);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_WRITE_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if (len == 511) {
retval = spi_erase_eeprom_chip(chip);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_WRITE_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
} else {
len = (unsigned short)min(scsi_bufflen(srb), (unsigned int)len);
buf = (u8 *)vmalloc(len);
if (buf == NULL) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
rtsx_stor_get_xfer_buf(buf, len, srb);
scsi_set_resid(srb, scsi_bufflen(srb) - len);
for (i = 0; i < len; i++) {
retval = spi_write_eeprom(chip, i, buf[i]);
if (retval != STATUS_SUCCESS) {
vfree(buf);
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_WRITE_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
}
vfree(buf);
}
return TRANSPORT_GOOD;
}
static int read_mem(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned short addr, len, i;
int retval;
u8 *buf;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
addr = ((u16)srb->cmnd[2] << 8) | srb->cmnd[3];
len = ((u16)srb->cmnd[4] << 8) | srb->cmnd[5];
if (addr < 0xFC00) {
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
buf = (u8 *)vmalloc(len);
if (!buf) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
retval = rtsx_force_power_on(chip, SSC_PDCTL);
if (retval != STATUS_SUCCESS) {
vfree(buf);
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_WRITE_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
for (i = 0; i < len; i++) {
retval = rtsx_read_register(chip, addr + i, buf + i);
if (retval != STATUS_SUCCESS) {
vfree(buf);
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
}
len = (unsigned short)min(scsi_bufflen(srb), (unsigned int)len);
rtsx_stor_set_xfer_buf(buf, len, srb);
scsi_set_resid(srb, scsi_bufflen(srb) - len);
vfree(buf);
return TRANSPORT_GOOD;
}
static int write_mem(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned short addr, len, i;
int retval;
u8 *buf;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
addr = ((u16)srb->cmnd[2] << 8) | srb->cmnd[3];
len = ((u16)srb->cmnd[4] << 8) | srb->cmnd[5];
if (addr < 0xFC00) {
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
len = (unsigned short)min(scsi_bufflen(srb), (unsigned int)len);
buf = (u8 *)vmalloc(len);
if (buf == NULL) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
rtsx_stor_get_xfer_buf(buf, len, srb);
scsi_set_resid(srb, scsi_bufflen(srb) - len);
retval = rtsx_force_power_on(chip, SSC_PDCTL);
if (retval != STATUS_SUCCESS) {
vfree(buf);
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_WRITE_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
for (i = 0; i < len; i++) {
retval = rtsx_write_register(chip, addr + i, 0xFF, buf[i]);
if (retval != STATUS_SUCCESS) {
vfree(buf);
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_WRITE_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
}
vfree(buf);
return TRANSPORT_GOOD;
}
static int get_sd_csd(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
struct sd_info *sd_card = &(chip->sd_card);
unsigned int lun = SCSI_LUN(srb);
if (!check_card_ready(chip, lun)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_NOT_PRESENT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if (get_lun_card(chip, lun) != SD_CARD) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
scsi_set_resid(srb, 0);
rtsx_stor_set_xfer_buf(sd_card->raw_csd, scsi_bufflen(srb), srb);
return TRANSPORT_GOOD;
}
static int toggle_gpio_cmd(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
u8 gpio = srb->cmnd[2];
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
if (gpio > 3)
gpio = 1;
toggle_gpio(chip, gpio);
return TRANSPORT_GOOD;
}
#ifdef _MSG_TRACE
static int trace_msg_cmd(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned char *ptr, *buf = NULL;
int i, msg_cnt;
u8 clear;
unsigned int buf_len;
buf_len = 4 + ((2 + MSG_FUNC_LEN + MSG_FILE_LEN + TIME_VAL_LEN) * TRACE_ITEM_CNT);
if ((scsi_bufflen(srb) < buf_len) || (scsi_sglist(srb) == NULL)) {
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
clear = srb->cmnd[2];
buf = (unsigned char *)vmalloc(scsi_bufflen(srb));
if (buf == NULL) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
ptr = buf;
if (chip->trace_msg[chip->msg_idx].valid) {
msg_cnt = TRACE_ITEM_CNT;
} else {
msg_cnt = chip->msg_idx;
}
*(ptr++) = (u8)(msg_cnt >> 24);
*(ptr++) = (u8)(msg_cnt >> 16);
*(ptr++) = (u8)(msg_cnt >> 8);
*(ptr++) = (u8)msg_cnt;
RTSX_DEBUGP("Trace message count is %d\n", msg_cnt);
for (i = 1; i <= msg_cnt; i++) {
int j, idx;
idx = chip->msg_idx - i;
if (idx < 0)
idx += TRACE_ITEM_CNT;
*(ptr++) = (u8)(chip->trace_msg[idx].line >> 8);
*(ptr++) = (u8)(chip->trace_msg[idx].line);
for (j = 0; j < MSG_FUNC_LEN; j++) {
*(ptr++) = chip->trace_msg[idx].func[j];
}
for (j = 0; j < MSG_FILE_LEN; j++) {
*(ptr++) = chip->trace_msg[idx].file[j];
}
for (j = 0; j < TIME_VAL_LEN; j++) {
*(ptr++) = chip->trace_msg[idx].timeval_buf[j];
}
}
rtsx_stor_set_xfer_buf(buf, scsi_bufflen(srb), srb);
vfree(buf);
if (clear) {
chip->msg_idx = 0;
for (i = 0; i < TRACE_ITEM_CNT; i++)
chip->trace_msg[i].valid = 0;
}
scsi_set_resid(srb, 0);
return TRANSPORT_GOOD;
}
#endif
static int read_host_reg(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
u8 addr, buf[4];
u32 val;
unsigned int len;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
addr = srb->cmnd[4];
val = rtsx_readl(chip, addr);
RTSX_DEBUGP("Host register (0x%x): 0x%x\n", addr, val);
buf[0] = (u8)(val >> 24);
buf[1] = (u8)(val >> 16);
buf[2] = (u8)(val >> 8);
buf[3] = (u8)val;
len = min(scsi_bufflen(srb), (unsigned int)4);
rtsx_stor_set_xfer_buf(buf, len, srb);
scsi_set_resid(srb, scsi_bufflen(srb) - len);
return TRANSPORT_GOOD;
}
static int write_host_reg(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
u8 addr, buf[4];
u32 val;
unsigned int len;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
addr = srb->cmnd[4];
len = min(scsi_bufflen(srb), (unsigned int)4);
rtsx_stor_get_xfer_buf(buf, len, srb);
scsi_set_resid(srb, scsi_bufflen(srb) - len);
val = ((u32)buf[0] << 24) | ((u32)buf[1] << 16) | ((u32)buf[2] << 8) | buf[3];
rtsx_writel(chip, addr, val);
return TRANSPORT_GOOD;
}
static int set_variable(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned lun = SCSI_LUN(srb);
if (srb->cmnd[3] == 1) {
/* Variable Clock */
struct xd_info *xd_card = &(chip->xd_card);
struct sd_info *sd_card = &(chip->sd_card);
struct ms_info *ms_card = &(chip->ms_card);
switch (srb->cmnd[4]) {
case XD_CARD:
xd_card->xd_clock = srb->cmnd[5];
break;
case SD_CARD:
sd_card->sd_clock = srb->cmnd[5];
break;
case MS_CARD:
ms_card->ms_clock = srb->cmnd[5];
break;
default:
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
} else if (srb->cmnd[3] == 2) {
if (srb->cmnd[4]) {
chip->blink_led = 1;
} else {
int retval;
chip->blink_led = 0;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
retval = rtsx_force_power_on(chip, SSC_PDCTL);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_WRITE_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
turn_off_led(chip, LED_GPIO);
}
} else {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
return TRANSPORT_GOOD;
}
static int get_variable(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned int lun = SCSI_LUN(srb);
if (srb->cmnd[3] == 1) {
struct xd_info *xd_card = &(chip->xd_card);
struct sd_info *sd_card = &(chip->sd_card);
struct ms_info *ms_card = &(chip->ms_card);
u8 tmp;
switch (srb->cmnd[4]) {
case XD_CARD:
tmp = (u8)(xd_card->xd_clock);
break;
case SD_CARD:
tmp = (u8)(sd_card->sd_clock);
break;
case MS_CARD:
tmp = (u8)(ms_card->ms_clock);
break;
default:
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
rtsx_stor_set_xfer_buf(&tmp, 1, srb);
} else if (srb->cmnd[3] == 2) {
u8 tmp = chip->blink_led;
rtsx_stor_set_xfer_buf(&tmp, 1, srb);
} else {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
return TRANSPORT_GOOD;
}
static int dma_access_ring_buffer(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
int retval;
unsigned int lun = SCSI_LUN(srb);
u16 len;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
len = ((u16)(srb->cmnd[4]) << 8) | srb->cmnd[5];
len = min(len, (u16)scsi_bufflen(srb));
if (srb->sc_data_direction == DMA_FROM_DEVICE) {
RTSX_DEBUGP("Read from device\n");
} else {
RTSX_DEBUGP("Write to device\n");
}
retval = rtsx_transfer_data(chip, 0, scsi_sglist(srb), len,
scsi_sg_count(srb), srb->sc_data_direction, 1000);
if (retval < 0) {
if (srb->sc_data_direction == DMA_FROM_DEVICE) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
} else {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_WRITE_ERR);
}
TRACE_RET(chip, TRANSPORT_FAILED);
}
scsi_set_resid(srb, 0);
return TRANSPORT_GOOD;
}
static int get_dev_status(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
struct sd_info *sd_card = &(chip->sd_card);
struct ms_info *ms_card = &(chip->ms_card);
int buf_len;
unsigned int lun = SCSI_LUN(srb);
u8 card = get_lun_card(chip, lun);
u8 status[32];
#ifdef SUPPORT_OCP
u8 oc_now_mask = 0, oc_ever_mask = 0;
#endif
memset(status, 0, 32);
status[0] = (u8)(chip->product_id);
status[1] = chip->ic_version;
if (chip->auto_delink_en) {
status[2] = 0x10;
} else {
status[2] = 0x00;
}
status[3] = 20;
status[4] = 10;
status[5] = 05;
status[6] = 21;
if (chip->card_wp) {
status[7] = 0x20;
} else {
status[7] = 0x00;
}
#ifdef SUPPORT_OCP
status[8] = 0;
if (CHECK_LUN_MODE(chip, SD_MS_2LUN) && (chip->lun2card[lun] == MS_CARD)) {
oc_now_mask = MS_OC_NOW;
oc_ever_mask = MS_OC_EVER;
} else {
oc_now_mask = SD_OC_NOW;
oc_ever_mask = SD_OC_EVER;
}
if (chip->ocp_stat & oc_now_mask) {
status[8] |= 0x02;
}
if (chip->ocp_stat & oc_ever_mask) {
status[8] |= 0x01;
}
#endif
if (card == SD_CARD) {
if (CHK_SD(sd_card)) {
if (CHK_SD_HCXC(sd_card)) {
if (sd_card->capacity > 0x4000000) {
status[0x0E] = 0x02;
} else {
status[0x0E] = 0x01;
}
} else {
status[0x0E] = 0x00;
}
if (CHK_SD_SDR104(sd_card)) {
status[0x0F] = 0x03;
} else if (CHK_SD_DDR50(sd_card)) {
status[0x0F] = 0x04;
} else if (CHK_SD_SDR50(sd_card)) {
status[0x0F] = 0x02;
} else if (CHK_SD_HS(sd_card)) {
status[0x0F] = 0x01;
} else {
status[0x0F] = 0x00;
}
} else {
if (CHK_MMC_SECTOR_MODE(sd_card)) {
status[0x0E] = 0x01;
} else {
status[0x0E] = 0x00;
}
if (CHK_MMC_DDR52(sd_card)) {
status[0x0F] = 0x03;
} else if (CHK_MMC_52M(sd_card)) {
status[0x0F] = 0x02;
} else if (CHK_MMC_26M(sd_card)) {
status[0x0F] = 0x01;
} else {
status[0x0F] = 0x00;
}
}
} else if (card == MS_CARD) {
if (CHK_MSPRO(ms_card)) {
if (CHK_MSXC(ms_card)) {
status[0x0E] = 0x01;
} else {
status[0x0E] = 0x00;
}
if (CHK_HG8BIT(ms_card)) {
status[0x0F] = 0x01;
} else {
status[0x0F] = 0x00;
}
}
}
#ifdef SUPPORT_SD_LOCK
if (card == SD_CARD) {
status[0x17] = 0x80;
if (sd_card->sd_erase_status)
status[0x17] |= 0x01;
if (sd_card->sd_lock_status & SD_LOCKED) {
status[0x17] |= 0x02;
status[0x07] |= 0x40;
}
if (sd_card->sd_lock_status & SD_PWD_EXIST)
status[0x17] |= 0x04;
} else {
status[0x17] = 0x00;
}
RTSX_DEBUGP("status[0x17] = 0x%x\n", status[0x17]);
#endif
status[0x18] = 0x8A;
status[0x1A] = 0x28;
#ifdef SUPPORT_SD_LOCK
status[0x1F] = 0x01;
#endif
buf_len = min(scsi_bufflen(srb), (unsigned int)sizeof(status));
rtsx_stor_set_xfer_buf(status, buf_len, srb);
scsi_set_resid(srb, scsi_bufflen(srb) - buf_len);
return TRANSPORT_GOOD;
}
static int set_chip_mode(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
int phy_debug_mode;
int retval;
u16 reg;
if (!CHECK_PID(chip, 0x5208)) {
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
phy_debug_mode = (int)(srb->cmnd[3]);
if (phy_debug_mode) {
chip->phy_debug_mode = 1;
retval = rtsx_write_register(chip, CDRESUMECTL, 0x77, 0);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_FAILED);
}
rtsx_disable_bus_int(chip);
retval = rtsx_read_phy_register(chip, 0x1C, ®);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_FAILED);
}
reg |= 0x0001;
retval = rtsx_write_phy_register(chip, 0x1C, reg);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_FAILED);
}
} else {
chip->phy_debug_mode = 0;
retval = rtsx_write_register(chip, CDRESUMECTL, 0x77, 0x77);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_FAILED);
}
rtsx_enable_bus_int(chip);
retval = rtsx_read_phy_register(chip, 0x1C, ®);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_FAILED);
}
reg &= 0xFFFE;
retval = rtsx_write_phy_register(chip, 0x1C, reg);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_FAILED);
}
}
return TRANSPORT_GOOD;
}
static int rw_mem_cmd_buf(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
int retval = STATUS_SUCCESS;
unsigned int lun = SCSI_LUN(srb);
u8 cmd_type, mask, value, idx;
u16 addr;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
switch (srb->cmnd[3]) {
case INIT_BATCHCMD:
rtsx_init_cmd(chip);
break;
case ADD_BATCHCMD:
cmd_type = srb->cmnd[4];
if (cmd_type > 2) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
addr = (srb->cmnd[5] << 8) | srb->cmnd[6];
mask = srb->cmnd[7];
value = srb->cmnd[8];
rtsx_add_cmd(chip, cmd_type, addr, mask, value);
break;
case SEND_BATCHCMD:
retval = rtsx_send_cmd(chip, 0, 1000);
break;
case GET_BATCHRSP:
idx = srb->cmnd[4];
value = *(rtsx_get_cmd_data(chip) + idx);
if (scsi_bufflen(srb) < 1) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
rtsx_stor_set_xfer_buf(&value, 1, srb);
scsi_set_resid(srb, 0);
break;
default:
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_WRITE_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
return TRANSPORT_GOOD;
}
static int suit_cmd(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
int result;
switch (srb->cmnd[3]) {
case INIT_BATCHCMD:
case ADD_BATCHCMD:
case SEND_BATCHCMD:
case GET_BATCHRSP:
result = rw_mem_cmd_buf(srb, chip);
break;
default:
result = TRANSPORT_ERROR;
}
return result;
}
static int read_phy_register(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned short addr, len, i;
int retval;
u8 *buf;
u16 val;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
addr = ((u16)srb->cmnd[4] << 8) | srb->cmnd[5];
len = ((u16)srb->cmnd[6] << 8) | srb->cmnd[7];
if (len % 2)
len -= len % 2;
if (len) {
buf = (u8 *)vmalloc(len);
if (!buf) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
retval = rtsx_force_power_on(chip, SSC_PDCTL);
if (retval != STATUS_SUCCESS) {
vfree(buf);
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
for (i = 0; i < len / 2; i++) {
retval = rtsx_read_phy_register(chip, addr + i, &val);
if (retval != STATUS_SUCCESS) {
vfree(buf);
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
buf[2*i] = (u8)(val >> 8);
buf[2*i+1] = (u8)val;
}
len = (unsigned short)min(scsi_bufflen(srb), (unsigned int)len);
rtsx_stor_set_xfer_buf(buf, len, srb);
scsi_set_resid(srb, scsi_bufflen(srb) - len);
vfree(buf);
}
return TRANSPORT_GOOD;
}
static int write_phy_register(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned short addr, len, i;
int retval;
u8 *buf;
u16 val;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
addr = ((u16)srb->cmnd[4] << 8) | srb->cmnd[5];
len = ((u16)srb->cmnd[6] << 8) | srb->cmnd[7];
if (len % 2)
len -= len % 2;
if (len) {
len = (unsigned short)min(scsi_bufflen(srb), (unsigned int)len);
buf = (u8 *)vmalloc(len);
if (buf == NULL) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
rtsx_stor_get_xfer_buf(buf, len, srb);
scsi_set_resid(srb, scsi_bufflen(srb) - len);
retval = rtsx_force_power_on(chip, SSC_PDCTL);
if (retval != STATUS_SUCCESS) {
vfree(buf);
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_WRITE_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
for (i = 0; i < len / 2; i++) {
val = ((u16)buf[2*i] << 8) | buf[2*i+1];
retval = rtsx_write_phy_register(chip, addr + i, val);
if (retval != STATUS_SUCCESS) {
vfree(buf);
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_WRITE_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
}
vfree(buf);
}
return TRANSPORT_GOOD;
}
static int erase_eeprom2(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned short addr;
int retval;
u8 mode;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
retval = rtsx_force_power_on(chip, SSC_PDCTL);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_WRITE_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
mode = srb->cmnd[3];
addr = ((u16)srb->cmnd[4] << 8) | srb->cmnd[5];
if (mode == 0) {
retval = spi_erase_eeprom_chip(chip);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_WRITE_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
} else if (mode == 1) {
retval = spi_erase_eeprom_byte(chip, addr);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_WRITE_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
} else {
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
return TRANSPORT_GOOD;
}
static int read_eeprom2(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned short addr, len, i;
int retval;
u8 *buf;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
addr = ((u16)srb->cmnd[4] << 8) | srb->cmnd[5];
len = ((u16)srb->cmnd[6] << 8) | srb->cmnd[7];
buf = (u8 *)vmalloc(len);
if (!buf) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
retval = rtsx_force_power_on(chip, SSC_PDCTL);
if (retval != STATUS_SUCCESS) {
vfree(buf);
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
for (i = 0; i < len; i++) {
retval = spi_read_eeprom(chip, addr + i, buf + i);
if (retval != STATUS_SUCCESS) {
vfree(buf);
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
}
len = (unsigned short)min(scsi_bufflen(srb), (unsigned int)len);
rtsx_stor_set_xfer_buf(buf, len, srb);
scsi_set_resid(srb, scsi_bufflen(srb) - len);
vfree(buf);
return TRANSPORT_GOOD;
}
static int write_eeprom2(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned short addr, len, i;
int retval;
u8 *buf;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
addr = ((u16)srb->cmnd[4] << 8) | srb->cmnd[5];
len = ((u16)srb->cmnd[6] << 8) | srb->cmnd[7];
len = (unsigned short)min(scsi_bufflen(srb), (unsigned int)len);
buf = (u8 *)vmalloc(len);
if (buf == NULL) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
rtsx_stor_get_xfer_buf(buf, len, srb);
scsi_set_resid(srb, scsi_bufflen(srb) - len);
retval = rtsx_force_power_on(chip, SSC_PDCTL);
if (retval != STATUS_SUCCESS) {
vfree(buf);
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_WRITE_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
for (i = 0; i < len; i++) {
retval = spi_write_eeprom(chip, addr + i, buf[i]);
if (retval != STATUS_SUCCESS) {
vfree(buf);
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_WRITE_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
}
vfree(buf);
return TRANSPORT_GOOD;
}
static int read_efuse(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
int retval;
u8 addr, len, i;
u8 *buf;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
addr = srb->cmnd[4];
len = srb->cmnd[5];
buf = (u8 *)vmalloc(len);
if (!buf) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
retval = rtsx_force_power_on(chip, SSC_PDCTL);
if (retval != STATUS_SUCCESS) {
vfree(buf);
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
for (i = 0; i < len; i++) {
retval = rtsx_read_efuse(chip, addr + i, buf + i);
if (retval != STATUS_SUCCESS) {
vfree(buf);
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
}
len = (u8)min(scsi_bufflen(srb), (unsigned int)len);
rtsx_stor_set_xfer_buf(buf, len, srb);
scsi_set_resid(srb, scsi_bufflen(srb) - len);
vfree(buf);
return TRANSPORT_GOOD;
}
static int write_efuse(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
int retval, result = TRANSPORT_GOOD;
u16 val;
u8 addr, len, i;
u8 *buf;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
addr = srb->cmnd[4];
len = srb->cmnd[5];
len = (u8)min(scsi_bufflen(srb), (unsigned int)len);
buf = (u8 *)vmalloc(len);
if (buf == NULL) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
rtsx_stor_get_xfer_buf(buf, len, srb);
scsi_set_resid(srb, scsi_bufflen(srb) - len);
retval = rtsx_force_power_on(chip, SSC_PDCTL);
if (retval != STATUS_SUCCESS) {
vfree(buf);
TRACE_RET(chip, TRANSPORT_ERROR);
}
if (chip->asic_code) {
retval = rtsx_read_phy_register(chip, 0x08, &val);
if (retval != STATUS_SUCCESS) {
vfree(buf);
TRACE_RET(chip, TRANSPORT_ERROR);
}
retval = rtsx_write_register(chip, PWR_GATE_CTRL, LDO3318_PWR_MASK, LDO_OFF);
if (retval != STATUS_SUCCESS) {
vfree(buf);
TRACE_RET(chip, TRANSPORT_ERROR);
}
wait_timeout(600);
retval = rtsx_write_phy_register(chip, 0x08, 0x4C00 | chip->phy_voltage);
if (retval != STATUS_SUCCESS) {
vfree(buf);
TRACE_RET(chip, TRANSPORT_ERROR);
}
retval = rtsx_write_register(chip, PWR_GATE_CTRL, LDO3318_PWR_MASK, LDO_ON);
if (retval != STATUS_SUCCESS) {
vfree(buf);
TRACE_RET(chip, TRANSPORT_ERROR);
}
wait_timeout(600);
}
retval = card_power_on(chip, SPI_CARD);
if (retval != STATUS_SUCCESS) {
vfree(buf);
TRACE_RET(chip, TRANSPORT_ERROR);
}
wait_timeout(50);
for (i = 0; i < len; i++) {
retval = rtsx_write_efuse(chip, addr + i, buf[i]);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_WRITE_ERR);
result = TRANSPORT_FAILED;
TRACE_GOTO(chip, Exit);
}
}
Exit:
vfree(buf);
retval = card_power_off(chip, SPI_CARD);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
if (chip->asic_code) {
retval = rtsx_write_register(chip, PWR_GATE_CTRL, LDO3318_PWR_MASK, LDO_OFF);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
wait_timeout(600);
retval = rtsx_write_phy_register(chip, 0x08, val);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
retval = rtsx_write_register(chip, PWR_GATE_CTRL, LDO3318_PWR_MASK, LDO_ON);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
}
return result;
}
static int read_cfg_byte(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
int retval;
u8 func, func_max;
u16 addr, len;
u8 *buf;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
func = srb->cmnd[3];
addr = ((u16)(srb->cmnd[4]) << 8) | srb->cmnd[5];
len = ((u16)(srb->cmnd[6]) << 8) | srb->cmnd[7];
RTSX_DEBUGP("%s: func = %d, addr = 0x%x, len = %d\n", __func__, func, addr, len);
if (CHK_SDIO_EXIST(chip) && !CHK_SDIO_IGNORED(chip)) {
func_max = 1;
} else {
func_max = 0;
}
if (func > func_max) {
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
buf = (u8 *)vmalloc(len);
if (!buf) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
retval = rtsx_read_cfg_seq(chip, func, addr, buf, len);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
vfree(buf);
TRACE_RET(chip, TRANSPORT_FAILED);
}
len = (u16)min(scsi_bufflen(srb), (unsigned int)len);
rtsx_stor_set_xfer_buf(buf, len, srb);
scsi_set_resid(srb, scsi_bufflen(srb) - len);
vfree(buf);
return TRANSPORT_GOOD;
}
static int write_cfg_byte(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
int retval;
u8 func, func_max;
u16 addr, len;
u8 *buf;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
func = srb->cmnd[3];
addr = ((u16)(srb->cmnd[4]) << 8) | srb->cmnd[5];
len = ((u16)(srb->cmnd[6]) << 8) | srb->cmnd[7];
RTSX_DEBUGP("%s: func = %d, addr = 0x%x\n", __func__, func, addr);
if (CHK_SDIO_EXIST(chip) && !CHK_SDIO_IGNORED(chip)) {
func_max = 1;
} else {
func_max = 0;
}
if (func > func_max) {
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
len = (unsigned short)min(scsi_bufflen(srb), (unsigned int)len);
buf = (u8 *)vmalloc(len);
if (!buf) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
rtsx_stor_get_xfer_buf(buf, len, srb);
scsi_set_resid(srb, scsi_bufflen(srb) - len);
retval = rtsx_write_cfg_seq(chip, func, addr, buf, len);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_WRITE_ERR);
vfree(buf);
TRACE_RET(chip, TRANSPORT_FAILED);
}
vfree(buf);
return TRANSPORT_GOOD;
}
static int app_cmd(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
int result;
switch (srb->cmnd[2]) {
case PP_READ10:
case PP_WRITE10:
result = read_write(srb, chip);
break;
case READ_HOST_REG:
result = read_host_reg(srb, chip);
break;
case WRITE_HOST_REG:
result = write_host_reg(srb, chip);
break;
case GET_VAR:
result = get_variable(srb, chip);
break;
case SET_VAR:
result = set_variable(srb, chip);
break;
case DMA_READ:
case DMA_WRITE:
result = dma_access_ring_buffer(srb, chip);
break;
case READ_PHY:
result = read_phy_register(srb, chip);
break;
case WRITE_PHY:
result = write_phy_register(srb, chip);
break;
case ERASE_EEPROM2:
result = erase_eeprom2(srb, chip);
break;
case READ_EEPROM2:
result = read_eeprom2(srb, chip);
break;
case WRITE_EEPROM2:
result = write_eeprom2(srb, chip);
break;
case READ_EFUSE:
result = read_efuse(srb, chip);
break;
case WRITE_EFUSE:
result = write_efuse(srb, chip);
break;
case READ_CFG:
result = read_cfg_byte(srb, chip);
break;
case WRITE_CFG:
result = write_cfg_byte(srb, chip);
break;
case SET_CHIP_MODE:
result = set_chip_mode(srb, chip);
break;
case SUIT_CMD:
result = suit_cmd(srb, chip);
break;
case GET_DEV_STATUS:
result = get_dev_status(srb, chip);
break;
default:
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
return result;
}
static int read_status(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
u8 rtsx_status[16];
int buf_len;
unsigned int lun = SCSI_LUN(srb);
rtsx_status[0] = (u8)(chip->vendor_id >> 8);
rtsx_status[1] = (u8)(chip->vendor_id);
rtsx_status[2] = (u8)(chip->product_id >> 8);
rtsx_status[3] = (u8)(chip->product_id);
rtsx_status[4] = (u8)lun;
if (CHECK_LUN_MODE(chip, SD_MS_2LUN)) {
if (chip->lun2card[lun] == SD_CARD) {
rtsx_status[5] = 2;
} else {
rtsx_status[5] = 3;
}
} else {
if (chip->card_exist) {
if (chip->card_exist & XD_CARD) {
rtsx_status[5] = 4;
} else if (chip->card_exist & SD_CARD) {
rtsx_status[5] = 2;
} else if (chip->card_exist & MS_CARD) {
rtsx_status[5] = 3;
} else {
rtsx_status[5] = 7;
}
} else {
rtsx_status[5] = 7;
}
}
if (CHECK_LUN_MODE(chip, SD_MS_2LUN)) {
rtsx_status[6] = 2;
} else {
rtsx_status[6] = 1;
}
rtsx_status[7] = (u8)(chip->product_id);
rtsx_status[8] = chip->ic_version;
if (check_card_exist(chip, lun)) {
rtsx_status[9] = 1;
} else {
rtsx_status[9] = 0;
}
if (CHECK_LUN_MODE(chip, SD_MS_2LUN)) {
rtsx_status[10] = 0;
} else {
rtsx_status[10] = 1;
}
if (CHECK_LUN_MODE(chip, SD_MS_2LUN)) {
if (chip->lun2card[lun] == SD_CARD) {
rtsx_status[11] = SD_CARD;
} else {
rtsx_status[11] = MS_CARD;
}
} else {
rtsx_status[11] = XD_CARD | SD_CARD | MS_CARD;
}
if (check_card_ready(chip, lun)) {
rtsx_status[12] = 1;
} else {
rtsx_status[12] = 0;
}
if (get_lun_card(chip, lun) == XD_CARD) {
rtsx_status[13] = 0x40;
} else if (get_lun_card(chip, lun) == SD_CARD) {
struct sd_info *sd_card = &(chip->sd_card);
rtsx_status[13] = 0x20;
if (CHK_SD(sd_card)) {
if (CHK_SD_HCXC(sd_card))
rtsx_status[13] |= 0x04;
if (CHK_SD_HS(sd_card))
rtsx_status[13] |= 0x02;
} else {
rtsx_status[13] |= 0x08;
if (CHK_MMC_52M(sd_card))
rtsx_status[13] |= 0x02;
if (CHK_MMC_SECTOR_MODE(sd_card))
rtsx_status[13] |= 0x04;
}
} else if (get_lun_card(chip, lun) == MS_CARD) {
struct ms_info *ms_card = &(chip->ms_card);
if (CHK_MSPRO(ms_card)) {
rtsx_status[13] = 0x38;
if (CHK_HG8BIT(ms_card))
rtsx_status[13] |= 0x04;
#ifdef SUPPORT_MSXC
if (CHK_MSXC(ms_card))
rtsx_status[13] |= 0x01;
#endif
} else {
rtsx_status[13] = 0x30;
}
} else {
if (CHECK_LUN_MODE(chip, DEFAULT_SINGLE)) {
#ifdef SUPPORT_SDIO
if (chip->sd_io && chip->sd_int) {
rtsx_status[13] = 0x60;
} else {
rtsx_status[13] = 0x70;
}
#else
rtsx_status[13] = 0x70;
#endif
} else {
if (chip->lun2card[lun] == SD_CARD) {
rtsx_status[13] = 0x20;
} else {
rtsx_status[13] = 0x30;
}
}
}
rtsx_status[14] = 0x78;
if (CHK_SDIO_EXIST(chip) && !CHK_SDIO_IGNORED(chip)) {
rtsx_status[15] = 0x83;
} else {
rtsx_status[15] = 0x82;
}
buf_len = min(scsi_bufflen(srb), (unsigned int)sizeof(rtsx_status));
rtsx_stor_set_xfer_buf(rtsx_status, buf_len, srb);
scsi_set_resid(srb, scsi_bufflen(srb) - buf_len);
return TRANSPORT_GOOD;
}
static int get_card_bus_width(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned int lun = SCSI_LUN(srb);
u8 card, bus_width;
if (!check_card_ready(chip, lun)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_NOT_PRESENT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
card = get_lun_card(chip, lun);
if ((card == SD_CARD) || (card == MS_CARD)) {
bus_width = chip->card_bus_width[lun];
} else {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
TRACE_RET(chip, TRANSPORT_FAILED);
}
scsi_set_resid(srb, 0);
rtsx_stor_set_xfer_buf(&bus_width, scsi_bufflen(srb), srb);
return TRANSPORT_GOOD;
}
static int spi_vendor_cmd(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
int result;
unsigned int lun = SCSI_LUN(srb);
u8 gpio_dir;
if (CHECK_PID(chip, 0x5208) && CHECK_PID(chip, 0x5288)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
rtsx_force_power_on(chip, SSC_PDCTL);
rtsx_read_register(chip, CARD_GPIO_DIR, &gpio_dir);
rtsx_write_register(chip, CARD_GPIO_DIR, 0x07, gpio_dir & 0x06);
switch (srb->cmnd[2]) {
case SCSI_SPI_GETSTATUS:
result = spi_get_status(srb, chip);
break;
case SCSI_SPI_SETPARAMETER:
result = spi_set_parameter(srb, chip);
break;
case SCSI_SPI_READFALSHID:
result = spi_read_flash_id(srb, chip);
break;
case SCSI_SPI_READFLASH:
result = spi_read_flash(srb, chip);
break;
case SCSI_SPI_WRITEFLASH:
result = spi_write_flash(srb, chip);
break;
case SCSI_SPI_WRITEFLASHSTATUS:
result = spi_write_flash_status(srb, chip);
break;
case SCSI_SPI_ERASEFLASH:
result = spi_erase_flash(srb, chip);
break;
default:
rtsx_write_register(chip, CARD_GPIO_DIR, 0x07, gpio_dir);
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
rtsx_write_register(chip, CARD_GPIO_DIR, 0x07, gpio_dir);
if (result != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_FAILED);
}
return TRANSPORT_GOOD;
}
static int vendor_cmnd(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
int result;
switch (srb->cmnd[1]) {
case READ_STATUS:
result = read_status(srb, chip);
break;
case READ_MEM:
result = read_mem(srb, chip);
break;
case WRITE_MEM:
result = write_mem(srb, chip);
break;
case READ_EEPROM:
result = read_eeprom(srb, chip);
break;
case WRITE_EEPROM:
result = write_eeprom(srb, chip);
break;
case TOGGLE_GPIO:
result = toggle_gpio_cmd(srb, chip);
break;
case GET_SD_CSD:
result = get_sd_csd(srb, chip);
break;
case GET_BUS_WIDTH:
result = get_card_bus_width(srb, chip);
break;
#ifdef _MSG_TRACE
case TRACE_MSG:
result = trace_msg_cmd(srb, chip);
break;
#endif
case SCSI_APP_CMD:
result = app_cmd(srb, chip);
break;
case SPI_VENDOR_COMMAND:
result = spi_vendor_cmd(srb, chip);
break;
default:
set_sense_type(chip, SCSI_LUN(srb), SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
return result;
}
#if !defined(LED_AUTO_BLINK) && !defined(REGULAR_BLINK)
void led_shine(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned int lun = SCSI_LUN(srb);
u16 sec_cnt;
if ((srb->cmnd[0] == READ_10) || (srb->cmnd[0] == WRITE_10)) {
sec_cnt = ((u16)(srb->cmnd[7]) << 8) | srb->cmnd[8];
} else if ((srb->cmnd[0] == READ_6) || (srb->cmnd[0] == WRITE_6)) {
sec_cnt = srb->cmnd[4];
} else {
return;
}
if (chip->rw_cap[lun] >= GPIO_TOGGLE_THRESHOLD) {
toggle_gpio(chip, LED_GPIO);
chip->rw_cap[lun] = 0;
} else {
chip->rw_cap[lun] += sec_cnt;
}
}
#endif
static int ms_format_cmnd(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
struct ms_info *ms_card = &(chip->ms_card);
unsigned int lun = SCSI_LUN(srb);
int retval, quick_format;
if (get_lun_card(chip, lun) != MS_CARD) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_LUN_NOT_SUPPORT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if ((srb->cmnd[3] != 0x4D) || (srb->cmnd[4] != 0x47) ||
(srb->cmnd[5] != 0x66) || (srb->cmnd[6] != 0x6D) ||
(srb->cmnd[7] != 0x74)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
if (!check_card_ready(chip, lun) ||
(get_card_size(chip, lun) == 0)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_NOT_PRESENT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
if (srb->cmnd[8] & 0x01) {
quick_format = 0;
} else {
quick_format = 1;
}
if (!(chip->card_ready & MS_CARD)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_NOT_PRESENT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if (chip->card_wp & MS_CARD) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_WRITE_PROTECT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if (!CHK_MSPRO(ms_card)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_LUN_NOT_SUPPORT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
retval = mspro_format(srb, chip, MS_SHORT_DATA_LEN, quick_format);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_FORMAT_CMD_FAILED);
TRACE_RET(chip, TRANSPORT_FAILED);
}
scsi_set_resid(srb, 0);
return TRANSPORT_GOOD;
}
#ifdef SUPPORT_PCGL_1P18
static int get_ms_information(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
struct ms_info *ms_card = &(chip->ms_card);
unsigned int lun = SCSI_LUN(srb);
u8 dev_info_id, data_len;
u8 *buf;
unsigned int buf_len;
int i;
if (!check_card_ready(chip, lun)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_NOT_PRESENT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if ((get_lun_card(chip, lun) != MS_CARD)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_LUN_NOT_SUPPORT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if ((srb->cmnd[2] != 0xB0) || (srb->cmnd[4] != 0x4D) ||
(srb->cmnd[5] != 0x53) || (srb->cmnd[6] != 0x49) ||
(srb->cmnd[7] != 0x44)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
dev_info_id = srb->cmnd[3];
if ((CHK_MSXC(ms_card) && (dev_info_id == 0x10)) ||
(!CHK_MSXC(ms_card) && (dev_info_id == 0x13)) ||
!CHK_MSPRO(ms_card)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if (dev_info_id == 0x15) {
buf_len = data_len = 0x3A;
} else {
buf_len = data_len = 0x6A;
}
buf = (u8 *)kmalloc(buf_len, GFP_KERNEL);
if (!buf) {
TRACE_RET(chip, TRANSPORT_ERROR);
}
i = 0;
/* GET Memory Stick Media Information Response Header */
buf[i++] = 0x00; /* Data length MSB */
buf[i++] = data_len; /* Data length LSB */
/* Device Information Type Code */
if (CHK_MSXC(ms_card)) {
buf[i++] = 0x03;
} else {
buf[i++] = 0x02;
}
/* SGM bit */
buf[i++] = 0x01;
/* Reserved */
buf[i++] = 0x00;
buf[i++] = 0x00;
buf[i++] = 0x00;
/* Number of Device Information */
buf[i++] = 0x01;
/* Device Information Body */
/* Device Information ID Number */
buf[i++] = dev_info_id;
/* Device Information Length */
if (dev_info_id == 0x15) {
data_len = 0x31;
} else {
data_len = 0x61;
}
buf[i++] = 0x00; /* Data length MSB */
buf[i++] = data_len; /* Data length LSB */
/* Valid Bit */
buf[i++] = 0x80;
if ((dev_info_id == 0x10) || (dev_info_id == 0x13)) {
/* System Information */
memcpy(buf+i, ms_card->raw_sys_info, 96);
} else {
/* Model Name */
memcpy(buf+i, ms_card->raw_model_name, 48);
}
rtsx_stor_set_xfer_buf(buf, buf_len, srb);
if (dev_info_id == 0x15) {
scsi_set_resid(srb, scsi_bufflen(srb)-0x3C);
} else {
scsi_set_resid(srb, scsi_bufflen(srb)-0x6C);
}
kfree(buf);
return STATUS_SUCCESS;
}
#endif
static int ms_sp_cmnd(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
int retval = TRANSPORT_ERROR;
if (srb->cmnd[2] == MS_FORMAT) {
retval = ms_format_cmnd(srb, chip);
}
#ifdef SUPPORT_PCGL_1P18
else if (srb->cmnd[2] == GET_MS_INFORMATION) {
retval = get_ms_information(srb, chip);
}
#endif
return retval;
}
#ifdef SUPPORT_CPRM
static int sd_extention_cmnd(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
unsigned int lun = SCSI_LUN(srb);
int result;
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
sd_cleanup_work(chip);
if (!check_card_ready(chip, lun)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_NOT_PRESENT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if ((get_lun_card(chip, lun) != SD_CARD)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_LUN_NOT_SUPPORT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
switch (srb->cmnd[0]) {
case SD_PASS_THRU_MODE:
result = sd_pass_thru_mode(srb, chip);
break;
case SD_EXECUTE_NO_DATA:
result = sd_execute_no_data(srb, chip);
break;
case SD_EXECUTE_READ:
result = sd_execute_read_data(srb, chip);
break;
case SD_EXECUTE_WRITE:
result = sd_execute_write_data(srb, chip);
break;
case SD_GET_RSP:
result = sd_get_cmd_rsp(srb, chip);
break;
case SD_HW_RST:
result = sd_hw_rst(srb, chip);
break;
default:
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
return result;
}
#endif
#ifdef SUPPORT_MAGIC_GATE
static int mg_report_key(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
struct ms_info *ms_card = &(chip->ms_card);
unsigned int lun = SCSI_LUN(srb);
int retval;
u8 key_format;
RTSX_DEBUGP("--%s--\n", __func__);
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
ms_cleanup_work(chip);
if (!check_card_ready(chip, lun)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_NOT_PRESENT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if ((get_lun_card(chip, lun) != MS_CARD)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_LUN_NOT_SUPPORT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if (srb->cmnd[7] != KC_MG_R_PRO) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if (!CHK_MSPRO(ms_card)) {
set_sense_type(chip, lun, SENSE_TYPE_MG_INCOMPATIBLE_MEDIUM);
TRACE_RET(chip, TRANSPORT_FAILED);
}
key_format = srb->cmnd[10] & 0x3F;
RTSX_DEBUGP("key_format = 0x%x\n", key_format);
switch (key_format) {
case KF_GET_LOC_EKB:
if ((scsi_bufflen(srb) == 0x41C) &&
(srb->cmnd[8] == 0x04) &&
(srb->cmnd[9] == 0x1C)) {
retval = mg_get_local_EKB(srb, chip);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_FAILED);
}
} else {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
break;
case KF_RSP_CHG:
if ((scsi_bufflen(srb) == 0x24) &&
(srb->cmnd[8] == 0x00) &&
(srb->cmnd[9] == 0x24)) {
retval = mg_get_rsp_chg(srb, chip);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_FAILED);
}
} else {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
break;
case KF_GET_ICV:
ms_card->mg_entry_num = srb->cmnd[5];
if ((scsi_bufflen(srb) == 0x404) &&
(srb->cmnd[8] == 0x04) &&
(srb->cmnd[9] == 0x04) &&
(srb->cmnd[2] == 0x00) &&
(srb->cmnd[3] == 0x00) &&
(srb->cmnd[4] == 0x00) &&
(srb->cmnd[5] < 32)) {
retval = mg_get_ICV(srb, chip);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_FAILED);
}
} else {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
break;
default:
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
scsi_set_resid(srb, 0);
return TRANSPORT_GOOD;
}
static int mg_send_key(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
struct ms_info *ms_card = &(chip->ms_card);
unsigned int lun = SCSI_LUN(srb);
int retval;
u8 key_format;
RTSX_DEBUGP("--%s--\n", __func__);
rtsx_disable_aspm(chip);
if (chip->ss_en && (rtsx_get_stat(chip) == RTSX_STAT_SS)) {
rtsx_exit_ss(chip);
wait_timeout(100);
}
rtsx_set_stat(chip, RTSX_STAT_RUN);
ms_cleanup_work(chip);
if (!check_card_ready(chip, lun)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_NOT_PRESENT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if (check_card_wp(chip, lun)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_WRITE_PROTECT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if ((get_lun_card(chip, lun) != MS_CARD)) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_LUN_NOT_SUPPORT);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if (srb->cmnd[7] != KC_MG_R_PRO) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
if (!CHK_MSPRO(ms_card)) {
set_sense_type(chip, lun, SENSE_TYPE_MG_INCOMPATIBLE_MEDIUM);
TRACE_RET(chip, TRANSPORT_FAILED);
}
key_format = srb->cmnd[10] & 0x3F;
RTSX_DEBUGP("key_format = 0x%x\n", key_format);
switch (key_format) {
case KF_SET_LEAF_ID:
if ((scsi_bufflen(srb) == 0x0C) &&
(srb->cmnd[8] == 0x00) &&
(srb->cmnd[9] == 0x0C)) {
retval = mg_set_leaf_id(srb, chip);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_FAILED);
}
} else {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
break;
case KF_CHG_HOST:
if ((scsi_bufflen(srb) == 0x0C) &&
(srb->cmnd[8] == 0x00) &&
(srb->cmnd[9] == 0x0C)) {
retval = mg_chg(srb, chip);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_FAILED);
}
} else {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
break;
case KF_RSP_HOST:
if ((scsi_bufflen(srb) == 0x0C) &&
(srb->cmnd[8] == 0x00) &&
(srb->cmnd[9] == 0x0C)) {
retval = mg_rsp(srb, chip);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_FAILED);
}
} else {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
break;
case KF_SET_ICV:
ms_card->mg_entry_num = srb->cmnd[5];
if ((scsi_bufflen(srb) == 0x404) &&
(srb->cmnd[8] == 0x04) &&
(srb->cmnd[9] == 0x04) &&
(srb->cmnd[2] == 0x00) &&
(srb->cmnd[3] == 0x00) &&
(srb->cmnd[4] == 0x00) &&
(srb->cmnd[5] < 32)) {
retval = mg_set_ICV(srb, chip);
if (retval != STATUS_SUCCESS) {
TRACE_RET(chip, TRANSPORT_FAILED);
}
} else {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
break;
default:
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, TRANSPORT_FAILED);
}
scsi_set_resid(srb, 0);
return TRANSPORT_GOOD;
}
#endif
int rtsx_scsi_handler(struct scsi_cmnd *srb, struct rtsx_chip *chip)
{
#ifdef SUPPORT_SD_LOCK
struct sd_info *sd_card = &(chip->sd_card);
#endif
struct ms_info *ms_card = &(chip->ms_card);
unsigned int lun = SCSI_LUN(srb);
int result;
#ifdef SUPPORT_SD_LOCK
if (sd_card->sd_erase_status) {
/* Block all SCSI command except for
* REQUEST_SENSE and rs_ppstatus
*/
if (!((srb->cmnd[0] == VENDOR_CMND) &&
(srb->cmnd[1] == SCSI_APP_CMD) &&
(srb->cmnd[2] == GET_DEV_STATUS)) &&
(srb->cmnd[0] != REQUEST_SENSE)) {
/* Logical Unit Not Ready Format in Progress */
set_sense_data(chip, lun, CUR_ERR,
0x02, 0, 0x04, 0x04, 0, 0);
TRACE_RET(chip, TRANSPORT_FAILED);
}
}
#endif
if ((get_lun_card(chip, lun) == MS_CARD) &&
(ms_card->format_status == FORMAT_IN_PROGRESS)) {
if ((srb->cmnd[0] != REQUEST_SENSE) && (srb->cmnd[0] != INQUIRY)) {
/* Logical Unit Not Ready Format in Progress */
set_sense_data(chip, lun, CUR_ERR, 0x02, 0, 0x04, 0x04,
0, (u16)(ms_card->progress));
TRACE_RET(chip, TRANSPORT_FAILED);
}
}
switch (srb->cmnd[0]) {
case READ_10:
case WRITE_10:
case READ_6:
case WRITE_6:
result = read_write(srb, chip);
#if !defined(LED_AUTO_BLINK) && !defined(REGULAR_BLINK)
led_shine(srb, chip);
#endif
break;
case TEST_UNIT_READY:
result = test_unit_ready(srb, chip);
break;
case INQUIRY:
result = inquiry(srb, chip);
break;
case READ_CAPACITY:
result = read_capacity(srb, chip);
break;
case START_STOP:
result = start_stop_unit(srb, chip);
break;
case ALLOW_MEDIUM_REMOVAL:
result = allow_medium_removal(srb, chip);
break;
case REQUEST_SENSE:
result = request_sense(srb, chip);
break;
case MODE_SENSE:
case MODE_SENSE_10:
result = mode_sense(srb, chip);
break;
case 0x23:
result = read_format_capacity(srb, chip);
break;
case VENDOR_CMND:
result = vendor_cmnd(srb, chip);
break;
case MS_SP_CMND:
result = ms_sp_cmnd(srb, chip);
break;
#ifdef SUPPORT_CPRM
case SD_PASS_THRU_MODE:
case SD_EXECUTE_NO_DATA:
case SD_EXECUTE_READ:
case SD_EXECUTE_WRITE:
case SD_GET_RSP:
case SD_HW_RST:
result = sd_extention_cmnd(srb, chip);
break;
#endif
#ifdef SUPPORT_MAGIC_GATE
case CMD_MSPRO_MG_RKEY:
result = mg_report_key(srb, chip);
break;
case CMD_MSPRO_MG_SKEY:
result = mg_send_key(srb, chip);
break;
#endif
case FORMAT_UNIT:
case MODE_SELECT:
case VERIFY:
result = TRANSPORT_GOOD;
break;
default:
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
result = TRANSPORT_FAILED;
}
return result;
}
| gpl-2.0 |
jfdsmabalot/kernel_mako | mm/huge_memory.c | 3176 | 64948 | /*
* Copyright (C) 2009 Red Hat, Inc.
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*/
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/highmem.h>
#include <linux/hugetlb.h>
#include <linux/mmu_notifier.h>
#include <linux/rmap.h>
#include <linux/swap.h>
#include <linux/mm_inline.h>
#include <linux/kthread.h>
#include <linux/khugepaged.h>
#include <linux/freezer.h>
#include <linux/mman.h>
#include <asm/tlb.h>
#include <asm/pgalloc.h>
#include "internal.h"
/*
* By default transparent hugepage support is enabled for all mappings
* and khugepaged scans all mappings. Defrag is only invoked by
* khugepaged hugepage allocations and by page faults inside
* MADV_HUGEPAGE regions to avoid the risk of slowing down short lived
* allocations.
*/
unsigned long transparent_hugepage_flags __read_mostly =
#ifdef CONFIG_TRANSPARENT_HUGEPAGE_ALWAYS
(1<<TRANSPARENT_HUGEPAGE_FLAG)|
#endif
#ifdef CONFIG_TRANSPARENT_HUGEPAGE_MADVISE
(1<<TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG)|
#endif
(1<<TRANSPARENT_HUGEPAGE_DEFRAG_FLAG)|
(1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
/* default scan 8*512 pte (or vmas) every 30 second */
static unsigned int khugepaged_pages_to_scan __read_mostly = HPAGE_PMD_NR*8;
static unsigned int khugepaged_pages_collapsed;
static unsigned int khugepaged_full_scans;
static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
/* during fragmentation poll the hugepage allocator once every minute */
static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
static struct task_struct *khugepaged_thread __read_mostly;
static DEFINE_MUTEX(khugepaged_mutex);
static DEFINE_SPINLOCK(khugepaged_mm_lock);
static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
/*
* default collapse hugepages if there is at least one pte mapped like
* it would have happened if the vma was large enough during page
* fault.
*/
static unsigned int khugepaged_max_ptes_none __read_mostly = HPAGE_PMD_NR-1;
static int khugepaged(void *none);
static int mm_slots_hash_init(void);
static int khugepaged_slab_init(void);
static void khugepaged_slab_free(void);
#define MM_SLOTS_HASH_HEADS 1024
static struct hlist_head *mm_slots_hash __read_mostly;
static struct kmem_cache *mm_slot_cache __read_mostly;
/**
* struct mm_slot - hash lookup from mm to mm_slot
* @hash: hash collision list
* @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
* @mm: the mm that this information is valid for
*/
struct mm_slot {
struct hlist_node hash;
struct list_head mm_node;
struct mm_struct *mm;
};
/**
* struct khugepaged_scan - cursor for scanning
* @mm_head: the head of the mm list to scan
* @mm_slot: the current mm_slot we are scanning
* @address: the next address inside that to be scanned
*
* There is only the one khugepaged_scan instance of this cursor structure.
*/
struct khugepaged_scan {
struct list_head mm_head;
struct mm_slot *mm_slot;
unsigned long address;
};
static struct khugepaged_scan khugepaged_scan = {
.mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
};
static int set_recommended_min_free_kbytes(void)
{
struct zone *zone;
int nr_zones = 0;
unsigned long recommended_min;
extern int min_free_kbytes;
if (!test_bit(TRANSPARENT_HUGEPAGE_FLAG,
&transparent_hugepage_flags) &&
!test_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
&transparent_hugepage_flags))
return 0;
for_each_populated_zone(zone)
nr_zones++;
/* Make sure at least 2 hugepages are free for MIGRATE_RESERVE */
recommended_min = pageblock_nr_pages * nr_zones * 2;
/*
* Make sure that on average at least two pageblocks are almost free
* of another type, one for a migratetype to fall back to and a
* second to avoid subsequent fallbacks of other types There are 3
* MIGRATE_TYPES we care about.
*/
recommended_min += pageblock_nr_pages * nr_zones *
MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
/* don't ever allow to reserve more than 5% of the lowmem */
recommended_min = min(recommended_min,
(unsigned long) nr_free_buffer_pages() / 20);
recommended_min <<= (PAGE_SHIFT-10);
if (recommended_min > min_free_kbytes)
min_free_kbytes = recommended_min;
setup_per_zone_wmarks();
return 0;
}
late_initcall(set_recommended_min_free_kbytes);
static int start_khugepaged(void)
{
int err = 0;
if (khugepaged_enabled()) {
int wakeup;
if (unlikely(!mm_slot_cache || !mm_slots_hash)) {
err = -ENOMEM;
goto out;
}
mutex_lock(&khugepaged_mutex);
if (!khugepaged_thread)
khugepaged_thread = kthread_run(khugepaged, NULL,
"khugepaged");
if (unlikely(IS_ERR(khugepaged_thread))) {
printk(KERN_ERR
"khugepaged: kthread_run(khugepaged) failed\n");
err = PTR_ERR(khugepaged_thread);
khugepaged_thread = NULL;
}
wakeup = !list_empty(&khugepaged_scan.mm_head);
mutex_unlock(&khugepaged_mutex);
if (wakeup)
wake_up_interruptible(&khugepaged_wait);
set_recommended_min_free_kbytes();
} else
/* wakeup to exit */
wake_up_interruptible(&khugepaged_wait);
out:
return err;
}
#ifdef CONFIG_SYSFS
static ssize_t double_flag_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf,
enum transparent_hugepage_flag enabled,
enum transparent_hugepage_flag req_madv)
{
if (test_bit(enabled, &transparent_hugepage_flags)) {
VM_BUG_ON(test_bit(req_madv, &transparent_hugepage_flags));
return sprintf(buf, "[always] madvise never\n");
} else if (test_bit(req_madv, &transparent_hugepage_flags))
return sprintf(buf, "always [madvise] never\n");
else
return sprintf(buf, "always madvise [never]\n");
}
static ssize_t double_flag_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count,
enum transparent_hugepage_flag enabled,
enum transparent_hugepage_flag req_madv)
{
if (!memcmp("always", buf,
min(sizeof("always")-1, count))) {
set_bit(enabled, &transparent_hugepage_flags);
clear_bit(req_madv, &transparent_hugepage_flags);
} else if (!memcmp("madvise", buf,
min(sizeof("madvise")-1, count))) {
clear_bit(enabled, &transparent_hugepage_flags);
set_bit(req_madv, &transparent_hugepage_flags);
} else if (!memcmp("never", buf,
min(sizeof("never")-1, count))) {
clear_bit(enabled, &transparent_hugepage_flags);
clear_bit(req_madv, &transparent_hugepage_flags);
} else
return -EINVAL;
return count;
}
static ssize_t enabled_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return double_flag_show(kobj, attr, buf,
TRANSPARENT_HUGEPAGE_FLAG,
TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG);
}
static ssize_t enabled_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
ssize_t ret;
ret = double_flag_store(kobj, attr, buf, count,
TRANSPARENT_HUGEPAGE_FLAG,
TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG);
if (ret > 0) {
int err = start_khugepaged();
if (err)
ret = err;
}
if (ret > 0 &&
(test_bit(TRANSPARENT_HUGEPAGE_FLAG,
&transparent_hugepage_flags) ||
test_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
&transparent_hugepage_flags)))
set_recommended_min_free_kbytes();
return ret;
}
static struct kobj_attribute enabled_attr =
__ATTR(enabled, 0644, enabled_show, enabled_store);
static ssize_t single_flag_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf,
enum transparent_hugepage_flag flag)
{
return sprintf(buf, "%d\n",
!!test_bit(flag, &transparent_hugepage_flags));
}
static ssize_t single_flag_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count,
enum transparent_hugepage_flag flag)
{
unsigned long value;
int ret;
ret = kstrtoul(buf, 10, &value);
if (ret < 0)
return ret;
if (value > 1)
return -EINVAL;
if (value)
set_bit(flag, &transparent_hugepage_flags);
else
clear_bit(flag, &transparent_hugepage_flags);
return count;
}
/*
* Currently defrag only disables __GFP_NOWAIT for allocation. A blind
* __GFP_REPEAT is too aggressive, it's never worth swapping tons of
* memory just to allocate one more hugepage.
*/
static ssize_t defrag_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return double_flag_show(kobj, attr, buf,
TRANSPARENT_HUGEPAGE_DEFRAG_FLAG,
TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG);
}
static ssize_t defrag_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
return double_flag_store(kobj, attr, buf, count,
TRANSPARENT_HUGEPAGE_DEFRAG_FLAG,
TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG);
}
static struct kobj_attribute defrag_attr =
__ATTR(defrag, 0644, defrag_show, defrag_store);
#ifdef CONFIG_DEBUG_VM
static ssize_t debug_cow_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return single_flag_show(kobj, attr, buf,
TRANSPARENT_HUGEPAGE_DEBUG_COW_FLAG);
}
static ssize_t debug_cow_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
return single_flag_store(kobj, attr, buf, count,
TRANSPARENT_HUGEPAGE_DEBUG_COW_FLAG);
}
static struct kobj_attribute debug_cow_attr =
__ATTR(debug_cow, 0644, debug_cow_show, debug_cow_store);
#endif /* CONFIG_DEBUG_VM */
static struct attribute *hugepage_attr[] = {
&enabled_attr.attr,
&defrag_attr.attr,
#ifdef CONFIG_DEBUG_VM
&debug_cow_attr.attr,
#endif
NULL,
};
static struct attribute_group hugepage_attr_group = {
.attrs = hugepage_attr,
};
static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
return sprintf(buf, "%u\n", khugepaged_scan_sleep_millisecs);
}
static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
unsigned long msecs;
int err;
err = strict_strtoul(buf, 10, &msecs);
if (err || msecs > UINT_MAX)
return -EINVAL;
khugepaged_scan_sleep_millisecs = msecs;
wake_up_interruptible(&khugepaged_wait);
return count;
}
static struct kobj_attribute scan_sleep_millisecs_attr =
__ATTR(scan_sleep_millisecs, 0644, scan_sleep_millisecs_show,
scan_sleep_millisecs_store);
static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
return sprintf(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
}
static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
unsigned long msecs;
int err;
err = strict_strtoul(buf, 10, &msecs);
if (err || msecs > UINT_MAX)
return -EINVAL;
khugepaged_alloc_sleep_millisecs = msecs;
wake_up_interruptible(&khugepaged_wait);
return count;
}
static struct kobj_attribute alloc_sleep_millisecs_attr =
__ATTR(alloc_sleep_millisecs, 0644, alloc_sleep_millisecs_show,
alloc_sleep_millisecs_store);
static ssize_t pages_to_scan_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
return sprintf(buf, "%u\n", khugepaged_pages_to_scan);
}
static ssize_t pages_to_scan_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
int err;
unsigned long pages;
err = strict_strtoul(buf, 10, &pages);
if (err || !pages || pages > UINT_MAX)
return -EINVAL;
khugepaged_pages_to_scan = pages;
return count;
}
static struct kobj_attribute pages_to_scan_attr =
__ATTR(pages_to_scan, 0644, pages_to_scan_show,
pages_to_scan_store);
static ssize_t pages_collapsed_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
return sprintf(buf, "%u\n", khugepaged_pages_collapsed);
}
static struct kobj_attribute pages_collapsed_attr =
__ATTR_RO(pages_collapsed);
static ssize_t full_scans_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
return sprintf(buf, "%u\n", khugepaged_full_scans);
}
static struct kobj_attribute full_scans_attr =
__ATTR_RO(full_scans);
static ssize_t khugepaged_defrag_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return single_flag_show(kobj, attr, buf,
TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
}
static ssize_t khugepaged_defrag_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
return single_flag_store(kobj, attr, buf, count,
TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
}
static struct kobj_attribute khugepaged_defrag_attr =
__ATTR(defrag, 0644, khugepaged_defrag_show,
khugepaged_defrag_store);
/*
* max_ptes_none controls if khugepaged should collapse hugepages over
* any unmapped ptes in turn potentially increasing the memory
* footprint of the vmas. When max_ptes_none is 0 khugepaged will not
* reduce the available free memory in the system as it
* runs. Increasing max_ptes_none will instead potentially reduce the
* free memory in the system during the khugepaged scan.
*/
static ssize_t khugepaged_max_ptes_none_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
return sprintf(buf, "%u\n", khugepaged_max_ptes_none);
}
static ssize_t khugepaged_max_ptes_none_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
int err;
unsigned long max_ptes_none;
err = strict_strtoul(buf, 10, &max_ptes_none);
if (err || max_ptes_none > HPAGE_PMD_NR-1)
return -EINVAL;
khugepaged_max_ptes_none = max_ptes_none;
return count;
}
static struct kobj_attribute khugepaged_max_ptes_none_attr =
__ATTR(max_ptes_none, 0644, khugepaged_max_ptes_none_show,
khugepaged_max_ptes_none_store);
static struct attribute *khugepaged_attr[] = {
&khugepaged_defrag_attr.attr,
&khugepaged_max_ptes_none_attr.attr,
&pages_to_scan_attr.attr,
&pages_collapsed_attr.attr,
&full_scans_attr.attr,
&scan_sleep_millisecs_attr.attr,
&alloc_sleep_millisecs_attr.attr,
NULL,
};
static struct attribute_group khugepaged_attr_group = {
.attrs = khugepaged_attr,
.name = "khugepaged",
};
static int __init hugepage_init_sysfs(struct kobject **hugepage_kobj)
{
int err;
*hugepage_kobj = kobject_create_and_add("transparent_hugepage", mm_kobj);
if (unlikely(!*hugepage_kobj)) {
printk(KERN_ERR "hugepage: failed kobject create\n");
return -ENOMEM;
}
err = sysfs_create_group(*hugepage_kobj, &hugepage_attr_group);
if (err) {
printk(KERN_ERR "hugepage: failed register hugeage group\n");
goto delete_obj;
}
err = sysfs_create_group(*hugepage_kobj, &khugepaged_attr_group);
if (err) {
printk(KERN_ERR "hugepage: failed register hugeage group\n");
goto remove_hp_group;
}
return 0;
remove_hp_group:
sysfs_remove_group(*hugepage_kobj, &hugepage_attr_group);
delete_obj:
kobject_put(*hugepage_kobj);
return err;
}
static void __init hugepage_exit_sysfs(struct kobject *hugepage_kobj)
{
sysfs_remove_group(hugepage_kobj, &khugepaged_attr_group);
sysfs_remove_group(hugepage_kobj, &hugepage_attr_group);
kobject_put(hugepage_kobj);
}
#else
static inline int hugepage_init_sysfs(struct kobject **hugepage_kobj)
{
return 0;
}
static inline void hugepage_exit_sysfs(struct kobject *hugepage_kobj)
{
}
#endif /* CONFIG_SYSFS */
static int __init hugepage_init(void)
{
int err;
struct kobject *hugepage_kobj;
if (!has_transparent_hugepage()) {
transparent_hugepage_flags = 0;
return -EINVAL;
}
err = hugepage_init_sysfs(&hugepage_kobj);
if (err)
return err;
err = khugepaged_slab_init();
if (err)
goto out;
err = mm_slots_hash_init();
if (err) {
khugepaged_slab_free();
goto out;
}
/*
* By default disable transparent hugepages on smaller systems,
* where the extra memory used could hurt more than TLB overhead
* is likely to save. The admin can still enable it through /sys.
*/
if (totalram_pages < (512 << (20 - PAGE_SHIFT)))
transparent_hugepage_flags = 0;
start_khugepaged();
set_recommended_min_free_kbytes();
return 0;
out:
hugepage_exit_sysfs(hugepage_kobj);
return err;
}
module_init(hugepage_init)
static int __init setup_transparent_hugepage(char *str)
{
int ret = 0;
if (!str)
goto out;
if (!strcmp(str, "always")) {
set_bit(TRANSPARENT_HUGEPAGE_FLAG,
&transparent_hugepage_flags);
clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
&transparent_hugepage_flags);
ret = 1;
} else if (!strcmp(str, "madvise")) {
clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
&transparent_hugepage_flags);
set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
&transparent_hugepage_flags);
ret = 1;
} else if (!strcmp(str, "never")) {
clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
&transparent_hugepage_flags);
clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
&transparent_hugepage_flags);
ret = 1;
}
out:
if (!ret)
printk(KERN_WARNING
"transparent_hugepage= cannot parse, ignored\n");
return ret;
}
__setup("transparent_hugepage=", setup_transparent_hugepage);
static void prepare_pmd_huge_pte(pgtable_t pgtable,
struct mm_struct *mm)
{
assert_spin_locked(&mm->page_table_lock);
/* FIFO */
if (!mm->pmd_huge_pte)
INIT_LIST_HEAD(&pgtable->lru);
else
list_add(&pgtable->lru, &mm->pmd_huge_pte->lru);
mm->pmd_huge_pte = pgtable;
}
static inline pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma)
{
if (likely(vma->vm_flags & VM_WRITE))
pmd = pmd_mkwrite(pmd);
return pmd;
}
static int __do_huge_pmd_anonymous_page(struct mm_struct *mm,
struct vm_area_struct *vma,
unsigned long haddr, pmd_t *pmd,
struct page *page)
{
int ret = 0;
pgtable_t pgtable;
VM_BUG_ON(!PageCompound(page));
pgtable = pte_alloc_one(mm, haddr);
if (unlikely(!pgtable)) {
mem_cgroup_uncharge_page(page);
put_page(page);
return VM_FAULT_OOM;
}
clear_huge_page(page, haddr, HPAGE_PMD_NR);
__SetPageUptodate(page);
spin_lock(&mm->page_table_lock);
if (unlikely(!pmd_none(*pmd))) {
spin_unlock(&mm->page_table_lock);
mem_cgroup_uncharge_page(page);
put_page(page);
pte_free(mm, pgtable);
} else {
pmd_t entry;
entry = mk_pmd(page, vma->vm_page_prot);
entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
entry = pmd_mkhuge(entry);
/*
* The spinlocking to take the lru_lock inside
* page_add_new_anon_rmap() acts as a full memory
* barrier to be sure clear_huge_page writes become
* visible after the set_pmd_at() write.
*/
page_add_new_anon_rmap(page, vma, haddr);
set_pmd_at(mm, haddr, pmd, entry);
prepare_pmd_huge_pte(pgtable, mm);
add_mm_counter(mm, MM_ANONPAGES, HPAGE_PMD_NR);
mm->nr_ptes++;
spin_unlock(&mm->page_table_lock);
}
return ret;
}
static inline gfp_t alloc_hugepage_gfpmask(int defrag, gfp_t extra_gfp)
{
return (GFP_TRANSHUGE & ~(defrag ? 0 : __GFP_WAIT)) | extra_gfp;
}
static inline struct page *alloc_hugepage_vma(int defrag,
struct vm_area_struct *vma,
unsigned long haddr, int nd,
gfp_t extra_gfp)
{
return alloc_pages_vma(alloc_hugepage_gfpmask(defrag, extra_gfp),
HPAGE_PMD_ORDER, vma, haddr, nd);
}
#ifndef CONFIG_NUMA
static inline struct page *alloc_hugepage(int defrag)
{
return alloc_pages(alloc_hugepage_gfpmask(defrag, 0),
HPAGE_PMD_ORDER);
}
#endif
int do_huge_pmd_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma,
unsigned long address, pmd_t *pmd,
unsigned int flags)
{
struct page *page;
unsigned long haddr = address & HPAGE_PMD_MASK;
pte_t *pte;
if (haddr >= vma->vm_start && haddr + HPAGE_PMD_SIZE <= vma->vm_end) {
if (unlikely(anon_vma_prepare(vma)))
return VM_FAULT_OOM;
if (unlikely(khugepaged_enter(vma)))
return VM_FAULT_OOM;
page = alloc_hugepage_vma(transparent_hugepage_defrag(vma),
vma, haddr, numa_node_id(), 0);
if (unlikely(!page)) {
count_vm_event(THP_FAULT_FALLBACK);
goto out;
}
count_vm_event(THP_FAULT_ALLOC);
if (unlikely(mem_cgroup_newpage_charge(page, mm, GFP_KERNEL))) {
put_page(page);
goto out;
}
return __do_huge_pmd_anonymous_page(mm, vma, haddr, pmd, page);
}
out:
/*
* Use __pte_alloc instead of pte_alloc_map, because we can't
* run pte_offset_map on the pmd, if an huge pmd could
* materialize from under us from a different thread.
*/
if (unlikely(__pte_alloc(mm, vma, pmd, address)))
return VM_FAULT_OOM;
/* if an huge pmd materialized from under us just retry later */
if (unlikely(pmd_trans_huge(*pmd)))
return 0;
/*
* A regular pmd is established and it can't morph into a huge pmd
* from under us anymore at this point because we hold the mmap_sem
* read mode and khugepaged takes it in write mode. So now it's
* safe to run pte_offset_map().
*/
pte = pte_offset_map(pmd, address);
return handle_pte_fault(mm, vma, address, pte, pmd, flags);
}
int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm,
pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
struct vm_area_struct *vma)
{
struct page *src_page;
pmd_t pmd;
pgtable_t pgtable;
int ret;
ret = -ENOMEM;
pgtable = pte_alloc_one(dst_mm, addr);
if (unlikely(!pgtable))
goto out;
spin_lock(&dst_mm->page_table_lock);
spin_lock_nested(&src_mm->page_table_lock, SINGLE_DEPTH_NESTING);
ret = -EAGAIN;
pmd = *src_pmd;
if (unlikely(!pmd_trans_huge(pmd))) {
pte_free(dst_mm, pgtable);
goto out_unlock;
}
if (unlikely(pmd_trans_splitting(pmd))) {
/* split huge page running from under us */
spin_unlock(&src_mm->page_table_lock);
spin_unlock(&dst_mm->page_table_lock);
pte_free(dst_mm, pgtable);
wait_split_huge_page(vma->anon_vma, src_pmd); /* src_vma */
goto out;
}
src_page = pmd_page(pmd);
VM_BUG_ON(!PageHead(src_page));
get_page(src_page);
page_dup_rmap(src_page);
add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
pmdp_set_wrprotect(src_mm, addr, src_pmd);
pmd = pmd_mkold(pmd_wrprotect(pmd));
set_pmd_at(dst_mm, addr, dst_pmd, pmd);
prepare_pmd_huge_pte(pgtable, dst_mm);
dst_mm->nr_ptes++;
ret = 0;
out_unlock:
spin_unlock(&src_mm->page_table_lock);
spin_unlock(&dst_mm->page_table_lock);
out:
return ret;
}
/* no "address" argument so destroys page coloring of some arch */
pgtable_t get_pmd_huge_pte(struct mm_struct *mm)
{
pgtable_t pgtable;
assert_spin_locked(&mm->page_table_lock);
/* FIFO */
pgtable = mm->pmd_huge_pte;
if (list_empty(&pgtable->lru))
mm->pmd_huge_pte = NULL;
else {
mm->pmd_huge_pte = list_entry(pgtable->lru.next,
struct page, lru);
list_del(&pgtable->lru);
}
return pgtable;
}
static int do_huge_pmd_wp_page_fallback(struct mm_struct *mm,
struct vm_area_struct *vma,
unsigned long address,
pmd_t *pmd, pmd_t orig_pmd,
struct page *page,
unsigned long haddr)
{
pgtable_t pgtable;
pmd_t _pmd;
int ret = 0, i;
struct page **pages;
pages = kmalloc(sizeof(struct page *) * HPAGE_PMD_NR,
GFP_KERNEL);
if (unlikely(!pages)) {
ret |= VM_FAULT_OOM;
goto out;
}
for (i = 0; i < HPAGE_PMD_NR; i++) {
pages[i] = alloc_page_vma_node(GFP_HIGHUSER_MOVABLE |
__GFP_OTHER_NODE,
vma, address, page_to_nid(page));
if (unlikely(!pages[i] ||
mem_cgroup_newpage_charge(pages[i], mm,
GFP_KERNEL))) {
if (pages[i])
put_page(pages[i]);
mem_cgroup_uncharge_start();
while (--i >= 0) {
mem_cgroup_uncharge_page(pages[i]);
put_page(pages[i]);
}
mem_cgroup_uncharge_end();
kfree(pages);
ret |= VM_FAULT_OOM;
goto out;
}
}
for (i = 0; i < HPAGE_PMD_NR; i++) {
copy_user_highpage(pages[i], page + i,
haddr + PAGE_SIZE * i, vma);
__SetPageUptodate(pages[i]);
cond_resched();
}
spin_lock(&mm->page_table_lock);
if (unlikely(!pmd_same(*pmd, orig_pmd)))
goto out_free_pages;
VM_BUG_ON(!PageHead(page));
pmdp_clear_flush_notify(vma, haddr, pmd);
/* leave pmd empty until pte is filled */
pgtable = get_pmd_huge_pte(mm);
pmd_populate(mm, &_pmd, pgtable);
for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
pte_t *pte, entry;
entry = mk_pte(pages[i], vma->vm_page_prot);
entry = maybe_mkwrite(pte_mkdirty(entry), vma);
page_add_new_anon_rmap(pages[i], vma, haddr);
pte = pte_offset_map(&_pmd, haddr);
VM_BUG_ON(!pte_none(*pte));
set_pte_at(mm, haddr, pte, entry);
pte_unmap(pte);
}
kfree(pages);
smp_wmb(); /* make pte visible before pmd */
pmd_populate(mm, pmd, pgtable);
page_remove_rmap(page);
spin_unlock(&mm->page_table_lock);
ret |= VM_FAULT_WRITE;
put_page(page);
out:
return ret;
out_free_pages:
spin_unlock(&mm->page_table_lock);
mem_cgroup_uncharge_start();
for (i = 0; i < HPAGE_PMD_NR; i++) {
mem_cgroup_uncharge_page(pages[i]);
put_page(pages[i]);
}
mem_cgroup_uncharge_end();
kfree(pages);
goto out;
}
int do_huge_pmd_wp_page(struct mm_struct *mm, struct vm_area_struct *vma,
unsigned long address, pmd_t *pmd, pmd_t orig_pmd)
{
int ret = 0;
struct page *page, *new_page;
unsigned long haddr;
VM_BUG_ON(!vma->anon_vma);
spin_lock(&mm->page_table_lock);
if (unlikely(!pmd_same(*pmd, orig_pmd)))
goto out_unlock;
page = pmd_page(orig_pmd);
VM_BUG_ON(!PageCompound(page) || !PageHead(page));
haddr = address & HPAGE_PMD_MASK;
if (page_mapcount(page) == 1) {
pmd_t entry;
entry = pmd_mkyoung(orig_pmd);
entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
if (pmdp_set_access_flags(vma, haddr, pmd, entry, 1))
update_mmu_cache(vma, address, entry);
ret |= VM_FAULT_WRITE;
goto out_unlock;
}
get_page(page);
spin_unlock(&mm->page_table_lock);
if (transparent_hugepage_enabled(vma) &&
!transparent_hugepage_debug_cow())
new_page = alloc_hugepage_vma(transparent_hugepage_defrag(vma),
vma, haddr, numa_node_id(), 0);
else
new_page = NULL;
if (unlikely(!new_page)) {
count_vm_event(THP_FAULT_FALLBACK);
ret = do_huge_pmd_wp_page_fallback(mm, vma, address,
pmd, orig_pmd, page, haddr);
put_page(page);
goto out;
}
count_vm_event(THP_FAULT_ALLOC);
if (unlikely(mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL))) {
put_page(new_page);
put_page(page);
ret |= VM_FAULT_OOM;
goto out;
}
copy_user_huge_page(new_page, page, haddr, vma, HPAGE_PMD_NR);
__SetPageUptodate(new_page);
spin_lock(&mm->page_table_lock);
put_page(page);
if (unlikely(!pmd_same(*pmd, orig_pmd))) {
mem_cgroup_uncharge_page(new_page);
put_page(new_page);
} else {
pmd_t entry;
VM_BUG_ON(!PageHead(page));
entry = mk_pmd(new_page, vma->vm_page_prot);
entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
entry = pmd_mkhuge(entry);
pmdp_clear_flush_notify(vma, haddr, pmd);
page_add_new_anon_rmap(new_page, vma, haddr);
set_pmd_at(mm, haddr, pmd, entry);
update_mmu_cache(vma, address, entry);
page_remove_rmap(page);
put_page(page);
ret |= VM_FAULT_WRITE;
}
out_unlock:
spin_unlock(&mm->page_table_lock);
out:
return ret;
}
struct page *follow_trans_huge_pmd(struct mm_struct *mm,
unsigned long addr,
pmd_t *pmd,
unsigned int flags)
{
struct page *page = NULL;
assert_spin_locked(&mm->page_table_lock);
if (flags & FOLL_WRITE && !pmd_write(*pmd))
goto out;
page = pmd_page(*pmd);
VM_BUG_ON(!PageHead(page));
if (flags & FOLL_TOUCH) {
pmd_t _pmd;
/*
* We should set the dirty bit only for FOLL_WRITE but
* for now the dirty bit in the pmd is meaningless.
* And if the dirty bit will become meaningful and
* we'll only set it with FOLL_WRITE, an atomic
* set_bit will be required on the pmd to set the
* young bit, instead of the current set_pmd_at.
*/
_pmd = pmd_mkyoung(pmd_mkdirty(*pmd));
set_pmd_at(mm, addr & HPAGE_PMD_MASK, pmd, _pmd);
}
page += (addr & ~HPAGE_PMD_MASK) >> PAGE_SHIFT;
VM_BUG_ON(!PageCompound(page));
if (flags & FOLL_GET)
get_page_foll(page);
out:
return page;
}
int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
pmd_t *pmd, unsigned long addr)
{
int ret = 0;
if (__pmd_trans_huge_lock(pmd, vma) == 1) {
struct page *page;
pgtable_t pgtable;
pgtable = get_pmd_huge_pte(tlb->mm);
page = pmd_page(*pmd);
pmd_clear(pmd);
tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
page_remove_rmap(page);
VM_BUG_ON(page_mapcount(page) < 0);
add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR);
VM_BUG_ON(!PageHead(page));
tlb->mm->nr_ptes--;
spin_unlock(&tlb->mm->page_table_lock);
tlb_remove_page(tlb, page);
pte_free(tlb->mm, pgtable);
ret = 1;
}
return ret;
}
int mincore_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
unsigned long addr, unsigned long end,
unsigned char *vec)
{
int ret = 0;
if (__pmd_trans_huge_lock(pmd, vma) == 1) {
/*
* All logical pages in the range are present
* if backed by a huge page.
*/
spin_unlock(&vma->vm_mm->page_table_lock);
memset(vec, 1, (end - addr) >> PAGE_SHIFT);
ret = 1;
}
return ret;
}
int move_huge_pmd(struct vm_area_struct *vma, struct vm_area_struct *new_vma,
unsigned long old_addr,
unsigned long new_addr, unsigned long old_end,
pmd_t *old_pmd, pmd_t *new_pmd)
{
int ret = 0;
pmd_t pmd;
struct mm_struct *mm = vma->vm_mm;
if ((old_addr & ~HPAGE_PMD_MASK) ||
(new_addr & ~HPAGE_PMD_MASK) ||
old_end - old_addr < HPAGE_PMD_SIZE ||
(new_vma->vm_flags & VM_NOHUGEPAGE))
goto out;
/*
* The destination pmd shouldn't be established, free_pgtables()
* should have release it.
*/
if (WARN_ON(!pmd_none(*new_pmd))) {
VM_BUG_ON(pmd_trans_huge(*new_pmd));
goto out;
}
ret = __pmd_trans_huge_lock(old_pmd, vma);
if (ret == 1) {
pmd = pmdp_get_and_clear(mm, old_addr, old_pmd);
VM_BUG_ON(!pmd_none(*new_pmd));
set_pmd_at(mm, new_addr, new_pmd, pmd);
spin_unlock(&mm->page_table_lock);
}
out:
return ret;
}
int change_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
unsigned long addr, pgprot_t newprot)
{
struct mm_struct *mm = vma->vm_mm;
int ret = 0;
if (__pmd_trans_huge_lock(pmd, vma) == 1) {
pmd_t entry;
entry = pmdp_get_and_clear(mm, addr, pmd);
entry = pmd_modify(entry, newprot);
set_pmd_at(mm, addr, pmd, entry);
spin_unlock(&vma->vm_mm->page_table_lock);
ret = 1;
}
return ret;
}
/*
* Returns 1 if a given pmd maps a stable (not under splitting) thp.
* Returns -1 if it maps a thp under splitting. Returns 0 otherwise.
*
* Note that if it returns 1, this routine returns without unlocking page
* table locks. So callers must unlock them.
*/
int __pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma)
{
spin_lock(&vma->vm_mm->page_table_lock);
if (likely(pmd_trans_huge(*pmd))) {
if (unlikely(pmd_trans_splitting(*pmd))) {
spin_unlock(&vma->vm_mm->page_table_lock);
wait_split_huge_page(vma->anon_vma, pmd);
return -1;
} else {
/* Thp mapped by 'pmd' is stable, so we can
* handle it as it is. */
return 1;
}
}
spin_unlock(&vma->vm_mm->page_table_lock);
return 0;
}
pmd_t *page_check_address_pmd(struct page *page,
struct mm_struct *mm,
unsigned long address,
enum page_check_address_pmd_flag flag)
{
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd, *ret = NULL;
if (address & ~HPAGE_PMD_MASK)
goto out;
pgd = pgd_offset(mm, address);
if (!pgd_present(*pgd))
goto out;
pud = pud_offset(pgd, address);
if (!pud_present(*pud))
goto out;
pmd = pmd_offset(pud, address);
if (pmd_none(*pmd))
goto out;
if (pmd_page(*pmd) != page)
goto out;
/*
* split_vma() may create temporary aliased mappings. There is
* no risk as long as all huge pmd are found and have their
* splitting bit set before __split_huge_page_refcount
* runs. Finding the same huge pmd more than once during the
* same rmap walk is not a problem.
*/
if (flag == PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG &&
pmd_trans_splitting(*pmd))
goto out;
if (pmd_trans_huge(*pmd)) {
VM_BUG_ON(flag == PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG &&
!pmd_trans_splitting(*pmd));
ret = pmd;
}
out:
return ret;
}
static int __split_huge_page_splitting(struct page *page,
struct vm_area_struct *vma,
unsigned long address)
{
struct mm_struct *mm = vma->vm_mm;
pmd_t *pmd;
int ret = 0;
spin_lock(&mm->page_table_lock);
pmd = page_check_address_pmd(page, mm, address,
PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG);
if (pmd) {
/*
* We can't temporarily set the pmd to null in order
* to split it, the pmd must remain marked huge at all
* times or the VM won't take the pmd_trans_huge paths
* and it won't wait on the anon_vma->root->mutex to
* serialize against split_huge_page*.
*/
pmdp_splitting_flush_notify(vma, address, pmd);
ret = 1;
}
spin_unlock(&mm->page_table_lock);
return ret;
}
static void __split_huge_page_refcount(struct page *page)
{
int i;
struct zone *zone = page_zone(page);
int tail_count = 0;
/* prevent PageLRU to go away from under us, and freeze lru stats */
spin_lock_irq(&zone->lru_lock);
compound_lock(page);
/* complete memcg works before add pages to LRU */
mem_cgroup_split_huge_fixup(page);
for (i = HPAGE_PMD_NR - 1; i >= 1; i--) {
struct page *page_tail = page + i;
/* tail_page->_mapcount cannot change */
BUG_ON(page_mapcount(page_tail) < 0);
tail_count += page_mapcount(page_tail);
/* check for overflow */
BUG_ON(tail_count < 0);
BUG_ON(atomic_read(&page_tail->_count) != 0);
/*
* tail_page->_count is zero and not changing from
* under us. But get_page_unless_zero() may be running
* from under us on the tail_page. If we used
* atomic_set() below instead of atomic_add(), we
* would then run atomic_set() concurrently with
* get_page_unless_zero(), and atomic_set() is
* implemented in C not using locked ops. spin_unlock
* on x86 sometime uses locked ops because of PPro
* errata 66, 92, so unless somebody can guarantee
* atomic_set() here would be safe on all archs (and
* not only on x86), it's safer to use atomic_add().
*/
atomic_add(page_mapcount(page) + page_mapcount(page_tail) + 1,
&page_tail->_count);
/* after clearing PageTail the gup refcount can be released */
smp_mb();
/*
* retain hwpoison flag of the poisoned tail page:
* fix for the unsuitable process killed on Guest Machine(KVM)
* by the memory-failure.
*/
page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP | __PG_HWPOISON;
page_tail->flags |= (page->flags &
((1L << PG_referenced) |
(1L << PG_swapbacked) |
(1L << PG_mlocked) |
(1L << PG_uptodate)));
page_tail->flags |= (1L << PG_dirty);
/* clear PageTail before overwriting first_page */
smp_wmb();
/*
* __split_huge_page_splitting() already set the
* splitting bit in all pmd that could map this
* hugepage, that will ensure no CPU can alter the
* mapcount on the head page. The mapcount is only
* accounted in the head page and it has to be
* transferred to all tail pages in the below code. So
* for this code to be safe, the split the mapcount
* can't change. But that doesn't mean userland can't
* keep changing and reading the page contents while
* we transfer the mapcount, so the pmd splitting
* status is achieved setting a reserved bit in the
* pmd, not by clearing the present bit.
*/
page_tail->_mapcount = page->_mapcount;
BUG_ON(page_tail->mapping);
page_tail->mapping = page->mapping;
page_tail->index = page->index + i;
BUG_ON(!PageAnon(page_tail));
BUG_ON(!PageUptodate(page_tail));
BUG_ON(!PageDirty(page_tail));
BUG_ON(!PageSwapBacked(page_tail));
lru_add_page_tail(zone, page, page_tail);
}
atomic_sub(tail_count, &page->_count);
BUG_ON(atomic_read(&page->_count) <= 0);
__dec_zone_page_state(page, NR_ANON_TRANSPARENT_HUGEPAGES);
__mod_zone_page_state(zone, NR_ANON_PAGES, HPAGE_PMD_NR);
ClearPageCompound(page);
compound_unlock(page);
spin_unlock_irq(&zone->lru_lock);
for (i = 1; i < HPAGE_PMD_NR; i++) {
struct page *page_tail = page + i;
BUG_ON(page_count(page_tail) <= 0);
/*
* Tail pages may be freed if there wasn't any mapping
* like if add_to_swap() is running on a lru page that
* had its mapping zapped. And freeing these pages
* requires taking the lru_lock so we do the put_page
* of the tail pages after the split is complete.
*/
put_page(page_tail);
}
/*
* Only the head page (now become a regular page) is required
* to be pinned by the caller.
*/
BUG_ON(page_count(page) <= 0);
}
static int __split_huge_page_map(struct page *page,
struct vm_area_struct *vma,
unsigned long address)
{
struct mm_struct *mm = vma->vm_mm;
pmd_t *pmd, _pmd;
int ret = 0, i;
pgtable_t pgtable;
unsigned long haddr;
spin_lock(&mm->page_table_lock);
pmd = page_check_address_pmd(page, mm, address,
PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG);
if (pmd) {
pgtable = get_pmd_huge_pte(mm);
pmd_populate(mm, &_pmd, pgtable);
for (i = 0, haddr = address; i < HPAGE_PMD_NR;
i++, haddr += PAGE_SIZE) {
pte_t *pte, entry;
BUG_ON(PageCompound(page+i));
entry = mk_pte(page + i, vma->vm_page_prot);
entry = maybe_mkwrite(pte_mkdirty(entry), vma);
if (!pmd_write(*pmd))
entry = pte_wrprotect(entry);
else
BUG_ON(page_mapcount(page) != 1);
if (!pmd_young(*pmd))
entry = pte_mkold(entry);
pte = pte_offset_map(&_pmd, haddr);
BUG_ON(!pte_none(*pte));
set_pte_at(mm, haddr, pte, entry);
pte_unmap(pte);
}
smp_wmb(); /* make pte visible before pmd */
/*
* Up to this point the pmd is present and huge and
* userland has the whole access to the hugepage
* during the split (which happens in place). If we
* overwrite the pmd with the not-huge version
* pointing to the pte here (which of course we could
* if all CPUs were bug free), userland could trigger
* a small page size TLB miss on the small sized TLB
* while the hugepage TLB entry is still established
* in the huge TLB. Some CPU doesn't like that. See
* http://support.amd.com/us/Processor_TechDocs/41322.pdf,
* Erratum 383 on page 93. Intel should be safe but is
* also warns that it's only safe if the permission
* and cache attributes of the two entries loaded in
* the two TLB is identical (which should be the case
* here). But it is generally safer to never allow
* small and huge TLB entries for the same virtual
* address to be loaded simultaneously. So instead of
* doing "pmd_populate(); flush_tlb_range();" we first
* mark the current pmd notpresent (atomically because
* here the pmd_trans_huge and pmd_trans_splitting
* must remain set at all times on the pmd until the
* split is complete for this pmd), then we flush the
* SMP TLB and finally we write the non-huge version
* of the pmd entry with pmd_populate.
*/
set_pmd_at(mm, address, pmd, pmd_mknotpresent(*pmd));
flush_tlb_range(vma, address, address + HPAGE_PMD_SIZE);
pmd_populate(mm, pmd, pgtable);
ret = 1;
}
spin_unlock(&mm->page_table_lock);
return ret;
}
/* must be called with anon_vma->root->mutex hold */
static void __split_huge_page(struct page *page,
struct anon_vma *anon_vma)
{
int mapcount, mapcount2;
struct anon_vma_chain *avc;
BUG_ON(!PageHead(page));
BUG_ON(PageTail(page));
mapcount = 0;
list_for_each_entry(avc, &anon_vma->head, same_anon_vma) {
struct vm_area_struct *vma = avc->vma;
unsigned long addr = vma_address(page, vma);
BUG_ON(is_vma_temporary_stack(vma));
if (addr == -EFAULT)
continue;
mapcount += __split_huge_page_splitting(page, vma, addr);
}
/*
* It is critical that new vmas are added to the tail of the
* anon_vma list. This guarantes that if copy_huge_pmd() runs
* and establishes a child pmd before
* __split_huge_page_splitting() freezes the parent pmd (so if
* we fail to prevent copy_huge_pmd() from running until the
* whole __split_huge_page() is complete), we will still see
* the newly established pmd of the child later during the
* walk, to be able to set it as pmd_trans_splitting too.
*/
if (mapcount != page_mapcount(page))
printk(KERN_ERR "mapcount %d page_mapcount %d\n",
mapcount, page_mapcount(page));
BUG_ON(mapcount != page_mapcount(page));
__split_huge_page_refcount(page);
mapcount2 = 0;
list_for_each_entry(avc, &anon_vma->head, same_anon_vma) {
struct vm_area_struct *vma = avc->vma;
unsigned long addr = vma_address(page, vma);
BUG_ON(is_vma_temporary_stack(vma));
if (addr == -EFAULT)
continue;
mapcount2 += __split_huge_page_map(page, vma, addr);
}
if (mapcount != mapcount2)
printk(KERN_ERR "mapcount %d mapcount2 %d page_mapcount %d\n",
mapcount, mapcount2, page_mapcount(page));
BUG_ON(mapcount != mapcount2);
}
int split_huge_page(struct page *page)
{
struct anon_vma *anon_vma;
int ret = 1;
BUG_ON(!PageAnon(page));
anon_vma = page_lock_anon_vma(page);
if (!anon_vma)
goto out;
ret = 0;
if (!PageCompound(page))
goto out_unlock;
BUG_ON(!PageSwapBacked(page));
__split_huge_page(page, anon_vma);
count_vm_event(THP_SPLIT);
BUG_ON(PageCompound(page));
out_unlock:
page_unlock_anon_vma(anon_vma);
out:
return ret;
}
#define VM_NO_THP (VM_SPECIAL|VM_INSERTPAGE|VM_MIXEDMAP|VM_SAO| \
VM_HUGETLB|VM_SHARED|VM_MAYSHARE)
int hugepage_madvise(struct vm_area_struct *vma,
unsigned long *vm_flags, int advice)
{
switch (advice) {
case MADV_HUGEPAGE:
/*
* Be somewhat over-protective like KSM for now!
*/
if (*vm_flags & (VM_HUGEPAGE | VM_NO_THP))
return -EINVAL;
*vm_flags &= ~VM_NOHUGEPAGE;
*vm_flags |= VM_HUGEPAGE;
/*
* If the vma become good for khugepaged to scan,
* register it here without waiting a page fault that
* may not happen any time soon.
*/
if (unlikely(khugepaged_enter_vma_merge(vma)))
return -ENOMEM;
break;
case MADV_NOHUGEPAGE:
/*
* Be somewhat over-protective like KSM for now!
*/
if (*vm_flags & (VM_NOHUGEPAGE | VM_NO_THP))
return -EINVAL;
*vm_flags &= ~VM_HUGEPAGE;
*vm_flags |= VM_NOHUGEPAGE;
/*
* Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
* this vma even if we leave the mm registered in khugepaged if
* it got registered before VM_NOHUGEPAGE was set.
*/
break;
}
return 0;
}
static int __init khugepaged_slab_init(void)
{
mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
sizeof(struct mm_slot),
__alignof__(struct mm_slot), 0, NULL);
if (!mm_slot_cache)
return -ENOMEM;
return 0;
}
static void __init khugepaged_slab_free(void)
{
kmem_cache_destroy(mm_slot_cache);
mm_slot_cache = NULL;
}
static inline struct mm_slot *alloc_mm_slot(void)
{
if (!mm_slot_cache) /* initialization failed */
return NULL;
return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
}
static inline void free_mm_slot(struct mm_slot *mm_slot)
{
kmem_cache_free(mm_slot_cache, mm_slot);
}
static int __init mm_slots_hash_init(void)
{
mm_slots_hash = kzalloc(MM_SLOTS_HASH_HEADS * sizeof(struct hlist_head),
GFP_KERNEL);
if (!mm_slots_hash)
return -ENOMEM;
return 0;
}
#if 0
static void __init mm_slots_hash_free(void)
{
kfree(mm_slots_hash);
mm_slots_hash = NULL;
}
#endif
static struct mm_slot *get_mm_slot(struct mm_struct *mm)
{
struct mm_slot *mm_slot;
struct hlist_head *bucket;
struct hlist_node *node;
bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
% MM_SLOTS_HASH_HEADS];
hlist_for_each_entry(mm_slot, node, bucket, hash) {
if (mm == mm_slot->mm)
return mm_slot;
}
return NULL;
}
static void insert_to_mm_slots_hash(struct mm_struct *mm,
struct mm_slot *mm_slot)
{
struct hlist_head *bucket;
bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
% MM_SLOTS_HASH_HEADS];
mm_slot->mm = mm;
hlist_add_head(&mm_slot->hash, bucket);
}
static inline int khugepaged_test_exit(struct mm_struct *mm)
{
return atomic_read(&mm->mm_users) == 0;
}
int __khugepaged_enter(struct mm_struct *mm)
{
struct mm_slot *mm_slot;
int wakeup;
mm_slot = alloc_mm_slot();
if (!mm_slot)
return -ENOMEM;
/* __khugepaged_exit() must not run from under us */
VM_BUG_ON(khugepaged_test_exit(mm));
if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
free_mm_slot(mm_slot);
return 0;
}
spin_lock(&khugepaged_mm_lock);
insert_to_mm_slots_hash(mm, mm_slot);
/*
* Insert just behind the scanning cursor, to let the area settle
* down a little.
*/
wakeup = list_empty(&khugepaged_scan.mm_head);
list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
spin_unlock(&khugepaged_mm_lock);
atomic_inc(&mm->mm_count);
if (wakeup)
wake_up_interruptible(&khugepaged_wait);
return 0;
}
int khugepaged_enter_vma_merge(struct vm_area_struct *vma)
{
unsigned long hstart, hend;
if (!vma->anon_vma)
/*
* Not yet faulted in so we will register later in the
* page fault if needed.
*/
return 0;
if (vma->vm_ops)
/* khugepaged not yet working on file or special mappings */
return 0;
/*
* If is_pfn_mapping() is true is_learn_pfn_mapping() must be
* true too, verify it here.
*/
VM_BUG_ON(is_linear_pfn_mapping(vma) || vma->vm_flags & VM_NO_THP);
hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
hend = vma->vm_end & HPAGE_PMD_MASK;
if (hstart < hend)
return khugepaged_enter(vma);
return 0;
}
void __khugepaged_exit(struct mm_struct *mm)
{
struct mm_slot *mm_slot;
int free = 0;
spin_lock(&khugepaged_mm_lock);
mm_slot = get_mm_slot(mm);
if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
hlist_del(&mm_slot->hash);
list_del(&mm_slot->mm_node);
free = 1;
}
spin_unlock(&khugepaged_mm_lock);
if (free) {
clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
free_mm_slot(mm_slot);
mmdrop(mm);
} else if (mm_slot) {
/*
* This is required to serialize against
* khugepaged_test_exit() (which is guaranteed to run
* under mmap sem read mode). Stop here (after we
* return all pagetables will be destroyed) until
* khugepaged has finished working on the pagetables
* under the mmap_sem.
*/
down_write(&mm->mmap_sem);
up_write(&mm->mmap_sem);
}
}
static void release_pte_page(struct page *page)
{
/* 0 stands for page_is_file_cache(page) == false */
dec_zone_page_state(page, NR_ISOLATED_ANON + 0);
unlock_page(page);
putback_lru_page(page);
}
static void release_pte_pages(pte_t *pte, pte_t *_pte)
{
while (--_pte >= pte) {
pte_t pteval = *_pte;
if (!pte_none(pteval))
release_pte_page(pte_page(pteval));
}
}
static void release_all_pte_pages(pte_t *pte)
{
release_pte_pages(pte, pte + HPAGE_PMD_NR);
}
static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
unsigned long address,
pte_t *pte)
{
struct page *page;
pte_t *_pte;
int referenced = 0, isolated = 0, none = 0;
for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
_pte++, address += PAGE_SIZE) {
pte_t pteval = *_pte;
if (pte_none(pteval)) {
if (++none <= khugepaged_max_ptes_none)
continue;
else {
release_pte_pages(pte, _pte);
goto out;
}
}
if (!pte_present(pteval) || !pte_write(pteval)) {
release_pte_pages(pte, _pte);
goto out;
}
page = vm_normal_page(vma, address, pteval);
if (unlikely(!page)) {
release_pte_pages(pte, _pte);
goto out;
}
VM_BUG_ON(PageCompound(page));
BUG_ON(!PageAnon(page));
VM_BUG_ON(!PageSwapBacked(page));
/* cannot use mapcount: can't collapse if there's a gup pin */
if (page_count(page) != 1) {
release_pte_pages(pte, _pte);
goto out;
}
/*
* We can do it before isolate_lru_page because the
* page can't be freed from under us. NOTE: PG_lock
* is needed to serialize against split_huge_page
* when invoked from the VM.
*/
if (!trylock_page(page)) {
release_pte_pages(pte, _pte);
goto out;
}
/*
* Isolate the page to avoid collapsing an hugepage
* currently in use by the VM.
*/
if (isolate_lru_page(page)) {
unlock_page(page);
release_pte_pages(pte, _pte);
goto out;
}
/* 0 stands for page_is_file_cache(page) == false */
inc_zone_page_state(page, NR_ISOLATED_ANON + 0);
VM_BUG_ON(!PageLocked(page));
VM_BUG_ON(PageLRU(page));
/* If there is no mapped pte young don't collapse the page */
if (pte_young(pteval) || PageReferenced(page) ||
mmu_notifier_test_young(vma->vm_mm, address))
referenced = 1;
}
if (unlikely(!referenced))
release_all_pte_pages(pte);
else
isolated = 1;
out:
return isolated;
}
static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
struct vm_area_struct *vma,
unsigned long address,
spinlock_t *ptl)
{
pte_t *_pte;
for (_pte = pte; _pte < pte+HPAGE_PMD_NR; _pte++) {
pte_t pteval = *_pte;
struct page *src_page;
if (pte_none(pteval)) {
clear_user_highpage(page, address);
add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
} else {
src_page = pte_page(pteval);
copy_user_highpage(page, src_page, address, vma);
VM_BUG_ON(page_mapcount(src_page) != 1);
VM_BUG_ON(page_count(src_page) != 2);
release_pte_page(src_page);
/*
* ptl mostly unnecessary, but preempt has to
* be disabled to update the per-cpu stats
* inside page_remove_rmap().
*/
spin_lock(ptl);
/*
* paravirt calls inside pte_clear here are
* superfluous.
*/
pte_clear(vma->vm_mm, address, _pte);
page_remove_rmap(src_page);
spin_unlock(ptl);
free_page_and_swap_cache(src_page);
}
address += PAGE_SIZE;
page++;
}
}
static void collapse_huge_page(struct mm_struct *mm,
unsigned long address,
struct page **hpage,
struct vm_area_struct *vma,
int node)
{
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd, _pmd;
pte_t *pte;
pgtable_t pgtable;
struct page *new_page;
spinlock_t *ptl;
int isolated;
unsigned long hstart, hend;
VM_BUG_ON(address & ~HPAGE_PMD_MASK);
#ifndef CONFIG_NUMA
up_read(&mm->mmap_sem);
VM_BUG_ON(!*hpage);
new_page = *hpage;
#else
VM_BUG_ON(*hpage);
/*
* Allocate the page while the vma is still valid and under
* the mmap_sem read mode so there is no memory allocation
* later when we take the mmap_sem in write mode. This is more
* friendly behavior (OTOH it may actually hide bugs) to
* filesystems in userland with daemons allocating memory in
* the userland I/O paths. Allocating memory with the
* mmap_sem in read mode is good idea also to allow greater
* scalability.
*/
new_page = alloc_hugepage_vma(khugepaged_defrag(), vma, address,
node, __GFP_OTHER_NODE);
/*
* After allocating the hugepage, release the mmap_sem read lock in
* preparation for taking it in write mode.
*/
up_read(&mm->mmap_sem);
if (unlikely(!new_page)) {
count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
*hpage = ERR_PTR(-ENOMEM);
return;
}
#endif
count_vm_event(THP_COLLAPSE_ALLOC);
if (unlikely(mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL))) {
#ifdef CONFIG_NUMA
put_page(new_page);
#endif
return;
}
/*
* Prevent all access to pagetables with the exception of
* gup_fast later hanlded by the ptep_clear_flush and the VM
* handled by the anon_vma lock + PG_lock.
*/
down_write(&mm->mmap_sem);
if (unlikely(khugepaged_test_exit(mm)))
goto out;
vma = find_vma(mm, address);
hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
hend = vma->vm_end & HPAGE_PMD_MASK;
if (address < hstart || address + HPAGE_PMD_SIZE > hend)
goto out;
if ((!(vma->vm_flags & VM_HUGEPAGE) && !khugepaged_always()) ||
(vma->vm_flags & VM_NOHUGEPAGE))
goto out;
if (!vma->anon_vma || vma->vm_ops)
goto out;
if (is_vma_temporary_stack(vma))
goto out;
/*
* If is_pfn_mapping() is true is_learn_pfn_mapping() must be
* true too, verify it here.
*/
VM_BUG_ON(is_linear_pfn_mapping(vma) || vma->vm_flags & VM_NO_THP);
pgd = pgd_offset(mm, address);
if (!pgd_present(*pgd))
goto out;
pud = pud_offset(pgd, address);
if (!pud_present(*pud))
goto out;
pmd = pmd_offset(pud, address);
/* pmd can't go away or become huge under us */
if (!pmd_present(*pmd) || pmd_trans_huge(*pmd))
goto out;
anon_vma_lock(vma->anon_vma);
pte = pte_offset_map(pmd, address);
ptl = pte_lockptr(mm, pmd);
spin_lock(&mm->page_table_lock); /* probably unnecessary */
/*
* After this gup_fast can't run anymore. This also removes
* any huge TLB entry from the CPU so we won't allow
* huge and small TLB entries for the same virtual address
* to avoid the risk of CPU bugs in that area.
*/
_pmd = pmdp_clear_flush_notify(vma, address, pmd);
spin_unlock(&mm->page_table_lock);
spin_lock(ptl);
isolated = __collapse_huge_page_isolate(vma, address, pte);
spin_unlock(ptl);
if (unlikely(!isolated)) {
pte_unmap(pte);
spin_lock(&mm->page_table_lock);
BUG_ON(!pmd_none(*pmd));
set_pmd_at(mm, address, pmd, _pmd);
spin_unlock(&mm->page_table_lock);
anon_vma_unlock(vma->anon_vma);
goto out;
}
/*
* All pages are isolated and locked so anon_vma rmap
* can't run anymore.
*/
anon_vma_unlock(vma->anon_vma);
__collapse_huge_page_copy(pte, new_page, vma, address, ptl);
pte_unmap(pte);
__SetPageUptodate(new_page);
pgtable = pmd_pgtable(_pmd);
VM_BUG_ON(page_count(pgtable) != 1);
VM_BUG_ON(page_mapcount(pgtable) != 0);
_pmd = mk_pmd(new_page, vma->vm_page_prot);
_pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
_pmd = pmd_mkhuge(_pmd);
/*
* spin_lock() below is not the equivalent of smp_wmb(), so
* this is needed to avoid the copy_huge_page writes to become
* visible after the set_pmd_at() write.
*/
smp_wmb();
spin_lock(&mm->page_table_lock);
BUG_ON(!pmd_none(*pmd));
page_add_new_anon_rmap(new_page, vma, address);
set_pmd_at(mm, address, pmd, _pmd);
update_mmu_cache(vma, address, _pmd);
prepare_pmd_huge_pte(pgtable, mm);
spin_unlock(&mm->page_table_lock);
#ifndef CONFIG_NUMA
*hpage = NULL;
#endif
khugepaged_pages_collapsed++;
out_up_write:
up_write(&mm->mmap_sem);
return;
out:
mem_cgroup_uncharge_page(new_page);
#ifdef CONFIG_NUMA
put_page(new_page);
#endif
goto out_up_write;
}
static int khugepaged_scan_pmd(struct mm_struct *mm,
struct vm_area_struct *vma,
unsigned long address,
struct page **hpage)
{
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte, *_pte;
int ret = 0, referenced = 0, none = 0;
struct page *page;
unsigned long _address;
spinlock_t *ptl;
int node = -1;
VM_BUG_ON(address & ~HPAGE_PMD_MASK);
pgd = pgd_offset(mm, address);
if (!pgd_present(*pgd))
goto out;
pud = pud_offset(pgd, address);
if (!pud_present(*pud))
goto out;
pmd = pmd_offset(pud, address);
if (!pmd_present(*pmd) || pmd_trans_huge(*pmd))
goto out;
pte = pte_offset_map_lock(mm, pmd, address, &ptl);
for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
_pte++, _address += PAGE_SIZE) {
pte_t pteval = *_pte;
if (pte_none(pteval)) {
if (++none <= khugepaged_max_ptes_none)
continue;
else
goto out_unmap;
}
if (!pte_present(pteval) || !pte_write(pteval))
goto out_unmap;
page = vm_normal_page(vma, _address, pteval);
if (unlikely(!page))
goto out_unmap;
/*
* Chose the node of the first page. This could
* be more sophisticated and look at more pages,
* but isn't for now.
*/
if (node == -1)
node = page_to_nid(page);
VM_BUG_ON(PageCompound(page));
if (!PageLRU(page) || PageLocked(page) || !PageAnon(page))
goto out_unmap;
/* cannot use mapcount: can't collapse if there's a gup pin */
if (page_count(page) != 1)
goto out_unmap;
if (pte_young(pteval) || PageReferenced(page) ||
mmu_notifier_test_young(vma->vm_mm, address))
referenced = 1;
}
if (referenced)
ret = 1;
out_unmap:
pte_unmap_unlock(pte, ptl);
if (ret)
/* collapse_huge_page will return with the mmap_sem released */
collapse_huge_page(mm, address, hpage, vma, node);
out:
return ret;
}
static void collect_mm_slot(struct mm_slot *mm_slot)
{
struct mm_struct *mm = mm_slot->mm;
VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
if (khugepaged_test_exit(mm)) {
/* free mm_slot */
hlist_del(&mm_slot->hash);
list_del(&mm_slot->mm_node);
/*
* Not strictly needed because the mm exited already.
*
* clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
*/
/* khugepaged_mm_lock actually not necessary for the below */
free_mm_slot(mm_slot);
mmdrop(mm);
}
}
static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
struct page **hpage)
__releases(&khugepaged_mm_lock)
__acquires(&khugepaged_mm_lock)
{
struct mm_slot *mm_slot;
struct mm_struct *mm;
struct vm_area_struct *vma;
int progress = 0;
VM_BUG_ON(!pages);
VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
if (khugepaged_scan.mm_slot)
mm_slot = khugepaged_scan.mm_slot;
else {
mm_slot = list_entry(khugepaged_scan.mm_head.next,
struct mm_slot, mm_node);
khugepaged_scan.address = 0;
khugepaged_scan.mm_slot = mm_slot;
}
spin_unlock(&khugepaged_mm_lock);
mm = mm_slot->mm;
down_read(&mm->mmap_sem);
if (unlikely(khugepaged_test_exit(mm)))
vma = NULL;
else
vma = find_vma(mm, khugepaged_scan.address);
progress++;
for (; vma; vma = vma->vm_next) {
unsigned long hstart, hend;
cond_resched();
if (unlikely(khugepaged_test_exit(mm))) {
progress++;
break;
}
if ((!(vma->vm_flags & VM_HUGEPAGE) &&
!khugepaged_always()) ||
(vma->vm_flags & VM_NOHUGEPAGE)) {
skip:
progress++;
continue;
}
if (!vma->anon_vma || vma->vm_ops)
goto skip;
if (is_vma_temporary_stack(vma))
goto skip;
/*
* If is_pfn_mapping() is true is_learn_pfn_mapping()
* must be true too, verify it here.
*/
VM_BUG_ON(is_linear_pfn_mapping(vma) ||
vma->vm_flags & VM_NO_THP);
hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
hend = vma->vm_end & HPAGE_PMD_MASK;
if (hstart >= hend)
goto skip;
if (khugepaged_scan.address > hend)
goto skip;
if (khugepaged_scan.address < hstart)
khugepaged_scan.address = hstart;
VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
while (khugepaged_scan.address < hend) {
int ret;
cond_resched();
if (unlikely(khugepaged_test_exit(mm)))
goto breakouterloop;
VM_BUG_ON(khugepaged_scan.address < hstart ||
khugepaged_scan.address + HPAGE_PMD_SIZE >
hend);
ret = khugepaged_scan_pmd(mm, vma,
khugepaged_scan.address,
hpage);
/* move to next address */
khugepaged_scan.address += HPAGE_PMD_SIZE;
progress += HPAGE_PMD_NR;
if (ret)
/* we released mmap_sem so break loop */
goto breakouterloop_mmap_sem;
if (progress >= pages)
goto breakouterloop;
}
}
breakouterloop:
up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */
breakouterloop_mmap_sem:
spin_lock(&khugepaged_mm_lock);
VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
/*
* Release the current mm_slot if this mm is about to die, or
* if we scanned all vmas of this mm.
*/
if (khugepaged_test_exit(mm) || !vma) {
/*
* Make sure that if mm_users is reaching zero while
* khugepaged runs here, khugepaged_exit will find
* mm_slot not pointing to the exiting mm.
*/
if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
khugepaged_scan.mm_slot = list_entry(
mm_slot->mm_node.next,
struct mm_slot, mm_node);
khugepaged_scan.address = 0;
} else {
khugepaged_scan.mm_slot = NULL;
khugepaged_full_scans++;
}
collect_mm_slot(mm_slot);
}
return progress;
}
static int khugepaged_has_work(void)
{
return !list_empty(&khugepaged_scan.mm_head) &&
khugepaged_enabled();
}
static int khugepaged_wait_event(void)
{
return !list_empty(&khugepaged_scan.mm_head) ||
!khugepaged_enabled();
}
static void khugepaged_do_scan(struct page **hpage)
{
unsigned int progress = 0, pass_through_head = 0;
unsigned int pages = khugepaged_pages_to_scan;
barrier(); /* write khugepaged_pages_to_scan to local stack */
while (progress < pages) {
cond_resched();
#ifndef CONFIG_NUMA
if (!*hpage) {
*hpage = alloc_hugepage(khugepaged_defrag());
if (unlikely(!*hpage)) {
count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
break;
}
count_vm_event(THP_COLLAPSE_ALLOC);
}
#else
if (IS_ERR(*hpage))
break;
#endif
if (unlikely(kthread_should_stop() || freezing(current)))
break;
spin_lock(&khugepaged_mm_lock);
if (!khugepaged_scan.mm_slot)
pass_through_head++;
if (khugepaged_has_work() &&
pass_through_head < 2)
progress += khugepaged_scan_mm_slot(pages - progress,
hpage);
else
progress = pages;
spin_unlock(&khugepaged_mm_lock);
}
}
static void khugepaged_alloc_sleep(void)
{
wait_event_freezable_timeout(khugepaged_wait, false,
msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
}
#ifndef CONFIG_NUMA
static struct page *khugepaged_alloc_hugepage(void)
{
struct page *hpage;
do {
hpage = alloc_hugepage(khugepaged_defrag());
if (!hpage) {
count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
khugepaged_alloc_sleep();
} else
count_vm_event(THP_COLLAPSE_ALLOC);
} while (unlikely(!hpage) &&
likely(khugepaged_enabled()));
return hpage;
}
#endif
static void khugepaged_loop(void)
{
struct page *hpage;
#ifdef CONFIG_NUMA
hpage = NULL;
#endif
while (likely(khugepaged_enabled())) {
#ifndef CONFIG_NUMA
hpage = khugepaged_alloc_hugepage();
if (unlikely(!hpage))
break;
#else
if (IS_ERR(hpage)) {
khugepaged_alloc_sleep();
hpage = NULL;
}
#endif
khugepaged_do_scan(&hpage);
#ifndef CONFIG_NUMA
if (hpage)
put_page(hpage);
#endif
try_to_freeze();
if (unlikely(kthread_should_stop()))
break;
if (khugepaged_has_work()) {
if (!khugepaged_scan_sleep_millisecs)
continue;
wait_event_freezable_timeout(khugepaged_wait, false,
msecs_to_jiffies(khugepaged_scan_sleep_millisecs));
} else if (khugepaged_enabled())
wait_event_freezable(khugepaged_wait,
khugepaged_wait_event());
}
}
static int khugepaged(void *none)
{
struct mm_slot *mm_slot;
set_freezable();
set_user_nice(current, 19);
/* serialize with start_khugepaged() */
mutex_lock(&khugepaged_mutex);
for (;;) {
mutex_unlock(&khugepaged_mutex);
VM_BUG_ON(khugepaged_thread != current);
khugepaged_loop();
VM_BUG_ON(khugepaged_thread != current);
mutex_lock(&khugepaged_mutex);
if (!khugepaged_enabled())
break;
if (unlikely(kthread_should_stop()))
break;
}
spin_lock(&khugepaged_mm_lock);
mm_slot = khugepaged_scan.mm_slot;
khugepaged_scan.mm_slot = NULL;
if (mm_slot)
collect_mm_slot(mm_slot);
spin_unlock(&khugepaged_mm_lock);
khugepaged_thread = NULL;
mutex_unlock(&khugepaged_mutex);
return 0;
}
void __split_huge_page_pmd(struct mm_struct *mm, pmd_t *pmd)
{
struct page *page;
spin_lock(&mm->page_table_lock);
if (unlikely(!pmd_trans_huge(*pmd))) {
spin_unlock(&mm->page_table_lock);
return;
}
page = pmd_page(*pmd);
VM_BUG_ON(!page_count(page));
get_page(page);
spin_unlock(&mm->page_table_lock);
split_huge_page(page);
put_page(page);
BUG_ON(pmd_trans_huge(*pmd));
}
static void split_huge_page_address(struct mm_struct *mm,
unsigned long address)
{
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
VM_BUG_ON(!(address & ~HPAGE_PMD_MASK));
pgd = pgd_offset(mm, address);
if (!pgd_present(*pgd))
return;
pud = pud_offset(pgd, address);
if (!pud_present(*pud))
return;
pmd = pmd_offset(pud, address);
if (!pmd_present(*pmd))
return;
/*
* Caller holds the mmap_sem write mode, so a huge pmd cannot
* materialize from under us.
*/
split_huge_page_pmd(mm, pmd);
}
void __vma_adjust_trans_huge(struct vm_area_struct *vma,
unsigned long start,
unsigned long end,
long adjust_next)
{
/*
* If the new start address isn't hpage aligned and it could
* previously contain an hugepage: check if we need to split
* an huge pmd.
*/
if (start & ~HPAGE_PMD_MASK &&
(start & HPAGE_PMD_MASK) >= vma->vm_start &&
(start & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
split_huge_page_address(vma->vm_mm, start);
/*
* If the new end address isn't hpage aligned and it could
* previously contain an hugepage: check if we need to split
* an huge pmd.
*/
if (end & ~HPAGE_PMD_MASK &&
(end & HPAGE_PMD_MASK) >= vma->vm_start &&
(end & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
split_huge_page_address(vma->vm_mm, end);
/*
* If we're also updating the vma->vm_next->vm_start, if the new
* vm_next->vm_start isn't page aligned and it could previously
* contain an hugepage: check if we need to split an huge pmd.
*/
if (adjust_next > 0) {
struct vm_area_struct *next = vma->vm_next;
unsigned long nstart = next->vm_start;
nstart += adjust_next << PAGE_SHIFT;
if (nstart & ~HPAGE_PMD_MASK &&
(nstart & HPAGE_PMD_MASK) >= next->vm_start &&
(nstart & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= next->vm_end)
split_huge_page_address(next->vm_mm, nstart);
}
}
| gpl-2.0 |
greg17477/kernel_motley_mako | arch/arm/mm/idmap.c | 3176 | 2832 | #include <linux/kernel.h>
#include <asm/cputype.h>
#include <asm/idmap.h>
#include <asm/pgalloc.h>
#include <asm/pgtable.h>
#include <asm/sections.h>
#include <asm/system_info.h>
pgd_t *idmap_pgd;
#ifdef CONFIG_ARM_LPAE
static void idmap_add_pmd(pud_t *pud, unsigned long addr, unsigned long end,
unsigned long prot)
{
pmd_t *pmd;
unsigned long next;
if (pud_none_or_clear_bad(pud) || (pud_val(*pud) & L_PGD_SWAPPER)) {
pmd = pmd_alloc_one(&init_mm, addr);
if (!pmd) {
pr_warning("Failed to allocate identity pmd.\n");
return;
}
pud_populate(&init_mm, pud, pmd);
pmd += pmd_index(addr);
} else
pmd = pmd_offset(pud, addr);
do {
next = pmd_addr_end(addr, end);
*pmd = __pmd((addr & PMD_MASK) | prot);
flush_pmd_entry(pmd);
} while (pmd++, addr = next, addr != end);
}
#else /* !CONFIG_ARM_LPAE */
static void idmap_add_pmd(pud_t *pud, unsigned long addr, unsigned long end,
unsigned long prot)
{
pmd_t *pmd = pmd_offset(pud, addr);
addr = (addr & PMD_MASK) | prot;
pmd[0] = __pmd(addr);
addr += SECTION_SIZE;
pmd[1] = __pmd(addr);
flush_pmd_entry(pmd);
}
#endif /* CONFIG_ARM_LPAE */
static void idmap_add_pud(pgd_t *pgd, unsigned long addr, unsigned long end,
unsigned long prot)
{
pud_t *pud = pud_offset(pgd, addr);
unsigned long next;
do {
next = pud_addr_end(addr, end);
idmap_add_pmd(pud, addr, next, prot);
} while (pud++, addr = next, addr != end);
}
static void identity_mapping_add(pgd_t *pgd, unsigned long addr, unsigned long end)
{
unsigned long prot, next;
prot = PMD_TYPE_SECT | PMD_SECT_AP_WRITE | PMD_SECT_AF;
if (cpu_architecture() <= CPU_ARCH_ARMv5TEJ && !cpu_is_xscale())
prot |= PMD_BIT4;
pgd += pgd_index(addr);
do {
next = pgd_addr_end(addr, end);
idmap_add_pud(pgd, addr, next, prot);
} while (pgd++, addr = next, addr != end);
}
extern char __idmap_text_start[], __idmap_text_end[];
static int __init init_static_idmap(void)
{
phys_addr_t idmap_start, idmap_end;
idmap_pgd = pgd_alloc(&init_mm);
if (!idmap_pgd)
return -ENOMEM;
/* Add an identity mapping for the physical address of the section. */
idmap_start = virt_to_phys((void *)__idmap_text_start);
idmap_end = virt_to_phys((void *)__idmap_text_end);
pr_info("Setting up static identity map for 0x%llx - 0x%llx\n",
(long long)idmap_start, (long long)idmap_end);
identity_mapping_add(idmap_pgd, idmap_start, idmap_end);
return 0;
}
early_initcall(init_static_idmap);
/*
* In order to soft-boot, we need to switch to a 1:1 mapping for the
* cpu_reset functions. This will then ensure that we have predictable
* results when turning off the mmu.
*/
void setup_mm_for_reboot(void)
{
/* Clean and invalidate L1. */
flush_cache_all();
/* Switch to the identity mapping. */
cpu_switch_mm(idmap_pgd, &init_mm);
/* Flush the TLB. */
local_flush_tlb_all();
}
| gpl-2.0 |
u-ra/android_kernel_htc_msm8660 | drivers/media/radio/tef6862.c | 3176 | 5713 | /*
* tef6862.c Philips TEF6862 Car Radio Enhanced Selectivity Tuner
* Copyright (c) 2009 Intel Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-device.h>
#include <media/v4l2-chip-ident.h>
#define DRIVER_NAME "tef6862"
#define FREQ_MUL 16000
#define TEF6862_LO_FREQ (875 * FREQ_MUL / 10)
#define TEF6862_HI_FREQ (108 * FREQ_MUL)
/* Write mode sub addresses */
#define WM_SUB_BANDWIDTH 0x0
#define WM_SUB_PLLM 0x1
#define WM_SUB_PLLL 0x2
#define WM_SUB_DAA 0x3
#define WM_SUB_AGC 0x4
#define WM_SUB_BAND 0x5
#define WM_SUB_CONTROL 0x6
#define WM_SUB_LEVEL 0x7
#define WM_SUB_IFCF 0x8
#define WM_SUB_IFCAP 0x9
#define WM_SUB_ACD 0xA
#define WM_SUB_TEST 0xF
/* Different modes of the MSA register */
#define MODE_BUFFER 0x0
#define MODE_PRESET 0x1
#define MODE_SEARCH 0x2
#define MODE_AF_UPDATE 0x3
#define MODE_JUMP 0x4
#define MODE_CHECK 0x5
#define MODE_LOAD 0x6
#define MODE_END 0x7
#define MODE_SHIFT 5
struct tef6862_state {
struct v4l2_subdev sd;
unsigned long freq;
};
static inline struct tef6862_state *to_state(struct v4l2_subdev *sd)
{
return container_of(sd, struct tef6862_state, sd);
}
static u16 tef6862_sigstr(struct i2c_client *client)
{
u8 buf[4];
int err = i2c_master_recv(client, buf, sizeof(buf));
if (err == sizeof(buf))
return buf[3] << 8;
return 0;
}
static int tef6862_g_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *v)
{
if (v->index > 0)
return -EINVAL;
/* only support FM for now */
strlcpy(v->name, "FM", sizeof(v->name));
v->type = V4L2_TUNER_RADIO;
v->rangelow = TEF6862_LO_FREQ;
v->rangehigh = TEF6862_HI_FREQ;
v->rxsubchans = V4L2_TUNER_SUB_MONO;
v->capability = V4L2_TUNER_CAP_LOW;
v->audmode = V4L2_TUNER_MODE_STEREO;
v->signal = tef6862_sigstr(v4l2_get_subdevdata(sd));
return 0;
}
static int tef6862_s_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *v)
{
return v->index ? -EINVAL : 0;
}
static int tef6862_s_frequency(struct v4l2_subdev *sd, struct v4l2_frequency *f)
{
struct tef6862_state *state = to_state(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
u16 pll;
u8 i2cmsg[3];
int err;
if (f->tuner != 0)
return -EINVAL;
pll = 1964 + ((f->frequency - TEF6862_LO_FREQ) * 20) / FREQ_MUL;
i2cmsg[0] = (MODE_PRESET << MODE_SHIFT) | WM_SUB_PLLM;
i2cmsg[1] = (pll >> 8) & 0xff;
i2cmsg[2] = pll & 0xff;
err = i2c_master_send(client, i2cmsg, sizeof(i2cmsg));
if (!err)
state->freq = f->frequency;
return err;
}
static int tef6862_g_frequency(struct v4l2_subdev *sd, struct v4l2_frequency *f)
{
struct tef6862_state *state = to_state(sd);
if (f->tuner != 0)
return -EINVAL;
f->type = V4L2_TUNER_RADIO;
f->frequency = state->freq;
return 0;
}
static int tef6862_g_chip_ident(struct v4l2_subdev *sd,
struct v4l2_dbg_chip_ident *chip)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_TEF6862, 0);
}
static const struct v4l2_subdev_tuner_ops tef6862_tuner_ops = {
.g_tuner = tef6862_g_tuner,
.s_tuner = tef6862_s_tuner,
.s_frequency = tef6862_s_frequency,
.g_frequency = tef6862_g_frequency,
};
static const struct v4l2_subdev_core_ops tef6862_core_ops = {
.g_chip_ident = tef6862_g_chip_ident,
};
static const struct v4l2_subdev_ops tef6862_ops = {
.core = &tef6862_core_ops,
.tuner = &tef6862_tuner_ops,
};
/*
* Generic i2c probe
* concerning the addresses: i2c wants 7 bit (without the r/w bit), so '>>1'
*/
static int __devinit tef6862_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct tef6862_state *state;
struct v4l2_subdev *sd;
/* Check if the adapter supports the needed features */
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -EIO;
v4l_info(client, "chip found @ 0x%02x (%s)\n",
client->addr << 1, client->adapter->name);
state = kzalloc(sizeof(struct tef6862_state), GFP_KERNEL);
if (state == NULL)
return -ENOMEM;
state->freq = TEF6862_LO_FREQ;
sd = &state->sd;
v4l2_i2c_subdev_init(sd, client, &tef6862_ops);
return 0;
}
static int __devexit tef6862_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
v4l2_device_unregister_subdev(sd);
kfree(to_state(sd));
return 0;
}
static const struct i2c_device_id tef6862_id[] = {
{DRIVER_NAME, 0},
{},
};
MODULE_DEVICE_TABLE(i2c, tef6862_id);
static struct i2c_driver tef6862_driver = {
.driver = {
.owner = THIS_MODULE,
.name = DRIVER_NAME,
},
.probe = tef6862_probe,
.remove = tef6862_remove,
.id_table = tef6862_id,
};
static __init int tef6862_init(void)
{
return i2c_add_driver(&tef6862_driver);
}
static __exit void tef6862_exit(void)
{
i2c_del_driver(&tef6862_driver);
}
module_init(tef6862_init);
module_exit(tef6862_exit);
MODULE_DESCRIPTION("TEF6862 Car Radio Enhanced Selectivity Tuner");
MODULE_AUTHOR("Mocean Laboratories");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
UDOOboard/Kernel_Unico | drivers/media/radio/tef6862.c | 3176 | 5713 | /*
* tef6862.c Philips TEF6862 Car Radio Enhanced Selectivity Tuner
* Copyright (c) 2009 Intel Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-device.h>
#include <media/v4l2-chip-ident.h>
#define DRIVER_NAME "tef6862"
#define FREQ_MUL 16000
#define TEF6862_LO_FREQ (875 * FREQ_MUL / 10)
#define TEF6862_HI_FREQ (108 * FREQ_MUL)
/* Write mode sub addresses */
#define WM_SUB_BANDWIDTH 0x0
#define WM_SUB_PLLM 0x1
#define WM_SUB_PLLL 0x2
#define WM_SUB_DAA 0x3
#define WM_SUB_AGC 0x4
#define WM_SUB_BAND 0x5
#define WM_SUB_CONTROL 0x6
#define WM_SUB_LEVEL 0x7
#define WM_SUB_IFCF 0x8
#define WM_SUB_IFCAP 0x9
#define WM_SUB_ACD 0xA
#define WM_SUB_TEST 0xF
/* Different modes of the MSA register */
#define MODE_BUFFER 0x0
#define MODE_PRESET 0x1
#define MODE_SEARCH 0x2
#define MODE_AF_UPDATE 0x3
#define MODE_JUMP 0x4
#define MODE_CHECK 0x5
#define MODE_LOAD 0x6
#define MODE_END 0x7
#define MODE_SHIFT 5
struct tef6862_state {
struct v4l2_subdev sd;
unsigned long freq;
};
static inline struct tef6862_state *to_state(struct v4l2_subdev *sd)
{
return container_of(sd, struct tef6862_state, sd);
}
static u16 tef6862_sigstr(struct i2c_client *client)
{
u8 buf[4];
int err = i2c_master_recv(client, buf, sizeof(buf));
if (err == sizeof(buf))
return buf[3] << 8;
return 0;
}
static int tef6862_g_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *v)
{
if (v->index > 0)
return -EINVAL;
/* only support FM for now */
strlcpy(v->name, "FM", sizeof(v->name));
v->type = V4L2_TUNER_RADIO;
v->rangelow = TEF6862_LO_FREQ;
v->rangehigh = TEF6862_HI_FREQ;
v->rxsubchans = V4L2_TUNER_SUB_MONO;
v->capability = V4L2_TUNER_CAP_LOW;
v->audmode = V4L2_TUNER_MODE_STEREO;
v->signal = tef6862_sigstr(v4l2_get_subdevdata(sd));
return 0;
}
static int tef6862_s_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *v)
{
return v->index ? -EINVAL : 0;
}
static int tef6862_s_frequency(struct v4l2_subdev *sd, struct v4l2_frequency *f)
{
struct tef6862_state *state = to_state(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
u16 pll;
u8 i2cmsg[3];
int err;
if (f->tuner != 0)
return -EINVAL;
pll = 1964 + ((f->frequency - TEF6862_LO_FREQ) * 20) / FREQ_MUL;
i2cmsg[0] = (MODE_PRESET << MODE_SHIFT) | WM_SUB_PLLM;
i2cmsg[1] = (pll >> 8) & 0xff;
i2cmsg[2] = pll & 0xff;
err = i2c_master_send(client, i2cmsg, sizeof(i2cmsg));
if (!err)
state->freq = f->frequency;
return err;
}
static int tef6862_g_frequency(struct v4l2_subdev *sd, struct v4l2_frequency *f)
{
struct tef6862_state *state = to_state(sd);
if (f->tuner != 0)
return -EINVAL;
f->type = V4L2_TUNER_RADIO;
f->frequency = state->freq;
return 0;
}
static int tef6862_g_chip_ident(struct v4l2_subdev *sd,
struct v4l2_dbg_chip_ident *chip)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_TEF6862, 0);
}
static const struct v4l2_subdev_tuner_ops tef6862_tuner_ops = {
.g_tuner = tef6862_g_tuner,
.s_tuner = tef6862_s_tuner,
.s_frequency = tef6862_s_frequency,
.g_frequency = tef6862_g_frequency,
};
static const struct v4l2_subdev_core_ops tef6862_core_ops = {
.g_chip_ident = tef6862_g_chip_ident,
};
static const struct v4l2_subdev_ops tef6862_ops = {
.core = &tef6862_core_ops,
.tuner = &tef6862_tuner_ops,
};
/*
* Generic i2c probe
* concerning the addresses: i2c wants 7 bit (without the r/w bit), so '>>1'
*/
static int __devinit tef6862_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct tef6862_state *state;
struct v4l2_subdev *sd;
/* Check if the adapter supports the needed features */
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -EIO;
v4l_info(client, "chip found @ 0x%02x (%s)\n",
client->addr << 1, client->adapter->name);
state = kzalloc(sizeof(struct tef6862_state), GFP_KERNEL);
if (state == NULL)
return -ENOMEM;
state->freq = TEF6862_LO_FREQ;
sd = &state->sd;
v4l2_i2c_subdev_init(sd, client, &tef6862_ops);
return 0;
}
static int __devexit tef6862_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
v4l2_device_unregister_subdev(sd);
kfree(to_state(sd));
return 0;
}
static const struct i2c_device_id tef6862_id[] = {
{DRIVER_NAME, 0},
{},
};
MODULE_DEVICE_TABLE(i2c, tef6862_id);
static struct i2c_driver tef6862_driver = {
.driver = {
.owner = THIS_MODULE,
.name = DRIVER_NAME,
},
.probe = tef6862_probe,
.remove = tef6862_remove,
.id_table = tef6862_id,
};
static __init int tef6862_init(void)
{
return i2c_add_driver(&tef6862_driver);
}
static __exit void tef6862_exit(void)
{
i2c_del_driver(&tef6862_driver);
}
module_init(tef6862_init);
module_exit(tef6862_exit);
MODULE_DESCRIPTION("TEF6862 Car Radio Enhanced Selectivity Tuner");
MODULE_AUTHOR("Mocean Laboratories");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
dhiru1602/android_kernel_samsung_smdk4412 | drivers/input/misc/cobalt_btns.c | 4200 | 4662 | /*
* Cobalt button interface driver.
*
* Copyright (C) 2007-2008 Yoichi Yuasa <yuasa@linux-mips.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This 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/init.h>
#include <linux/input-polldev.h>
#include <linux/ioport.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#define BUTTONS_POLL_INTERVAL 30 /* msec */
#define BUTTONS_COUNT_THRESHOLD 3
#define BUTTONS_STATUS_MASK 0xfe000000
static const unsigned short cobalt_map[] = {
KEY_RESERVED,
KEY_RESTART,
KEY_LEFT,
KEY_UP,
KEY_DOWN,
KEY_RIGHT,
KEY_ENTER,
KEY_SELECT
};
struct buttons_dev {
struct input_polled_dev *poll_dev;
unsigned short keymap[ARRAY_SIZE(cobalt_map)];
int count[ARRAY_SIZE(cobalt_map)];
void __iomem *reg;
};
static void handle_buttons(struct input_polled_dev *dev)
{
struct buttons_dev *bdev = dev->private;
struct input_dev *input = dev->input;
uint32_t status;
int i;
status = ~readl(bdev->reg) >> 24;
for (i = 0; i < ARRAY_SIZE(bdev->keymap); i++) {
if (status & (1U << i)) {
if (++bdev->count[i] == BUTTONS_COUNT_THRESHOLD) {
input_event(input, EV_MSC, MSC_SCAN, i);
input_report_key(input, bdev->keymap[i], 1);
input_sync(input);
}
} else {
if (bdev->count[i] >= BUTTONS_COUNT_THRESHOLD) {
input_event(input, EV_MSC, MSC_SCAN, i);
input_report_key(input, bdev->keymap[i], 0);
input_sync(input);
}
bdev->count[i] = 0;
}
}
}
static int __devinit cobalt_buttons_probe(struct platform_device *pdev)
{
struct buttons_dev *bdev;
struct input_polled_dev *poll_dev;
struct input_dev *input;
struct resource *res;
int error, i;
bdev = kzalloc(sizeof(struct buttons_dev), GFP_KERNEL);
poll_dev = input_allocate_polled_device();
if (!bdev || !poll_dev) {
error = -ENOMEM;
goto err_free_mem;
}
memcpy(bdev->keymap, cobalt_map, sizeof(bdev->keymap));
poll_dev->private = bdev;
poll_dev->poll = handle_buttons;
poll_dev->poll_interval = BUTTONS_POLL_INTERVAL;
input = poll_dev->input;
input->name = "Cobalt buttons";
input->phys = "cobalt/input0";
input->id.bustype = BUS_HOST;
input->dev.parent = &pdev->dev;
input->keycode = bdev->keymap;
input->keycodemax = ARRAY_SIZE(bdev->keymap);
input->keycodesize = sizeof(unsigned short);
input_set_capability(input, EV_MSC, MSC_SCAN);
__set_bit(EV_KEY, input->evbit);
for (i = 0; i < ARRAY_SIZE(cobalt_map); i++)
__set_bit(bdev->keymap[i], input->keybit);
__clear_bit(KEY_RESERVED, input->keybit);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
error = -EBUSY;
goto err_free_mem;
}
bdev->poll_dev = poll_dev;
bdev->reg = ioremap(res->start, resource_size(res));
dev_set_drvdata(&pdev->dev, bdev);
error = input_register_polled_device(poll_dev);
if (error)
goto err_iounmap;
return 0;
err_iounmap:
iounmap(bdev->reg);
err_free_mem:
input_free_polled_device(poll_dev);
kfree(bdev);
dev_set_drvdata(&pdev->dev, NULL);
return error;
}
static int __devexit cobalt_buttons_remove(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct buttons_dev *bdev = dev_get_drvdata(dev);
input_unregister_polled_device(bdev->poll_dev);
input_free_polled_device(bdev->poll_dev);
iounmap(bdev->reg);
kfree(bdev);
dev_set_drvdata(dev, NULL);
return 0;
}
MODULE_AUTHOR("Yoichi Yuasa <yuasa@linux-mips.org>");
MODULE_DESCRIPTION("Cobalt button interface driver");
MODULE_LICENSE("GPL");
/* work with hotplug and coldplug */
MODULE_ALIAS("platform:Cobalt buttons");
static struct platform_driver cobalt_buttons_driver = {
.probe = cobalt_buttons_probe,
.remove = __devexit_p(cobalt_buttons_remove),
.driver = {
.name = "Cobalt buttons",
.owner = THIS_MODULE,
},
};
static int __init cobalt_buttons_init(void)
{
return platform_driver_register(&cobalt_buttons_driver);
}
static void __exit cobalt_buttons_exit(void)
{
platform_driver_unregister(&cobalt_buttons_driver);
}
module_init(cobalt_buttons_init);
module_exit(cobalt_buttons_exit);
| gpl-2.0 |
cameron581/lge-kernel-gproj | fs/jbd2/recovery.c | 4456 | 19087 | /*
* linux/fs/jbd2/recovery.c
*
* Written by Stephen C. Tweedie <sct@redhat.com>, 1999
*
* Copyright 1999-2000 Red Hat Software --- All Rights Reserved
*
* This file is part of the Linux kernel and is made available under
* the terms of the GNU General Public License, version 2, or at your
* option, any later version, incorporated herein by reference.
*
* Journal recovery routines for the generic filesystem journaling code;
* part of the ext2fs journaling system.
*/
#ifndef __KERNEL__
#include "jfs_user.h"
#else
#include <linux/time.h>
#include <linux/fs.h>
#include <linux/jbd2.h>
#include <linux/errno.h>
#include <linux/crc32.h>
#include <linux/blkdev.h>
#endif
/*
* Maintain information about the progress of the recovery job, so that
* the different passes can carry information between them.
*/
struct recovery_info
{
tid_t start_transaction;
tid_t end_transaction;
int nr_replays;
int nr_revokes;
int nr_revoke_hits;
};
enum passtype {PASS_SCAN, PASS_REVOKE, PASS_REPLAY};
static int do_one_pass(journal_t *journal,
struct recovery_info *info, enum passtype pass);
static int scan_revoke_records(journal_t *, struct buffer_head *,
tid_t, struct recovery_info *);
#ifdef __KERNEL__
/* Release readahead buffers after use */
static void journal_brelse_array(struct buffer_head *b[], int n)
{
while (--n >= 0)
brelse (b[n]);
}
/*
* When reading from the journal, we are going through the block device
* layer directly and so there is no readahead being done for us. We
* need to implement any readahead ourselves if we want it to happen at
* all. Recovery is basically one long sequential read, so make sure we
* do the IO in reasonably large chunks.
*
* This is not so critical that we need to be enormously clever about
* the readahead size, though. 128K is a purely arbitrary, good-enough
* fixed value.
*/
#define MAXBUF 8
static int do_readahead(journal_t *journal, unsigned int start)
{
int err;
unsigned int max, nbufs, next;
unsigned long long blocknr;
struct buffer_head *bh;
struct buffer_head * bufs[MAXBUF];
/* Do up to 128K of readahead */
max = start + (128 * 1024 / journal->j_blocksize);
if (max > journal->j_maxlen)
max = journal->j_maxlen;
/* Do the readahead itself. We'll submit MAXBUF buffer_heads at
* a time to the block device IO layer. */
nbufs = 0;
for (next = start; next < max; next++) {
err = jbd2_journal_bmap(journal, next, &blocknr);
if (err) {
printk(KERN_ERR "JBD2: bad block at offset %u\n",
next);
goto failed;
}
bh = __getblk(journal->j_dev, blocknr, journal->j_blocksize);
if (!bh) {
err = -ENOMEM;
goto failed;
}
if (!buffer_uptodate(bh) && !buffer_locked(bh)) {
bufs[nbufs++] = bh;
if (nbufs == MAXBUF) {
ll_rw_block(READ, nbufs, bufs);
journal_brelse_array(bufs, nbufs);
nbufs = 0;
}
} else
brelse(bh);
}
if (nbufs)
ll_rw_block(READ, nbufs, bufs);
err = 0;
failed:
if (nbufs)
journal_brelse_array(bufs, nbufs);
return err;
}
#endif /* __KERNEL__ */
/*
* Read a block from the journal
*/
static int jread(struct buffer_head **bhp, journal_t *journal,
unsigned int offset)
{
int err;
unsigned long long blocknr;
struct buffer_head *bh;
*bhp = NULL;
if (offset >= journal->j_maxlen) {
printk(KERN_ERR "JBD2: corrupted journal superblock\n");
return -EIO;
}
err = jbd2_journal_bmap(journal, offset, &blocknr);
if (err) {
printk(KERN_ERR "JBD2: bad block at offset %u\n",
offset);
return err;
}
bh = __getblk(journal->j_dev, blocknr, journal->j_blocksize);
if (!bh)
return -ENOMEM;
if (!buffer_uptodate(bh)) {
/* If this is a brand new buffer, start readahead.
Otherwise, we assume we are already reading it. */
if (!buffer_req(bh))
do_readahead(journal, offset);
wait_on_buffer(bh);
}
if (!buffer_uptodate(bh)) {
printk(KERN_ERR "JBD2: Failed to read block at offset %u\n",
offset);
brelse(bh);
return -EIO;
}
*bhp = bh;
return 0;
}
/*
* Count the number of in-use tags in a journal descriptor block.
*/
static int count_tags(journal_t *journal, struct buffer_head *bh)
{
char * tagp;
journal_block_tag_t * tag;
int nr = 0, size = journal->j_blocksize;
int tag_bytes = journal_tag_bytes(journal);
tagp = &bh->b_data[sizeof(journal_header_t)];
while ((tagp - bh->b_data + tag_bytes) <= size) {
tag = (journal_block_tag_t *) tagp;
nr++;
tagp += tag_bytes;
if (!(tag->t_flags & cpu_to_be32(JBD2_FLAG_SAME_UUID)))
tagp += 16;
if (tag->t_flags & cpu_to_be32(JBD2_FLAG_LAST_TAG))
break;
}
return nr;
}
/* Make sure we wrap around the log correctly! */
#define wrap(journal, var) \
do { \
if (var >= (journal)->j_last) \
var -= ((journal)->j_last - (journal)->j_first); \
} while (0)
/**
* jbd2_journal_recover - recovers a on-disk journal
* @journal: the journal to recover
*
* The primary function for recovering the log contents when mounting a
* journaled device.
*
* Recovery is done in three passes. In the first pass, we look for the
* end of the log. In the second, we assemble the list of revoke
* blocks. In the third and final pass, we replay any un-revoked blocks
* in the log.
*/
int jbd2_journal_recover(journal_t *journal)
{
int err, err2;
journal_superblock_t * sb;
struct recovery_info info;
memset(&info, 0, sizeof(info));
sb = journal->j_superblock;
/*
* The journal superblock's s_start field (the current log head)
* is always zero if, and only if, the journal was cleanly
* unmounted.
*/
if (!sb->s_start) {
jbd_debug(1, "No recovery required, last transaction %d\n",
be32_to_cpu(sb->s_sequence));
journal->j_transaction_sequence = be32_to_cpu(sb->s_sequence) + 1;
return 0;
}
err = do_one_pass(journal, &info, PASS_SCAN);
if (!err)
err = do_one_pass(journal, &info, PASS_REVOKE);
if (!err)
err = do_one_pass(journal, &info, PASS_REPLAY);
jbd_debug(1, "JBD2: recovery, exit status %d, "
"recovered transactions %u to %u\n",
err, info.start_transaction, info.end_transaction);
jbd_debug(1, "JBD2: Replayed %d and revoked %d/%d blocks\n",
info.nr_replays, info.nr_revoke_hits, info.nr_revokes);
/* Restart the log at the next transaction ID, thus invalidating
* any existing commit records in the log. */
journal->j_transaction_sequence = ++info.end_transaction;
jbd2_journal_clear_revoke(journal);
err2 = sync_blockdev(journal->j_fs_dev);
if (!err)
err = err2;
/* Make sure all replayed data is on permanent storage */
if (journal->j_flags & JBD2_BARRIER)
blkdev_issue_flush(journal->j_fs_dev, GFP_KERNEL, NULL);
return err;
}
/**
* jbd2_journal_skip_recovery - Start journal and wipe exiting records
* @journal: journal to startup
*
* Locate any valid recovery information from the journal and set up the
* journal structures in memory to ignore it (presumably because the
* caller has evidence that it is out of date).
* This function does'nt appear to be exorted..
*
* We perform one pass over the journal to allow us to tell the user how
* much recovery information is being erased, and to let us initialise
* the journal transaction sequence numbers to the next unused ID.
*/
int jbd2_journal_skip_recovery(journal_t *journal)
{
int err;
struct recovery_info info;
memset (&info, 0, sizeof(info));
err = do_one_pass(journal, &info, PASS_SCAN);
if (err) {
printk(KERN_ERR "JBD2: error %d scanning journal\n", err);
++journal->j_transaction_sequence;
} else {
#ifdef CONFIG_JBD2_DEBUG
int dropped = info.end_transaction -
be32_to_cpu(journal->j_superblock->s_sequence);
jbd_debug(1,
"JBD2: ignoring %d transaction%s from the journal.\n",
dropped, (dropped == 1) ? "" : "s");
#endif
journal->j_transaction_sequence = ++info.end_transaction;
}
journal->j_tail = 0;
return err;
}
static inline unsigned long long read_tag_block(int tag_bytes, journal_block_tag_t *tag)
{
unsigned long long block = be32_to_cpu(tag->t_blocknr);
if (tag_bytes > JBD2_TAG_SIZE32)
block |= (u64)be32_to_cpu(tag->t_blocknr_high) << 32;
return block;
}
/*
* calc_chksums calculates the checksums for the blocks described in the
* descriptor block.
*/
static int calc_chksums(journal_t *journal, struct buffer_head *bh,
unsigned long *next_log_block, __u32 *crc32_sum)
{
int i, num_blks, err;
unsigned long io_block;
struct buffer_head *obh;
num_blks = count_tags(journal, bh);
/* Calculate checksum of the descriptor block. */
*crc32_sum = crc32_be(*crc32_sum, (void *)bh->b_data, bh->b_size);
for (i = 0; i < num_blks; i++) {
io_block = (*next_log_block)++;
wrap(journal, *next_log_block);
err = jread(&obh, journal, io_block);
if (err) {
printk(KERN_ERR "JBD2: IO error %d recovering block "
"%lu in log\n", err, io_block);
return 1;
} else {
*crc32_sum = crc32_be(*crc32_sum, (void *)obh->b_data,
obh->b_size);
}
put_bh(obh);
}
return 0;
}
static int do_one_pass(journal_t *journal,
struct recovery_info *info, enum passtype pass)
{
unsigned int first_commit_ID, next_commit_ID;
unsigned long next_log_block;
int err, success = 0;
journal_superblock_t * sb;
journal_header_t * tmp;
struct buffer_head * bh;
unsigned int sequence;
int blocktype;
int tag_bytes = journal_tag_bytes(journal);
__u32 crc32_sum = ~0; /* Transactional Checksums */
/*
* First thing is to establish what we expect to find in the log
* (in terms of transaction IDs), and where (in terms of log
* block offsets): query the superblock.
*/
sb = journal->j_superblock;
next_commit_ID = be32_to_cpu(sb->s_sequence);
next_log_block = be32_to_cpu(sb->s_start);
first_commit_ID = next_commit_ID;
if (pass == PASS_SCAN)
info->start_transaction = first_commit_ID;
jbd_debug(1, "Starting recovery pass %d\n", pass);
/*
* Now we walk through the log, transaction by transaction,
* making sure that each transaction has a commit block in the
* expected place. Each complete transaction gets replayed back
* into the main filesystem.
*/
while (1) {
int flags;
char * tagp;
journal_block_tag_t * tag;
struct buffer_head * obh;
struct buffer_head * nbh;
cond_resched();
/* If we already know where to stop the log traversal,
* check right now that we haven't gone past the end of
* the log. */
if (pass != PASS_SCAN)
if (tid_geq(next_commit_ID, info->end_transaction))
break;
jbd_debug(2, "Scanning for sequence ID %u at %lu/%lu\n",
next_commit_ID, next_log_block, journal->j_last);
/* Skip over each chunk of the transaction looking
* either the next descriptor block or the final commit
* record. */
jbd_debug(3, "JBD2: checking block %ld\n", next_log_block);
err = jread(&bh, journal, next_log_block);
if (err)
goto failed;
next_log_block++;
wrap(journal, next_log_block);
/* What kind of buffer is it?
*
* If it is a descriptor block, check that it has the
* expected sequence number. Otherwise, we're all done
* here. */
tmp = (journal_header_t *)bh->b_data;
if (tmp->h_magic != cpu_to_be32(JBD2_MAGIC_NUMBER)) {
brelse(bh);
break;
}
blocktype = be32_to_cpu(tmp->h_blocktype);
sequence = be32_to_cpu(tmp->h_sequence);
jbd_debug(3, "Found magic %d, sequence %d\n",
blocktype, sequence);
if (sequence != next_commit_ID) {
brelse(bh);
break;
}
/* OK, we have a valid descriptor block which matches
* all of the sequence number checks. What are we going
* to do with it? That depends on the pass... */
switch(blocktype) {
case JBD2_DESCRIPTOR_BLOCK:
/* If it is a valid descriptor block, replay it
* in pass REPLAY; if journal_checksums enabled, then
* calculate checksums in PASS_SCAN, otherwise,
* just skip over the blocks it describes. */
if (pass != PASS_REPLAY) {
if (pass == PASS_SCAN &&
JBD2_HAS_COMPAT_FEATURE(journal,
JBD2_FEATURE_COMPAT_CHECKSUM) &&
!info->end_transaction) {
if (calc_chksums(journal, bh,
&next_log_block,
&crc32_sum)) {
put_bh(bh);
break;
}
put_bh(bh);
continue;
}
next_log_block += count_tags(journal, bh);
wrap(journal, next_log_block);
put_bh(bh);
continue;
}
/* A descriptor block: we can now write all of
* the data blocks. Yay, useful work is finally
* getting done here! */
tagp = &bh->b_data[sizeof(journal_header_t)];
while ((tagp - bh->b_data + tag_bytes)
<= journal->j_blocksize) {
unsigned long io_block;
tag = (journal_block_tag_t *) tagp;
flags = be32_to_cpu(tag->t_flags);
io_block = next_log_block++;
wrap(journal, next_log_block);
err = jread(&obh, journal, io_block);
if (err) {
/* Recover what we can, but
* report failure at the end. */
success = err;
printk(KERN_ERR
"JBD2: IO error %d recovering "
"block %ld in log\n",
err, io_block);
} else {
unsigned long long blocknr;
J_ASSERT(obh != NULL);
blocknr = read_tag_block(tag_bytes,
tag);
/* If the block has been
* revoked, then we're all done
* here. */
if (jbd2_journal_test_revoke
(journal, blocknr,
next_commit_ID)) {
brelse(obh);
++info->nr_revoke_hits;
goto skip_write;
}
/* Find a buffer for the new
* data being restored */
nbh = __getblk(journal->j_fs_dev,
blocknr,
journal->j_blocksize);
if (nbh == NULL) {
printk(KERN_ERR
"JBD2: Out of memory "
"during recovery.\n");
err = -ENOMEM;
brelse(bh);
brelse(obh);
goto failed;
}
lock_buffer(nbh);
memcpy(nbh->b_data, obh->b_data,
journal->j_blocksize);
if (flags & JBD2_FLAG_ESCAPE) {
*((__be32 *)nbh->b_data) =
cpu_to_be32(JBD2_MAGIC_NUMBER);
}
BUFFER_TRACE(nbh, "marking dirty");
set_buffer_uptodate(nbh);
mark_buffer_dirty(nbh);
BUFFER_TRACE(nbh, "marking uptodate");
++info->nr_replays;
/* ll_rw_block(WRITE, 1, &nbh); */
unlock_buffer(nbh);
brelse(obh);
brelse(nbh);
}
skip_write:
tagp += tag_bytes;
if (!(flags & JBD2_FLAG_SAME_UUID))
tagp += 16;
if (flags & JBD2_FLAG_LAST_TAG)
break;
}
brelse(bh);
continue;
case JBD2_COMMIT_BLOCK:
/* How to differentiate between interrupted commit
* and journal corruption ?
*
* {nth transaction}
* Checksum Verification Failed
* |
* ____________________
* | |
* async_commit sync_commit
* | |
* | GO TO NEXT "Journal Corruption"
* | TRANSACTION
* |
* {(n+1)th transanction}
* |
* _______|______________
* | |
* Commit block found Commit block not found
* | |
* "Journal Corruption" |
* _____________|_________
* | |
* nth trans corrupt OR nth trans
* and (n+1)th interrupted interrupted
* before commit block
* could reach the disk.
* (Cannot find the difference in above
* mentioned conditions. Hence assume
* "Interrupted Commit".)
*/
/* Found an expected commit block: if checksums
* are present verify them in PASS_SCAN; else not
* much to do other than move on to the next sequence
* number. */
if (pass == PASS_SCAN &&
JBD2_HAS_COMPAT_FEATURE(journal,
JBD2_FEATURE_COMPAT_CHECKSUM)) {
int chksum_err, chksum_seen;
struct commit_header *cbh =
(struct commit_header *)bh->b_data;
unsigned found_chksum =
be32_to_cpu(cbh->h_chksum[0]);
chksum_err = chksum_seen = 0;
if (info->end_transaction) {
journal->j_failed_commit =
info->end_transaction;
brelse(bh);
break;
}
if (crc32_sum == found_chksum &&
cbh->h_chksum_type == JBD2_CRC32_CHKSUM &&
cbh->h_chksum_size ==
JBD2_CRC32_CHKSUM_SIZE)
chksum_seen = 1;
else if (!(cbh->h_chksum_type == 0 &&
cbh->h_chksum_size == 0 &&
found_chksum == 0 &&
!chksum_seen))
/*
* If fs is mounted using an old kernel and then
* kernel with journal_chksum is used then we
* get a situation where the journal flag has
* checksum flag set but checksums are not
* present i.e chksum = 0, in the individual
* commit blocks.
* Hence to avoid checksum failures, in this
* situation, this extra check is added.
*/
chksum_err = 1;
if (chksum_err) {
info->end_transaction = next_commit_ID;
if (!JBD2_HAS_INCOMPAT_FEATURE(journal,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT)){
journal->j_failed_commit =
next_commit_ID;
brelse(bh);
break;
}
}
crc32_sum = ~0;
}
brelse(bh);
next_commit_ID++;
continue;
case JBD2_REVOKE_BLOCK:
/* If we aren't in the REVOKE pass, then we can
* just skip over this block. */
if (pass != PASS_REVOKE) {
brelse(bh);
continue;
}
err = scan_revoke_records(journal, bh,
next_commit_ID, info);
brelse(bh);
if (err)
goto failed;
continue;
default:
jbd_debug(3, "Unrecognised magic %d, end of scan.\n",
blocktype);
brelse(bh);
goto done;
}
}
done:
/*
* We broke out of the log scan loop: either we came to the
* known end of the log or we found an unexpected block in the
* log. If the latter happened, then we know that the "current"
* transaction marks the end of the valid log.
*/
if (pass == PASS_SCAN) {
if (!info->end_transaction)
info->end_transaction = next_commit_ID;
} else {
/* It's really bad news if different passes end up at
* different places (but possible due to IO errors). */
if (info->end_transaction != next_commit_ID) {
printk(KERN_ERR "JBD2: recovery pass %d ended at "
"transaction %u, expected %u\n",
pass, next_commit_ID, info->end_transaction);
if (!success)
success = -EIO;
}
}
return success;
failed:
return err;
}
/* Scan a revoke record, marking all blocks mentioned as revoked. */
static int scan_revoke_records(journal_t *journal, struct buffer_head *bh,
tid_t sequence, struct recovery_info *info)
{
jbd2_journal_revoke_header_t *header;
int offset, max;
int record_len = 4;
header = (jbd2_journal_revoke_header_t *) bh->b_data;
offset = sizeof(jbd2_journal_revoke_header_t);
max = be32_to_cpu(header->r_count);
if (JBD2_HAS_INCOMPAT_FEATURE(journal, JBD2_FEATURE_INCOMPAT_64BIT))
record_len = 8;
while (offset + record_len <= max) {
unsigned long long blocknr;
int err;
if (record_len == 4)
blocknr = be32_to_cpu(* ((__be32 *) (bh->b_data+offset)));
else
blocknr = be64_to_cpu(* ((__be64 *) (bh->b_data+offset)));
offset += record_len;
err = jbd2_journal_set_revoke(journal, blocknr, sequence);
if (err)
return err;
++info->nr_revokes;
}
return 0;
}
| gpl-2.0 |
profglavcho/ALPS.L0.MP8.V2.1_LCSH6735_65C_HZ_L_KERNEL | drivers/scsi/libsas/sas_dump.c | 4712 | 2348 | /*
* 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",
[4] = "PHYE_RESUME_TIMEOUT",
};
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 |
AAN3AC/android_kernel_google_msm | arch/arm/mach-at91/board-rm9200ek.c | 4712 | 5061 | /*
* linux/arch/arm/mach-at91/board-rm9200ek.c
*
* Copyright (C) 2005 SAN People
*
* Epson S1D framebuffer glue code is:
* Copyright (C) 2005 Thibaut VARENE <varenet@parisc-linux.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/types.h>
#include <linux/gpio.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/spi/spi.h>
#include <linux/mtd/physmap.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <asm/irq.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/hardware.h>
#include <mach/board.h>
#include <mach/at91rm9200_mc.h>
#include <mach/at91_ramc.h>
#include "generic.h"
static void __init ek_init_early(void)
{
/* Initialize processor: 18.432 MHz crystal */
at91_initialize(18432000);
/* Setup the LEDs */
at91_init_leds(AT91_PIN_PB1, AT91_PIN_PB2);
/* DBGU on ttyS0. (Rx & Tx only) */
at91_register_uart(0, 0, 0);
/* USART1 on ttyS1. (Rx, Tx, CTS, RTS, DTR, DSR, DCD, RI) */
at91_register_uart(AT91RM9200_ID_US1, 1, ATMEL_UART_CTS | ATMEL_UART_RTS
| ATMEL_UART_DTR | ATMEL_UART_DSR | ATMEL_UART_DCD
| ATMEL_UART_RI);
/* set serial console to ttyS0 (ie, DBGU) */
at91_set_serial_console(0);
}
static struct macb_platform_data __initdata ek_eth_data = {
.phy_irq_pin = AT91_PIN_PC4,
.is_rmii = 1,
};
static struct at91_usbh_data __initdata ek_usbh_data = {
.ports = 2,
.vbus_pin = {-EINVAL, -EINVAL},
.overcurrent_pin= {-EINVAL, -EINVAL},
};
static struct at91_udc_data __initdata ek_udc_data = {
.vbus_pin = AT91_PIN_PD4,
.pullup_pin = AT91_PIN_PD5,
};
#ifndef CONFIG_MTD_AT91_DATAFLASH_CARD
static struct at91_mmc_data __initdata ek_mmc_data = {
.det_pin = AT91_PIN_PB27,
.slot_b = 0,
.wire4 = 1,
.wp_pin = AT91_PIN_PA17,
.vcc_pin = -EINVAL,
};
#endif
static struct spi_board_info ek_spi_devices[] = {
{ /* DataFlash chip */
.modalias = "mtd_dataflash",
.chip_select = 0,
.max_speed_hz = 15 * 1000 * 1000,
},
#ifdef CONFIG_MTD_AT91_DATAFLASH_CARD
{ /* DataFlash card */
.modalias = "mtd_dataflash",
.chip_select = 3,
.max_speed_hz = 15 * 1000 * 1000,
},
#endif
};
static struct i2c_board_info __initdata ek_i2c_devices[] = {
{
I2C_BOARD_INFO("ics1523", 0x26),
},
{
I2C_BOARD_INFO("dac3550", 0x4d),
}
};
#define EK_FLASH_BASE AT91_CHIPSELECT_0
#define EK_FLASH_SIZE SZ_8M
static struct physmap_flash_data ek_flash_data = {
.width = 2,
};
static struct resource ek_flash_resource = {
.start = EK_FLASH_BASE,
.end = EK_FLASH_BASE + EK_FLASH_SIZE - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device ek_flash = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &ek_flash_data,
},
.resource = &ek_flash_resource,
.num_resources = 1,
};
static struct gpio_led ek_leds[] = {
{ /* "user led 1", DS2 */
.name = "green",
.gpio = AT91_PIN_PB0,
.active_low = 1,
.default_trigger = "mmc0",
},
{ /* "user led 2", DS4 */
.name = "yellow",
.gpio = AT91_PIN_PB1,
.active_low = 1,
.default_trigger = "heartbeat",
},
{ /* "user led 3", DS6 */
.name = "red",
.gpio = AT91_PIN_PB2,
.active_low = 1,
}
};
static void __init ek_board_init(void)
{
/* Serial */
at91_add_device_serial();
/* Ethernet */
at91_add_device_eth(&ek_eth_data);
/* USB Host */
at91_add_device_usbh(&ek_usbh_data);
/* USB Device */
at91_add_device_udc(&ek_udc_data);
at91_set_multi_drive(ek_udc_data.pullup_pin, 1); /* pullup_pin is connected to reset */
/* I2C */
at91_add_device_i2c(ek_i2c_devices, ARRAY_SIZE(ek_i2c_devices));
/* SPI */
at91_add_device_spi(ek_spi_devices, ARRAY_SIZE(ek_spi_devices));
#ifdef CONFIG_MTD_AT91_DATAFLASH_CARD
/* DataFlash card */
at91_set_gpio_output(AT91_PIN_PB22, 0);
#else
/* MMC */
at91_set_gpio_output(AT91_PIN_PB22, 1); /* this MMC card slot can optionally use SPI signaling (CS3). */
at91_add_device_mmc(0, &ek_mmc_data);
#endif
/* NOR Flash */
platform_device_register(&ek_flash);
/* LEDs */
at91_gpio_leds(ek_leds, ARRAY_SIZE(ek_leds));
/* VGA */
// ek_add_device_video();
}
MACHINE_START(AT91RM9200EK, "Atmel AT91RM9200-EK")
/* Maintainer: SAN People/Atmel */
.timer = &at91rm9200_timer,
.map_io = at91_map_io,
.init_early = ek_init_early,
.init_irq = at91_init_irq_default,
.init_machine = ek_board_init,
MACHINE_END
| gpl-2.0 |
TeamExodus/kernel_lge_hammerhead | arch/arm/mach-at91/board-sam9261ek.c | 4712 | 15004 | /*
* linux/arch/arm/mach-at91/board-sam9261ek.c
*
* Copyright (C) 2005 SAN People
* Copyright (C) 2006 Atmel
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/types.h>
#include <linux/gpio.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/spi/spi.h>
#include <linux/spi/ads7846.h>
#include <linux/spi/at73c213.h>
#include <linux/clk.h>
#include <linux/dm9000.h>
#include <linux/fb.h>
#include <linux/gpio_keys.h>
#include <linux/input.h>
#include <video/atmel_lcdc.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <asm/irq.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/hardware.h>
#include <mach/board.h>
#include <mach/at91sam9_smc.h>
#include <mach/at91_shdwc.h>
#include <mach/system_rev.h>
#include "sam9_smc.h"
#include "generic.h"
static void __init ek_init_early(void)
{
/* Initialize processor: 18.432 MHz crystal */
at91_initialize(18432000);
/* Setup the LEDs */
at91_init_leds(AT91_PIN_PA13, AT91_PIN_PA14);
/* DBGU on ttyS0. (Rx & Tx only) */
at91_register_uart(0, 0, 0);
/* set serial console to ttyS0 (ie, DBGU) */
at91_set_serial_console(0);
}
/*
* DM9000 ethernet device
*/
#if defined(CONFIG_DM9000)
static struct resource dm9000_resource[] = {
[0] = {
.start = AT91_CHIPSELECT_2,
.end = AT91_CHIPSELECT_2 + 3,
.flags = IORESOURCE_MEM
},
[1] = {
.start = AT91_CHIPSELECT_2 + 0x44,
.end = AT91_CHIPSELECT_2 + 0xFF,
.flags = IORESOURCE_MEM
},
[2] = {
.flags = IORESOURCE_IRQ
| IORESOURCE_IRQ_LOWEDGE | IORESOURCE_IRQ_HIGHEDGE,
}
};
static struct dm9000_plat_data dm9000_platdata = {
.flags = DM9000_PLATF_16BITONLY | DM9000_PLATF_NO_EEPROM,
};
static struct platform_device dm9000_device = {
.name = "dm9000",
.id = 0,
.num_resources = ARRAY_SIZE(dm9000_resource),
.resource = dm9000_resource,
.dev = {
.platform_data = &dm9000_platdata,
}
};
/*
* SMC timings for the DM9000.
* Note: These timings were calculated for MASTER_CLOCK = 100000000 according to the DM9000 timings.
*/
static struct sam9_smc_config __initdata dm9000_smc_config = {
.ncs_read_setup = 0,
.nrd_setup = 2,
.ncs_write_setup = 0,
.nwe_setup = 2,
.ncs_read_pulse = 8,
.nrd_pulse = 4,
.ncs_write_pulse = 8,
.nwe_pulse = 4,
.read_cycle = 16,
.write_cycle = 16,
.mode = AT91_SMC_READMODE | AT91_SMC_WRITEMODE | AT91_SMC_EXNWMODE_DISABLE | AT91_SMC_BAT_WRITE | AT91_SMC_DBW_16,
.tdf_cycles = 1,
};
static void __init ek_add_device_dm9000(void)
{
struct resource *r = &dm9000_resource[2];
/* Configure chip-select 2 (DM9000) */
sam9_smc_configure(0, 2, &dm9000_smc_config);
/* Configure Reset signal as output */
at91_set_gpio_output(AT91_PIN_PC10, 0);
/* Configure Interrupt pin as input, no pull-up */
at91_set_gpio_input(AT91_PIN_PC11, 0);
r->start = r->end = gpio_to_irq(AT91_PIN_PC11);
platform_device_register(&dm9000_device);
}
#else
static void __init ek_add_device_dm9000(void) {}
#endif /* CONFIG_DM9000 */
/*
* USB Host Port
*/
static struct at91_usbh_data __initdata ek_usbh_data = {
.ports = 2,
.vbus_pin = {-EINVAL, -EINVAL},
.overcurrent_pin= {-EINVAL, -EINVAL},
};
/*
* USB Device Port
*/
static struct at91_udc_data __initdata ek_udc_data = {
.vbus_pin = AT91_PIN_PB29,
.pullup_pin = -EINVAL, /* pull-up driven by UDC */
};
/*
* NAND flash
*/
static struct mtd_partition __initdata ek_nand_partition[] = {
{
.name = "Partition 1",
.offset = 0,
.size = SZ_256K,
},
{
.name = "Partition 2",
.offset = MTDPART_OFS_NXTBLK,
.size = MTDPART_SIZ_FULL,
},
};
static struct atmel_nand_data __initdata ek_nand_data = {
.ale = 22,
.cle = 21,
.det_pin = -EINVAL,
.rdy_pin = AT91_PIN_PC15,
.enable_pin = AT91_PIN_PC14,
.ecc_mode = NAND_ECC_SOFT,
.on_flash_bbt = 1,
.parts = ek_nand_partition,
.num_parts = ARRAY_SIZE(ek_nand_partition),
};
static struct sam9_smc_config __initdata ek_nand_smc_config = {
.ncs_read_setup = 0,
.nrd_setup = 1,
.ncs_write_setup = 0,
.nwe_setup = 1,
.ncs_read_pulse = 3,
.nrd_pulse = 3,
.ncs_write_pulse = 3,
.nwe_pulse = 3,
.read_cycle = 5,
.write_cycle = 5,
.mode = AT91_SMC_READMODE | AT91_SMC_WRITEMODE | AT91_SMC_EXNWMODE_DISABLE,
.tdf_cycles = 2,
};
static void __init ek_add_device_nand(void)
{
ek_nand_data.bus_width_16 = board_have_nand_16bit();
/* setup bus-width (8 or 16) */
if (ek_nand_data.bus_width_16)
ek_nand_smc_config.mode |= AT91_SMC_DBW_16;
else
ek_nand_smc_config.mode |= AT91_SMC_DBW_8;
/* configure chip-select 3 (NAND) */
sam9_smc_configure(0, 3, &ek_nand_smc_config);
at91_add_device_nand(&ek_nand_data);
}
/*
* SPI related devices
*/
#if defined(CONFIG_SPI_ATMEL) || defined(CONFIG_SPI_ATMEL_MODULE)
/*
* ADS7846 Touchscreen
*/
#if defined(CONFIG_TOUCHSCREEN_ADS7846) || defined(CONFIG_TOUCHSCREEN_ADS7846_MODULE)
static int ads7843_pendown_state(void)
{
return !at91_get_gpio_value(AT91_PIN_PC2); /* Touchscreen PENIRQ */
}
static struct ads7846_platform_data ads_info = {
.model = 7843,
.x_min = 150,
.x_max = 3830,
.y_min = 190,
.y_max = 3830,
.vref_delay_usecs = 100,
.x_plate_ohms = 450,
.y_plate_ohms = 250,
.pressure_max = 15000,
.debounce_max = 1,
.debounce_rep = 0,
.debounce_tol = (~0),
.get_pendown_state = ads7843_pendown_state,
};
static void __init ek_add_device_ts(void)
{
at91_set_B_periph(AT91_PIN_PC2, 1); /* External IRQ0, with pullup */
at91_set_gpio_input(AT91_PIN_PA11, 1); /* Touchscreen BUSY signal */
}
#else
static void __init ek_add_device_ts(void) {}
#endif
/*
* Audio
*/
static struct at73c213_board_info at73c213_data = {
.ssc_id = 1,
#if defined(CONFIG_MACH_AT91SAM9261EK)
.shortname = "AT91SAM9261-EK external DAC",
#else
.shortname = "AT91SAM9G10-EK external DAC",
#endif
};
#if defined(CONFIG_SND_AT73C213) || defined(CONFIG_SND_AT73C213_MODULE)
static void __init at73c213_set_clk(struct at73c213_board_info *info)
{
struct clk *pck2;
struct clk *plla;
pck2 = clk_get(NULL, "pck2");
plla = clk_get(NULL, "plla");
/* AT73C213 MCK Clock */
at91_set_B_periph(AT91_PIN_PB31, 0); /* PCK2 */
clk_set_parent(pck2, plla);
clk_put(plla);
info->dac_clk = pck2;
}
#else
static void __init at73c213_set_clk(struct at73c213_board_info *info) {}
#endif
/*
* SPI devices
*/
static struct spi_board_info ek_spi_devices[] = {
{ /* DataFlash chip */
.modalias = "mtd_dataflash",
.chip_select = 0,
.max_speed_hz = 15 * 1000 * 1000,
.bus_num = 0,
},
#if defined(CONFIG_TOUCHSCREEN_ADS7846) || defined(CONFIG_TOUCHSCREEN_ADS7846_MODULE)
{
.modalias = "ads7846",
.chip_select = 2,
.max_speed_hz = 125000 * 26, /* (max sample rate @ 3V) * (cmd + data + overhead) */
.bus_num = 0,
.platform_data = &ads_info,
.irq = AT91SAM9261_ID_IRQ0,
.controller_data = (void *) AT91_PIN_PA28, /* CS pin */
},
#endif
#if defined(CONFIG_MTD_AT91_DATAFLASH_CARD)
{ /* DataFlash card - jumper (J12) configurable to CS3 or CS0 */
.modalias = "mtd_dataflash",
.chip_select = 3,
.max_speed_hz = 15 * 1000 * 1000,
.bus_num = 0,
},
#elif defined(CONFIG_SND_AT73C213) || defined(CONFIG_SND_AT73C213_MODULE)
{ /* AT73C213 DAC */
.modalias = "at73c213",
.chip_select = 3,
.max_speed_hz = 10 * 1000 * 1000,
.bus_num = 0,
.mode = SPI_MODE_1,
.platform_data = &at73c213_data,
.controller_data = (void*) AT91_PIN_PA29, /* default for CS3 is PA6, but it must be PA29 */
},
#endif
};
#else /* CONFIG_SPI_ATMEL_* */
/* spi0 and mmc/sd share the same PIO pins: cannot be used at the same time */
/*
* MCI (SD/MMC)
* det_pin, wp_pin and vcc_pin are not connected
*/
static struct at91_mmc_data __initdata ek_mmc_data = {
.wire4 = 1,
.det_pin = -EINVAL,
.wp_pin = -EINVAL,
.vcc_pin = -EINVAL,
};
#endif /* CONFIG_SPI_ATMEL_* */
/*
* LCD Controller
*/
#if defined(CONFIG_FB_ATMEL) || defined(CONFIG_FB_ATMEL_MODULE)
#if defined(CONFIG_FB_ATMEL_STN)
/* STN */
static struct fb_videomode at91_stn_modes[] = {
{
.name = "SP06Q002 @ 75",
.refresh = 75,
.xres = 320, .yres = 240,
.pixclock = KHZ2PICOS(1440),
.left_margin = 1, .right_margin = 1,
.upper_margin = 0, .lower_margin = 0,
.hsync_len = 1, .vsync_len = 1,
.sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
.vmode = FB_VMODE_NONINTERLACED,
},
};
static struct fb_monspecs at91fb_default_stn_monspecs = {
.manufacturer = "HIT",
.monitor = "SP06Q002",
.modedb = at91_stn_modes,
.modedb_len = ARRAY_SIZE(at91_stn_modes),
.hfmin = 15000,
.hfmax = 64000,
.vfmin = 50,
.vfmax = 150,
};
#define AT91SAM9261_DEFAULT_STN_LCDCON2 (ATMEL_LCDC_MEMOR_LITTLE \
| ATMEL_LCDC_DISTYPE_STNMONO \
| ATMEL_LCDC_CLKMOD_ALWAYSACTIVE \
| ATMEL_LCDC_IFWIDTH_4 \
| ATMEL_LCDC_SCANMOD_SINGLE)
static void at91_lcdc_stn_power_control(int on)
{
/* backlight */
if (on) { /* power up */
at91_set_gpio_value(AT91_PIN_PC14, 0);
at91_set_gpio_value(AT91_PIN_PC15, 0);
} else { /* power down */
at91_set_gpio_value(AT91_PIN_PC14, 1);
at91_set_gpio_value(AT91_PIN_PC15, 1);
}
}
static struct atmel_lcdfb_info __initdata ek_lcdc_data = {
.default_bpp = 1,
.default_dmacon = ATMEL_LCDC_DMAEN,
.default_lcdcon2 = AT91SAM9261_DEFAULT_STN_LCDCON2,
.default_monspecs = &at91fb_default_stn_monspecs,
.atmel_lcdfb_power_control = at91_lcdc_stn_power_control,
.guard_time = 1,
#if defined(CONFIG_MACH_AT91SAM9G10EK)
.lcd_wiring_mode = ATMEL_LCDC_WIRING_RGB,
#endif
};
#else
/* TFT */
static struct fb_videomode at91_tft_vga_modes[] = {
{
.name = "TX09D50VM1CCA @ 60",
.refresh = 60,
.xres = 240, .yres = 320,
.pixclock = KHZ2PICOS(4965),
.left_margin = 1, .right_margin = 33,
.upper_margin = 1, .lower_margin = 0,
.hsync_len = 5, .vsync_len = 1,
.sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
.vmode = FB_VMODE_NONINTERLACED,
},
};
static struct fb_monspecs at91fb_default_tft_monspecs = {
.manufacturer = "HIT",
.monitor = "TX09D50VM1CCA",
.modedb = at91_tft_vga_modes,
.modedb_len = ARRAY_SIZE(at91_tft_vga_modes),
.hfmin = 15000,
.hfmax = 64000,
.vfmin = 50,
.vfmax = 150,
};
#define AT91SAM9261_DEFAULT_TFT_LCDCON2 (ATMEL_LCDC_MEMOR_LITTLE \
| ATMEL_LCDC_DISTYPE_TFT \
| ATMEL_LCDC_CLKMOD_ALWAYSACTIVE)
static void at91_lcdc_tft_power_control(int on)
{
if (on)
at91_set_gpio_value(AT91_PIN_PA12, 0); /* power up */
else
at91_set_gpio_value(AT91_PIN_PA12, 1); /* power down */
}
static struct atmel_lcdfb_info __initdata ek_lcdc_data = {
.lcdcon_is_backlight = true,
.default_bpp = 16,
.default_dmacon = ATMEL_LCDC_DMAEN,
.default_lcdcon2 = AT91SAM9261_DEFAULT_TFT_LCDCON2,
.default_monspecs = &at91fb_default_tft_monspecs,
.atmel_lcdfb_power_control = at91_lcdc_tft_power_control,
.guard_time = 1,
#if defined(CONFIG_MACH_AT91SAM9G10EK)
.lcd_wiring_mode = ATMEL_LCDC_WIRING_RGB,
#endif
};
#endif
#else
static struct atmel_lcdfb_info __initdata ek_lcdc_data;
#endif
/*
* GPIO Buttons
*/
#if defined(CONFIG_KEYBOARD_GPIO) || defined(CONFIG_KEYBOARD_GPIO_MODULE)
static struct gpio_keys_button ek_buttons[] = {
{
.gpio = AT91_PIN_PA27,
.code = BTN_0,
.desc = "Button 0",
.active_low = 1,
.wakeup = 1,
},
{
.gpio = AT91_PIN_PA26,
.code = BTN_1,
.desc = "Button 1",
.active_low = 1,
.wakeup = 1,
},
{
.gpio = AT91_PIN_PA25,
.code = BTN_2,
.desc = "Button 2",
.active_low = 1,
.wakeup = 1,
},
{
.gpio = AT91_PIN_PA24,
.code = BTN_3,
.desc = "Button 3",
.active_low = 1,
.wakeup = 1,
}
};
static struct gpio_keys_platform_data ek_button_data = {
.buttons = ek_buttons,
.nbuttons = ARRAY_SIZE(ek_buttons),
};
static struct platform_device ek_button_device = {
.name = "gpio-keys",
.id = -1,
.num_resources = 0,
.dev = {
.platform_data = &ek_button_data,
}
};
static void __init ek_add_device_buttons(void)
{
at91_set_gpio_input(AT91_PIN_PA27, 1); /* btn0 */
at91_set_deglitch(AT91_PIN_PA27, 1);
at91_set_gpio_input(AT91_PIN_PA26, 1); /* btn1 */
at91_set_deglitch(AT91_PIN_PA26, 1);
at91_set_gpio_input(AT91_PIN_PA25, 1); /* btn2 */
at91_set_deglitch(AT91_PIN_PA25, 1);
at91_set_gpio_input(AT91_PIN_PA24, 1); /* btn3 */
at91_set_deglitch(AT91_PIN_PA24, 1);
platform_device_register(&ek_button_device);
}
#else
static void __init ek_add_device_buttons(void) {}
#endif
/*
* LEDs
*/
static struct gpio_led ek_leds[] = {
{ /* "bottom" led, green, userled1 to be defined */
.name = "ds7",
.gpio = AT91_PIN_PA14,
.active_low = 1,
.default_trigger = "none",
},
{ /* "top" led, green, userled2 to be defined */
.name = "ds8",
.gpio = AT91_PIN_PA13,
.active_low = 1,
.default_trigger = "none",
},
{ /* "power" led, yellow */
.name = "ds1",
.gpio = AT91_PIN_PA23,
.default_trigger = "heartbeat",
}
};
static void __init ek_board_init(void)
{
/* Serial */
at91_add_device_serial();
/* USB Host */
at91_add_device_usbh(&ek_usbh_data);
/* USB Device */
at91_add_device_udc(&ek_udc_data);
/* I2C */
at91_add_device_i2c(NULL, 0);
/* NAND */
ek_add_device_nand();
/* DM9000 ethernet */
ek_add_device_dm9000();
/* spi0 and mmc/sd share the same PIO pins */
#if defined(CONFIG_SPI_ATMEL) || defined(CONFIG_SPI_ATMEL_MODULE)
/* SPI */
at91_add_device_spi(ek_spi_devices, ARRAY_SIZE(ek_spi_devices));
/* Touchscreen */
ek_add_device_ts();
/* SSC (to AT73C213) */
at73c213_set_clk(&at73c213_data);
at91_add_device_ssc(AT91SAM9261_ID_SSC1, ATMEL_SSC_TX);
#else
/* MMC */
at91_add_device_mmc(0, &ek_mmc_data);
#endif
/* LCD Controller */
at91_add_device_lcdc(&ek_lcdc_data);
/* Push Buttons */
ek_add_device_buttons();
/* LEDs */
at91_gpio_leds(ek_leds, ARRAY_SIZE(ek_leds));
}
#if defined(CONFIG_MACH_AT91SAM9261EK)
MACHINE_START(AT91SAM9261EK, "Atmel AT91SAM9261-EK")
#else
MACHINE_START(AT91SAM9G10EK, "Atmel AT91SAM9G10-EK")
#endif
/* Maintainer: Atmel */
.timer = &at91sam926x_timer,
.map_io = at91_map_io,
.init_early = ek_init_early,
.init_irq = at91_init_irq_default,
.init_machine = ek_board_init,
MACHINE_END
| gpl-2.0 |
sktjdgns1189/android_kernel_samsung_c1skt | arch/mips/fw/arc/tree.c | 12136 | 3220 | /*
* 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.
*
* PROM component device tree code.
*
* Copyright (C) 1996 David S. Miller (davem@davemloft.net)
* Copyright (C) 1999 Ralf Baechle (ralf@gnu.org)
* Copyright (C) 1999 Silicon Graphics, Inc.
*/
#include <linux/init.h>
#include <asm/fw/arc/types.h>
#include <asm/sgialib.h>
#undef DEBUG_PROM_TREE
pcomponent * __init
ArcGetPeer(pcomponent *Current)
{
if (Current == PROM_NULL_COMPONENT)
return PROM_NULL_COMPONENT;
return (pcomponent *) ARC_CALL1(next_component, Current);
}
pcomponent * __init
ArcGetChild(pcomponent *Current)
{
return (pcomponent *) ARC_CALL1(child_component, Current);
}
pcomponent * __init
ArcGetParent(pcomponent *Current)
{
if (Current == PROM_NULL_COMPONENT)
return PROM_NULL_COMPONENT;
return (pcomponent *) ARC_CALL1(parent_component, Current);
}
LONG __init
ArcGetConfigurationData(VOID *Buffer, pcomponent *Current)
{
return ARC_CALL2(component_data, Buffer, Current);
}
pcomponent * __init
ArcAddChild(pcomponent *Current, pcomponent *Template, VOID *ConfigurationData)
{
return (pcomponent *)
ARC_CALL3(child_add, Current, Template, ConfigurationData);
}
LONG __init
ArcDeleteComponent(pcomponent *ComponentToDelete)
{
return ARC_CALL1(comp_del, ComponentToDelete);
}
pcomponent * __init
ArcGetComponent(CHAR *Path)
{
return (pcomponent *)ARC_CALL1(component_by_path, Path);
}
#ifdef DEBUG_PROM_TREE
static char *classes[] = {
"system", "processor", "cache", "adapter", "controller", "peripheral",
"memory"
};
static char *types[] = {
"arc", "cpu", "fpu", "picache", "pdcache", "sicache", "sdcache",
"sccache", "memdev", "eisa adapter", "tc adapter", "scsi adapter",
"dti adapter", "multi-func adapter", "disk controller",
"tp controller", "cdrom controller", "worm controller",
"serial controller", "net controller", "display controller",
"parallel controller", "pointer controller", "keyboard controller",
"audio controller", "misc controller", "disk peripheral",
"floppy peripheral", "tp peripheral", "modem peripheral",
"monitor peripheral", "printer peripheral", "pointer peripheral",
"keyboard peripheral", "terminal peripheral", "line peripheral",
"net peripheral", "misc peripheral", "anonymous"
};
static char *iflags[] = {
"bogus", "read only", "removable", "console in", "console out",
"input", "output"
};
static void __init
dump_component(pcomponent *p)
{
printk("[%p]:class<%s>type<%s>flags<%s>ver<%d>rev<%d>",
p, classes[p->class], types[p->type],
iflags[p->iflags], p->vers, p->rev);
printk("key<%08lx>\n\tamask<%08lx>cdsize<%d>ilen<%d>iname<%s>\n",
p->key, p->amask, (int)p->cdsize, (int)p->ilen, p->iname);
}
static void __init
traverse(pcomponent *p, int op)
{
dump_component(p);
if(ArcGetChild(p))
traverse(ArcGetChild(p), 1);
if(ArcGetPeer(p) && op)
traverse(ArcGetPeer(p), 1);
}
void __init
prom_testtree(void)
{
pcomponent *p;
p = ArcGetChild(PROM_NULL_COMPONENT);
dump_component(p);
p = ArcGetChild(p);
while(p) {
dump_component(p);
p = ArcGetPeer(p);
}
}
#endif /* DEBUG_PROM_TREE */
| gpl-2.0 |
Renzo-Olivares/BAMF_android_kernel_htc_msm8660 | net/ipv6/ip6_input.c | 105 | 7952 | /*
* IPv6 input
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
* Ian P. Morris <I.P.Morris@soton.ac.uk>
*
* Based in linux/net/ipv4/ip_input.c
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
/* Changes
*
* Mitsuru KANDA @USAGI and
* YOSHIFUJI Hideaki @USAGI: Remove ipv6_parse_exthdrs().
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/in6.h>
#include <linux/icmpv6.h>
#include <linux/mroute6.h>
#include <linux/slab.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv6.h>
#include <net/sock.h>
#include <net/snmp.h>
#include <net/ipv6.h>
#include <net/protocol.h>
#include <net/transp_v6.h>
#include <net/rawv6.h>
#include <net/ndisc.h>
#include <net/ip6_route.h>
#include <net/addrconf.h>
#include <net/xfrm.h>
inline int ip6_rcv_finish( struct sk_buff *skb)
{
if (skb_dst(skb) == NULL)
ip6_route_input(skb);
return dst_input(skb);
}
int ipv6_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev)
{
const struct ipv6hdr *hdr;
u32 pkt_len;
struct inet6_dev *idev;
struct net *net = dev_net(skb->dev);
if (skb->pkt_type == PACKET_OTHERHOST) {
kfree_skb(skb);
return NET_RX_DROP;
}
rcu_read_lock();
idev = __in6_dev_get(skb->dev);
IP6_UPD_PO_STATS_BH(net, idev, IPSTATS_MIB_IN, skb->len);
if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL ||
!idev || unlikely(idev->cnf.disable_ipv6)) {
IP6_INC_STATS_BH(net, idev, IPSTATS_MIB_INDISCARDS);
goto drop;
}
memset(IP6CB(skb), 0, sizeof(struct inet6_skb_parm));
/*
* Store incoming device index. When the packet will
* be queued, we cannot refer to skb->dev anymore.
*
* BTW, when we send a packet for our own local address on a
* non-loopback interface (e.g. ethX), it is being delivered
* via the loopback interface (lo) here; skb->dev = loopback_dev.
* It, however, should be considered as if it is being
* arrived via the sending interface (ethX), because of the
* nature of scoping architecture. --yoshfuji
*/
IP6CB(skb)->iif = skb_dst(skb) ? ip6_dst_idev(skb_dst(skb))->dev->ifindex : dev->ifindex;
if (unlikely(!pskb_may_pull(skb, sizeof(*hdr))))
goto err;
hdr = ipv6_hdr(skb);
if (hdr->version != 6)
goto err;
/*
* RFC4291 2.5.3
* A packet received on an interface with a destination address
* of loopback must be dropped.
*/
if (!(dev->flags & IFF_LOOPBACK) &&
ipv6_addr_loopback(&hdr->daddr))
goto err;
skb->transport_header = skb->network_header + sizeof(*hdr);
IP6CB(skb)->nhoff = offsetof(struct ipv6hdr, nexthdr);
pkt_len = ntohs(hdr->payload_len);
/* pkt_len may be zero if Jumbo payload option is present */
if (pkt_len || hdr->nexthdr != NEXTHDR_HOP) {
if (pkt_len + sizeof(struct ipv6hdr) > skb->len) {
IP6_INC_STATS_BH(net,
idev, IPSTATS_MIB_INTRUNCATEDPKTS);
goto drop;
}
if (pskb_trim_rcsum(skb, pkt_len + sizeof(struct ipv6hdr))) {
IP6_INC_STATS_BH(net, idev, IPSTATS_MIB_INHDRERRORS);
goto drop;
}
hdr = ipv6_hdr(skb);
}
if (hdr->nexthdr == NEXTHDR_HOP) {
if (ipv6_parse_hopopts(skb) < 0) {
IP6_INC_STATS_BH(net, idev, IPSTATS_MIB_INHDRERRORS);
rcu_read_unlock();
return NET_RX_DROP;
}
}
rcu_read_unlock();
/* Must drop socket now because of tproxy. */
skb_orphan(skb);
return NF_HOOK(NFPROTO_IPV6, NF_INET_PRE_ROUTING, skb, dev, NULL,
ip6_rcv_finish);
err:
IP6_INC_STATS_BH(net, idev, IPSTATS_MIB_INHDRERRORS);
drop:
rcu_read_unlock();
#ifdef CONFIG_HTC_NETWORK_MODIFY
if (!IS_ERR(skb) && (skb))
kfree_skb(skb);
#else
kfree_skb(skb);
#endif
return NET_RX_DROP;
}
/*
* Deliver the packet to the host
*/
static int ip6_input_finish(struct sk_buff *skb)
{
const struct inet6_protocol *ipprot;
unsigned int nhoff;
int nexthdr, raw;
u8 hash;
struct inet6_dev *idev;
struct net *net = dev_net(skb_dst(skb)->dev);
/*
* Parse extension headers
*/
rcu_read_lock();
resubmit:
idev = ip6_dst_idev(skb_dst(skb));
if (!pskb_pull(skb, skb_transport_offset(skb)))
goto discard;
nhoff = IP6CB(skb)->nhoff;
nexthdr = skb_network_header(skb)[nhoff];
raw = raw6_local_deliver(skb, nexthdr);
hash = nexthdr & (MAX_INET_PROTOS - 1);
if ((ipprot = rcu_dereference(inet6_protos[hash])) != NULL) {
int ret;
if (ipprot->flags & INET6_PROTO_FINAL) {
const struct ipv6hdr *hdr;
/* Free reference early: we don't need it any more,
and it may hold ip_conntrack module loaded
indefinitely. */
nf_reset(skb);
skb_postpull_rcsum(skb, skb_network_header(skb),
skb_network_header_len(skb));
hdr = ipv6_hdr(skb);
if (ipv6_addr_is_multicast(&hdr->daddr) &&
!ipv6_chk_mcast_addr(skb->dev, &hdr->daddr,
&hdr->saddr) &&
!ipv6_is_mld(skb, nexthdr))
goto discard;
}
if (!(ipprot->flags & INET6_PROTO_NOPOLICY) &&
!xfrm6_policy_check(NULL, XFRM_POLICY_IN, skb))
goto discard;
ret = ipprot->handler(skb);
if (ret > 0)
goto resubmit;
else if (ret == 0)
IP6_INC_STATS_BH(net, idev, IPSTATS_MIB_INDELIVERS);
} else {
if (!raw) {
if (xfrm6_policy_check(NULL, XFRM_POLICY_IN, skb)) {
IP6_INC_STATS_BH(net, idev,
IPSTATS_MIB_INUNKNOWNPROTOS);
icmpv6_send(skb, ICMPV6_PARAMPROB,
ICMPV6_UNK_NEXTHDR, nhoff);
}
} else
IP6_INC_STATS_BH(net, idev, IPSTATS_MIB_INDELIVERS);
kfree_skb(skb);
}
rcu_read_unlock();
return 0;
discard:
IP6_INC_STATS_BH(net, idev, IPSTATS_MIB_INDISCARDS);
rcu_read_unlock();
kfree_skb(skb);
return 0;
}
int ip6_input(struct sk_buff *skb)
{
return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_IN, skb, skb->dev, NULL,
ip6_input_finish);
}
int ip6_mc_input(struct sk_buff *skb)
{
const struct ipv6hdr *hdr;
int deliver;
IP6_UPD_PO_STATS_BH(dev_net(skb_dst(skb)->dev),
ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_INMCAST,
skb->len);
hdr = ipv6_hdr(skb);
deliver = ipv6_chk_mcast_addr(skb->dev, &hdr->daddr, NULL);
#ifdef CONFIG_IPV6_MROUTE
/*
* IPv6 multicast router mode is now supported ;)
*/
if (dev_net(skb->dev)->ipv6.devconf_all->mc_forwarding &&
!(ipv6_addr_type(&hdr->daddr) &
(IPV6_ADDR_LOOPBACK|IPV6_ADDR_LINKLOCAL)) &&
likely(!(IP6CB(skb)->flags & IP6SKB_FORWARDED))) {
/*
* Okay, we try to forward - split and duplicate
* packets.
*/
struct sk_buff *skb2;
struct inet6_skb_parm *opt = IP6CB(skb);
/* Check for MLD */
if (unlikely(opt->ra)) {
/* Check if this is a mld message */
u8 *ptr = skb_network_header(skb) + opt->ra;
struct icmp6hdr *icmp6;
u8 nexthdr = hdr->nexthdr;
int offset;
/* Check if the value of Router Alert
* is for MLD (0x0000).
*/
if ((ptr[2] | ptr[3]) == 0) {
deliver = 0;
if (!ipv6_ext_hdr(nexthdr)) {
/* BUG */
goto out;
}
offset = ipv6_skip_exthdr(skb, sizeof(*hdr),
&nexthdr);
if (offset < 0)
goto out;
if (nexthdr != IPPROTO_ICMPV6)
goto out;
if (!pskb_may_pull(skb, (skb_network_header(skb) +
offset + 1 - skb->data)))
goto out;
icmp6 = (struct icmp6hdr *)(skb_network_header(skb) + offset);
switch (icmp6->icmp6_type) {
case ICMPV6_MGM_QUERY:
case ICMPV6_MGM_REPORT:
case ICMPV6_MGM_REDUCTION:
case ICMPV6_MLD2_REPORT:
deliver = 1;
break;
}
goto out;
}
/* unknown RA - process it normally */
}
if (deliver)
skb2 = skb_clone(skb, GFP_ATOMIC);
else {
skb2 = skb;
skb = NULL;
}
if (skb2) {
ip6_mr_input(skb2);
}
}
out:
#endif
if (likely(deliver))
ip6_input(skb);
else {
/* discard */
kfree_skb(skb);
}
return 0;
}
| gpl-2.0 |
heptalium/rpi-sources-3.16 | drivers/staging/comedi/drivers/addi_apci_035.c | 105 | 2044 | #include <linux/module.h>
#include <linux/pci.h>
#include "../comedidev.h"
#include "comedi_fc.h"
#include "amcc_s5933.h"
#include "addi-data/addi_common.h"
#define ADDIDATA_WATCHDOG 2 /* Or shold it be something else */
#include "addi-data/addi_eeprom.c"
#include "addi-data/hwdrv_apci035.c"
#include "addi-data/addi_common.c"
static const struct addi_board apci035_boardtypes[] = {
{
.pc_DriverName = "apci035",
.i_IorangeBase1 = APCI035_ADDRESS_RANGE,
.i_PCIEeprom = 1,
.pc_EepromChip = ADDIDATA_S5920,
.i_NbrAiChannel = 16,
.i_NbrAiChannelDiff = 8,
.i_AiChannelList = 16,
.i_AiMaxdata = 0xff,
.pr_AiRangelist = &range_apci035_ai,
.i_Timer = 1,
.ui_MinAcquisitiontimeNs = 10000,
.ui_MinDelaytimeNs = 100000,
.interrupt = apci035_interrupt,
.reset = apci035_reset,
.ai_config = apci035_ai_config,
.ai_read = apci035_ai_read,
.timer_config = apci035_timer_config,
.timer_write = apci035_timer_write,
.timer_read = apci035_timer_read,
},
};
static int apci035_auto_attach(struct comedi_device *dev,
unsigned long context)
{
dev->board_ptr = &apci035_boardtypes[0];
return addi_auto_attach(dev, context);
}
static struct comedi_driver apci035_driver = {
.driver_name = "addi_apci_035",
.module = THIS_MODULE,
.auto_attach = apci035_auto_attach,
.detach = i_ADDI_Detach,
};
static int apci035_pci_probe(struct pci_dev *dev,
const struct pci_device_id *id)
{
return comedi_pci_auto_config(dev, &apci035_driver, id->driver_data);
}
static const struct pci_device_id apci035_pci_table[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_ADDIDATA, 0x0300) },
{ 0 }
};
MODULE_DEVICE_TABLE(pci, apci035_pci_table);
static struct pci_driver apci035_pci_driver = {
.name = "addi_apci_035",
.id_table = apci035_pci_table,
.probe = apci035_pci_probe,
.remove = comedi_pci_auto_unconfig,
};
module_comedi_pci_driver(apci035_driver, apci035_pci_driver);
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
fabiocannizzo/linux | drivers/gpu/drm/nouveau/nvkm/engine/fifo/chang84.c | 361 | 7678 | /*
* 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
*/
#include "channv50.h"
#include <core/client.h>
#include <core/ramht.h>
#include <subdev/mmu.h>
#include <subdev/timer.h>
#include <nvif/cl826e.h>
static int
g84_fifo_chan_ntfy(struct nvkm_fifo_chan *chan, u32 type,
struct nvkm_event **pevent)
{
switch (type) {
case NV826E_V0_NTFY_NON_STALL_INTERRUPT:
*pevent = &chan->fifo->uevent;
return 0;
default:
break;
}
return -EINVAL;
}
static int
g84_fifo_chan_engine_addr(struct nvkm_engine *engine)
{
switch (engine->subdev.type) {
case NVKM_ENGINE_DMAOBJ:
case NVKM_ENGINE_SW : return -1;
case NVKM_ENGINE_GR : return 0x0020;
case NVKM_ENGINE_VP :
case NVKM_ENGINE_MSPDEC: return 0x0040;
case NVKM_ENGINE_MPEG :
case NVKM_ENGINE_MSPPP : return 0x0060;
case NVKM_ENGINE_BSP :
case NVKM_ENGINE_MSVLD : return 0x0080;
case NVKM_ENGINE_CIPHER:
case NVKM_ENGINE_SEC : return 0x00a0;
case NVKM_ENGINE_CE : return 0x00c0;
default:
WARN_ON(1);
return -1;
}
}
static int
g84_fifo_chan_engine_fini(struct nvkm_fifo_chan *base,
struct nvkm_engine *engine, bool suspend)
{
struct nv50_fifo_chan *chan = nv50_fifo_chan(base);
struct nv50_fifo *fifo = chan->fifo;
struct nvkm_subdev *subdev = &fifo->base.engine.subdev;
struct nvkm_device *device = subdev->device;
u32 engn, save;
int offset;
bool done;
offset = g84_fifo_chan_engine_addr(engine);
if (offset < 0)
return 0;
engn = fifo->base.func->engine_id(&fifo->base, engine) - 1;
save = nvkm_mask(device, 0x002520, 0x0000003f, 1 << engn);
nvkm_wr32(device, 0x0032fc, chan->base.inst->addr >> 12);
done = nvkm_msec(device, 2000,
if (nvkm_rd32(device, 0x0032fc) != 0xffffffff)
break;
) >= 0;
nvkm_wr32(device, 0x002520, save);
if (!done) {
nvkm_error(subdev, "channel %d [%s] unload timeout\n",
chan->base.chid, chan->base.object.client->name);
if (suspend)
return -EBUSY;
}
nvkm_kmap(chan->eng);
nvkm_wo32(chan->eng, offset + 0x00, 0x00000000);
nvkm_wo32(chan->eng, offset + 0x04, 0x00000000);
nvkm_wo32(chan->eng, offset + 0x08, 0x00000000);
nvkm_wo32(chan->eng, offset + 0x0c, 0x00000000);
nvkm_wo32(chan->eng, offset + 0x10, 0x00000000);
nvkm_wo32(chan->eng, offset + 0x14, 0x00000000);
nvkm_done(chan->eng);
return 0;
}
static int
g84_fifo_chan_engine_init(struct nvkm_fifo_chan *base,
struct nvkm_engine *engine)
{
struct nv50_fifo_chan *chan = nv50_fifo_chan(base);
struct nvkm_gpuobj *engn = *nv50_fifo_chan_engine(chan, engine);
u64 limit, start;
int offset;
offset = g84_fifo_chan_engine_addr(engine);
if (offset < 0)
return 0;
limit = engn->addr + engn->size - 1;
start = engn->addr;
nvkm_kmap(chan->eng);
nvkm_wo32(chan->eng, offset + 0x00, 0x00190000);
nvkm_wo32(chan->eng, offset + 0x04, lower_32_bits(limit));
nvkm_wo32(chan->eng, offset + 0x08, lower_32_bits(start));
nvkm_wo32(chan->eng, offset + 0x0c, upper_32_bits(limit) << 24 |
upper_32_bits(start));
nvkm_wo32(chan->eng, offset + 0x10, 0x00000000);
nvkm_wo32(chan->eng, offset + 0x14, 0x00000000);
nvkm_done(chan->eng);
return 0;
}
static int
g84_fifo_chan_engine_ctor(struct nvkm_fifo_chan *base,
struct nvkm_engine *engine,
struct nvkm_object *object)
{
struct nv50_fifo_chan *chan = nv50_fifo_chan(base);
if (g84_fifo_chan_engine_addr(engine) < 0)
return 0;
return nvkm_object_bind(object, NULL, 0, nv50_fifo_chan_engine(chan, engine));
}
static int
g84_fifo_chan_object_ctor(struct nvkm_fifo_chan *base,
struct nvkm_object *object)
{
struct nv50_fifo_chan *chan = nv50_fifo_chan(base);
u32 handle = object->handle;
u32 context;
switch (object->engine->subdev.type) {
case NVKM_ENGINE_DMAOBJ:
case NVKM_ENGINE_SW : context = 0x00000000; break;
case NVKM_ENGINE_GR : context = 0x00100000; break;
case NVKM_ENGINE_MPEG :
case NVKM_ENGINE_MSPPP : context = 0x00200000; break;
case NVKM_ENGINE_ME :
case NVKM_ENGINE_CE : context = 0x00300000; break;
case NVKM_ENGINE_VP :
case NVKM_ENGINE_MSPDEC: context = 0x00400000; break;
case NVKM_ENGINE_CIPHER:
case NVKM_ENGINE_SEC :
case NVKM_ENGINE_VIC : context = 0x00500000; break;
case NVKM_ENGINE_BSP :
case NVKM_ENGINE_MSVLD : context = 0x00600000; break;
default:
WARN_ON(1);
return -EINVAL;
}
return nvkm_ramht_insert(chan->ramht, object, 0, 4, handle, context);
}
static void
g84_fifo_chan_init(struct nvkm_fifo_chan *base)
{
struct nv50_fifo_chan *chan = nv50_fifo_chan(base);
struct nv50_fifo *fifo = chan->fifo;
struct nvkm_device *device = fifo->base.engine.subdev.device;
u64 addr = chan->ramfc->addr >> 8;
u32 chid = chan->base.chid;
nvkm_wr32(device, 0x002600 + (chid * 4), 0x80000000 | addr);
nv50_fifo_runlist_update(fifo);
}
static const struct nvkm_fifo_chan_func
g84_fifo_chan_func = {
.dtor = nv50_fifo_chan_dtor,
.init = g84_fifo_chan_init,
.fini = nv50_fifo_chan_fini,
.ntfy = g84_fifo_chan_ntfy,
.engine_ctor = g84_fifo_chan_engine_ctor,
.engine_dtor = nv50_fifo_chan_engine_dtor,
.engine_init = g84_fifo_chan_engine_init,
.engine_fini = g84_fifo_chan_engine_fini,
.object_ctor = g84_fifo_chan_object_ctor,
.object_dtor = nv50_fifo_chan_object_dtor,
};
int
g84_fifo_chan_ctor(struct nv50_fifo *fifo, u64 vmm, u64 push,
const struct nvkm_oclass *oclass,
struct nv50_fifo_chan *chan)
{
struct nvkm_device *device = fifo->base.engine.subdev.device;
int ret;
if (!vmm)
return -EINVAL;
ret = nvkm_fifo_chan_ctor(&g84_fifo_chan_func, &fifo->base,
0x10000, 0x1000, false, vmm, push,
BIT(G84_FIFO_ENGN_SW) |
BIT(G84_FIFO_ENGN_GR) |
BIT(G84_FIFO_ENGN_MPEG) |
BIT(G84_FIFO_ENGN_MSPPP) |
BIT(G84_FIFO_ENGN_ME) |
BIT(G84_FIFO_ENGN_CE0) |
BIT(G84_FIFO_ENGN_VP) |
BIT(G84_FIFO_ENGN_MSPDEC) |
BIT(G84_FIFO_ENGN_CIPHER) |
BIT(G84_FIFO_ENGN_SEC) |
BIT(G84_FIFO_ENGN_VIC) |
BIT(G84_FIFO_ENGN_BSP) |
BIT(G84_FIFO_ENGN_MSVLD) |
BIT(G84_FIFO_ENGN_DMA),
0, 0xc00000, 0x2000, oclass, &chan->base);
chan->fifo = fifo;
if (ret)
return ret;
ret = nvkm_gpuobj_new(device, 0x0200, 0, true, chan->base.inst,
&chan->eng);
if (ret)
return ret;
ret = nvkm_gpuobj_new(device, 0x4000, 0, false, chan->base.inst,
&chan->pgd);
if (ret)
return ret;
ret = nvkm_gpuobj_new(device, 0x1000, 0x400, true, chan->base.inst,
&chan->cache);
if (ret)
return ret;
ret = nvkm_gpuobj_new(device, 0x100, 0x100, true, chan->base.inst,
&chan->ramfc);
if (ret)
return ret;
return nvkm_ramht_new(device, 0x8000, 16, chan->base.inst, &chan->ramht);
}
| gpl-2.0 |
playfulgod/android_kernel_lge_ms910 | drivers/ide/ide-cd.c | 873 | 46460 | /*
* ATAPI CD-ROM driver.
*
* Copyright (C) 1994-1996 Scott Snyder <snyder@fnald0.fnal.gov>
* Copyright (C) 1996-1998 Erik Andersen <andersee@debian.org>
* Copyright (C) 1998-2000 Jens Axboe <axboe@suse.de>
* Copyright (C) 2005, 2007-2009 Bartlomiej Zolnierkiewicz
*
* May be copied or modified under the terms of the GNU General Public
* License. See linux/COPYING for more information.
*
* See Documentation/cdrom/ide-cd for usage information.
*
* Suggestions are welcome. Patches that work are more welcome though. ;-)
*
* Documentation:
* Mt. Fuji (SFF8090 version 4) and ATAPI (SFF-8020i rev 2.6) standards.
*
* For historical changelog please see:
* Documentation/ide/ChangeLog.ide-cd.1994-2004
*/
#define DRV_NAME "ide-cd"
#define PFX DRV_NAME ": "
#define IDECD_VERSION "5.00"
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/timer.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/errno.h>
#include <linux/cdrom.h>
#include <linux/ide.h>
#include <linux/completion.h>
#include <linux/mutex.h>
#include <linux/bcd.h>
/* For SCSI -> ATAPI command conversion */
#include <scsi/scsi.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <asm/byteorder.h>
#include <linux/uaccess.h>
#include <asm/unaligned.h>
#include "ide-cd.h"
static DEFINE_MUTEX(idecd_ref_mutex);
static void ide_cd_release(struct device *);
static struct cdrom_info *ide_cd_get(struct gendisk *disk)
{
struct cdrom_info *cd = NULL;
mutex_lock(&idecd_ref_mutex);
cd = ide_drv_g(disk, cdrom_info);
if (cd) {
if (ide_device_get(cd->drive))
cd = NULL;
else
get_device(&cd->dev);
}
mutex_unlock(&idecd_ref_mutex);
return cd;
}
static void ide_cd_put(struct cdrom_info *cd)
{
ide_drive_t *drive = cd->drive;
mutex_lock(&idecd_ref_mutex);
put_device(&cd->dev);
ide_device_put(drive);
mutex_unlock(&idecd_ref_mutex);
}
/*
* Generic packet command support and error handling routines.
*/
/* Mark that we've seen a media change and invalidate our internal buffers. */
static void cdrom_saw_media_change(ide_drive_t *drive)
{
drive->dev_flags |= IDE_DFLAG_MEDIA_CHANGED;
drive->atapi_flags &= ~IDE_AFLAG_TOC_VALID;
}
static int cdrom_log_sense(ide_drive_t *drive, struct request *rq)
{
struct request_sense *sense = &drive->sense_data;
int log = 0;
if (!sense || !rq || (rq->cmd_flags & REQ_QUIET))
return 0;
ide_debug_log(IDE_DBG_SENSE, "sense_key: 0x%x", sense->sense_key);
switch (sense->sense_key) {
case NO_SENSE:
case RECOVERED_ERROR:
break;
case NOT_READY:
/*
* don't care about tray state messages for e.g. capacity
* commands or in-progress or becoming ready
*/
if (sense->asc == 0x3a || sense->asc == 0x04)
break;
log = 1;
break;
case ILLEGAL_REQUEST:
/*
* don't log START_STOP unit with LoEj set, since we cannot
* reliably check if drive can auto-close
*/
if (rq->cmd[0] == GPCMD_START_STOP_UNIT && sense->asc == 0x24)
break;
log = 1;
break;
case UNIT_ATTENTION:
/*
* Make good and sure we've seen this potential media change.
* Some drives (i.e. Creative) fail to present the correct sense
* key in the error register.
*/
cdrom_saw_media_change(drive);
break;
default:
log = 1;
break;
}
return log;
}
static void cdrom_analyze_sense_data(ide_drive_t *drive,
struct request *failed_command)
{
struct request_sense *sense = &drive->sense_data;
struct cdrom_info *info = drive->driver_data;
unsigned long sector;
unsigned long bio_sectors;
ide_debug_log(IDE_DBG_SENSE, "error_code: 0x%x, sense_key: 0x%x",
sense->error_code, sense->sense_key);
if (failed_command)
ide_debug_log(IDE_DBG_SENSE, "failed cmd: 0x%x",
failed_command->cmd[0]);
if (!cdrom_log_sense(drive, failed_command))
return;
/*
* If a read toc is executed for a CD-R or CD-RW medium where the first
* toc has not been recorded yet, it will fail with 05/24/00 (which is a
* confusing error)
*/
if (failed_command && failed_command->cmd[0] == GPCMD_READ_TOC_PMA_ATIP)
if (sense->sense_key == 0x05 && sense->asc == 0x24)
return;
/* current error */
if (sense->error_code == 0x70) {
switch (sense->sense_key) {
case MEDIUM_ERROR:
case VOLUME_OVERFLOW:
case ILLEGAL_REQUEST:
if (!sense->valid)
break;
if (failed_command == NULL ||
!blk_fs_request(failed_command))
break;
sector = (sense->information[0] << 24) |
(sense->information[1] << 16) |
(sense->information[2] << 8) |
(sense->information[3]);
if (queue_logical_block_size(drive->queue) == 2048)
/* device sector size is 2K */
sector <<= 2;
bio_sectors = max(bio_sectors(failed_command->bio), 4U);
sector &= ~(bio_sectors - 1);
/*
* The SCSI specification allows for the value
* returned by READ CAPACITY to be up to 75 2K
* sectors past the last readable block.
* Therefore, if we hit a medium error within the
* last 75 2K sectors, we decrease the saved size
* value.
*/
if (sector < get_capacity(info->disk) &&
drive->probed_capacity - sector < 4 * 75)
set_capacity(info->disk, sector);
}
}
ide_cd_log_error(drive->name, failed_command, sense);
}
static void ide_cd_complete_failed_rq(ide_drive_t *drive, struct request *rq)
{
/*
* For REQ_TYPE_SENSE, "rq->special" points to the original
* failed request. Also, the sense data should be read
* directly from rq which might be different from the original
* sense buffer if it got copied during mapping.
*/
struct request *failed = (struct request *)rq->special;
void *sense = bio_data(rq->bio);
if (failed) {
if (failed->sense) {
/*
* Sense is always read into drive->sense_data.
* Copy back if the failed request has its
* sense pointer set.
*/
memcpy(failed->sense, sense, 18);
failed->sense_len = rq->sense_len;
}
cdrom_analyze_sense_data(drive, failed);
if (ide_end_rq(drive, failed, -EIO, blk_rq_bytes(failed)))
BUG();
} else
cdrom_analyze_sense_data(drive, NULL);
}
/*
* Allow the drive 5 seconds to recover; some devices will return NOT_READY
* while flushing data from cache.
*
* returns: 0 failed (write timeout expired)
* 1 success
*/
static int ide_cd_breathe(ide_drive_t *drive, struct request *rq)
{
struct cdrom_info *info = drive->driver_data;
if (!rq->errors)
info->write_timeout = jiffies + ATAPI_WAIT_WRITE_BUSY;
rq->errors = 1;
if (time_after(jiffies, info->write_timeout))
return 0;
else {
struct request_queue *q = drive->queue;
unsigned long flags;
/*
* take a breather relying on the unplug timer to kick us again
*/
spin_lock_irqsave(q->queue_lock, flags);
blk_plug_device(q);
spin_unlock_irqrestore(q->queue_lock, flags);
return 1;
}
}
/**
* Returns:
* 0: if the request should be continued.
* 1: if the request will be going through error recovery.
* 2: if the request should be ended.
*/
static int cdrom_decode_status(ide_drive_t *drive, u8 stat)
{
ide_hwif_t *hwif = drive->hwif;
struct request *rq = hwif->rq;
int err, sense_key, do_end_request = 0;
/* get the IDE error register */
err = ide_read_error(drive);
sense_key = err >> 4;
ide_debug_log(IDE_DBG_RQ, "cmd: 0x%x, rq->cmd_type: 0x%x, err: 0x%x, "
"stat 0x%x",
rq->cmd[0], rq->cmd_type, err, stat);
if (blk_sense_request(rq)) {
/*
* We got an error trying to get sense info from the drive
* (probably while trying to recover from a former error).
* Just give up.
*/
rq->cmd_flags |= REQ_FAILED;
return 2;
}
/* if we have an error, pass CHECK_CONDITION as the SCSI status byte */
if (blk_pc_request(rq) && !rq->errors)
rq->errors = SAM_STAT_CHECK_CONDITION;
if (blk_noretry_request(rq))
do_end_request = 1;
switch (sense_key) {
case NOT_READY:
if (blk_fs_request(rq) && rq_data_dir(rq) == WRITE) {
if (ide_cd_breathe(drive, rq))
return 1;
} else {
cdrom_saw_media_change(drive);
if (blk_fs_request(rq) && !blk_rq_quiet(rq))
printk(KERN_ERR PFX "%s: tray open\n",
drive->name);
}
do_end_request = 1;
break;
case UNIT_ATTENTION:
cdrom_saw_media_change(drive);
if (blk_fs_request(rq) == 0)
return 0;
/*
* Arrange to retry the request but be sure to give up if we've
* retried too many times.
*/
if (++rq->errors > ERROR_MAX)
do_end_request = 1;
break;
case ILLEGAL_REQUEST:
/*
* Don't print error message for this condition -- SFF8090i
* indicates that 5/24/00 is the correct response to a request
* to close the tray if the drive doesn't have that capability.
*
* cdrom_log_sense() knows this!
*/
if (rq->cmd[0] == GPCMD_START_STOP_UNIT)
break;
/* fall-through */
case DATA_PROTECT:
/*
* No point in retrying after an illegal request or data
* protect error.
*/
if (!blk_rq_quiet(rq))
ide_dump_status(drive, "command error", stat);
do_end_request = 1;
break;
case MEDIUM_ERROR:
/*
* No point in re-trying a zillion times on a bad sector.
* If we got here the error is not correctable.
*/
if (!blk_rq_quiet(rq))
ide_dump_status(drive, "media error "
"(bad sector)", stat);
do_end_request = 1;
break;
case BLANK_CHECK:
/* disk appears blank? */
if (!blk_rq_quiet(rq))
ide_dump_status(drive, "media error (blank)",
stat);
do_end_request = 1;
break;
default:
if (blk_fs_request(rq) == 0)
break;
if (err & ~ATA_ABORTED) {
/* go to the default handler for other errors */
ide_error(drive, "cdrom_decode_status", stat);
return 1;
} else if (++rq->errors > ERROR_MAX)
/* we've racked up too many retries, abort */
do_end_request = 1;
}
if (blk_fs_request(rq) == 0) {
rq->cmd_flags |= REQ_FAILED;
do_end_request = 1;
}
/*
* End a request through request sense analysis when we have sense data.
* We need this in order to perform end of media processing.
*/
if (do_end_request)
goto end_request;
/* if we got a CHECK_CONDITION status, queue a request sense command */
if (stat & ATA_ERR)
return ide_queue_sense_rq(drive, NULL) ? 2 : 1;
return 1;
end_request:
if (stat & ATA_ERR) {
hwif->rq = NULL;
return ide_queue_sense_rq(drive, rq) ? 2 : 1;
} else
return 2;
}
static void ide_cd_request_sense_fixup(ide_drive_t *drive, struct ide_cmd *cmd)
{
struct request *rq = cmd->rq;
ide_debug_log(IDE_DBG_FUNC, "rq->cmd[0]: 0x%x", rq->cmd[0]);
/*
* Some of the trailing request sense fields are optional,
* and some drives don't send them. Sigh.
*/
if (rq->cmd[0] == GPCMD_REQUEST_SENSE &&
cmd->nleft > 0 && cmd->nleft <= 5)
cmd->nleft = 0;
}
int ide_cd_queue_pc(ide_drive_t *drive, const unsigned char *cmd,
int write, void *buffer, unsigned *bufflen,
struct request_sense *sense, int timeout,
unsigned int cmd_flags)
{
struct cdrom_info *info = drive->driver_data;
struct request_sense local_sense;
int retries = 10;
unsigned int flags = 0;
if (!sense)
sense = &local_sense;
ide_debug_log(IDE_DBG_PC, "cmd[0]: 0x%x, write: 0x%x, timeout: %d, "
"cmd_flags: 0x%x",
cmd[0], write, timeout, cmd_flags);
/* start of retry loop */
do {
struct request *rq;
int error;
rq = blk_get_request(drive->queue, write, __GFP_WAIT);
memcpy(rq->cmd, cmd, BLK_MAX_CDB);
rq->cmd_type = REQ_TYPE_ATA_PC;
rq->sense = sense;
rq->cmd_flags |= cmd_flags;
rq->timeout = timeout;
if (buffer) {
error = blk_rq_map_kern(drive->queue, rq, buffer,
*bufflen, GFP_NOIO);
if (error) {
blk_put_request(rq);
return error;
}
}
error = blk_execute_rq(drive->queue, info->disk, rq, 0);
if (buffer)
*bufflen = rq->resid_len;
flags = rq->cmd_flags;
blk_put_request(rq);
/*
* FIXME: we should probably abort/retry or something in case of
* failure.
*/
if (flags & REQ_FAILED) {
/*
* The request failed. Retry if it was due to a unit
* attention status (usually means media was changed).
*/
struct request_sense *reqbuf = sense;
if (reqbuf->sense_key == UNIT_ATTENTION)
cdrom_saw_media_change(drive);
else if (reqbuf->sense_key == NOT_READY &&
reqbuf->asc == 4 && reqbuf->ascq != 4) {
/*
* The drive is in the process of loading
* a disk. Retry, but wait a little to give
* the drive time to complete the load.
*/
ssleep(2);
} else {
/* otherwise, don't retry */
retries = 0;
}
--retries;
}
/* end of retry loop */
} while ((flags & REQ_FAILED) && retries >= 0);
/* return an error if the command failed */
return (flags & REQ_FAILED) ? -EIO : 0;
}
/*
* returns true if rq has been completed
*/
static bool ide_cd_error_cmd(ide_drive_t *drive, struct ide_cmd *cmd)
{
unsigned int nr_bytes = cmd->nbytes - cmd->nleft;
if (cmd->tf_flags & IDE_TFLAG_WRITE)
nr_bytes -= cmd->last_xfer_len;
if (nr_bytes > 0) {
ide_complete_rq(drive, 0, nr_bytes);
return true;
}
return false;
}
static ide_startstop_t cdrom_newpc_intr(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
struct ide_cmd *cmd = &hwif->cmd;
struct request *rq = hwif->rq;
ide_expiry_t *expiry = NULL;
int dma_error = 0, dma, thislen, uptodate = 0;
int write = (rq_data_dir(rq) == WRITE) ? 1 : 0, rc = 0;
int sense = blk_sense_request(rq);
unsigned int timeout;
u16 len;
u8 ireason, stat;
ide_debug_log(IDE_DBG_PC, "cmd: 0x%x, write: 0x%x", rq->cmd[0], write);
/* check for errors */
dma = drive->dma;
if (dma) {
drive->dma = 0;
drive->waiting_for_dma = 0;
dma_error = hwif->dma_ops->dma_end(drive);
ide_dma_unmap_sg(drive, cmd);
if (dma_error) {
printk(KERN_ERR PFX "%s: DMA %s error\n", drive->name,
write ? "write" : "read");
ide_dma_off(drive);
}
}
/* check status */
stat = hwif->tp_ops->read_status(hwif);
if (!OK_STAT(stat, 0, BAD_R_STAT)) {
rc = cdrom_decode_status(drive, stat);
if (rc) {
if (rc == 2)
goto out_end;
return ide_stopped;
}
}
/* using dma, transfer is complete now */
if (dma) {
if (dma_error)
return ide_error(drive, "dma error", stat);
uptodate = 1;
goto out_end;
}
ide_read_bcount_and_ireason(drive, &len, &ireason);
thislen = blk_fs_request(rq) ? len : cmd->nleft;
if (thislen > len)
thislen = len;
ide_debug_log(IDE_DBG_PC, "DRQ: stat: 0x%x, thislen: %d",
stat, thislen);
/* If DRQ is clear, the command has completed. */
if ((stat & ATA_DRQ) == 0) {
if (blk_fs_request(rq)) {
/*
* If we're not done reading/writing, complain.
* Otherwise, complete the command normally.
*/
uptodate = 1;
if (cmd->nleft > 0) {
printk(KERN_ERR PFX "%s: %s: data underrun "
"(%u bytes)\n", drive->name, __func__,
cmd->nleft);
if (!write)
rq->cmd_flags |= REQ_FAILED;
uptodate = 0;
}
} else if (!blk_pc_request(rq)) {
ide_cd_request_sense_fixup(drive, cmd);
uptodate = cmd->nleft ? 0 : 1;
/*
* suck out the remaining bytes from the drive in an
* attempt to complete the data xfer. (see BZ#13399)
*/
if (!(stat & ATA_ERR) && !uptodate && thislen) {
ide_pio_bytes(drive, cmd, write, thislen);
uptodate = cmd->nleft ? 0 : 1;
}
if (!uptodate)
rq->cmd_flags |= REQ_FAILED;
}
goto out_end;
}
rc = ide_check_ireason(drive, rq, len, ireason, write);
if (rc)
goto out_end;
cmd->last_xfer_len = 0;
ide_debug_log(IDE_DBG_PC, "data transfer, rq->cmd_type: 0x%x, "
"ireason: 0x%x",
rq->cmd_type, ireason);
/* transfer data */
while (thislen > 0) {
int blen = min_t(int, thislen, cmd->nleft);
if (cmd->nleft == 0)
break;
ide_pio_bytes(drive, cmd, write, blen);
cmd->last_xfer_len += blen;
thislen -= blen;
len -= blen;
if (sense && write == 0)
rq->sense_len += blen;
}
/* pad, if necessary */
if (len > 0) {
if (blk_fs_request(rq) == 0 || write == 0)
ide_pad_transfer(drive, write, len);
else {
printk(KERN_ERR PFX "%s: confused, missing data\n",
drive->name);
blk_dump_rq_flags(rq, "cdrom_newpc_intr");
}
}
if (blk_pc_request(rq)) {
timeout = rq->timeout;
} else {
timeout = ATAPI_WAIT_PC;
if (!blk_fs_request(rq))
expiry = ide_cd_expiry;
}
hwif->expiry = expiry;
ide_set_handler(drive, cdrom_newpc_intr, timeout);
return ide_started;
out_end:
if (blk_pc_request(rq) && rc == 0) {
rq->resid_len = 0;
blk_end_request_all(rq, 0);
hwif->rq = NULL;
} else {
if (sense && uptodate)
ide_cd_complete_failed_rq(drive, rq);
if (blk_fs_request(rq)) {
if (cmd->nleft == 0)
uptodate = 1;
} else {
if (uptodate <= 0 && rq->errors == 0)
rq->errors = -EIO;
}
if (uptodate == 0 && rq->bio)
if (ide_cd_error_cmd(drive, cmd))
return ide_stopped;
/* make sure it's fully ended */
if (blk_fs_request(rq) == 0) {
rq->resid_len -= cmd->nbytes - cmd->nleft;
if (uptodate == 0 && (cmd->tf_flags & IDE_TFLAG_WRITE))
rq->resid_len += cmd->last_xfer_len;
}
ide_complete_rq(drive, uptodate ? 0 : -EIO, blk_rq_bytes(rq));
if (sense && rc == 2)
ide_error(drive, "request sense failure", stat);
}
return ide_stopped;
}
static ide_startstop_t cdrom_start_rw(ide_drive_t *drive, struct request *rq)
{
struct cdrom_info *cd = drive->driver_data;
struct request_queue *q = drive->queue;
int write = rq_data_dir(rq) == WRITE;
unsigned short sectors_per_frame =
queue_logical_block_size(q) >> SECTOR_BITS;
ide_debug_log(IDE_DBG_RQ, "rq->cmd[0]: 0x%x, rq->cmd_flags: 0x%x, "
"secs_per_frame: %u",
rq->cmd[0], rq->cmd_flags, sectors_per_frame);
if (write) {
/* disk has become write protected */
if (get_disk_ro(cd->disk))
return ide_stopped;
} else {
/*
* We may be retrying this request after an error. Fix up any
* weirdness which might be present in the request packet.
*/
q->prep_rq_fn(q, rq);
}
/* fs requests *must* be hardware frame aligned */
if ((blk_rq_sectors(rq) & (sectors_per_frame - 1)) ||
(blk_rq_pos(rq) & (sectors_per_frame - 1)))
return ide_stopped;
/* use DMA, if possible */
drive->dma = !!(drive->dev_flags & IDE_DFLAG_USING_DMA);
if (write)
cd->devinfo.media_written = 1;
rq->timeout = ATAPI_WAIT_PC;
return ide_started;
}
static void cdrom_do_block_pc(ide_drive_t *drive, struct request *rq)
{
ide_debug_log(IDE_DBG_PC, "rq->cmd[0]: 0x%x, rq->cmd_type: 0x%x",
rq->cmd[0], rq->cmd_type);
if (blk_pc_request(rq))
rq->cmd_flags |= REQ_QUIET;
else
rq->cmd_flags &= ~REQ_FAILED;
drive->dma = 0;
/* sg request */
if (rq->bio) {
struct request_queue *q = drive->queue;
char *buf = bio_data(rq->bio);
unsigned int alignment;
drive->dma = !!(drive->dev_flags & IDE_DFLAG_USING_DMA);
/*
* check if dma is safe
*
* NOTE! The "len" and "addr" checks should possibly have
* separate masks.
*/
alignment = queue_dma_alignment(q) | q->dma_pad_mask;
if ((unsigned long)buf & alignment
|| blk_rq_bytes(rq) & q->dma_pad_mask
|| object_is_on_stack(buf))
drive->dma = 0;
}
}
static ide_startstop_t ide_cd_do_request(ide_drive_t *drive, struct request *rq,
sector_t block)
{
struct ide_cmd cmd;
int uptodate = 0, nsectors;
ide_debug_log(IDE_DBG_RQ, "cmd: 0x%x, block: %llu",
rq->cmd[0], (unsigned long long)block);
if (drive->debug_mask & IDE_DBG_RQ)
blk_dump_rq_flags(rq, "ide_cd_do_request");
if (blk_fs_request(rq)) {
if (cdrom_start_rw(drive, rq) == ide_stopped)
goto out_end;
} else if (blk_sense_request(rq) || blk_pc_request(rq) ||
rq->cmd_type == REQ_TYPE_ATA_PC) {
if (!rq->timeout)
rq->timeout = ATAPI_WAIT_PC;
cdrom_do_block_pc(drive, rq);
} else if (blk_special_request(rq)) {
/* right now this can only be a reset... */
uptodate = 1;
goto out_end;
} else
BUG();
/* prepare sense request for this command */
ide_prep_sense(drive, rq);
memset(&cmd, 0, sizeof(cmd));
if (rq_data_dir(rq))
cmd.tf_flags |= IDE_TFLAG_WRITE;
cmd.rq = rq;
if (blk_fs_request(rq) || blk_rq_bytes(rq)) {
ide_init_sg_cmd(&cmd, blk_rq_bytes(rq));
ide_map_sg(drive, &cmd);
}
return ide_issue_pc(drive, &cmd);
out_end:
nsectors = blk_rq_sectors(rq);
if (nsectors == 0)
nsectors = 1;
ide_complete_rq(drive, uptodate ? 0 : -EIO, nsectors << 9);
return ide_stopped;
}
/*
* Ioctl handling.
*
* Routines which queue packet commands take as a final argument a pointer to a
* request_sense struct. If execution of the command results in an error with a
* CHECK CONDITION status, this structure will be filled with the results of the
* subsequent request sense command. The pointer can also be NULL, in which case
* no sense information is returned.
*/
static void msf_from_bcd(struct atapi_msf *msf)
{
msf->minute = bcd2bin(msf->minute);
msf->second = bcd2bin(msf->second);
msf->frame = bcd2bin(msf->frame);
}
int cdrom_check_status(ide_drive_t *drive, struct request_sense *sense)
{
struct cdrom_info *info = drive->driver_data;
struct cdrom_device_info *cdi = &info->devinfo;
unsigned char cmd[BLK_MAX_CDB];
ide_debug_log(IDE_DBG_FUNC, "enter");
memset(cmd, 0, BLK_MAX_CDB);
cmd[0] = GPCMD_TEST_UNIT_READY;
/*
* Sanyo 3 CD changer uses byte 7 of TEST_UNIT_READY to switch CDs
* instead of supporting the LOAD_UNLOAD opcode.
*/
cmd[7] = cdi->sanyo_slot % 3;
return ide_cd_queue_pc(drive, cmd, 0, NULL, NULL, sense, 0, REQ_QUIET);
}
static int cdrom_read_capacity(ide_drive_t *drive, unsigned long *capacity,
unsigned long *sectors_per_frame,
struct request_sense *sense)
{
struct {
__be32 lba;
__be32 blocklen;
} capbuf;
int stat;
unsigned char cmd[BLK_MAX_CDB];
unsigned len = sizeof(capbuf);
u32 blocklen;
ide_debug_log(IDE_DBG_FUNC, "enter");
memset(cmd, 0, BLK_MAX_CDB);
cmd[0] = GPCMD_READ_CDVD_CAPACITY;
stat = ide_cd_queue_pc(drive, cmd, 0, &capbuf, &len, sense, 0,
REQ_QUIET);
if (stat)
return stat;
/*
* Sanity check the given block size, in so far as making
* sure the sectors_per_frame we give to the caller won't
* end up being bogus.
*/
blocklen = be32_to_cpu(capbuf.blocklen);
blocklen = (blocklen >> SECTOR_BITS) << SECTOR_BITS;
switch (blocklen) {
case 512:
case 1024:
case 2048:
case 4096:
break;
default:
printk_once(KERN_ERR PFX "%s: weird block size %u; "
"setting default block size to 2048\n",
drive->name, blocklen);
blocklen = 2048;
break;
}
*capacity = 1 + be32_to_cpu(capbuf.lba);
*sectors_per_frame = blocklen >> SECTOR_BITS;
ide_debug_log(IDE_DBG_PROBE, "cap: %lu, sectors_per_frame: %lu",
*capacity, *sectors_per_frame);
return 0;
}
static int cdrom_read_tocentry(ide_drive_t *drive, int trackno, int msf_flag,
int format, char *buf, int buflen,
struct request_sense *sense)
{
unsigned char cmd[BLK_MAX_CDB];
ide_debug_log(IDE_DBG_FUNC, "enter");
memset(cmd, 0, BLK_MAX_CDB);
cmd[0] = GPCMD_READ_TOC_PMA_ATIP;
cmd[6] = trackno;
cmd[7] = (buflen >> 8);
cmd[8] = (buflen & 0xff);
cmd[9] = (format << 6);
if (msf_flag)
cmd[1] = 2;
return ide_cd_queue_pc(drive, cmd, 0, buf, &buflen, sense, 0, REQ_QUIET);
}
/* Try to read the entire TOC for the disk into our internal buffer. */
int ide_cd_read_toc(ide_drive_t *drive, struct request_sense *sense)
{
int stat, ntracks, i;
struct cdrom_info *info = drive->driver_data;
struct cdrom_device_info *cdi = &info->devinfo;
struct atapi_toc *toc = info->toc;
struct {
struct atapi_toc_header hdr;
struct atapi_toc_entry ent;
} ms_tmp;
long last_written;
unsigned long sectors_per_frame = SECTORS_PER_FRAME;
ide_debug_log(IDE_DBG_FUNC, "enter");
if (toc == NULL) {
/* try to allocate space */
toc = kmalloc(sizeof(struct atapi_toc), GFP_KERNEL);
if (toc == NULL) {
printk(KERN_ERR PFX "%s: No cdrom TOC buffer!\n",
drive->name);
return -ENOMEM;
}
info->toc = toc;
}
/*
* Check to see if the existing data is still valid. If it is,
* just return.
*/
(void) cdrom_check_status(drive, sense);
if (drive->atapi_flags & IDE_AFLAG_TOC_VALID)
return 0;
/* try to get the total cdrom capacity and sector size */
stat = cdrom_read_capacity(drive, &toc->capacity, §ors_per_frame,
sense);
if (stat)
toc->capacity = 0x1fffff;
set_capacity(info->disk, toc->capacity * sectors_per_frame);
/* save a private copy of the TOC capacity for error handling */
drive->probed_capacity = toc->capacity * sectors_per_frame;
blk_queue_logical_block_size(drive->queue,
sectors_per_frame << SECTOR_BITS);
/* first read just the header, so we know how long the TOC is */
stat = cdrom_read_tocentry(drive, 0, 1, 0, (char *) &toc->hdr,
sizeof(struct atapi_toc_header), sense);
if (stat)
return stat;
if (drive->atapi_flags & IDE_AFLAG_TOCTRACKS_AS_BCD) {
toc->hdr.first_track = bcd2bin(toc->hdr.first_track);
toc->hdr.last_track = bcd2bin(toc->hdr.last_track);
}
ntracks = toc->hdr.last_track - toc->hdr.first_track + 1;
if (ntracks <= 0)
return -EIO;
if (ntracks > MAX_TRACKS)
ntracks = MAX_TRACKS;
/* now read the whole schmeer */
stat = cdrom_read_tocentry(drive, toc->hdr.first_track, 1, 0,
(char *)&toc->hdr,
sizeof(struct atapi_toc_header) +
(ntracks + 1) *
sizeof(struct atapi_toc_entry), sense);
if (stat && toc->hdr.first_track > 1) {
/*
* Cds with CDI tracks only don't have any TOC entries, despite
* of this the returned values are
* first_track == last_track = number of CDI tracks + 1,
* so that this case is indistinguishable from the same layout
* plus an additional audio track. If we get an error for the
* regular case, we assume a CDI without additional audio
* tracks. In this case the readable TOC is empty (CDI tracks
* are not included) and only holds the Leadout entry.
*
* Heiko Eißfeldt.
*/
ntracks = 0;
stat = cdrom_read_tocentry(drive, CDROM_LEADOUT, 1, 0,
(char *)&toc->hdr,
sizeof(struct atapi_toc_header) +
(ntracks + 1) *
sizeof(struct atapi_toc_entry),
sense);
if (stat)
return stat;
if (drive->atapi_flags & IDE_AFLAG_TOCTRACKS_AS_BCD) {
toc->hdr.first_track = (u8)bin2bcd(CDROM_LEADOUT);
toc->hdr.last_track = (u8)bin2bcd(CDROM_LEADOUT);
} else {
toc->hdr.first_track = CDROM_LEADOUT;
toc->hdr.last_track = CDROM_LEADOUT;
}
}
if (stat)
return stat;
toc->hdr.toc_length = be16_to_cpu(toc->hdr.toc_length);
if (drive->atapi_flags & IDE_AFLAG_TOCTRACKS_AS_BCD) {
toc->hdr.first_track = bcd2bin(toc->hdr.first_track);
toc->hdr.last_track = bcd2bin(toc->hdr.last_track);
}
for (i = 0; i <= ntracks; i++) {
if (drive->atapi_flags & IDE_AFLAG_TOCADDR_AS_BCD) {
if (drive->atapi_flags & IDE_AFLAG_TOCTRACKS_AS_BCD)
toc->ent[i].track = bcd2bin(toc->ent[i].track);
msf_from_bcd(&toc->ent[i].addr.msf);
}
toc->ent[i].addr.lba = msf_to_lba(toc->ent[i].addr.msf.minute,
toc->ent[i].addr.msf.second,
toc->ent[i].addr.msf.frame);
}
if (toc->hdr.first_track != CDROM_LEADOUT) {
/* read the multisession information */
stat = cdrom_read_tocentry(drive, 0, 0, 1, (char *)&ms_tmp,
sizeof(ms_tmp), sense);
if (stat)
return stat;
toc->last_session_lba = be32_to_cpu(ms_tmp.ent.addr.lba);
} else {
ms_tmp.hdr.last_track = CDROM_LEADOUT;
ms_tmp.hdr.first_track = ms_tmp.hdr.last_track;
toc->last_session_lba = msf_to_lba(0, 2, 0); /* 0m 2s 0f */
}
if (drive->atapi_flags & IDE_AFLAG_TOCADDR_AS_BCD) {
/* re-read multisession information using MSF format */
stat = cdrom_read_tocentry(drive, 0, 1, 1, (char *)&ms_tmp,
sizeof(ms_tmp), sense);
if (stat)
return stat;
msf_from_bcd(&ms_tmp.ent.addr.msf);
toc->last_session_lba = msf_to_lba(ms_tmp.ent.addr.msf.minute,
ms_tmp.ent.addr.msf.second,
ms_tmp.ent.addr.msf.frame);
}
toc->xa_flag = (ms_tmp.hdr.first_track != ms_tmp.hdr.last_track);
/* now try to get the total cdrom capacity */
stat = cdrom_get_last_written(cdi, &last_written);
if (!stat && (last_written > toc->capacity)) {
toc->capacity = last_written;
set_capacity(info->disk, toc->capacity * sectors_per_frame);
drive->probed_capacity = toc->capacity * sectors_per_frame;
}
/* Remember that we've read this stuff. */
drive->atapi_flags |= IDE_AFLAG_TOC_VALID;
return 0;
}
int ide_cdrom_get_capabilities(ide_drive_t *drive, u8 *buf)
{
struct cdrom_info *info = drive->driver_data;
struct cdrom_device_info *cdi = &info->devinfo;
struct packet_command cgc;
int stat, attempts = 3, size = ATAPI_CAPABILITIES_PAGE_SIZE;
ide_debug_log(IDE_DBG_FUNC, "enter");
if ((drive->atapi_flags & IDE_AFLAG_FULL_CAPS_PAGE) == 0)
size -= ATAPI_CAPABILITIES_PAGE_PAD_SIZE;
init_cdrom_command(&cgc, buf, size, CGC_DATA_UNKNOWN);
do {
/* we seem to get stat=0x01,err=0x00 the first time (??) */
stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CAPABILITIES_PAGE, 0);
if (!stat)
break;
} while (--attempts);
return stat;
}
void ide_cdrom_update_speed(ide_drive_t *drive, u8 *buf)
{
struct cdrom_info *cd = drive->driver_data;
u16 curspeed, maxspeed;
ide_debug_log(IDE_DBG_FUNC, "enter");
if (drive->atapi_flags & IDE_AFLAG_LE_SPEED_FIELDS) {
curspeed = le16_to_cpup((__le16 *)&buf[8 + 14]);
maxspeed = le16_to_cpup((__le16 *)&buf[8 + 8]);
} else {
curspeed = be16_to_cpup((__be16 *)&buf[8 + 14]);
maxspeed = be16_to_cpup((__be16 *)&buf[8 + 8]);
}
ide_debug_log(IDE_DBG_PROBE, "curspeed: %u, maxspeed: %u",
curspeed, maxspeed);
cd->current_speed = DIV_ROUND_CLOSEST(curspeed, 176);
cd->max_speed = DIV_ROUND_CLOSEST(maxspeed, 176);
}
#define IDE_CD_CAPABILITIES \
(CDC_CLOSE_TRAY | CDC_OPEN_TRAY | CDC_LOCK | CDC_SELECT_SPEED | \
CDC_SELECT_DISC | CDC_MULTI_SESSION | CDC_MCN | CDC_MEDIA_CHANGED | \
CDC_PLAY_AUDIO | CDC_RESET | CDC_DRIVE_STATUS | CDC_CD_R | \
CDC_CD_RW | CDC_DVD | CDC_DVD_R | CDC_DVD_RAM | CDC_GENERIC_PACKET | \
CDC_MO_DRIVE | CDC_MRW | CDC_MRW_W | CDC_RAM)
static struct cdrom_device_ops ide_cdrom_dops = {
.open = ide_cdrom_open_real,
.release = ide_cdrom_release_real,
.drive_status = ide_cdrom_drive_status,
.media_changed = ide_cdrom_check_media_change_real,
.tray_move = ide_cdrom_tray_move,
.lock_door = ide_cdrom_lock_door,
.select_speed = ide_cdrom_select_speed,
.get_last_session = ide_cdrom_get_last_session,
.get_mcn = ide_cdrom_get_mcn,
.reset = ide_cdrom_reset,
.audio_ioctl = ide_cdrom_audio_ioctl,
.capability = IDE_CD_CAPABILITIES,
.generic_packet = ide_cdrom_packet,
};
static int ide_cdrom_register(ide_drive_t *drive, int nslots)
{
struct cdrom_info *info = drive->driver_data;
struct cdrom_device_info *devinfo = &info->devinfo;
ide_debug_log(IDE_DBG_PROBE, "nslots: %d", nslots);
devinfo->ops = &ide_cdrom_dops;
devinfo->speed = info->current_speed;
devinfo->capacity = nslots;
devinfo->handle = drive;
strcpy(devinfo->name, drive->name);
if (drive->atapi_flags & IDE_AFLAG_NO_SPEED_SELECT)
devinfo->mask |= CDC_SELECT_SPEED;
devinfo->disk = info->disk;
return register_cdrom(devinfo);
}
static int ide_cdrom_probe_capabilities(ide_drive_t *drive)
{
struct cdrom_info *cd = drive->driver_data;
struct cdrom_device_info *cdi = &cd->devinfo;
u8 buf[ATAPI_CAPABILITIES_PAGE_SIZE];
mechtype_t mechtype;
int nslots = 1;
ide_debug_log(IDE_DBG_PROBE, "media: 0x%x, atapi_flags: 0x%lx",
drive->media, drive->atapi_flags);
cdi->mask = (CDC_CD_R | CDC_CD_RW | CDC_DVD | CDC_DVD_R |
CDC_DVD_RAM | CDC_SELECT_DISC | CDC_PLAY_AUDIO |
CDC_MO_DRIVE | CDC_RAM);
if (drive->media == ide_optical) {
cdi->mask &= ~(CDC_MO_DRIVE | CDC_RAM);
printk(KERN_ERR PFX "%s: ATAPI magneto-optical drive\n",
drive->name);
return nslots;
}
if (drive->atapi_flags & IDE_AFLAG_PRE_ATAPI12) {
drive->atapi_flags &= ~IDE_AFLAG_NO_EJECT;
cdi->mask &= ~CDC_PLAY_AUDIO;
return nslots;
}
/*
* We have to cheat a little here. the packet will eventually be queued
* with ide_cdrom_packet(), which extracts the drive from cdi->handle.
* Since this device hasn't been registered with the Uniform layer yet,
* it can't do this. Same goes for cdi->ops.
*/
cdi->handle = drive;
cdi->ops = &ide_cdrom_dops;
if (ide_cdrom_get_capabilities(drive, buf))
return 0;
if ((buf[8 + 6] & 0x01) == 0)
drive->dev_flags &= ~IDE_DFLAG_DOORLOCKING;
if (buf[8 + 6] & 0x08)
drive->atapi_flags &= ~IDE_AFLAG_NO_EJECT;
if (buf[8 + 3] & 0x01)
cdi->mask &= ~CDC_CD_R;
if (buf[8 + 3] & 0x02)
cdi->mask &= ~(CDC_CD_RW | CDC_RAM);
if (buf[8 + 2] & 0x38)
cdi->mask &= ~CDC_DVD;
if (buf[8 + 3] & 0x20)
cdi->mask &= ~(CDC_DVD_RAM | CDC_RAM);
if (buf[8 + 3] & 0x10)
cdi->mask &= ~CDC_DVD_R;
if ((buf[8 + 4] & 0x01) || (drive->atapi_flags & IDE_AFLAG_PLAY_AUDIO_OK))
cdi->mask &= ~CDC_PLAY_AUDIO;
mechtype = buf[8 + 6] >> 5;
if (mechtype == mechtype_caddy ||
mechtype == mechtype_popup ||
(drive->atapi_flags & IDE_AFLAG_NO_AUTOCLOSE))
cdi->mask |= CDC_CLOSE_TRAY;
if (cdi->sanyo_slot > 0) {
cdi->mask &= ~CDC_SELECT_DISC;
nslots = 3;
} else if (mechtype == mechtype_individual_changer ||
mechtype == mechtype_cartridge_changer) {
nslots = cdrom_number_of_slots(cdi);
if (nslots > 1)
cdi->mask &= ~CDC_SELECT_DISC;
}
ide_cdrom_update_speed(drive, buf);
printk(KERN_INFO PFX "%s: ATAPI", drive->name);
/* don't print speed if the drive reported 0 */
if (cd->max_speed)
printk(KERN_CONT " %dX", cd->max_speed);
printk(KERN_CONT " %s", (cdi->mask & CDC_DVD) ? "CD-ROM" : "DVD-ROM");
if ((cdi->mask & CDC_DVD_R) == 0 || (cdi->mask & CDC_DVD_RAM) == 0)
printk(KERN_CONT " DVD%s%s",
(cdi->mask & CDC_DVD_R) ? "" : "-R",
(cdi->mask & CDC_DVD_RAM) ? "" : "/RAM");
if ((cdi->mask & CDC_CD_R) == 0 || (cdi->mask & CDC_CD_RW) == 0)
printk(KERN_CONT " CD%s%s",
(cdi->mask & CDC_CD_R) ? "" : "-R",
(cdi->mask & CDC_CD_RW) ? "" : "/RW");
if ((cdi->mask & CDC_SELECT_DISC) == 0)
printk(KERN_CONT " changer w/%d slots", nslots);
else
printk(KERN_CONT " drive");
printk(KERN_CONT ", %dkB Cache\n",
be16_to_cpup((__be16 *)&buf[8 + 12]));
return nslots;
}
/* standard prep_rq_fn that builds 10 byte cmds */
static int ide_cdrom_prep_fs(struct request_queue *q, struct request *rq)
{
int hard_sect = queue_logical_block_size(q);
long block = (long)blk_rq_pos(rq) / (hard_sect >> 9);
unsigned long blocks = blk_rq_sectors(rq) / (hard_sect >> 9);
memset(rq->cmd, 0, BLK_MAX_CDB);
if (rq_data_dir(rq) == READ)
rq->cmd[0] = GPCMD_READ_10;
else
rq->cmd[0] = GPCMD_WRITE_10;
/*
* fill in lba
*/
rq->cmd[2] = (block >> 24) & 0xff;
rq->cmd[3] = (block >> 16) & 0xff;
rq->cmd[4] = (block >> 8) & 0xff;
rq->cmd[5] = block & 0xff;
/*
* and transfer length
*/
rq->cmd[7] = (blocks >> 8) & 0xff;
rq->cmd[8] = blocks & 0xff;
rq->cmd_len = 10;
return BLKPREP_OK;
}
/*
* Most of the SCSI commands are supported directly by ATAPI devices.
* This transform handles the few exceptions.
*/
static int ide_cdrom_prep_pc(struct request *rq)
{
u8 *c = rq->cmd;
/* transform 6-byte read/write commands to the 10-byte version */
if (c[0] == READ_6 || c[0] == WRITE_6) {
c[8] = c[4];
c[5] = c[3];
c[4] = c[2];
c[3] = c[1] & 0x1f;
c[2] = 0;
c[1] &= 0xe0;
c[0] += (READ_10 - READ_6);
rq->cmd_len = 10;
return BLKPREP_OK;
}
/*
* it's silly to pretend we understand 6-byte sense commands, just
* reject with ILLEGAL_REQUEST and the caller should take the
* appropriate action
*/
if (c[0] == MODE_SENSE || c[0] == MODE_SELECT) {
rq->errors = ILLEGAL_REQUEST;
return BLKPREP_KILL;
}
return BLKPREP_OK;
}
static int ide_cdrom_prep_fn(struct request_queue *q, struct request *rq)
{
if (blk_fs_request(rq))
return ide_cdrom_prep_fs(q, rq);
else if (blk_pc_request(rq))
return ide_cdrom_prep_pc(rq);
return 0;
}
struct cd_list_entry {
const char *id_model;
const char *id_firmware;
unsigned int cd_flags;
};
#ifdef CONFIG_IDE_PROC_FS
static sector_t ide_cdrom_capacity(ide_drive_t *drive)
{
unsigned long capacity, sectors_per_frame;
if (cdrom_read_capacity(drive, &capacity, §ors_per_frame, NULL))
return 0;
return capacity * sectors_per_frame;
}
static int idecd_capacity_proc_show(struct seq_file *m, void *v)
{
ide_drive_t *drive = m->private;
seq_printf(m, "%llu\n", (long long)ide_cdrom_capacity(drive));
return 0;
}
static int idecd_capacity_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, idecd_capacity_proc_show, PDE(inode)->data);
}
static const struct file_operations idecd_capacity_proc_fops = {
.owner = THIS_MODULE,
.open = idecd_capacity_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static ide_proc_entry_t idecd_proc[] = {
{ "capacity", S_IFREG|S_IRUGO, &idecd_capacity_proc_fops },
{}
};
static ide_proc_entry_t *ide_cd_proc_entries(ide_drive_t *drive)
{
return idecd_proc;
}
static const struct ide_proc_devset *ide_cd_proc_devsets(ide_drive_t *drive)
{
return NULL;
}
#endif
static const struct cd_list_entry ide_cd_quirks_list[] = {
/* SCR-3231 doesn't support the SET_CD_SPEED command. */
{ "SAMSUNG CD-ROM SCR-3231", NULL, IDE_AFLAG_NO_SPEED_SELECT },
/* Old NEC260 (not R) was released before ATAPI 1.2 spec. */
{ "NEC CD-ROM DRIVE:260", "1.01", IDE_AFLAG_TOCADDR_AS_BCD |
IDE_AFLAG_PRE_ATAPI12, },
/* Vertos 300, some versions of this drive like to talk BCD. */
{ "V003S0DS", NULL, IDE_AFLAG_VERTOS_300_SSD, },
/* Vertos 600 ESD. */
{ "V006E0DS", NULL, IDE_AFLAG_VERTOS_600_ESD, },
/*
* Sanyo 3 CD changer uses a non-standard command for CD changing
* (by default standard ATAPI support for CD changers is used).
*/
{ "CD-ROM CDR-C3 G", NULL, IDE_AFLAG_SANYO_3CD },
{ "CD-ROM CDR-C3G", NULL, IDE_AFLAG_SANYO_3CD },
{ "CD-ROM CDR_C36", NULL, IDE_AFLAG_SANYO_3CD },
/* Stingray 8X CD-ROM. */
{ "STINGRAY 8422 IDE 8X CD-ROM 7-27-95", NULL, IDE_AFLAG_PRE_ATAPI12 },
/*
* ACER 50X CD-ROM and WPI 32X CD-ROM require the full spec length
* mode sense page capabilities size, but older drives break.
*/
{ "ATAPI CD ROM DRIVE 50X MAX", NULL, IDE_AFLAG_FULL_CAPS_PAGE },
{ "WPI CDS-32X", NULL, IDE_AFLAG_FULL_CAPS_PAGE },
/* ACER/AOpen 24X CD-ROM has the speed fields byte-swapped. */
{ "", "241N", IDE_AFLAG_LE_SPEED_FIELDS },
/*
* Some drives used by Apple don't advertise audio play
* but they do support reading TOC & audio datas.
*/
{ "MATSHITADVD-ROM SR-8187", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "MATSHITADVD-ROM SR-8186", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "MATSHITADVD-ROM SR-8176", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "MATSHITADVD-ROM SR-8174", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "Optiarc DVD RW AD-5200A", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "Optiarc DVD RW AD-7200A", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "Optiarc DVD RW AD-7543A", NULL, IDE_AFLAG_NO_AUTOCLOSE },
{ "TEAC CD-ROM CD-224E", NULL, IDE_AFLAG_NO_AUTOCLOSE },
{ NULL, NULL, 0 }
};
static unsigned int ide_cd_flags(u16 *id)
{
const struct cd_list_entry *cle = ide_cd_quirks_list;
while (cle->id_model) {
if (strcmp(cle->id_model, (char *)&id[ATA_ID_PROD]) == 0 &&
(cle->id_firmware == NULL ||
strstr((char *)&id[ATA_ID_FW_REV], cle->id_firmware)))
return cle->cd_flags;
cle++;
}
return 0;
}
static int ide_cdrom_setup(ide_drive_t *drive)
{
struct cdrom_info *cd = drive->driver_data;
struct cdrom_device_info *cdi = &cd->devinfo;
struct request_queue *q = drive->queue;
u16 *id = drive->id;
char *fw_rev = (char *)&id[ATA_ID_FW_REV];
int nslots;
ide_debug_log(IDE_DBG_PROBE, "enter");
blk_queue_prep_rq(q, ide_cdrom_prep_fn);
blk_queue_dma_alignment(q, 31);
blk_queue_update_dma_pad(q, 15);
q->unplug_delay = max((1 * HZ) / 1000, 1);
drive->dev_flags |= IDE_DFLAG_MEDIA_CHANGED;
drive->atapi_flags = IDE_AFLAG_NO_EJECT | ide_cd_flags(id);
if ((drive->atapi_flags & IDE_AFLAG_VERTOS_300_SSD) &&
fw_rev[4] == '1' && fw_rev[6] <= '2')
drive->atapi_flags |= (IDE_AFLAG_TOCTRACKS_AS_BCD |
IDE_AFLAG_TOCADDR_AS_BCD);
else if ((drive->atapi_flags & IDE_AFLAG_VERTOS_600_ESD) &&
fw_rev[4] == '1' && fw_rev[6] <= '2')
drive->atapi_flags |= IDE_AFLAG_TOCTRACKS_AS_BCD;
else if (drive->atapi_flags & IDE_AFLAG_SANYO_3CD)
/* 3 => use CD in slot 0 */
cdi->sanyo_slot = 3;
nslots = ide_cdrom_probe_capabilities(drive);
blk_queue_logical_block_size(q, CD_FRAMESIZE);
if (ide_cdrom_register(drive, nslots)) {
printk(KERN_ERR PFX "%s: %s failed to register device with the"
" cdrom driver.\n", drive->name, __func__);
cd->devinfo.handle = NULL;
return 1;
}
ide_proc_register_driver(drive, cd->driver);
return 0;
}
static void ide_cd_remove(ide_drive_t *drive)
{
struct cdrom_info *info = drive->driver_data;
ide_debug_log(IDE_DBG_FUNC, "enter");
ide_proc_unregister_driver(drive, info->driver);
device_del(&info->dev);
del_gendisk(info->disk);
mutex_lock(&idecd_ref_mutex);
put_device(&info->dev);
mutex_unlock(&idecd_ref_mutex);
}
static void ide_cd_release(struct device *dev)
{
struct cdrom_info *info = to_ide_drv(dev, cdrom_info);
struct cdrom_device_info *devinfo = &info->devinfo;
ide_drive_t *drive = info->drive;
struct gendisk *g = info->disk;
ide_debug_log(IDE_DBG_FUNC, "enter");
kfree(info->toc);
if (devinfo->handle == drive)
unregister_cdrom(devinfo);
drive->driver_data = NULL;
blk_queue_prep_rq(drive->queue, NULL);
g->private_data = NULL;
put_disk(g);
kfree(info);
}
static int ide_cd_probe(ide_drive_t *);
static struct ide_driver ide_cdrom_driver = {
.gen_driver = {
.owner = THIS_MODULE,
.name = "ide-cdrom",
.bus = &ide_bus_type,
},
.probe = ide_cd_probe,
.remove = ide_cd_remove,
.version = IDECD_VERSION,
.do_request = ide_cd_do_request,
#ifdef CONFIG_IDE_PROC_FS
.proc_entries = ide_cd_proc_entries,
.proc_devsets = ide_cd_proc_devsets,
#endif
};
static int idecd_open(struct block_device *bdev, fmode_t mode)
{
struct cdrom_info *info = ide_cd_get(bdev->bd_disk);
int rc = -ENOMEM;
if (!info)
return -ENXIO;
rc = cdrom_open(&info->devinfo, bdev, mode);
if (rc < 0)
ide_cd_put(info);
return rc;
}
static int idecd_release(struct gendisk *disk, fmode_t mode)
{
struct cdrom_info *info = ide_drv_g(disk, cdrom_info);
cdrom_release(&info->devinfo, mode);
ide_cd_put(info);
return 0;
}
static int idecd_set_spindown(struct cdrom_device_info *cdi, unsigned long arg)
{
struct packet_command cgc;
char buffer[16];
int stat;
char spindown;
if (copy_from_user(&spindown, (void __user *)arg, sizeof(char)))
return -EFAULT;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_UNKNOWN);
stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CDROM_PAGE, 0);
if (stat)
return stat;
buffer[11] = (buffer[11] & 0xf0) | (spindown & 0x0f);
return cdrom_mode_select(cdi, &cgc);
}
static int idecd_get_spindown(struct cdrom_device_info *cdi, unsigned long arg)
{
struct packet_command cgc;
char buffer[16];
int stat;
char spindown;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_UNKNOWN);
stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CDROM_PAGE, 0);
if (stat)
return stat;
spindown = buffer[11] & 0x0f;
if (copy_to_user((void __user *)arg, &spindown, sizeof(char)))
return -EFAULT;
return 0;
}
static int idecd_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
struct cdrom_info *info = ide_drv_g(bdev->bd_disk, cdrom_info);
int err;
switch (cmd) {
case CDROMSETSPINDOWN:
return idecd_set_spindown(&info->devinfo, arg);
case CDROMGETSPINDOWN:
return idecd_get_spindown(&info->devinfo, arg);
default:
break;
}
err = generic_ide_ioctl(info->drive, bdev, cmd, arg);
if (err == -EINVAL)
err = cdrom_ioctl(&info->devinfo, bdev, mode, cmd, arg);
return err;
}
static int idecd_media_changed(struct gendisk *disk)
{
struct cdrom_info *info = ide_drv_g(disk, cdrom_info);
return cdrom_media_changed(&info->devinfo);
}
static int idecd_revalidate_disk(struct gendisk *disk)
{
struct cdrom_info *info = ide_drv_g(disk, cdrom_info);
struct request_sense sense;
ide_cd_read_toc(info->drive, &sense);
return 0;
}
static const struct block_device_operations idecd_ops = {
.owner = THIS_MODULE,
.open = idecd_open,
.release = idecd_release,
.locked_ioctl = idecd_ioctl,
.media_changed = idecd_media_changed,
.revalidate_disk = idecd_revalidate_disk
};
/* module options */
static unsigned long debug_mask;
module_param(debug_mask, ulong, 0644);
MODULE_DESCRIPTION("ATAPI CD-ROM Driver");
static int ide_cd_probe(ide_drive_t *drive)
{
struct cdrom_info *info;
struct gendisk *g;
struct request_sense sense;
ide_debug_log(IDE_DBG_PROBE, "driver_req: %s, media: 0x%x",
drive->driver_req, drive->media);
if (!strstr("ide-cdrom", drive->driver_req))
goto failed;
if (drive->media != ide_cdrom && drive->media != ide_optical)
goto failed;
drive->debug_mask = debug_mask;
drive->irq_handler = cdrom_newpc_intr;
info = kzalloc(sizeof(struct cdrom_info), GFP_KERNEL);
if (info == NULL) {
printk(KERN_ERR PFX "%s: Can't allocate a cdrom structure\n",
drive->name);
goto failed;
}
g = alloc_disk(1 << PARTN_BITS);
if (!g)
goto out_free_cd;
ide_init_disk(g, drive);
info->dev.parent = &drive->gendev;
info->dev.release = ide_cd_release;
dev_set_name(&info->dev, dev_name(&drive->gendev));
if (device_register(&info->dev))
goto out_free_disk;
info->drive = drive;
info->driver = &ide_cdrom_driver;
info->disk = g;
g->private_data = &info->driver;
drive->driver_data = info;
g->minors = 1;
g->driverfs_dev = &drive->gendev;
g->flags = GENHD_FL_CD | GENHD_FL_REMOVABLE;
if (ide_cdrom_setup(drive)) {
put_device(&info->dev);
goto failed;
}
ide_cd_read_toc(drive, &sense);
g->fops = &idecd_ops;
g->flags |= GENHD_FL_REMOVABLE;
add_disk(g);
return 0;
out_free_disk:
put_disk(g);
out_free_cd:
kfree(info);
failed:
return -ENODEV;
}
static void __exit ide_cdrom_exit(void)
{
driver_unregister(&ide_cdrom_driver.gen_driver);
}
static int __init ide_cdrom_init(void)
{
printk(KERN_INFO DRV_NAME " driver " IDECD_VERSION "\n");
return driver_register(&ide_cdrom_driver.gen_driver);
}
MODULE_ALIAS("ide:*m-cdrom*");
MODULE_ALIAS("ide-cd");
module_init(ide_cdrom_init);
module_exit(ide_cdrom_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
CyanogenMod/android_kernel_cyanogen_msm8916 | arch/arm/mach-iop13xx/setup.c | 873 | 15036 | /*
* iop13xx platform Initialization
* Copyright (c) 2005-2006, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307 USA.
*
*/
#include <linux/dma-mapping.h>
#include <linux/serial_8250.h>
#include <linux/io.h>
#ifdef CONFIG_MTD_PHYSMAP
#include <linux/mtd/physmap.h>
#endif
#include <asm/mach/map.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/hardware/iop_adma.h>
#define IOP13XX_UART_XTAL 33334000
#define IOP13XX_SETUP_DEBUG 0
#define PRINTK(x...) ((void)(IOP13XX_SETUP_DEBUG && printk(x)))
/* Standard IO mapping for all IOP13XX based systems
*/
static struct map_desc iop13xx_std_desc[] __initdata = {
{ /* mem mapped registers */
.virtual = (unsigned long)IOP13XX_PMMR_VIRT_MEM_BASE,
.pfn = __phys_to_pfn(IOP13XX_PMMR_PHYS_MEM_BASE),
.length = IOP13XX_PMMR_SIZE,
.type = MT_DEVICE,
},
};
static struct resource iop13xx_uart0_resources[] = {
[0] = {
.start = IOP13XX_UART0_PHYS,
.end = IOP13XX_UART0_PHYS + 0x3f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_IOP13XX_UART0,
.end = IRQ_IOP13XX_UART0,
.flags = IORESOURCE_IRQ
}
};
static struct resource iop13xx_uart1_resources[] = {
[0] = {
.start = IOP13XX_UART1_PHYS,
.end = IOP13XX_UART1_PHYS + 0x3f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_IOP13XX_UART1,
.end = IRQ_IOP13XX_UART1,
.flags = IORESOURCE_IRQ
}
};
static struct plat_serial8250_port iop13xx_uart0_data[] = {
{
.membase = IOP13XX_UART0_VIRT,
.mapbase = IOP13XX_UART0_PHYS,
.irq = IRQ_IOP13XX_UART0,
.uartclk = IOP13XX_UART_XTAL,
.regshift = 2,
.iotype = UPIO_MEM,
.flags = UPF_SKIP_TEST,
},
{ },
};
static struct plat_serial8250_port iop13xx_uart1_data[] = {
{
.membase = IOP13XX_UART1_VIRT,
.mapbase = IOP13XX_UART1_PHYS,
.irq = IRQ_IOP13XX_UART1,
.uartclk = IOP13XX_UART_XTAL,
.regshift = 2,
.iotype = UPIO_MEM,
.flags = UPF_SKIP_TEST,
},
{ },
};
/* The ids are fixed up later in iop13xx_platform_init */
static struct platform_device iop13xx_uart0 = {
.name = "serial8250",
.id = 0,
.dev.platform_data = iop13xx_uart0_data,
.num_resources = 2,
.resource = iop13xx_uart0_resources,
};
static struct platform_device iop13xx_uart1 = {
.name = "serial8250",
.id = 0,
.dev.platform_data = iop13xx_uart1_data,
.num_resources = 2,
.resource = iop13xx_uart1_resources
};
static struct resource iop13xx_i2c_0_resources[] = {
[0] = {
.start = IOP13XX_I2C0_PHYS,
.end = IOP13XX_I2C0_PHYS + 0x18,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_IOP13XX_I2C_0,
.end = IRQ_IOP13XX_I2C_0,
.flags = IORESOURCE_IRQ
}
};
static struct resource iop13xx_i2c_1_resources[] = {
[0] = {
.start = IOP13XX_I2C1_PHYS,
.end = IOP13XX_I2C1_PHYS + 0x18,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_IOP13XX_I2C_1,
.end = IRQ_IOP13XX_I2C_1,
.flags = IORESOURCE_IRQ
}
};
static struct resource iop13xx_i2c_2_resources[] = {
[0] = {
.start = IOP13XX_I2C2_PHYS,
.end = IOP13XX_I2C2_PHYS + 0x18,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_IOP13XX_I2C_2,
.end = IRQ_IOP13XX_I2C_2,
.flags = IORESOURCE_IRQ
}
};
/* I2C controllers. The IOP13XX uses the same block as the IOP3xx, so
* we just use the same device name.
*/
/* The ids are fixed up later in iop13xx_platform_init */
static struct platform_device iop13xx_i2c_0_controller = {
.name = "IOP3xx-I2C",
.id = 0,
.num_resources = 2,
.resource = iop13xx_i2c_0_resources
};
static struct platform_device iop13xx_i2c_1_controller = {
.name = "IOP3xx-I2C",
.id = 0,
.num_resources = 2,
.resource = iop13xx_i2c_1_resources
};
static struct platform_device iop13xx_i2c_2_controller = {
.name = "IOP3xx-I2C",
.id = 0,
.num_resources = 2,
.resource = iop13xx_i2c_2_resources
};
#ifdef CONFIG_MTD_PHYSMAP
/* PBI Flash Device
*/
static struct physmap_flash_data iq8134x_flash_data = {
.width = 2,
};
static struct resource iq8134x_flash_resource = {
.start = IQ81340_FLASHBASE,
.end = 0,
.flags = IORESOURCE_MEM,
};
static struct platform_device iq8134x_flash = {
.name = "physmap-flash",
.id = 0,
.dev = { .platform_data = &iq8134x_flash_data, },
.num_resources = 1,
.resource = &iq8134x_flash_resource,
};
static unsigned long iq8134x_probe_flash_size(void)
{
uint8_t __iomem *flash_addr = ioremap(IQ81340_FLASHBASE, PAGE_SIZE);
int i;
char query[3];
unsigned long size = 0;
int width = iq8134x_flash_data.width;
if (flash_addr) {
/* send CFI 'query' command */
writew(0x98, flash_addr);
/* check for CFI compliance */
for (i = 0; i < 3 * width; i += width)
query[i / width] = readb(flash_addr + (0x10 * width) + i);
/* read the size */
if (memcmp(query, "QRY", 3) == 0)
size = 1 << readb(flash_addr + (0x27 * width));
/* send CFI 'read array' command */
writew(0xff, flash_addr);
iounmap(flash_addr);
}
return size;
}
#endif
/* ADMA Channels */
static struct resource iop13xx_adma_0_resources[] = {
[0] = {
.start = IOP13XX_ADMA_PHYS_BASE(0),
.end = IOP13XX_ADMA_UPPER_PA(0),
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_IOP13XX_ADMA0_EOT,
.end = IRQ_IOP13XX_ADMA0_EOT,
.flags = IORESOURCE_IRQ
},
[2] = {
.start = IRQ_IOP13XX_ADMA0_EOC,
.end = IRQ_IOP13XX_ADMA0_EOC,
.flags = IORESOURCE_IRQ
},
[3] = {
.start = IRQ_IOP13XX_ADMA0_ERR,
.end = IRQ_IOP13XX_ADMA0_ERR,
.flags = IORESOURCE_IRQ
}
};
static struct resource iop13xx_adma_1_resources[] = {
[0] = {
.start = IOP13XX_ADMA_PHYS_BASE(1),
.end = IOP13XX_ADMA_UPPER_PA(1),
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_IOP13XX_ADMA1_EOT,
.end = IRQ_IOP13XX_ADMA1_EOT,
.flags = IORESOURCE_IRQ
},
[2] = {
.start = IRQ_IOP13XX_ADMA1_EOC,
.end = IRQ_IOP13XX_ADMA1_EOC,
.flags = IORESOURCE_IRQ
},
[3] = {
.start = IRQ_IOP13XX_ADMA1_ERR,
.end = IRQ_IOP13XX_ADMA1_ERR,
.flags = IORESOURCE_IRQ
}
};
static struct resource iop13xx_adma_2_resources[] = {
[0] = {
.start = IOP13XX_ADMA_PHYS_BASE(2),
.end = IOP13XX_ADMA_UPPER_PA(2),
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_IOP13XX_ADMA2_EOT,
.end = IRQ_IOP13XX_ADMA2_EOT,
.flags = IORESOURCE_IRQ
},
[2] = {
.start = IRQ_IOP13XX_ADMA2_EOC,
.end = IRQ_IOP13XX_ADMA2_EOC,
.flags = IORESOURCE_IRQ
},
[3] = {
.start = IRQ_IOP13XX_ADMA2_ERR,
.end = IRQ_IOP13XX_ADMA2_ERR,
.flags = IORESOURCE_IRQ
}
};
static u64 iop13xx_adma_dmamask = DMA_BIT_MASK(64);
static struct iop_adma_platform_data iop13xx_adma_0_data = {
.hw_id = 0,
.pool_size = PAGE_SIZE,
};
static struct iop_adma_platform_data iop13xx_adma_1_data = {
.hw_id = 1,
.pool_size = PAGE_SIZE,
};
static struct iop_adma_platform_data iop13xx_adma_2_data = {
.hw_id = 2,
.pool_size = PAGE_SIZE,
};
/* The ids are fixed up later in iop13xx_platform_init */
static struct platform_device iop13xx_adma_0_channel = {
.name = "iop-adma",
.id = 0,
.num_resources = 4,
.resource = iop13xx_adma_0_resources,
.dev = {
.dma_mask = &iop13xx_adma_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(64),
.platform_data = (void *) &iop13xx_adma_0_data,
},
};
static struct platform_device iop13xx_adma_1_channel = {
.name = "iop-adma",
.id = 0,
.num_resources = 4,
.resource = iop13xx_adma_1_resources,
.dev = {
.dma_mask = &iop13xx_adma_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(64),
.platform_data = (void *) &iop13xx_adma_1_data,
},
};
static struct platform_device iop13xx_adma_2_channel = {
.name = "iop-adma",
.id = 0,
.num_resources = 4,
.resource = iop13xx_adma_2_resources,
.dev = {
.dma_mask = &iop13xx_adma_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(64),
.platform_data = (void *) &iop13xx_adma_2_data,
},
};
void __init iop13xx_map_io(void)
{
/* Initialize the Static Page Table maps */
iotable_init(iop13xx_std_desc, ARRAY_SIZE(iop13xx_std_desc));
}
static int init_uart;
static int init_i2c;
static int init_adma;
void __init iop13xx_platform_init(void)
{
int i;
u32 uart_idx, i2c_idx, adma_idx, plat_idx;
struct platform_device *iop13xx_devices[IQ81340_MAX_PLAT_DEVICES];
/* set the bases so we can read the device id */
iop13xx_set_atu_mmr_bases();
memset(iop13xx_devices, 0, sizeof(iop13xx_devices));
if (init_uart == IOP13XX_INIT_UART_DEFAULT) {
switch (iop13xx_dev_id()) {
/* enable both uarts on iop341 */
case 0x3380:
case 0x3384:
case 0x3388:
case 0x338c:
init_uart |= IOP13XX_INIT_UART_0;
init_uart |= IOP13XX_INIT_UART_1;
break;
/* only enable uart 1 */
default:
init_uart |= IOP13XX_INIT_UART_1;
}
}
if (init_i2c == IOP13XX_INIT_I2C_DEFAULT) {
switch (iop13xx_dev_id()) {
/* enable all i2c units on iop341 and iop342 */
case 0x3380:
case 0x3384:
case 0x3388:
case 0x338c:
case 0x3382:
case 0x3386:
case 0x338a:
case 0x338e:
init_i2c |= IOP13XX_INIT_I2C_0;
init_i2c |= IOP13XX_INIT_I2C_1;
init_i2c |= IOP13XX_INIT_I2C_2;
break;
/* only enable i2c 1 and 2 */
default:
init_i2c |= IOP13XX_INIT_I2C_1;
init_i2c |= IOP13XX_INIT_I2C_2;
}
}
if (init_adma == IOP13XX_INIT_ADMA_DEFAULT) {
init_adma |= IOP13XX_INIT_ADMA_0;
init_adma |= IOP13XX_INIT_ADMA_1;
init_adma |= IOP13XX_INIT_ADMA_2;
}
plat_idx = 0;
uart_idx = 0;
i2c_idx = 0;
/* uart 1 (if enabled) is ttyS0 */
if (init_uart & IOP13XX_INIT_UART_1) {
PRINTK("Adding uart1 to platform device list\n");
iop13xx_uart1.id = uart_idx++;
iop13xx_devices[plat_idx++] = &iop13xx_uart1;
}
if (init_uart & IOP13XX_INIT_UART_0) {
PRINTK("Adding uart0 to platform device list\n");
iop13xx_uart0.id = uart_idx++;
iop13xx_devices[plat_idx++] = &iop13xx_uart0;
}
for(i = 0; i < IQ81340_NUM_I2C; i++) {
if ((init_i2c & (1 << i)) && IOP13XX_SETUP_DEBUG)
printk("Adding i2c%d to platform device list\n", i);
switch(init_i2c & (1 << i)) {
case IOP13XX_INIT_I2C_0:
iop13xx_i2c_0_controller.id = i2c_idx++;
iop13xx_devices[plat_idx++] =
&iop13xx_i2c_0_controller;
break;
case IOP13XX_INIT_I2C_1:
iop13xx_i2c_1_controller.id = i2c_idx++;
iop13xx_devices[plat_idx++] =
&iop13xx_i2c_1_controller;
break;
case IOP13XX_INIT_I2C_2:
iop13xx_i2c_2_controller.id = i2c_idx++;
iop13xx_devices[plat_idx++] =
&iop13xx_i2c_2_controller;
break;
}
}
/* initialize adma channel ids and capabilities */
adma_idx = 0;
for (i = 0; i < IQ81340_NUM_ADMA; i++) {
struct iop_adma_platform_data *plat_data;
if ((init_adma & (1 << i)) && IOP13XX_SETUP_DEBUG)
printk(KERN_INFO
"Adding adma%d to platform device list\n", i);
switch (init_adma & (1 << i)) {
case IOP13XX_INIT_ADMA_0:
iop13xx_adma_0_channel.id = adma_idx++;
iop13xx_devices[plat_idx++] = &iop13xx_adma_0_channel;
plat_data = &iop13xx_adma_0_data;
dma_cap_set(DMA_MEMCPY, plat_data->cap_mask);
dma_cap_set(DMA_XOR, plat_data->cap_mask);
dma_cap_set(DMA_XOR_VAL, plat_data->cap_mask);
dma_cap_set(DMA_MEMSET, plat_data->cap_mask);
dma_cap_set(DMA_INTERRUPT, plat_data->cap_mask);
break;
case IOP13XX_INIT_ADMA_1:
iop13xx_adma_1_channel.id = adma_idx++;
iop13xx_devices[plat_idx++] = &iop13xx_adma_1_channel;
plat_data = &iop13xx_adma_1_data;
dma_cap_set(DMA_MEMCPY, plat_data->cap_mask);
dma_cap_set(DMA_XOR, plat_data->cap_mask);
dma_cap_set(DMA_XOR_VAL, plat_data->cap_mask);
dma_cap_set(DMA_MEMSET, plat_data->cap_mask);
dma_cap_set(DMA_INTERRUPT, plat_data->cap_mask);
break;
case IOP13XX_INIT_ADMA_2:
iop13xx_adma_2_channel.id = adma_idx++;
iop13xx_devices[plat_idx++] = &iop13xx_adma_2_channel;
plat_data = &iop13xx_adma_2_data;
dma_cap_set(DMA_MEMCPY, plat_data->cap_mask);
dma_cap_set(DMA_XOR, plat_data->cap_mask);
dma_cap_set(DMA_XOR_VAL, plat_data->cap_mask);
dma_cap_set(DMA_MEMSET, plat_data->cap_mask);
dma_cap_set(DMA_INTERRUPT, plat_data->cap_mask);
dma_cap_set(DMA_PQ, plat_data->cap_mask);
dma_cap_set(DMA_PQ_VAL, plat_data->cap_mask);
break;
}
}
#ifdef CONFIG_MTD_PHYSMAP
iq8134x_flash_resource.end = iq8134x_flash_resource.start +
iq8134x_probe_flash_size() - 1;
if (iq8134x_flash_resource.end > iq8134x_flash_resource.start)
iop13xx_devices[plat_idx++] = &iq8134x_flash;
else
printk(KERN_ERR "%s: Failed to probe flash size\n", __func__);
#endif
platform_add_devices(iop13xx_devices, plat_idx);
}
static int __init iop13xx_init_uart_setup(char *str)
{
if (str) {
while (*str != '\0') {
switch(*str) {
case '0':
init_uart |= IOP13XX_INIT_UART_0;
break;
case '1':
init_uart |= IOP13XX_INIT_UART_1;
break;
case ',':
case '=':
break;
default:
PRINTK("\"iop13xx_init_uart\" malformed"
" at character: \'%c\'", *str);
*(str + 1) = '\0';
init_uart = IOP13XX_INIT_UART_DEFAULT;
}
str++;
}
}
return 1;
}
static int __init iop13xx_init_i2c_setup(char *str)
{
if (str) {
while (*str != '\0') {
switch(*str) {
case '0':
init_i2c |= IOP13XX_INIT_I2C_0;
break;
case '1':
init_i2c |= IOP13XX_INIT_I2C_1;
break;
case '2':
init_i2c |= IOP13XX_INIT_I2C_2;
break;
case ',':
case '=':
break;
default:
PRINTK("\"iop13xx_init_i2c\" malformed"
" at character: \'%c\'", *str);
*(str + 1) = '\0';
init_i2c = IOP13XX_INIT_I2C_DEFAULT;
}
str++;
}
}
return 1;
}
static int __init iop13xx_init_adma_setup(char *str)
{
if (str) {
while (*str != '\0') {
switch (*str) {
case '0':
init_adma |= IOP13XX_INIT_ADMA_0;
break;
case '1':
init_adma |= IOP13XX_INIT_ADMA_1;
break;
case '2':
init_adma |= IOP13XX_INIT_ADMA_2;
break;
case ',':
case '=':
break;
default:
PRINTK("\"iop13xx_init_adma\" malformed"
" at character: \'%c\'", *str);
*(str + 1) = '\0';
init_adma = IOP13XX_INIT_ADMA_DEFAULT;
}
str++;
}
}
return 1;
}
__setup("iop13xx_init_adma", iop13xx_init_adma_setup);
__setup("iop13xx_init_uart", iop13xx_init_uart_setup);
__setup("iop13xx_init_i2c", iop13xx_init_i2c_setup);
void iop13xx_restart(enum reboot_mode mode, const char *cmd)
{
/*
* Reset the internal bus (warning both cores are reset)
*/
write_wdtcr(IOP_WDTCR_EN_ARM);
write_wdtcr(IOP_WDTCR_EN);
write_wdtsr(IOP13XX_WDTSR_WRITE_EN | IOP13XX_WDTCR_IB_RESET);
write_wdtcr(0x1000);
}
| gpl-2.0 |
garwynn/D710BST_FI22_Kernel | fs/notify/mark.c | 873 | 11034 | /*
* Copyright (C) 2008 Red Hat, Inc., Eric Paris <eparis@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, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* fsnotify inode mark locking/lifetime/and refcnting
*
* REFCNT:
* The mark->refcnt tells how many "things" in the kernel currently are
* referencing this object. The object typically will live inside the kernel
* with a refcnt of 2, one for each list it is on (i_list, g_list). Any task
* which can find this object holding the appropriete locks, can take a reference
* and the object itself is guaranteed to survive until the reference is dropped.
*
* LOCKING:
* There are 3 spinlocks involved with fsnotify inode marks and they MUST
* be taken in order as follows:
*
* mark->lock
* group->mark_lock
* inode->i_lock
*
* mark->lock protects 2 things, mark->group and mark->inode. You must hold
* that lock to dereference either of these things (they could be NULL even with
* the lock)
*
* group->mark_lock protects the marks_list anchored inside a given group
* and each mark is hooked via the g_list. It also sorta protects the
* free_g_list, which when used is anchored by a private list on the stack of the
* task which held the group->mark_lock.
*
* inode->i_lock protects the i_fsnotify_marks list anchored inside a
* given inode and each mark is hooked via the i_list. (and sorta the
* free_i_list)
*
*
* LIFETIME:
* Inode marks survive between when they are added to an inode and when their
* refcnt==0.
*
* The inode mark can be cleared for a number of different reasons including:
* - The inode is unlinked for the last time. (fsnotify_inode_remove)
* - The inode is being evicted from cache. (fsnotify_inode_delete)
* - The fs the inode is on is unmounted. (fsnotify_inode_delete/fsnotify_unmount_inodes)
* - Something explicitly requests that it be removed. (fsnotify_destroy_mark)
* - The fsnotify_group associated with the mark is going away and all such marks
* need to be cleaned up. (fsnotify_clear_marks_by_group)
*
* Worst case we are given an inode and need to clean up all the marks on that
* inode. We take i_lock and walk the i_fsnotify_marks safely. For each
* mark on the list we take a reference (so the mark can't disappear under us).
* We remove that mark form the inode's list of marks and we add this mark to a
* private list anchored on the stack using i_free_list; At this point we no
* longer fear anything finding the mark using the inode's list of marks.
*
* We can safely and locklessly run the private list on the stack of everything
* we just unattached from the original inode. For each mark on the private list
* we grab the mark-> and can thus dereference mark->group and mark->inode. If
* we see the group and inode are not NULL we take those locks. Now holding all
* 3 locks we can completely remove the mark from other tasks finding it in the
* future. Remember, 10 things might already be referencing this mark, but they
* better be holding a ref. We drop our reference we took before we unhooked it
* from the inode. When the ref hits 0 we can free the mark.
*
* Very similarly for freeing by group, except we use free_g_list.
*
* This has the very interesting property of being able to run concurrently with
* any (or all) other directions.
*/
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kthread.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/srcu.h>
#include <asm/atomic.h>
#include <linux/fsnotify_backend.h>
#include "fsnotify.h"
struct srcu_struct fsnotify_mark_srcu;
static DEFINE_SPINLOCK(destroy_lock);
static LIST_HEAD(destroy_list);
static DECLARE_WAIT_QUEUE_HEAD(destroy_waitq);
void fsnotify_get_mark(struct fsnotify_mark *mark)
{
atomic_inc(&mark->refcnt);
}
void fsnotify_put_mark(struct fsnotify_mark *mark)
{
if (atomic_dec_and_test(&mark->refcnt))
mark->free_mark(mark);
}
/*
* Any time a mark is getting freed we end up here.
* The caller had better be holding a reference to this mark so we don't actually
* do the final put under the mark->lock
*/
void fsnotify_destroy_mark(struct fsnotify_mark *mark)
{
struct fsnotify_group *group;
struct inode *inode = NULL;
spin_lock(&mark->lock);
group = mark->group;
/* something else already called this function on this mark */
if (!(mark->flags & FSNOTIFY_MARK_FLAG_ALIVE)) {
spin_unlock(&mark->lock);
return;
}
mark->flags &= ~FSNOTIFY_MARK_FLAG_ALIVE;
/* 1 from caller and 1 for being on i_list/g_list */
BUG_ON(atomic_read(&mark->refcnt) < 2);
spin_lock(&group->mark_lock);
if (mark->flags & FSNOTIFY_MARK_FLAG_INODE) {
inode = mark->i.inode;
fsnotify_destroy_inode_mark(mark);
} else if (mark->flags & FSNOTIFY_MARK_FLAG_VFSMOUNT)
fsnotify_destroy_vfsmount_mark(mark);
else
BUG();
list_del_init(&mark->g_list);
spin_unlock(&group->mark_lock);
spin_unlock(&mark->lock);
spin_lock(&destroy_lock);
list_add(&mark->destroy_list, &destroy_list);
spin_unlock(&destroy_lock);
wake_up(&destroy_waitq);
/*
* Some groups like to know that marks are being freed. This is a
* callback to the group function to let it know that this mark
* is being freed.
*/
if (group->ops->freeing_mark)
group->ops->freeing_mark(mark, group);
/*
* __fsnotify_update_child_dentry_flags(inode);
*
* I really want to call that, but we can't, we have no idea if the inode
* still exists the second we drop the mark->lock.
*
* The next time an event arrive to this inode from one of it's children
* __fsnotify_parent will see that the inode doesn't care about it's
* children and will update all of these flags then. So really this
* is just a lazy update (and could be a perf win...)
*/
if (inode && (mark->flags & FSNOTIFY_MARK_FLAG_OBJECT_PINNED))
iput(inode);
/*
* it's possible that this group tried to destroy itself, but this
* this mark was simultaneously being freed by inode. If that's the
* case, we finish freeing the group here.
*/
if (unlikely(atomic_dec_and_test(&group->num_marks)))
fsnotify_final_destroy_group(group);
}
void fsnotify_set_mark_mask_locked(struct fsnotify_mark *mark, __u32 mask)
{
assert_spin_locked(&mark->lock);
mark->mask = mask;
if (mark->flags & FSNOTIFY_MARK_FLAG_INODE)
fsnotify_set_inode_mark_mask_locked(mark, mask);
}
void fsnotify_set_mark_ignored_mask_locked(struct fsnotify_mark *mark, __u32 mask)
{
assert_spin_locked(&mark->lock);
mark->ignored_mask = mask;
}
/*
* Attach an initialized mark to a given group and fs object.
* These marks may be used for the fsnotify backend to determine which
* event types should be delivered to which group.
*/
int fsnotify_add_mark(struct fsnotify_mark *mark,
struct fsnotify_group *group, struct inode *inode,
struct vfsmount *mnt, int allow_dups)
{
int ret = 0;
BUG_ON(inode && mnt);
BUG_ON(!inode && !mnt);
/*
* LOCKING ORDER!!!!
* mark->lock
* group->mark_lock
* inode->i_lock
*/
spin_lock(&mark->lock);
spin_lock(&group->mark_lock);
mark->flags |= FSNOTIFY_MARK_FLAG_ALIVE;
mark->group = group;
list_add(&mark->g_list, &group->marks_list);
atomic_inc(&group->num_marks);
fsnotify_get_mark(mark); /* for i_list and g_list */
if (inode) {
ret = fsnotify_add_inode_mark(mark, group, inode, allow_dups);
if (ret)
goto err;
} else if (mnt) {
ret = fsnotify_add_vfsmount_mark(mark, group, mnt, allow_dups);
if (ret)
goto err;
} else {
BUG();
}
spin_unlock(&group->mark_lock);
/* this will pin the object if appropriate */
fsnotify_set_mark_mask_locked(mark, mark->mask);
spin_unlock(&mark->lock);
if (inode)
__fsnotify_update_child_dentry_flags(inode);
return ret;
err:
mark->flags &= ~FSNOTIFY_MARK_FLAG_ALIVE;
list_del_init(&mark->g_list);
mark->group = NULL;
atomic_dec(&group->num_marks);
spin_unlock(&group->mark_lock);
spin_unlock(&mark->lock);
spin_lock(&destroy_lock);
list_add(&mark->destroy_list, &destroy_list);
spin_unlock(&destroy_lock);
wake_up(&destroy_waitq);
return ret;
}
/*
* clear any marks in a group in which mark->flags & flags is true
*/
void fsnotify_clear_marks_by_group_flags(struct fsnotify_group *group,
unsigned int flags)
{
struct fsnotify_mark *lmark, *mark;
LIST_HEAD(free_list);
spin_lock(&group->mark_lock);
list_for_each_entry_safe(mark, lmark, &group->marks_list, g_list) {
if (mark->flags & flags) {
list_add(&mark->free_g_list, &free_list);
list_del_init(&mark->g_list);
fsnotify_get_mark(mark);
}
}
spin_unlock(&group->mark_lock);
list_for_each_entry_safe(mark, lmark, &free_list, free_g_list) {
fsnotify_destroy_mark(mark);
fsnotify_put_mark(mark);
}
}
/*
* Given a group, destroy all of the marks associated with that group.
*/
void fsnotify_clear_marks_by_group(struct fsnotify_group *group)
{
fsnotify_clear_marks_by_group_flags(group, (unsigned int)-1);
}
void fsnotify_duplicate_mark(struct fsnotify_mark *new, struct fsnotify_mark *old)
{
assert_spin_locked(&old->lock);
new->i.inode = old->i.inode;
new->m.mnt = old->m.mnt;
new->group = old->group;
new->mask = old->mask;
new->free_mark = old->free_mark;
}
/*
* Nothing fancy, just initialize lists and locks and counters.
*/
void fsnotify_init_mark(struct fsnotify_mark *mark,
void (*free_mark)(struct fsnotify_mark *mark))
{
memset(mark, 0, sizeof(*mark));
spin_lock_init(&mark->lock);
atomic_set(&mark->refcnt, 1);
mark->free_mark = free_mark;
}
static int fsnotify_mark_destroy(void *ignored)
{
struct fsnotify_mark *mark, *next;
LIST_HEAD(private_destroy_list);
for (;;) {
spin_lock(&destroy_lock);
/* exchange the list head */
list_replace_init(&destroy_list, &private_destroy_list);
spin_unlock(&destroy_lock);
synchronize_srcu(&fsnotify_mark_srcu);
list_for_each_entry_safe(mark, next, &private_destroy_list, destroy_list) {
list_del_init(&mark->destroy_list);
fsnotify_put_mark(mark);
}
wait_event_interruptible(destroy_waitq, !list_empty(&destroy_list));
}
return 0;
}
static int __init fsnotify_mark_init(void)
{
struct task_struct *thread;
thread = kthread_run(fsnotify_mark_destroy, NULL,
"fsnotify_mark");
if (IS_ERR(thread))
panic("unable to start fsnotify mark destruction thread.");
return 0;
}
device_initcall(fsnotify_mark_init);
| gpl-2.0 |
cattleprod/XCeLL-XV | drivers/media/dvb/frontends/stv0297.c | 1641 | 17757 | /*
Driver for STV0297 demodulator
Copyright (C) 2004 Andrew de Quincey <adq_dvb@lidskialf.net>
Copyright (C) 2003-2004 Dennis Noermann <dennis.noermann@noernet.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/jiffies.h>
#include <linux/slab.h>
#include "dvb_frontend.h"
#include "stv0297.h"
struct stv0297_state {
struct i2c_adapter *i2c;
const struct stv0297_config *config;
struct dvb_frontend frontend;
unsigned long last_ber;
unsigned long base_freq;
};
#if 1
#define dprintk(x...) printk(x)
#else
#define dprintk(x...)
#endif
#define STV0297_CLOCK_KHZ 28900
static int stv0297_writereg(struct stv0297_state *state, u8 reg, u8 data)
{
int ret;
u8 buf[] = { reg, data };
struct i2c_msg msg = {.addr = state->config->demod_address,.flags = 0,.buf = buf,.len = 2 };
ret = i2c_transfer(state->i2c, &msg, 1);
if (ret != 1)
dprintk("%s: writereg error (reg == 0x%02x, val == 0x%02x, "
"ret == %i)\n", __func__, reg, data, ret);
return (ret != 1) ? -1 : 0;
}
static int stv0297_readreg(struct stv0297_state *state, u8 reg)
{
int ret;
u8 b0[] = { reg };
u8 b1[] = { 0 };
struct i2c_msg msg[] = { {.addr = state->config->demod_address,.flags = 0,.buf = b0,.len = 1},
{.addr = state->config->demod_address,.flags = I2C_M_RD,.buf = b1,.len = 1}
};
// this device needs a STOP between the register and data
if (state->config->stop_during_read) {
if ((ret = i2c_transfer(state->i2c, &msg[0], 1)) != 1) {
dprintk("%s: readreg error (reg == 0x%02x, ret == %i)\n", __func__, reg, ret);
return -1;
}
if ((ret = i2c_transfer(state->i2c, &msg[1], 1)) != 1) {
dprintk("%s: readreg error (reg == 0x%02x, ret == %i)\n", __func__, reg, ret);
return -1;
}
} else {
if ((ret = i2c_transfer(state->i2c, msg, 2)) != 2) {
dprintk("%s: readreg error (reg == 0x%02x, ret == %i)\n", __func__, reg, ret);
return -1;
}
}
return b1[0];
}
static int stv0297_writereg_mask(struct stv0297_state *state, u8 reg, u8 mask, u8 data)
{
int val;
val = stv0297_readreg(state, reg);
val &= ~mask;
val |= (data & mask);
stv0297_writereg(state, reg, val);
return 0;
}
static int stv0297_readregs(struct stv0297_state *state, u8 reg1, u8 * b, u8 len)
{
int ret;
struct i2c_msg msg[] = { {.addr = state->config->demod_address,.flags = 0,.buf =
®1,.len = 1},
{.addr = state->config->demod_address,.flags = I2C_M_RD,.buf = b,.len = len}
};
// this device needs a STOP between the register and data
if (state->config->stop_during_read) {
if ((ret = i2c_transfer(state->i2c, &msg[0], 1)) != 1) {
dprintk("%s: readreg error (reg == 0x%02x, ret == %i)\n", __func__, reg1, ret);
return -1;
}
if ((ret = i2c_transfer(state->i2c, &msg[1], 1)) != 1) {
dprintk("%s: readreg error (reg == 0x%02x, ret == %i)\n", __func__, reg1, ret);
return -1;
}
} else {
if ((ret = i2c_transfer(state->i2c, msg, 2)) != 2) {
dprintk("%s: readreg error (reg == 0x%02x, ret == %i)\n", __func__, reg1, ret);
return -1;
}
}
return 0;
}
static u32 stv0297_get_symbolrate(struct stv0297_state *state)
{
u64 tmp;
tmp = stv0297_readreg(state, 0x55);
tmp |= stv0297_readreg(state, 0x56) << 8;
tmp |= stv0297_readreg(state, 0x57) << 16;
tmp |= stv0297_readreg(state, 0x58) << 24;
tmp *= STV0297_CLOCK_KHZ;
tmp >>= 32;
return (u32) tmp;
}
static void stv0297_set_symbolrate(struct stv0297_state *state, u32 srate)
{
long tmp;
tmp = 131072L * srate; /* 131072 = 2^17 */
tmp = tmp / (STV0297_CLOCK_KHZ / 4); /* 1/4 = 2^-2 */
tmp = tmp * 8192L; /* 8192 = 2^13 */
stv0297_writereg(state, 0x55, (unsigned char) (tmp & 0xFF));
stv0297_writereg(state, 0x56, (unsigned char) (tmp >> 8));
stv0297_writereg(state, 0x57, (unsigned char) (tmp >> 16));
stv0297_writereg(state, 0x58, (unsigned char) (tmp >> 24));
}
static void stv0297_set_sweeprate(struct stv0297_state *state, short fshift, long symrate)
{
long tmp;
tmp = (long) fshift *262144L; /* 262144 = 2*18 */
tmp /= symrate;
tmp *= 1024; /* 1024 = 2*10 */
// adjust
if (tmp >= 0) {
tmp += 500000;
} else {
tmp -= 500000;
}
tmp /= 1000000;
stv0297_writereg(state, 0x60, tmp & 0xFF);
stv0297_writereg_mask(state, 0x69, 0xF0, (tmp >> 4) & 0xf0);
}
static void stv0297_set_carrieroffset(struct stv0297_state *state, long offset)
{
long tmp;
/* symrate is hardcoded to 10000 */
tmp = offset * 26844L; /* (2**28)/10000 */
if (tmp < 0)
tmp += 0x10000000;
tmp &= 0x0FFFFFFF;
stv0297_writereg(state, 0x66, (unsigned char) (tmp & 0xFF));
stv0297_writereg(state, 0x67, (unsigned char) (tmp >> 8));
stv0297_writereg(state, 0x68, (unsigned char) (tmp >> 16));
stv0297_writereg_mask(state, 0x69, 0x0F, (tmp >> 24) & 0x0f);
}
/*
static long stv0297_get_carrieroffset(struct stv0297_state *state)
{
s64 tmp;
stv0297_writereg(state, 0x6B, 0x00);
tmp = stv0297_readreg(state, 0x66);
tmp |= (stv0297_readreg(state, 0x67) << 8);
tmp |= (stv0297_readreg(state, 0x68) << 16);
tmp |= (stv0297_readreg(state, 0x69) & 0x0F) << 24;
tmp *= stv0297_get_symbolrate(state);
tmp >>= 28;
return (s32) tmp;
}
*/
static void stv0297_set_initialdemodfreq(struct stv0297_state *state, long freq)
{
s32 tmp;
if (freq > 10000)
freq -= STV0297_CLOCK_KHZ;
tmp = (STV0297_CLOCK_KHZ * 1000) / (1 << 16);
tmp = (freq * 1000) / tmp;
if (tmp > 0xffff)
tmp = 0xffff;
stv0297_writereg_mask(state, 0x25, 0x80, 0x80);
stv0297_writereg(state, 0x21, tmp >> 8);
stv0297_writereg(state, 0x20, tmp);
}
static int stv0297_set_qam(struct stv0297_state *state, fe_modulation_t modulation)
{
int val = 0;
switch (modulation) {
case QAM_16:
val = 0;
break;
case QAM_32:
val = 1;
break;
case QAM_64:
val = 4;
break;
case QAM_128:
val = 2;
break;
case QAM_256:
val = 3;
break;
default:
return -EINVAL;
}
stv0297_writereg_mask(state, 0x00, 0x70, val << 4);
return 0;
}
static int stv0297_set_inversion(struct stv0297_state *state, fe_spectral_inversion_t inversion)
{
int val = 0;
switch (inversion) {
case INVERSION_OFF:
val = 0;
break;
case INVERSION_ON:
val = 1;
break;
default:
return -EINVAL;
}
stv0297_writereg_mask(state, 0x83, 0x08, val << 3);
return 0;
}
static int stv0297_i2c_gate_ctrl(struct dvb_frontend *fe, int enable)
{
struct stv0297_state *state = fe->demodulator_priv;
if (enable) {
stv0297_writereg(state, 0x87, 0x78);
stv0297_writereg(state, 0x86, 0xc8);
}
return 0;
}
static int stv0297_init(struct dvb_frontend *fe)
{
struct stv0297_state *state = fe->demodulator_priv;
int i;
/* load init table */
for (i=0; !(state->config->inittab[i] == 0xff && state->config->inittab[i+1] == 0xff); i+=2)
stv0297_writereg(state, state->config->inittab[i], state->config->inittab[i+1]);
msleep(200);
state->last_ber = 0;
return 0;
}
static int stv0297_sleep(struct dvb_frontend *fe)
{
struct stv0297_state *state = fe->demodulator_priv;
stv0297_writereg_mask(state, 0x80, 1, 1);
return 0;
}
static int stv0297_read_status(struct dvb_frontend *fe, fe_status_t * status)
{
struct stv0297_state *state = fe->demodulator_priv;
u8 sync = stv0297_readreg(state, 0xDF);
*status = 0;
if (sync & 0x80)
*status |=
FE_HAS_SYNC | FE_HAS_SIGNAL | FE_HAS_CARRIER | FE_HAS_VITERBI | FE_HAS_LOCK;
return 0;
}
static int stv0297_read_ber(struct dvb_frontend *fe, u32 * ber)
{
struct stv0297_state *state = fe->demodulator_priv;
u8 BER[3];
stv0297_readregs(state, 0xA0, BER, 3);
if (!(BER[0] & 0x80)) {
state->last_ber = BER[2] << 8 | BER[1];
stv0297_writereg_mask(state, 0xA0, 0x80, 0x80);
}
*ber = state->last_ber;
return 0;
}
static int stv0297_read_signal_strength(struct dvb_frontend *fe, u16 * strength)
{
struct stv0297_state *state = fe->demodulator_priv;
u8 STRENGTH[3];
u16 tmp;
stv0297_readregs(state, 0x41, STRENGTH, 3);
tmp = (STRENGTH[1] & 0x03) << 8 | STRENGTH[0];
if (STRENGTH[2] & 0x20) {
if (tmp < 0x200)
tmp = 0;
else
tmp = tmp - 0x200;
} else {
if (tmp > 0x1ff)
tmp = 0;
else
tmp = 0x1ff - tmp;
}
*strength = (tmp << 7) | (tmp >> 2);
return 0;
}
static int stv0297_read_snr(struct dvb_frontend *fe, u16 * snr)
{
struct stv0297_state *state = fe->demodulator_priv;
u8 SNR[2];
stv0297_readregs(state, 0x07, SNR, 2);
*snr = SNR[1] << 8 | SNR[0];
return 0;
}
static int stv0297_read_ucblocks(struct dvb_frontend *fe, u32 * ucblocks)
{
struct stv0297_state *state = fe->demodulator_priv;
stv0297_writereg_mask(state, 0xDF, 0x03, 0x03); /* freeze the counters */
*ucblocks = (stv0297_readreg(state, 0xD5) << 8)
| stv0297_readreg(state, 0xD4);
stv0297_writereg_mask(state, 0xDF, 0x03, 0x02); /* clear the counters */
stv0297_writereg_mask(state, 0xDF, 0x03, 0x01); /* re-enable the counters */
return 0;
}
static int stv0297_set_frontend(struct dvb_frontend *fe, struct dvb_frontend_parameters *p)
{
struct stv0297_state *state = fe->demodulator_priv;
int u_threshold;
int initial_u;
int blind_u;
int delay;
int sweeprate;
int carrieroffset;
unsigned long starttime;
unsigned long timeout;
fe_spectral_inversion_t inversion;
switch (p->u.qam.modulation) {
case QAM_16:
case QAM_32:
case QAM_64:
delay = 100;
sweeprate = 1000;
break;
case QAM_128:
case QAM_256:
delay = 200;
sweeprate = 500;
break;
default:
return -EINVAL;
}
// determine inversion dependant parameters
inversion = p->inversion;
if (state->config->invert)
inversion = (inversion == INVERSION_ON) ? INVERSION_OFF : INVERSION_ON;
carrieroffset = -330;
switch (inversion) {
case INVERSION_OFF:
break;
case INVERSION_ON:
sweeprate = -sweeprate;
carrieroffset = -carrieroffset;
break;
default:
return -EINVAL;
}
stv0297_init(fe);
if (fe->ops.tuner_ops.set_params) {
fe->ops.tuner_ops.set_params(fe, p);
if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0);
}
/* clear software interrupts */
stv0297_writereg(state, 0x82, 0x0);
/* set initial demodulation frequency */
stv0297_set_initialdemodfreq(state, 7250);
/* setup AGC */
stv0297_writereg_mask(state, 0x43, 0x10, 0x00);
stv0297_writereg(state, 0x41, 0x00);
stv0297_writereg_mask(state, 0x42, 0x03, 0x01);
stv0297_writereg_mask(state, 0x36, 0x60, 0x00);
stv0297_writereg_mask(state, 0x36, 0x18, 0x00);
stv0297_writereg_mask(state, 0x71, 0x80, 0x80);
stv0297_writereg(state, 0x72, 0x00);
stv0297_writereg(state, 0x73, 0x00);
stv0297_writereg_mask(state, 0x74, 0x0F, 0x00);
stv0297_writereg_mask(state, 0x43, 0x08, 0x00);
stv0297_writereg_mask(state, 0x71, 0x80, 0x00);
/* setup STL */
stv0297_writereg_mask(state, 0x5a, 0x20, 0x20);
stv0297_writereg_mask(state, 0x5b, 0x02, 0x02);
stv0297_writereg_mask(state, 0x5b, 0x02, 0x00);
stv0297_writereg_mask(state, 0x5b, 0x01, 0x00);
stv0297_writereg_mask(state, 0x5a, 0x40, 0x40);
/* disable frequency sweep */
stv0297_writereg_mask(state, 0x6a, 0x01, 0x00);
/* reset deinterleaver */
stv0297_writereg_mask(state, 0x81, 0x01, 0x01);
stv0297_writereg_mask(state, 0x81, 0x01, 0x00);
/* ??? */
stv0297_writereg_mask(state, 0x83, 0x20, 0x20);
stv0297_writereg_mask(state, 0x83, 0x20, 0x00);
/* reset equaliser */
u_threshold = stv0297_readreg(state, 0x00) & 0xf;
initial_u = stv0297_readreg(state, 0x01) >> 4;
blind_u = stv0297_readreg(state, 0x01) & 0xf;
stv0297_writereg_mask(state, 0x84, 0x01, 0x01);
stv0297_writereg_mask(state, 0x84, 0x01, 0x00);
stv0297_writereg_mask(state, 0x00, 0x0f, u_threshold);
stv0297_writereg_mask(state, 0x01, 0xf0, initial_u << 4);
stv0297_writereg_mask(state, 0x01, 0x0f, blind_u);
/* data comes from internal A/D */
stv0297_writereg_mask(state, 0x87, 0x80, 0x00);
/* clear phase registers */
stv0297_writereg(state, 0x63, 0x00);
stv0297_writereg(state, 0x64, 0x00);
stv0297_writereg(state, 0x65, 0x00);
stv0297_writereg(state, 0x66, 0x00);
stv0297_writereg(state, 0x67, 0x00);
stv0297_writereg(state, 0x68, 0x00);
stv0297_writereg_mask(state, 0x69, 0x0f, 0x00);
/* set parameters */
stv0297_set_qam(state, p->u.qam.modulation);
stv0297_set_symbolrate(state, p->u.qam.symbol_rate / 1000);
stv0297_set_sweeprate(state, sweeprate, p->u.qam.symbol_rate / 1000);
stv0297_set_carrieroffset(state, carrieroffset);
stv0297_set_inversion(state, inversion);
/* kick off lock */
/* Disable corner detection for higher QAMs */
if (p->u.qam.modulation == QAM_128 ||
p->u.qam.modulation == QAM_256)
stv0297_writereg_mask(state, 0x88, 0x08, 0x00);
else
stv0297_writereg_mask(state, 0x88, 0x08, 0x08);
stv0297_writereg_mask(state, 0x5a, 0x20, 0x00);
stv0297_writereg_mask(state, 0x6a, 0x01, 0x01);
stv0297_writereg_mask(state, 0x43, 0x40, 0x40);
stv0297_writereg_mask(state, 0x5b, 0x30, 0x00);
stv0297_writereg_mask(state, 0x03, 0x0c, 0x0c);
stv0297_writereg_mask(state, 0x03, 0x03, 0x03);
stv0297_writereg_mask(state, 0x43, 0x10, 0x10);
/* wait for WGAGC lock */
starttime = jiffies;
timeout = jiffies + msecs_to_jiffies(2000);
while (time_before(jiffies, timeout)) {
msleep(10);
if (stv0297_readreg(state, 0x43) & 0x08)
break;
}
if (time_after(jiffies, timeout)) {
goto timeout;
}
msleep(20);
/* wait for equaliser partial convergence */
timeout = jiffies + msecs_to_jiffies(500);
while (time_before(jiffies, timeout)) {
msleep(10);
if (stv0297_readreg(state, 0x82) & 0x04) {
break;
}
}
if (time_after(jiffies, timeout)) {
goto timeout;
}
/* wait for equaliser full convergence */
timeout = jiffies + msecs_to_jiffies(delay);
while (time_before(jiffies, timeout)) {
msleep(10);
if (stv0297_readreg(state, 0x82) & 0x08) {
break;
}
}
if (time_after(jiffies, timeout)) {
goto timeout;
}
/* disable sweep */
stv0297_writereg_mask(state, 0x6a, 1, 0);
stv0297_writereg_mask(state, 0x88, 8, 0);
/* wait for main lock */
timeout = jiffies + msecs_to_jiffies(20);
while (time_before(jiffies, timeout)) {
msleep(10);
if (stv0297_readreg(state, 0xDF) & 0x80) {
break;
}
}
if (time_after(jiffies, timeout)) {
goto timeout;
}
msleep(100);
/* is it still locked after that delay? */
if (!(stv0297_readreg(state, 0xDF) & 0x80)) {
goto timeout;
}
/* success!! */
stv0297_writereg_mask(state, 0x5a, 0x40, 0x00);
state->base_freq = p->frequency;
return 0;
timeout:
stv0297_writereg_mask(state, 0x6a, 0x01, 0x00);
return 0;
}
static int stv0297_get_frontend(struct dvb_frontend *fe, struct dvb_frontend_parameters *p)
{
struct stv0297_state *state = fe->demodulator_priv;
int reg_00, reg_83;
reg_00 = stv0297_readreg(state, 0x00);
reg_83 = stv0297_readreg(state, 0x83);
p->frequency = state->base_freq;
p->inversion = (reg_83 & 0x08) ? INVERSION_ON : INVERSION_OFF;
if (state->config->invert)
p->inversion = (p->inversion == INVERSION_ON) ? INVERSION_OFF : INVERSION_ON;
p->u.qam.symbol_rate = stv0297_get_symbolrate(state) * 1000;
p->u.qam.fec_inner = FEC_NONE;
switch ((reg_00 >> 4) & 0x7) {
case 0:
p->u.qam.modulation = QAM_16;
break;
case 1:
p->u.qam.modulation = QAM_32;
break;
case 2:
p->u.qam.modulation = QAM_128;
break;
case 3:
p->u.qam.modulation = QAM_256;
break;
case 4:
p->u.qam.modulation = QAM_64;
break;
}
return 0;
}
static void stv0297_release(struct dvb_frontend *fe)
{
struct stv0297_state *state = fe->demodulator_priv;
kfree(state);
}
static struct dvb_frontend_ops stv0297_ops;
struct dvb_frontend *stv0297_attach(const struct stv0297_config *config,
struct i2c_adapter *i2c)
{
struct stv0297_state *state = NULL;
/* allocate memory for the internal state */
state = kzalloc(sizeof(struct stv0297_state), GFP_KERNEL);
if (state == NULL)
goto error;
/* setup the state */
state->config = config;
state->i2c = i2c;
state->last_ber = 0;
state->base_freq = 0;
/* check if the demod is there */
if ((stv0297_readreg(state, 0x80) & 0x70) != 0x20)
goto error;
/* create dvb_frontend */
memcpy(&state->frontend.ops, &stv0297_ops, sizeof(struct dvb_frontend_ops));
state->frontend.demodulator_priv = state;
return &state->frontend;
error:
kfree(state);
return NULL;
}
static struct dvb_frontend_ops stv0297_ops = {
.info = {
.name = "ST STV0297 DVB-C",
.type = FE_QAM,
.frequency_min = 47000000,
.frequency_max = 862000000,
.frequency_stepsize = 62500,
.symbol_rate_min = 870000,
.symbol_rate_max = 11700000,
.caps = FE_CAN_QAM_16 | FE_CAN_QAM_32 | FE_CAN_QAM_64 |
FE_CAN_QAM_128 | FE_CAN_QAM_256 | FE_CAN_FEC_AUTO},
.release = stv0297_release,
.init = stv0297_init,
.sleep = stv0297_sleep,
.i2c_gate_ctrl = stv0297_i2c_gate_ctrl,
.set_frontend = stv0297_set_frontend,
.get_frontend = stv0297_get_frontend,
.read_status = stv0297_read_status,
.read_ber = stv0297_read_ber,
.read_signal_strength = stv0297_read_signal_strength,
.read_snr = stv0297_read_snr,
.read_ucblocks = stv0297_read_ucblocks,
};
MODULE_DESCRIPTION("ST STV0297 DVB-C Demodulator driver");
MODULE_AUTHOR("Dennis Noermann and Andrew de Quincey");
MODULE_LICENSE("GPL");
EXPORT_SYMBOL(stv0297_attach);
| gpl-2.0 |
lg-devs/android_kernel_lge_msm8996 | drivers/rtc/rtc-fm3130.c | 1641 | 15758 | /*
* rtc-fm3130.c - RTC driver for Ramtron FM3130 I2C chip.
*
* Copyright (C) 2008 Sergey Lapin
* Based on ds1307 driver by James Chapman and David Brownell
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/rtc.h>
#include <linux/bcd.h>
#include <linux/slab.h>
#define FM3130_RTC_CONTROL (0x0)
#define FM3130_CAL_CONTROL (0x1)
#define FM3130_RTC_SECONDS (0x2)
#define FM3130_RTC_MINUTES (0x3)
#define FM3130_RTC_HOURS (0x4)
#define FM3130_RTC_DAY (0x5)
#define FM3130_RTC_DATE (0x6)
#define FM3130_RTC_MONTHS (0x7)
#define FM3130_RTC_YEARS (0x8)
#define FM3130_ALARM_SECONDS (0x9)
#define FM3130_ALARM_MINUTES (0xa)
#define FM3130_ALARM_HOURS (0xb)
#define FM3130_ALARM_DATE (0xc)
#define FM3130_ALARM_MONTHS (0xd)
#define FM3130_ALARM_WP_CONTROL (0xe)
#define FM3130_CAL_CONTROL_BIT_nOSCEN (1 << 7) /* Osciallator enabled */
#define FM3130_RTC_CONTROL_BIT_LB (1 << 7) /* Low battery */
#define FM3130_RTC_CONTROL_BIT_AF (1 << 6) /* Alarm flag */
#define FM3130_RTC_CONTROL_BIT_CF (1 << 5) /* Century overflow */
#define FM3130_RTC_CONTROL_BIT_POR (1 << 4) /* Power on reset */
#define FM3130_RTC_CONTROL_BIT_AEN (1 << 3) /* Alarm enable */
#define FM3130_RTC_CONTROL_BIT_CAL (1 << 2) /* Calibration mode */
#define FM3130_RTC_CONTROL_BIT_WRITE (1 << 1) /* W=1 -> write mode W=0 normal */
#define FM3130_RTC_CONTROL_BIT_READ (1 << 0) /* R=1 -> read mode R=0 normal */
#define FM3130_CLOCK_REGS 7
#define FM3130_ALARM_REGS 5
struct fm3130 {
u8 reg_addr_time;
u8 reg_addr_alarm;
u8 regs[15];
struct i2c_msg msg[4];
struct i2c_client *client;
struct rtc_device *rtc;
int alarm_valid;
int data_valid;
};
static const struct i2c_device_id fm3130_id[] = {
{ "fm3130", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, fm3130_id);
#define FM3130_MODE_NORMAL 0
#define FM3130_MODE_WRITE 1
#define FM3130_MODE_READ 2
static void fm3130_rtc_mode(struct device *dev, int mode)
{
struct fm3130 *fm3130 = dev_get_drvdata(dev);
fm3130->regs[FM3130_RTC_CONTROL] =
i2c_smbus_read_byte_data(fm3130->client, FM3130_RTC_CONTROL);
switch (mode) {
case FM3130_MODE_NORMAL:
fm3130->regs[FM3130_RTC_CONTROL] &=
~(FM3130_RTC_CONTROL_BIT_WRITE |
FM3130_RTC_CONTROL_BIT_READ);
break;
case FM3130_MODE_WRITE:
fm3130->regs[FM3130_RTC_CONTROL] |= FM3130_RTC_CONTROL_BIT_WRITE;
break;
case FM3130_MODE_READ:
fm3130->regs[FM3130_RTC_CONTROL] |= FM3130_RTC_CONTROL_BIT_READ;
break;
default:
dev_dbg(dev, "invalid mode %d\n", mode);
break;
}
i2c_smbus_write_byte_data(fm3130->client,
FM3130_RTC_CONTROL, fm3130->regs[FM3130_RTC_CONTROL]);
}
static int fm3130_get_time(struct device *dev, struct rtc_time *t)
{
struct fm3130 *fm3130 = dev_get_drvdata(dev);
int tmp;
if (!fm3130->data_valid) {
/* We have invalid data in RTC, probably due
to battery faults or other problems. Return EIO
for now, it will allow us to set data later instead
of error during probing which disables device */
return -EIO;
}
fm3130_rtc_mode(dev, FM3130_MODE_READ);
/* read the RTC date and time registers all at once */
tmp = i2c_transfer(to_i2c_adapter(fm3130->client->dev.parent),
fm3130->msg, 2);
if (tmp != 2) {
dev_err(dev, "%s error %d\n", "read", tmp);
return -EIO;
}
fm3130_rtc_mode(dev, FM3130_MODE_NORMAL);
dev_dbg(dev, "%s: %15ph\n", "read", fm3130->regs);
t->tm_sec = bcd2bin(fm3130->regs[FM3130_RTC_SECONDS] & 0x7f);
t->tm_min = bcd2bin(fm3130->regs[FM3130_RTC_MINUTES] & 0x7f);
tmp = fm3130->regs[FM3130_RTC_HOURS] & 0x3f;
t->tm_hour = bcd2bin(tmp);
t->tm_wday = bcd2bin(fm3130->regs[FM3130_RTC_DAY] & 0x07) - 1;
t->tm_mday = bcd2bin(fm3130->regs[FM3130_RTC_DATE] & 0x3f);
tmp = fm3130->regs[FM3130_RTC_MONTHS] & 0x1f;
t->tm_mon = bcd2bin(tmp) - 1;
/* assume 20YY not 19YY, and ignore CF bit */
t->tm_year = bcd2bin(fm3130->regs[FM3130_RTC_YEARS]) + 100;
dev_dbg(dev, "%s secs=%d, mins=%d, "
"hours=%d, mday=%d, mon=%d, year=%d, wday=%d\n",
"read", t->tm_sec, t->tm_min,
t->tm_hour, t->tm_mday,
t->tm_mon, t->tm_year, t->tm_wday);
/* initial clock setting can be undefined */
return rtc_valid_tm(t);
}
static int fm3130_set_time(struct device *dev, struct rtc_time *t)
{
struct fm3130 *fm3130 = dev_get_drvdata(dev);
int tmp, i;
u8 *buf = fm3130->regs;
dev_dbg(dev, "%s secs=%d, mins=%d, "
"hours=%d, mday=%d, mon=%d, year=%d, wday=%d\n",
"write", t->tm_sec, t->tm_min,
t->tm_hour, t->tm_mday,
t->tm_mon, t->tm_year, t->tm_wday);
/* first register addr */
buf[FM3130_RTC_SECONDS] = bin2bcd(t->tm_sec);
buf[FM3130_RTC_MINUTES] = bin2bcd(t->tm_min);
buf[FM3130_RTC_HOURS] = bin2bcd(t->tm_hour);
buf[FM3130_RTC_DAY] = bin2bcd(t->tm_wday + 1);
buf[FM3130_RTC_DATE] = bin2bcd(t->tm_mday);
buf[FM3130_RTC_MONTHS] = bin2bcd(t->tm_mon + 1);
/* assume 20YY not 19YY */
tmp = t->tm_year - 100;
buf[FM3130_RTC_YEARS] = bin2bcd(tmp);
dev_dbg(dev, "%s: %15ph\n", "write", buf);
fm3130_rtc_mode(dev, FM3130_MODE_WRITE);
/* Writing time registers, we don't support multibyte transfers */
for (i = 0; i < FM3130_CLOCK_REGS; i++) {
i2c_smbus_write_byte_data(fm3130->client,
FM3130_RTC_SECONDS + i,
fm3130->regs[FM3130_RTC_SECONDS + i]);
}
fm3130_rtc_mode(dev, FM3130_MODE_NORMAL);
/* We assume here that data are valid once written */
if (!fm3130->data_valid)
fm3130->data_valid = 1;
return 0;
}
static int fm3130_read_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct fm3130 *fm3130 = dev_get_drvdata(dev);
int tmp;
struct rtc_time *tm = &alrm->time;
if (!fm3130->alarm_valid) {
/*
* We have invalid alarm in RTC, probably due to battery faults
* or other problems. Return EIO for now, it will allow us to
* set alarm value later instead of error during probing which
* disables device
*/
return -EIO;
}
/* read the RTC alarm registers all at once */
tmp = i2c_transfer(to_i2c_adapter(fm3130->client->dev.parent),
&fm3130->msg[2], 2);
if (tmp != 2) {
dev_err(dev, "%s error %d\n", "read", tmp);
return -EIO;
}
dev_dbg(dev, "alarm read %02x %02x %02x %02x %02x\n",
fm3130->regs[FM3130_ALARM_SECONDS],
fm3130->regs[FM3130_ALARM_MINUTES],
fm3130->regs[FM3130_ALARM_HOURS],
fm3130->regs[FM3130_ALARM_DATE],
fm3130->regs[FM3130_ALARM_MONTHS]);
tm->tm_sec = bcd2bin(fm3130->regs[FM3130_ALARM_SECONDS] & 0x7F);
tm->tm_min = bcd2bin(fm3130->regs[FM3130_ALARM_MINUTES] & 0x7F);
tm->tm_hour = bcd2bin(fm3130->regs[FM3130_ALARM_HOURS] & 0x3F);
tm->tm_mday = bcd2bin(fm3130->regs[FM3130_ALARM_DATE] & 0x3F);
tm->tm_mon = bcd2bin(fm3130->regs[FM3130_ALARM_MONTHS] & 0x1F);
if (tm->tm_mon > 0)
tm->tm_mon -= 1; /* RTC is 1-12, tm_mon is 0-11 */
dev_dbg(dev, "%s secs=%d, mins=%d, "
"hours=%d, mday=%d, mon=%d, year=%d, wday=%d\n",
"read alarm", tm->tm_sec, tm->tm_min,
tm->tm_hour, tm->tm_mday,
tm->tm_mon, tm->tm_year, tm->tm_wday);
/* check if alarm enabled */
fm3130->regs[FM3130_RTC_CONTROL] =
i2c_smbus_read_byte_data(fm3130->client, FM3130_RTC_CONTROL);
if ((fm3130->regs[FM3130_RTC_CONTROL] & FM3130_RTC_CONTROL_BIT_AEN) &&
(~fm3130->regs[FM3130_RTC_CONTROL] &
FM3130_RTC_CONTROL_BIT_CAL)) {
alrm->enabled = 1;
}
return 0;
}
static int fm3130_set_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct fm3130 *fm3130 = dev_get_drvdata(dev);
struct rtc_time *tm = &alrm->time;
int i;
dev_dbg(dev, "%s secs=%d, mins=%d, "
"hours=%d, mday=%d, mon=%d, year=%d, wday=%d\n",
"write alarm", tm->tm_sec, tm->tm_min,
tm->tm_hour, tm->tm_mday,
tm->tm_mon, tm->tm_year, tm->tm_wday);
fm3130->regs[FM3130_ALARM_SECONDS] =
(tm->tm_sec != -1) ? bin2bcd(tm->tm_sec) : 0x80;
fm3130->regs[FM3130_ALARM_MINUTES] =
(tm->tm_min != -1) ? bin2bcd(tm->tm_min) : 0x80;
fm3130->regs[FM3130_ALARM_HOURS] =
(tm->tm_hour != -1) ? bin2bcd(tm->tm_hour) : 0x80;
fm3130->regs[FM3130_ALARM_DATE] =
(tm->tm_mday != -1) ? bin2bcd(tm->tm_mday) : 0x80;
fm3130->regs[FM3130_ALARM_MONTHS] =
(tm->tm_mon != -1) ? bin2bcd(tm->tm_mon + 1) : 0x80;
dev_dbg(dev, "alarm write %02x %02x %02x %02x %02x\n",
fm3130->regs[FM3130_ALARM_SECONDS],
fm3130->regs[FM3130_ALARM_MINUTES],
fm3130->regs[FM3130_ALARM_HOURS],
fm3130->regs[FM3130_ALARM_DATE],
fm3130->regs[FM3130_ALARM_MONTHS]);
/* Writing time registers, we don't support multibyte transfers */
for (i = 0; i < FM3130_ALARM_REGS; i++) {
i2c_smbus_write_byte_data(fm3130->client,
FM3130_ALARM_SECONDS + i,
fm3130->regs[FM3130_ALARM_SECONDS + i]);
}
fm3130->regs[FM3130_RTC_CONTROL] =
i2c_smbus_read_byte_data(fm3130->client, FM3130_RTC_CONTROL);
/* enable or disable alarm */
if (alrm->enabled) {
i2c_smbus_write_byte_data(fm3130->client, FM3130_RTC_CONTROL,
(fm3130->regs[FM3130_RTC_CONTROL] &
~(FM3130_RTC_CONTROL_BIT_CAL)) |
FM3130_RTC_CONTROL_BIT_AEN);
} else {
i2c_smbus_write_byte_data(fm3130->client, FM3130_RTC_CONTROL,
fm3130->regs[FM3130_RTC_CONTROL] &
~(FM3130_RTC_CONTROL_BIT_CAL) &
~(FM3130_RTC_CONTROL_BIT_AEN));
}
/* We assume here that data is valid once written */
if (!fm3130->alarm_valid)
fm3130->alarm_valid = 1;
return 0;
}
static int fm3130_alarm_irq_enable(struct device *dev, unsigned int enabled)
{
struct fm3130 *fm3130 = dev_get_drvdata(dev);
int ret = 0;
fm3130->regs[FM3130_RTC_CONTROL] =
i2c_smbus_read_byte_data(fm3130->client, FM3130_RTC_CONTROL);
dev_dbg(dev, "alarm_irq_enable: enable=%d, FM3130_RTC_CONTROL=%02x\n",
enabled, fm3130->regs[FM3130_RTC_CONTROL]);
switch (enabled) {
case 0: /* alarm off */
ret = i2c_smbus_write_byte_data(fm3130->client,
FM3130_RTC_CONTROL, fm3130->regs[FM3130_RTC_CONTROL] &
~(FM3130_RTC_CONTROL_BIT_CAL) &
~(FM3130_RTC_CONTROL_BIT_AEN));
break;
case 1: /* alarm on */
ret = i2c_smbus_write_byte_data(fm3130->client,
FM3130_RTC_CONTROL, (fm3130->regs[FM3130_RTC_CONTROL] &
~(FM3130_RTC_CONTROL_BIT_CAL)) |
FM3130_RTC_CONTROL_BIT_AEN);
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static const struct rtc_class_ops fm3130_rtc_ops = {
.read_time = fm3130_get_time,
.set_time = fm3130_set_time,
.read_alarm = fm3130_read_alarm,
.set_alarm = fm3130_set_alarm,
.alarm_irq_enable = fm3130_alarm_irq_enable,
};
static struct i2c_driver fm3130_driver;
static int fm3130_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct fm3130 *fm3130;
int err = -ENODEV;
int tmp;
struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
if (!i2c_check_functionality(adapter,
I2C_FUNC_I2C | I2C_FUNC_SMBUS_WRITE_BYTE_DATA))
return -EIO;
fm3130 = devm_kzalloc(&client->dev, sizeof(struct fm3130), GFP_KERNEL);
if (!fm3130)
return -ENOMEM;
fm3130->client = client;
i2c_set_clientdata(client, fm3130);
fm3130->reg_addr_time = FM3130_RTC_SECONDS;
fm3130->reg_addr_alarm = FM3130_ALARM_SECONDS;
/* Messages to read time */
fm3130->msg[0].addr = client->addr;
fm3130->msg[0].flags = 0;
fm3130->msg[0].len = 1;
fm3130->msg[0].buf = &fm3130->reg_addr_time;
fm3130->msg[1].addr = client->addr;
fm3130->msg[1].flags = I2C_M_RD;
fm3130->msg[1].len = FM3130_CLOCK_REGS;
fm3130->msg[1].buf = &fm3130->regs[FM3130_RTC_SECONDS];
/* Messages to read alarm */
fm3130->msg[2].addr = client->addr;
fm3130->msg[2].flags = 0;
fm3130->msg[2].len = 1;
fm3130->msg[2].buf = &fm3130->reg_addr_alarm;
fm3130->msg[3].addr = client->addr;
fm3130->msg[3].flags = I2C_M_RD;
fm3130->msg[3].len = FM3130_ALARM_REGS;
fm3130->msg[3].buf = &fm3130->regs[FM3130_ALARM_SECONDS];
fm3130->alarm_valid = 0;
fm3130->data_valid = 0;
tmp = i2c_transfer(adapter, fm3130->msg, 4);
if (tmp != 4) {
dev_dbg(&client->dev, "read error %d\n", tmp);
err = -EIO;
goto exit_free;
}
fm3130->regs[FM3130_RTC_CONTROL] =
i2c_smbus_read_byte_data(client, FM3130_RTC_CONTROL);
fm3130->regs[FM3130_CAL_CONTROL] =
i2c_smbus_read_byte_data(client, FM3130_CAL_CONTROL);
/* Disabling calibration mode */
if (fm3130->regs[FM3130_RTC_CONTROL] & FM3130_RTC_CONTROL_BIT_CAL) {
i2c_smbus_write_byte_data(client, FM3130_RTC_CONTROL,
fm3130->regs[FM3130_RTC_CONTROL] &
~(FM3130_RTC_CONTROL_BIT_CAL));
dev_warn(&client->dev, "Disabling calibration mode!\n");
}
/* Disabling read and write modes */
if (fm3130->regs[FM3130_RTC_CONTROL] & FM3130_RTC_CONTROL_BIT_WRITE ||
fm3130->regs[FM3130_RTC_CONTROL] & FM3130_RTC_CONTROL_BIT_READ) {
i2c_smbus_write_byte_data(client, FM3130_RTC_CONTROL,
fm3130->regs[FM3130_RTC_CONTROL] &
~(FM3130_RTC_CONTROL_BIT_READ |
FM3130_RTC_CONTROL_BIT_WRITE));
dev_warn(&client->dev, "Disabling READ or WRITE mode!\n");
}
/* oscillator off? turn it on, so clock can tick. */
if (fm3130->regs[FM3130_CAL_CONTROL] & FM3130_CAL_CONTROL_BIT_nOSCEN)
i2c_smbus_write_byte_data(client, FM3130_CAL_CONTROL,
fm3130->regs[FM3130_CAL_CONTROL] &
~(FM3130_CAL_CONTROL_BIT_nOSCEN));
/* low battery? clear flag, and warn */
if (fm3130->regs[FM3130_RTC_CONTROL] & FM3130_RTC_CONTROL_BIT_LB) {
i2c_smbus_write_byte_data(client, FM3130_RTC_CONTROL,
fm3130->regs[FM3130_RTC_CONTROL] &
~(FM3130_RTC_CONTROL_BIT_LB));
dev_warn(&client->dev, "Low battery!\n");
}
/* check if Power On Reset bit is set */
if (fm3130->regs[FM3130_RTC_CONTROL] & FM3130_RTC_CONTROL_BIT_POR) {
i2c_smbus_write_byte_data(client, FM3130_RTC_CONTROL,
fm3130->regs[FM3130_RTC_CONTROL] &
~FM3130_RTC_CONTROL_BIT_POR);
dev_dbg(&client->dev, "POR bit is set\n");
}
/* ACS is controlled by alarm */
i2c_smbus_write_byte_data(client, FM3130_ALARM_WP_CONTROL, 0x80);
/* alarm registers sanity check */
tmp = bcd2bin(fm3130->regs[FM3130_RTC_SECONDS] & 0x7f);
if (tmp > 59)
goto bad_alarm;
tmp = bcd2bin(fm3130->regs[FM3130_RTC_MINUTES] & 0x7f);
if (tmp > 59)
goto bad_alarm;
tmp = bcd2bin(fm3130->regs[FM3130_RTC_HOURS] & 0x3f);
if (tmp > 23)
goto bad_alarm;
tmp = bcd2bin(fm3130->regs[FM3130_RTC_DATE] & 0x3f);
if (tmp == 0 || tmp > 31)
goto bad_alarm;
tmp = bcd2bin(fm3130->regs[FM3130_RTC_MONTHS] & 0x1f);
if (tmp == 0 || tmp > 12)
goto bad_alarm;
fm3130->alarm_valid = 1;
bad_alarm:
/* clock registers sanity chek */
tmp = bcd2bin(fm3130->regs[FM3130_RTC_SECONDS] & 0x7f);
if (tmp > 59)
goto bad_clock;
tmp = bcd2bin(fm3130->regs[FM3130_RTC_MINUTES] & 0x7f);
if (tmp > 59)
goto bad_clock;
tmp = bcd2bin(fm3130->regs[FM3130_RTC_HOURS] & 0x3f);
if (tmp > 23)
goto bad_clock;
tmp = bcd2bin(fm3130->regs[FM3130_RTC_DAY] & 0x7);
if (tmp == 0 || tmp > 7)
goto bad_clock;
tmp = bcd2bin(fm3130->regs[FM3130_RTC_DATE] & 0x3f);
if (tmp == 0 || tmp > 31)
goto bad_clock;
tmp = bcd2bin(fm3130->regs[FM3130_RTC_MONTHS] & 0x1f);
if (tmp == 0 || tmp > 12)
goto bad_clock;
fm3130->data_valid = 1;
bad_clock:
if (!fm3130->data_valid || !fm3130->alarm_valid)
dev_dbg(&client->dev, "%s: %15ph\n", "bogus registers",
fm3130->regs);
/* We won't bail out here because we just got invalid data.
Time setting from u-boot doesn't work anyway */
fm3130->rtc = devm_rtc_device_register(&client->dev, client->name,
&fm3130_rtc_ops, THIS_MODULE);
if (IS_ERR(fm3130->rtc)) {
err = PTR_ERR(fm3130->rtc);
dev_err(&client->dev,
"unable to register the class device\n");
goto exit_free;
}
return 0;
exit_free:
return err;
}
static struct i2c_driver fm3130_driver = {
.driver = {
.name = "rtc-fm3130",
.owner = THIS_MODULE,
},
.probe = fm3130_probe,
.id_table = fm3130_id,
};
module_i2c_driver(fm3130_driver);
MODULE_DESCRIPTION("RTC driver for FM3130");
MODULE_AUTHOR("Sergey Lapin <slapin@ossfans.org>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
wanam/Adam-Kernel-GalaxyS6-G920F | arch/mips/powertv/asic/prealloc-cronus.c | 2153 | 9047 | /*
* Memory pre-allocations for Cronus boxes.
*
* Copyright (C) 2005-2009 Scientific-Atlanta, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Author: Ken Eppinett
* David Schleef <ds@schleef.org>
*/
#include <linux/init.h>
#include <linux/ioport.h>
#include <asm/mach-powertv/asic.h>
#include "prealloc.h"
/*
* DVR_CAPABLE CRONUS RESOURCES
*/
struct resource dvr_cronus_resources[] __initdata =
{
/*
* VIDEO1 / LX1
*/
/* Delta-Mu 1 image (2MiB) */
PREALLOC_NORMAL("ST231aImage", 0x24000000, 0x24200000-1,
IORESOURCE_MEM)
/* Delta-Mu 1 monitor (8KiB) */
PREALLOC_NORMAL("ST231aMonitor", 0x24200000, 0x24202000-1,
IORESOURCE_MEM)
/* Delta-Mu 1 RAM (~29.9MiB (32MiB - (2MiB + 8KiB))) */
PREALLOC_NORMAL("MediaMemory1", 0x24202000, 0x26000000-1,
IORESOURCE_MEM)
/*
* VIDEO2 / LX2
*/
/* Delta-Mu 2 image (2MiB) */
PREALLOC_NORMAL("ST231bImage", 0x60000000, 0x60200000-1,
IORESOURCE_MEM)
/* Delta-Mu 2 monitor (8KiB) */
PREALLOC_NORMAL("ST231bMonitor", 0x60200000, 0x60202000-1,
IORESOURCE_MEM)
/* Delta-Mu 2 RAM (~29.9MiB (32MiB - (2MiB + 8KiB))) */
PREALLOC_NORMAL("MediaMemory2", 0x60202000, 0x62000000-1,
IORESOURCE_MEM)
/*
* Sysaudio Driver
*/
/* DSP code and data images (1MiB) */
PREALLOC_NORMAL("DSP_Image_Buff", 0x00000000, 0x00100000-1,
(IORESOURCE_MEM|IORESOURCE_PTV_RES_LOEXT))
/* ADSC CPU PCM buffer (40KiB) */
PREALLOC_NORMAL("ADSC_CPU_PCM_Buff", 0x00000000, 0x0000A000-1,
(IORESOURCE_MEM|IORESOURCE_PTV_RES_LOEXT))
/* ADSC AUX buffer (128KiB) */
PREALLOC_NORMAL("ADSC_AUX_Buff", 0x00000000, 0x00020000-1,
(IORESOURCE_MEM|IORESOURCE_PTV_RES_LOEXT))
/* ADSC Main buffer (128KiB) */
PREALLOC_NORMAL("ADSC_Main_Buff", 0x00000000, 0x00020000-1,
(IORESOURCE_MEM|IORESOURCE_PTV_RES_LOEXT))
/*
* STAVEM driver/STAPI
*
* This memory area is used for allocating buffers for Video decoding
* purposes. Allocation/De-allocation within this buffer is managed
* by the STAVMEM driver of the STAPI. They could be Decimated
* Picture Buffers, Intermediate Buffers, as deemed necessary for
* video decoding purposes, for any video decoders on Zeus.
*/
/* 12MiB */
PREALLOC_NORMAL("AVMEMPartition0", 0x00000000, 0x00c00000-1,
IORESOURCE_MEM)
/*
* DOCSIS Subsystem
*/
/* 7MiB */
PREALLOC_DOCSIS("Docsis", 0x67500000, 0x67c00000-1, IORESOURCE_MEM)
/*
* GHW HAL Driver
*/
/* PowerTV Graphics Heap (14MiB) */
PREALLOC_NORMAL("GraphicsHeap", 0x62700000, 0x63500000-1,
IORESOURCE_MEM)
/*
* multi com buffer area
*/
/* 128KiB */
PREALLOC_NORMAL("MulticomSHM", 0x26000000, 0x26020000-1,
IORESOURCE_MEM)
/*
* DMA Ring buffer
*/
PREALLOC_NORMAL("BMM_Buffer", 0x00000000, 0x002EA000-1,
(IORESOURCE_MEM|IORESOURCE_PTV_RES_LOEXT))
/*
* Display bins buffer for unit0
*/
/* 4KiB */
PREALLOC_NORMAL("DisplayBins0", 0x00000000, 0x00001000-1,
(IORESOURCE_MEM|IORESOURCE_PTV_RES_LOEXT))
/*
* Display bins buffer for unit1
*/
/* 4KiB */
PREALLOC_NORMAL("DisplayBins1", 0x00000000, 0x00001000-1,
IORESOURCE_MEM)
/*
* ITFS
*/
/* 815,104 bytes each for 2 ITFS partitions. */
PREALLOC_NORMAL("ITFS", 0x00000000, 0x0018E000-1, IORESOURCE_MEM)
/*
* AVFS
*/
/* (945K * 8) = (128K * 3) 5 playbacks / 3 server */
PREALLOC_NORMAL("AvfsDmaMem", 0x00000000, 0x007c2000-1,
IORESOURCE_MEM)
/* 4KiB */
PREALLOC_NORMAL("AvfsFileSys", 0x00000000, 0x00001000-1,
IORESOURCE_MEM)
/*
* PMEM
*/
/* Persistent memory for diagnostics (64KiB) */
PREALLOC_PMEM("DiagPersistentMemory", 0x00000000, 0x10000-1,
(IORESOURCE_MEM|IORESOURCE_PTV_RES_LOEXT))
/*
* Smartcard
*/
/* Read and write buffers for Internal/External cards (10KiB) */
PREALLOC_NORMAL("SmartCardInfo", 0x00000000, 0x2800-1,
IORESOURCE_MEM)
/*
* KAVNET
*/
/* NP Reset Vector - must be of the form xxCxxxxx (4KiB) */
PREALLOC_NORMAL("NP_Reset_Vector", 0x27c00000, 0x27c01000-1,
IORESOURCE_MEM)
/* NP Image - must be video bank 1 (320KiB) */
PREALLOC_NORMAL("NP_Image", 0x27020000, 0x27070000-1, IORESOURCE_MEM)
/* NP IPC - must be video bank 2 (512KiB) */
PREALLOC_NORMAL("NP_IPC", 0x63500000, 0x63580000-1, IORESOURCE_MEM)
/*
* TFTPBuffer
*
* This buffer is used in some minimal configurations (e.g. two-way
* loader) for storing software images
*/
PREALLOC_TFTP("TFTPBuffer", 0x00000000, MEBIBYTE(80)-1,
(IORESOURCE_MEM|IORESOURCE_PTV_RES_LOEXT))
/*
* Add other resources here
*/
/*
* End of Resource marker
*/
{
.flags = 0,
},
};
/*
* NON_DVR_CAPABLE CRONUS RESOURCES
*/
struct resource non_dvr_cronus_resources[] __initdata =
{
/*
* VIDEO1 / LX1
*/
/* Delta-Mu 1 image (2MiB) */
PREALLOC_NORMAL("ST231aImage", 0x24000000, 0x24200000-1,
IORESOURCE_MEM)
/* Delta-Mu 1 monitor (8KiB) */
PREALLOC_NORMAL("ST231aMonitor", 0x24200000, 0x24202000-1,
IORESOURCE_MEM)
/* Delta-Mu 1 RAM (~29.9MiB (32MiB - (2MiB + 8KiB))) */
PREALLOC_NORMAL("MediaMemory1", 0x24202000, 0x26000000-1,
IORESOURCE_MEM)
/*
* VIDEO2 / LX2
*/
/* Delta-Mu 2 image (2MiB) */
PREALLOC_NORMAL("ST231bImage", 0x60000000, 0x60200000-1,
IORESOURCE_MEM)
/* Delta-Mu 2 monitor (8KiB) */
PREALLOC_NORMAL("ST231bMonitor", 0x60200000, 0x60202000-1,
IORESOURCE_MEM)
/* Delta-Mu 2 RAM (~29.9MiB (32MiB - (2MiB + 8KiB))) */
PREALLOC_NORMAL("MediaMemory2", 0x60202000, 0x62000000-1,
IORESOURCE_MEM)
/*
* Sysaudio Driver
*/
/* DSP code and data images (1MiB) */
PREALLOC_NORMAL("DSP_Image_Buff", 0x00000000, 0x00100000-1,
(IORESOURCE_MEM|IORESOURCE_PTV_RES_LOEXT))
/* ADSC CPU PCM buffer (40KiB) */
PREALLOC_NORMAL("ADSC_CPU_PCM_Buff", 0x00000000, 0x0000A000-1,
(IORESOURCE_MEM|IORESOURCE_PTV_RES_LOEXT))
/* ADSC AUX buffer (128KiB) */
PREALLOC_NORMAL("ADSC_AUX_Buff", 0x00000000, 0x00020000-1,
(IORESOURCE_MEM|IORESOURCE_PTV_RES_LOEXT))
/* ADSC Main buffer (128KiB) */
PREALLOC_NORMAL("ADSC_Main_Buff", 0x00000000, 0x00020000-1,
(IORESOURCE_MEM|IORESOURCE_PTV_RES_LOEXT))
/*
* STAVEM driver/STAPI
*
* This memory area is used for allocating buffers for Video decoding
* purposes. Allocation/De-allocation within this buffer is managed
* by the STAVMEM driver of the STAPI. They could be Decimated
* Picture Buffers, Intermediate Buffers, as deemed necessary for
* video decoding purposes, for any video decoders on Zeus.
*/
/* 12MiB */
PREALLOC_NORMAL("AVMEMPartition0", 0x00000000, 0x00c00000-1,
IORESOURCE_MEM)
/*
* DOCSIS Subsystem
*/
/* 7MiB */
PREALLOC_DOCSIS("Docsis", 0x67500000, 0x67c00000-1, IORESOURCE_MEM)
/*
* GHW HAL Driver
*/
/* PowerTV Graphics Heap (14MiB) */
PREALLOC_NORMAL("GraphicsHeap", 0x62700000, 0x63500000-1,
IORESOURCE_MEM)
/*
* multi com buffer area
*/
/* 128KiB */
PREALLOC_NORMAL("MulticomSHM", 0x26000000, 0x26020000-1,
IORESOURCE_MEM)
/*
* DMA Ring buffer (don't need recording buffers)
*/
/* 680KiB */
PREALLOC_NORMAL("BMM_Buffer", 0x00000000, 0x000AA000-1,
(IORESOURCE_MEM|IORESOURCE_PTV_RES_LOEXT))
/*
* Display bins buffer for unit0
*/
/* 4KiB */
PREALLOC_NORMAL("DisplayBins0", 0x00000000, 0x00001000-1,
(IORESOURCE_MEM|IORESOURCE_PTV_RES_LOEXT))
/*
* Display bins buffer for unit1
*/
/* 4KiB */
PREALLOC_NORMAL("DisplayBins1", 0x00000000, 0x00001000-1,
IORESOURCE_MEM)
/*
* AVFS: player HAL memory
*/
/* 945K * 3 for playback */
PREALLOC_NORMAL("AvfsDmaMem", 0x00000000, 0x002c4c00-1, IORESOURCE_MEM)
/*
* PMEM
*/
/* Persistent memory for diagnostics (64KiB) */
PREALLOC_PMEM("DiagPersistentMemory", 0x00000000, 0x10000-1,
(IORESOURCE_MEM|IORESOURCE_PTV_RES_LOEXT))
/*
* Smartcard
*/
/* Read and write buffers for Internal/External cards (10KiB) */
PREALLOC_NORMAL("SmartCardInfo", 0x00000000, 0x2800-1, IORESOURCE_MEM)
/*
* KAVNET
*/
/* NP Reset Vector - must be of the form xxCxxxxx (4KiB) */
PREALLOC_NORMAL("NP_Reset_Vector", 0x27c00000, 0x27c01000-1,
IORESOURCE_MEM)
/* NP Image - must be video bank 1 (320KiB) */
PREALLOC_NORMAL("NP_Image", 0x27020000, 0x27070000-1, IORESOURCE_MEM)
/* NP IPC - must be video bank 2 (512KiB) */
PREALLOC_NORMAL("NP_IPC", 0x63500000, 0x63580000-1, IORESOURCE_MEM)
/*
* NAND Flash
*/
/* 10KiB */
PREALLOC_NORMAL("NandFlash", NAND_FLASH_BASE, NAND_FLASH_BASE+0x400-1,
IORESOURCE_MEM)
/*
* Add other resources here
*/
/*
* End of Resource marker
*/
{
.flags = 0,
},
};
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.