repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
sleshepic/SM-G900P_kernel_ND2 | drivers/staging/wlan-ng/prism2usb.c | 5239 | 9974 | #include "hfa384x_usb.c"
#include "prism2mgmt.c"
#include "prism2mib.c"
#include "prism2sta.c"
#include "prism2fw.c"
#define PRISM_USB_DEVICE(vid, pid, name) \
USB_DEVICE(vid, pid), \
.driver_info = (unsigned long) name
static struct usb_device_id usb_prism_tbl[] = {
{PRISM_USB_DEVICE(0x04bb, 0x0922, "IOData AirPort WN-B11/USBS")},
{PRISM_USB_DEVICE(0x07aa, 0x0012, "Corega Wireless LAN USB Stick-11")},
{PRISM_USB_DEVICE(0x09aa, 0x3642, "Prism2.x 11Mbps WLAN USB Adapter")},
{PRISM_USB_DEVICE
(0x1668, 0x0408, "Actiontec Prism2.5 11Mbps WLAN USB Adapter")},
{PRISM_USB_DEVICE
(0x1668, 0x0421, "Actiontec Prism2.5 11Mbps WLAN USB Adapter")},
{PRISM_USB_DEVICE
(0x1915, 0x2236, "Linksys WUSB11v3.0 11Mbps WLAN USB Adapter")},
{PRISM_USB_DEVICE
(0x066b, 0x2212, "Linksys WUSB11v2.5 11Mbps WLAN USB Adapter")},
{PRISM_USB_DEVICE
(0x066b, 0x2213, "Linksys WUSB12v1.1 11Mbps WLAN USB Adapter")},
{PRISM_USB_DEVICE
(0x067c, 0x1022, "Siemens SpeedStream 1022 11Mbps WLAN USB Adapter")},
{PRISM_USB_DEVICE
(0x049f, 0x0033,
"Compaq/Intel W100 PRO/Wireless 11Mbps multiport WLAN Adapter")},
{PRISM_USB_DEVICE
(0x0411, 0x0016, "Melco WLI-USB-S11 11Mbps WLAN Adapter")},
{PRISM_USB_DEVICE
(0x08de, 0x7a01, "PRISM25 IEEE 802.11 Mini USB Adapter")},
{PRISM_USB_DEVICE
(0x8086, 0x1111, "Intel PRO/Wireless 2011B LAN USB Adapter")},
{PRISM_USB_DEVICE
(0x0d8e, 0x7a01, "PRISM25 IEEE 802.11 Mini USB Adapter")},
{PRISM_USB_DEVICE
(0x045e, 0x006e, "Microsoft MN510 Wireless USB Adapter")},
{PRISM_USB_DEVICE(0x0967, 0x0204, "Acer Warplink USB Adapter")},
{PRISM_USB_DEVICE
(0x0cde, 0x0002, "Z-Com 725/726 Prism2.5 USB/USB Integrated")},
{PRISM_USB_DEVICE
(0x0cde, 0x0005, "Z-Com Xl735 Wireless 802.11b USB Adapter")},
{PRISM_USB_DEVICE
(0x413c, 0x8100, "Dell TrueMobile 1180 Wireless USB Adapter")},
{PRISM_USB_DEVICE
(0x0b3b, 0x1601, "ALLNET 0193 11Mbps WLAN USB Adapter")},
{PRISM_USB_DEVICE
(0x0b3b, 0x1602, "ZyXEL ZyAIR B200 Wireless USB Adapter")},
{PRISM_USB_DEVICE
(0x0baf, 0x00eb, "USRobotics USR1120 Wireless USB Adapter")},
{PRISM_USB_DEVICE
(0x0411, 0x0027, "Melco WLI-USB-KS11G 11Mbps WLAN Adapter")},
{PRISM_USB_DEVICE
(0x04f1, 0x3009, "JVC MP-XP7250 Builtin USB WLAN Adapter")},
{PRISM_USB_DEVICE(0x0846, 0x4110, "NetGear MA111")},
{PRISM_USB_DEVICE(0x03f3, 0x0020, "Adaptec AWN-8020 USB WLAN Adapter")},
{PRISM_USB_DEVICE(0x2821, 0x3300, "ASUS-WL140 Wireless USB Adapter")},
{PRISM_USB_DEVICE(0x2001, 0x3700, "DWL-122 Wireless USB Adapter")},
{PRISM_USB_DEVICE
(0x2001, 0x3702, "DWL-120 Rev F Wireless USB Adapter")},
{PRISM_USB_DEVICE(0x50c2, 0x4013, "Averatec USB WLAN Adapter")},
{PRISM_USB_DEVICE(0x2c02, 0x14ea, "Planex GW-US11H WLAN USB Adapter")},
{PRISM_USB_DEVICE(0x124a, 0x168b, "Airvast PRISM3 WLAN USB Adapter")},
{PRISM_USB_DEVICE(0x083a, 0x3503, "T-Sinus 111 USB WLAN Adapter")},
{PRISM_USB_DEVICE(0x2821, 0x3300, "Hawking HighDB USB Adapter")},
{PRISM_USB_DEVICE
(0x0411, 0x0044, "Melco WLI-USB-KB11 11Mbps WLAN Adapter")},
{PRISM_USB_DEVICE(0x1668, 0x6106, "ROPEX FreeLan 802.11b USB Adapter")},
{PRISM_USB_DEVICE
(0x124a, 0x4017, "Pheenet WL-503IA 802.11b USB Adapter")},
{PRISM_USB_DEVICE(0x0bb2, 0x0302, "Ambit Microsystems Corp.")},
{PRISM_USB_DEVICE
(0x9016, 0x182d, "Sitecom WL-022 802.11b USB Adapter")},
{PRISM_USB_DEVICE
(0x0543, 0x0f01, "ViewSonic Airsync USB Adapter 11Mbps (Prism2.5)")},
{ /* terminator */ }
};
MODULE_DEVICE_TABLE(usb, usb_prism_tbl);
/*----------------------------------------------------------------
* prism2sta_probe_usb
*
* Probe routine called by the USB subsystem.
*
* Arguments:
* dev ptr to the usb_device struct
* ifnum interface number being offered
*
* Returns:
* NULL - we're not claiming the device+interface
* non-NULL - we are claiming the device+interface and
* this is a ptr to the data we want back
* when disconnect is called.
*
* Side effects:
*
* Call context:
* I'm not sure, assume it's interrupt.
*
----------------------------------------------------------------*/
static int prism2sta_probe_usb(struct usb_interface *interface,
const struct usb_device_id *id)
{
struct usb_device *dev;
wlandevice_t *wlandev = NULL;
hfa384x_t *hw = NULL;
int result = 0;
dev = interface_to_usbdev(interface);
wlandev = create_wlan();
if (wlandev == NULL) {
printk(KERN_ERR "%s: Memory allocation failure.\n", dev_info);
result = -EIO;
goto failed;
}
hw = wlandev->priv;
if (wlan_setup(wlandev, &(interface->dev)) != 0) {
printk(KERN_ERR "%s: wlan_setup() failed.\n", dev_info);
result = -EIO;
goto failed;
}
/* Initialize the hw data */
hfa384x_create(hw, dev);
hw->wlandev = wlandev;
/* Register the wlandev, this gets us a name and registers the
* linux netdevice.
*/
SET_NETDEV_DEV(wlandev->netdev, &(interface->dev));
/* Do a chip-level reset on the MAC */
if (prism2_doreset) {
result = hfa384x_corereset(hw,
prism2_reset_holdtime,
prism2_reset_settletime, 0);
if (result != 0) {
unregister_wlandev(wlandev);
hfa384x_destroy(hw);
result = -EIO;
printk(KERN_ERR
"%s: hfa384x_corereset() failed.\n", dev_info);
goto failed;
}
}
usb_get_dev(dev);
wlandev->msdstate = WLAN_MSD_HWPRESENT;
/* Try and load firmware, then enable card before we register */
prism2_fwtry(dev, wlandev);
prism2sta_ifstate(wlandev, P80211ENUM_ifstate_enable);
if (register_wlandev(wlandev) != 0) {
printk(KERN_ERR "%s: register_wlandev() failed.\n", dev_info);
result = -EIO;
goto failed;
}
goto done;
failed:
kfree(wlandev);
kfree(hw);
wlandev = NULL;
done:
usb_set_intfdata(interface, wlandev);
return result;
}
/*----------------------------------------------------------------
* prism2sta_disconnect_usb
*
* Called when a device previously claimed by probe is removed
* from the USB.
*
* Arguments:
* dev ptr to the usb_device struct
* ptr ptr returned by probe() when the device
* was claimed.
*
* Returns:
* Nothing
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
static void prism2sta_disconnect_usb(struct usb_interface *interface)
{
wlandevice_t *wlandev;
wlandev = (wlandevice_t *) usb_get_intfdata(interface);
if (wlandev != NULL) {
LIST_HEAD(cleanlist);
struct list_head *entry;
struct list_head *temp;
unsigned long flags;
hfa384x_t *hw = wlandev->priv;
if (!hw)
goto exit;
spin_lock_irqsave(&hw->ctlxq.lock, flags);
p80211netdev_hwremoved(wlandev);
list_splice_init(&hw->ctlxq.reapable, &cleanlist);
list_splice_init(&hw->ctlxq.completing, &cleanlist);
list_splice_init(&hw->ctlxq.pending, &cleanlist);
list_splice_init(&hw->ctlxq.active, &cleanlist);
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
/* There's no hardware to shutdown, but the driver
* might have some tasks or tasklets that must be
* stopped before we can tear everything down.
*/
prism2sta_ifstate(wlandev, P80211ENUM_ifstate_disable);
del_singleshot_timer_sync(&hw->throttle);
del_singleshot_timer_sync(&hw->reqtimer);
del_singleshot_timer_sync(&hw->resptimer);
/* Unlink all the URBs. This "removes the wheels"
* from the entire CTLX handling mechanism.
*/
usb_kill_urb(&hw->rx_urb);
usb_kill_urb(&hw->tx_urb);
usb_kill_urb(&hw->ctlx_urb);
tasklet_kill(&hw->completion_bh);
tasklet_kill(&hw->reaper_bh);
flush_scheduled_work();
/* Now we complete any outstanding commands
* and tell everyone who is waiting for their
* responses that we have shut down.
*/
list_for_each(entry, &cleanlist) {
hfa384x_usbctlx_t *ctlx;
ctlx = list_entry(entry, hfa384x_usbctlx_t, list);
complete(&ctlx->done);
}
/* Give any outstanding synchronous commands
* a chance to complete. All they need to do
* is "wake up", so that's easy.
* (I'd like a better way to do this, really.)
*/
msleep(100);
/* Now delete the CTLXs, because no-one else can now. */
list_for_each_safe(entry, temp, &cleanlist) {
hfa384x_usbctlx_t *ctlx;
ctlx = list_entry(entry, hfa384x_usbctlx_t, list);
kfree(ctlx);
}
/* Unhook the wlandev */
unregister_wlandev(wlandev);
wlan_unsetup(wlandev);
usb_put_dev(hw->usb);
hfa384x_destroy(hw);
kfree(hw);
kfree(wlandev);
}
exit:
usb_set_intfdata(interface, NULL);
}
#ifdef CONFIG_PM
static int prism2sta_suspend(struct usb_interface *interface,
pm_message_t message)
{
hfa384x_t *hw = NULL;
wlandevice_t *wlandev;
wlandev = (wlandevice_t *) usb_get_intfdata(interface);
if (!wlandev)
return -ENODEV;
hw = wlandev->priv;
if (!hw)
return -ENODEV;
prism2sta_ifstate(wlandev, P80211ENUM_ifstate_disable);
usb_kill_urb(&hw->rx_urb);
usb_kill_urb(&hw->tx_urb);
usb_kill_urb(&hw->ctlx_urb);
return 0;
}
static int prism2sta_resume(struct usb_interface *interface)
{
int result = 0;
hfa384x_t *hw = NULL;
wlandevice_t *wlandev;
wlandev = (wlandevice_t *) usb_get_intfdata(interface);
if (!wlandev)
return -ENODEV;
hw = wlandev->priv;
if (!hw)
return -ENODEV;
/* Do a chip-level reset on the MAC */
if (prism2_doreset) {
result = hfa384x_corereset(hw,
prism2_reset_holdtime,
prism2_reset_settletime, 0);
if (result != 0) {
unregister_wlandev(wlandev);
hfa384x_destroy(hw);
printk(KERN_ERR
"%s: hfa384x_corereset() failed.\n", dev_info);
kfree(wlandev);
kfree(hw);
wlandev = NULL;
return -ENODEV;
}
}
prism2sta_ifstate(wlandev, P80211ENUM_ifstate_enable);
return 0;
}
#else
#define prism2sta_suspend NULL
#define prism2sta_resume NULL
#endif /* CONFIG_PM */
static struct usb_driver prism2_usb_driver = {
.name = "prism2_usb",
.probe = prism2sta_probe_usb,
.disconnect = prism2sta_disconnect_usb,
.id_table = usb_prism_tbl,
.suspend = prism2sta_suspend,
.resume = prism2sta_resume,
.reset_resume = prism2sta_resume,
/* fops, minor? */
};
module_usb_driver(prism2_usb_driver);
| gpl-2.0 |
adiwgno/tes | drivers/gpu/drm/gma500/gtt.c | 5239 | 14929 | /*
* Copyright (c) 2007, Intel Corporation.
* All Rights Reserved.
*
* 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.
*
* Authors: Thomas Hellstrom <thomas-at-tungstengraphics.com>
* Alan Cox <alan@linux.intel.com>
*/
#include <drm/drmP.h>
#include <linux/shmem_fs.h>
#include "psb_drv.h"
/*
* GTT resource allocator - manage page mappings in GTT space
*/
/**
* psb_gtt_mask_pte - generate GTT pte entry
* @pfn: page number to encode
* @type: type of memory in the GTT
*
* Set the GTT entry for the appropriate memory type.
*/
static inline uint32_t psb_gtt_mask_pte(uint32_t pfn, int type)
{
uint32_t mask = PSB_PTE_VALID;
if (type & PSB_MMU_CACHED_MEMORY)
mask |= PSB_PTE_CACHED;
if (type & PSB_MMU_RO_MEMORY)
mask |= PSB_PTE_RO;
if (type & PSB_MMU_WO_MEMORY)
mask |= PSB_PTE_WO;
return (pfn << PAGE_SHIFT) | mask;
}
/**
* psb_gtt_entry - find the GTT entries for a gtt_range
* @dev: our DRM device
* @r: our GTT range
*
* Given a gtt_range object return the GTT offset of the page table
* entries for this gtt_range
*/
static u32 *psb_gtt_entry(struct drm_device *dev, struct gtt_range *r)
{
struct drm_psb_private *dev_priv = dev->dev_private;
unsigned long offset;
offset = r->resource.start - dev_priv->gtt_mem->start;
return dev_priv->gtt_map + (offset >> PAGE_SHIFT);
}
/**
* psb_gtt_insert - put an object into the GTT
* @dev: our DRM device
* @r: our GTT range
*
* Take our preallocated GTT range and insert the GEM object into
* the GTT. This is protected via the gtt mutex which the caller
* must hold.
*/
static int psb_gtt_insert(struct drm_device *dev, struct gtt_range *r)
{
u32 *gtt_slot, pte;
struct page **pages;
int i;
if (r->pages == NULL) {
WARN_ON(1);
return -EINVAL;
}
WARN_ON(r->stolen); /* refcount these maybe ? */
gtt_slot = psb_gtt_entry(dev, r);
pages = r->pages;
/* Make sure changes are visible to the GPU */
set_pages_array_uc(pages, r->npage);
/* Write our page entries into the GTT itself */
for (i = r->roll; i < r->npage; i++) {
pte = psb_gtt_mask_pte(page_to_pfn(r->pages[i]), 0);
iowrite32(pte, gtt_slot++);
}
for (i = 0; i < r->roll; i++) {
pte = psb_gtt_mask_pte(page_to_pfn(r->pages[i]), 0);
iowrite32(pte, gtt_slot++);
}
/* Make sure all the entries are set before we return */
ioread32(gtt_slot - 1);
return 0;
}
/**
* psb_gtt_remove - remove an object from the GTT
* @dev: our DRM device
* @r: our GTT range
*
* Remove a preallocated GTT range from the GTT. Overwrite all the
* page table entries with the dummy page. This is protected via the gtt
* mutex which the caller must hold.
*/
static void psb_gtt_remove(struct drm_device *dev, struct gtt_range *r)
{
struct drm_psb_private *dev_priv = dev->dev_private;
u32 *gtt_slot, pte;
int i;
WARN_ON(r->stolen);
gtt_slot = psb_gtt_entry(dev, r);
pte = psb_gtt_mask_pte(page_to_pfn(dev_priv->scratch_page), 0);
for (i = 0; i < r->npage; i++)
iowrite32(pte, gtt_slot++);
ioread32(gtt_slot - 1);
set_pages_array_wb(r->pages, r->npage);
}
/**
* psb_gtt_roll - set scrolling position
* @dev: our DRM device
* @r: the gtt mapping we are using
* @roll: roll offset
*
* Roll an existing pinned mapping by moving the pages through the GTT.
* This allows us to implement hardware scrolling on the consoles without
* a 2D engine
*/
void psb_gtt_roll(struct drm_device *dev, struct gtt_range *r, int roll)
{
u32 *gtt_slot, pte;
int i;
if (roll >= r->npage) {
WARN_ON(1);
return;
}
r->roll = roll;
/* Not currently in the GTT - no worry we will write the mapping at
the right position when it gets pinned */
if (!r->stolen && !r->in_gart)
return;
gtt_slot = psb_gtt_entry(dev, r);
for (i = r->roll; i < r->npage; i++) {
pte = psb_gtt_mask_pte(page_to_pfn(r->pages[i]), 0);
iowrite32(pte, gtt_slot++);
}
for (i = 0; i < r->roll; i++) {
pte = psb_gtt_mask_pte(page_to_pfn(r->pages[i]), 0);
iowrite32(pte, gtt_slot++);
}
ioread32(gtt_slot - 1);
}
/**
* psb_gtt_attach_pages - attach and pin GEM pages
* @gt: the gtt range
*
* Pin and build an in kernel list of the pages that back our GEM object.
* While we hold this the pages cannot be swapped out. This is protected
* via the gtt mutex which the caller must hold.
*/
static int psb_gtt_attach_pages(struct gtt_range *gt)
{
struct inode *inode;
struct address_space *mapping;
int i;
struct page *p;
int pages = gt->gem.size / PAGE_SIZE;
WARN_ON(gt->pages);
/* This is the shared memory object that backs the GEM resource */
inode = gt->gem.filp->f_path.dentry->d_inode;
mapping = inode->i_mapping;
gt->pages = kmalloc(pages * sizeof(struct page *), GFP_KERNEL);
if (gt->pages == NULL)
return -ENOMEM;
gt->npage = pages;
for (i = 0; i < pages; i++) {
p = shmem_read_mapping_page(mapping, i);
if (IS_ERR(p))
goto err;
gt->pages[i] = p;
}
return 0;
err:
while (i--)
page_cache_release(gt->pages[i]);
kfree(gt->pages);
gt->pages = NULL;
return PTR_ERR(p);
}
/**
* psb_gtt_detach_pages - attach and pin GEM pages
* @gt: the gtt range
*
* Undo the effect of psb_gtt_attach_pages. At this point the pages
* must have been removed from the GTT as they could now be paged out
* and move bus address. This is protected via the gtt mutex which the
* caller must hold.
*/
static void psb_gtt_detach_pages(struct gtt_range *gt)
{
int i;
for (i = 0; i < gt->npage; i++) {
/* FIXME: do we need to force dirty */
set_page_dirty(gt->pages[i]);
page_cache_release(gt->pages[i]);
}
kfree(gt->pages);
gt->pages = NULL;
}
/**
* psb_gtt_pin - pin pages into the GTT
* @gt: range to pin
*
* Pin a set of pages into the GTT. The pins are refcounted so that
* multiple pins need multiple unpins to undo.
*
* Non GEM backed objects treat this as a no-op as they are always GTT
* backed objects.
*/
int psb_gtt_pin(struct gtt_range *gt)
{
int ret = 0;
struct drm_device *dev = gt->gem.dev;
struct drm_psb_private *dev_priv = dev->dev_private;
mutex_lock(&dev_priv->gtt_mutex);
if (gt->in_gart == 0 && gt->stolen == 0) {
ret = psb_gtt_attach_pages(gt);
if (ret < 0)
goto out;
ret = psb_gtt_insert(dev, gt);
if (ret < 0) {
psb_gtt_detach_pages(gt);
goto out;
}
}
gt->in_gart++;
out:
mutex_unlock(&dev_priv->gtt_mutex);
return ret;
}
/**
* psb_gtt_unpin - Drop a GTT pin requirement
* @gt: range to pin
*
* Undoes the effect of psb_gtt_pin. On the last drop the GEM object
* will be removed from the GTT which will also drop the page references
* and allow the VM to clean up or page stuff.
*
* Non GEM backed objects treat this as a no-op as they are always GTT
* backed objects.
*/
void psb_gtt_unpin(struct gtt_range *gt)
{
struct drm_device *dev = gt->gem.dev;
struct drm_psb_private *dev_priv = dev->dev_private;
mutex_lock(&dev_priv->gtt_mutex);
WARN_ON(!gt->in_gart);
gt->in_gart--;
if (gt->in_gart == 0 && gt->stolen == 0) {
psb_gtt_remove(dev, gt);
psb_gtt_detach_pages(gt);
}
mutex_unlock(&dev_priv->gtt_mutex);
}
/*
* GTT resource allocator - allocate and manage GTT address space
*/
/**
* psb_gtt_alloc_range - allocate GTT address space
* @dev: Our DRM device
* @len: length (bytes) of address space required
* @name: resource name
* @backed: resource should be backed by stolen pages
*
* Ask the kernel core to find us a suitable range of addresses
* to use for a GTT mapping.
*
* Returns a gtt_range structure describing the object, or NULL on
* error. On successful return the resource is both allocated and marked
* as in use.
*/
struct gtt_range *psb_gtt_alloc_range(struct drm_device *dev, int len,
const char *name, int backed)
{
struct drm_psb_private *dev_priv = dev->dev_private;
struct gtt_range *gt;
struct resource *r = dev_priv->gtt_mem;
int ret;
unsigned long start, end;
if (backed) {
/* The start of the GTT is the stolen pages */
start = r->start;
end = r->start + dev_priv->gtt.stolen_size - 1;
} else {
/* The rest we will use for GEM backed objects */
start = r->start + dev_priv->gtt.stolen_size;
end = r->end;
}
gt = kzalloc(sizeof(struct gtt_range), GFP_KERNEL);
if (gt == NULL)
return NULL;
gt->resource.name = name;
gt->stolen = backed;
gt->in_gart = backed;
gt->roll = 0;
/* Ensure this is set for non GEM objects */
gt->gem.dev = dev;
ret = allocate_resource(dev_priv->gtt_mem, >->resource,
len, start, end, PAGE_SIZE, NULL, NULL);
if (ret == 0) {
gt->offset = gt->resource.start - r->start;
return gt;
}
kfree(gt);
return NULL;
}
/**
* psb_gtt_free_range - release GTT address space
* @dev: our DRM device
* @gt: a mapping created with psb_gtt_alloc_range
*
* Release a resource that was allocated with psb_gtt_alloc_range. If the
* object has been pinned by mmap users we clean this up here currently.
*/
void psb_gtt_free_range(struct drm_device *dev, struct gtt_range *gt)
{
/* Undo the mmap pin if we are destroying the object */
if (gt->mmapping) {
psb_gtt_unpin(gt);
gt->mmapping = 0;
}
WARN_ON(gt->in_gart && !gt->stolen);
release_resource(>->resource);
kfree(gt);
}
static void psb_gtt_alloc(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
init_rwsem(&dev_priv->gtt.sem);
}
void psb_gtt_takedown(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
if (dev_priv->gtt_map) {
iounmap(dev_priv->gtt_map);
dev_priv->gtt_map = NULL;
}
if (dev_priv->gtt_initialized) {
pci_write_config_word(dev->pdev, PSB_GMCH_CTRL,
dev_priv->gmch_ctrl);
PSB_WVDC32(dev_priv->pge_ctl, PSB_PGETBL_CTL);
(void) PSB_RVDC32(PSB_PGETBL_CTL);
}
if (dev_priv->vram_addr)
iounmap(dev_priv->gtt_map);
}
int psb_gtt_init(struct drm_device *dev, int resume)
{
struct drm_psb_private *dev_priv = dev->dev_private;
unsigned gtt_pages;
unsigned long stolen_size, vram_stolen_size;
unsigned i, num_pages;
unsigned pfn_base;
uint32_t vram_pages;
uint32_t dvmt_mode = 0;
struct psb_gtt *pg;
int ret = 0;
uint32_t pte;
mutex_init(&dev_priv->gtt_mutex);
psb_gtt_alloc(dev);
pg = &dev_priv->gtt;
/* Enable the GTT */
pci_read_config_word(dev->pdev, PSB_GMCH_CTRL, &dev_priv->gmch_ctrl);
pci_write_config_word(dev->pdev, PSB_GMCH_CTRL,
dev_priv->gmch_ctrl | _PSB_GMCH_ENABLED);
dev_priv->pge_ctl = PSB_RVDC32(PSB_PGETBL_CTL);
PSB_WVDC32(dev_priv->pge_ctl | _PSB_PGETBL_ENABLED, PSB_PGETBL_CTL);
(void) PSB_RVDC32(PSB_PGETBL_CTL);
/* The root resource we allocate address space from */
dev_priv->gtt_initialized = 1;
pg->gtt_phys_start = dev_priv->pge_ctl & PAGE_MASK;
/*
* The video mmu has a hw bug when accessing 0x0D0000000.
* Make gatt start at 0x0e000,0000. This doesn't actually
* matter for us but may do if the video acceleration ever
* gets opened up.
*/
pg->mmu_gatt_start = 0xE0000000;
pg->gtt_start = pci_resource_start(dev->pdev, PSB_GTT_RESOURCE);
gtt_pages = pci_resource_len(dev->pdev, PSB_GTT_RESOURCE)
>> PAGE_SHIFT;
/* CDV doesn't report this. In which case the system has 64 gtt pages */
if (pg->gtt_start == 0 || gtt_pages == 0) {
dev_dbg(dev->dev, "GTT PCI BAR not initialized.\n");
gtt_pages = 64;
pg->gtt_start = dev_priv->pge_ctl;
}
pg->gatt_start = pci_resource_start(dev->pdev, PSB_GATT_RESOURCE);
pg->gatt_pages = pci_resource_len(dev->pdev, PSB_GATT_RESOURCE)
>> PAGE_SHIFT;
dev_priv->gtt_mem = &dev->pdev->resource[PSB_GATT_RESOURCE];
if (pg->gatt_pages == 0 || pg->gatt_start == 0) {
static struct resource fudge; /* Preferably peppermint */
/* This can occur on CDV systems. Fudge it in this case.
We really don't care what imaginary space is being allocated
at this point */
dev_dbg(dev->dev, "GATT PCI BAR not initialized.\n");
pg->gatt_start = 0x40000000;
pg->gatt_pages = (128 * 1024 * 1024) >> PAGE_SHIFT;
/* This is a little confusing but in fact the GTT is providing
a view from the GPU into memory and not vice versa. As such
this is really allocating space that is not the same as the
CPU address space on CDV */
fudge.start = 0x40000000;
fudge.end = 0x40000000 + 128 * 1024 * 1024 - 1;
fudge.name = "fudge";
fudge.flags = IORESOURCE_MEM;
dev_priv->gtt_mem = &fudge;
}
pci_read_config_dword(dev->pdev, PSB_BSM, &dev_priv->stolen_base);
vram_stolen_size = pg->gtt_phys_start - dev_priv->stolen_base
- PAGE_SIZE;
stolen_size = vram_stolen_size;
printk(KERN_INFO "Stolen memory information\n");
printk(KERN_INFO " base in RAM: 0x%x\n", dev_priv->stolen_base);
printk(KERN_INFO " size: %luK, calculated by (GTT RAM base) - (Stolen base), seems wrong\n",
vram_stolen_size/1024);
dvmt_mode = (dev_priv->gmch_ctrl >> 4) & 0x7;
printk(KERN_INFO " the correct size should be: %dM(dvmt mode=%d)\n",
(dvmt_mode == 1) ? 1 : (2 << (dvmt_mode - 1)), dvmt_mode);
if (resume && (gtt_pages != pg->gtt_pages) &&
(stolen_size != pg->stolen_size)) {
dev_err(dev->dev, "GTT resume error.\n");
ret = -EINVAL;
goto out_err;
}
pg->gtt_pages = gtt_pages;
pg->stolen_size = stolen_size;
dev_priv->vram_stolen_size = vram_stolen_size;
/*
* Map the GTT and the stolen memory area
*/
dev_priv->gtt_map = ioremap_nocache(pg->gtt_phys_start,
gtt_pages << PAGE_SHIFT);
if (!dev_priv->gtt_map) {
dev_err(dev->dev, "Failure to map gtt.\n");
ret = -ENOMEM;
goto out_err;
}
dev_priv->vram_addr = ioremap_wc(dev_priv->stolen_base, stolen_size);
if (!dev_priv->vram_addr) {
dev_err(dev->dev, "Failure to map stolen base.\n");
ret = -ENOMEM;
goto out_err;
}
/*
* Insert vram stolen pages into the GTT
*/
pfn_base = dev_priv->stolen_base >> PAGE_SHIFT;
vram_pages = num_pages = vram_stolen_size >> PAGE_SHIFT;
printk(KERN_INFO"Set up %d stolen pages starting at 0x%08x, GTT offset %dK\n",
num_pages, pfn_base << PAGE_SHIFT, 0);
for (i = 0; i < num_pages; ++i) {
pte = psb_gtt_mask_pte(pfn_base + i, 0);
iowrite32(pte, dev_priv->gtt_map + i);
}
/*
* Init rest of GTT to the scratch page to avoid accidents or scribbles
*/
pfn_base = page_to_pfn(dev_priv->scratch_page);
pte = psb_gtt_mask_pte(pfn_base, 0);
for (; i < gtt_pages; ++i)
iowrite32(pte, dev_priv->gtt_map + i);
(void) ioread32(dev_priv->gtt_map + i - 1);
return 0;
out_err:
psb_gtt_takedown(dev);
return ret;
}
| gpl-2.0 |
mixtile/garage-linux | net/ceph/auth_none.c | 6007 | 2932 |
#include <linux/ceph/ceph_debug.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/random.h>
#include <linux/slab.h>
#include <linux/ceph/decode.h>
#include <linux/ceph/auth.h>
#include "auth_none.h"
static void reset(struct ceph_auth_client *ac)
{
struct ceph_auth_none_info *xi = ac->private;
xi->starting = true;
xi->built_authorizer = false;
}
static void destroy(struct ceph_auth_client *ac)
{
kfree(ac->private);
ac->private = NULL;
}
static int is_authenticated(struct ceph_auth_client *ac)
{
struct ceph_auth_none_info *xi = ac->private;
return !xi->starting;
}
static int should_authenticate(struct ceph_auth_client *ac)
{
struct ceph_auth_none_info *xi = ac->private;
return xi->starting;
}
/*
* the generic auth code decode the global_id, and we carry no actual
* authenticate state, so nothing happens here.
*/
static int handle_reply(struct ceph_auth_client *ac, int result,
void *buf, void *end)
{
struct ceph_auth_none_info *xi = ac->private;
xi->starting = false;
return result;
}
/*
* build an 'authorizer' with our entity_name and global_id. we can
* reuse a single static copy since it is identical for all services
* we connect to.
*/
static int ceph_auth_none_create_authorizer(
struct ceph_auth_client *ac, int peer_type,
struct ceph_authorizer **a,
void **buf, size_t *len,
void **reply_buf, size_t *reply_len)
{
struct ceph_auth_none_info *ai = ac->private;
struct ceph_none_authorizer *au = &ai->au;
void *p, *end;
int ret;
if (!ai->built_authorizer) {
p = au->buf;
end = p + sizeof(au->buf);
ceph_encode_8(&p, 1);
ret = ceph_entity_name_encode(ac->name, &p, end - 8);
if (ret < 0)
goto bad;
ceph_decode_need(&p, end, sizeof(u64), bad2);
ceph_encode_64(&p, ac->global_id);
au->buf_len = p - (void *)au->buf;
ai->built_authorizer = true;
dout("built authorizer len %d\n", au->buf_len);
}
*a = (struct ceph_authorizer *)au;
*buf = au->buf;
*len = au->buf_len;
*reply_buf = au->reply_buf;
*reply_len = sizeof(au->reply_buf);
return 0;
bad2:
ret = -ERANGE;
bad:
return ret;
}
static void ceph_auth_none_destroy_authorizer(struct ceph_auth_client *ac,
struct ceph_authorizer *a)
{
/* nothing to do */
}
static const struct ceph_auth_client_ops ceph_auth_none_ops = {
.name = "none",
.reset = reset,
.destroy = destroy,
.is_authenticated = is_authenticated,
.should_authenticate = should_authenticate,
.handle_reply = handle_reply,
.create_authorizer = ceph_auth_none_create_authorizer,
.destroy_authorizer = ceph_auth_none_destroy_authorizer,
};
int ceph_auth_none_init(struct ceph_auth_client *ac)
{
struct ceph_auth_none_info *xi;
dout("ceph_auth_none_init %p\n", ac);
xi = kzalloc(sizeof(*xi), GFP_NOFS);
if (!xi)
return -ENOMEM;
xi->starting = true;
xi->built_authorizer = false;
ac->protocol = CEPH_AUTH_NONE;
ac->private = xi;
ac->ops = &ceph_auth_none_ops;
return 0;
}
| gpl-2.0 |
bq/linux-e60622 | drivers/net/wireless/wl1251/tx.c | 10871 | 13649 | /*
* This file is part of wl1251
*
* Copyright (c) 1998-2007 Texas Instruments Incorporated
* 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 <linux/kernel.h>
#include <linux/module.h>
#include "wl1251.h"
#include "reg.h"
#include "tx.h"
#include "ps.h"
#include "io.h"
static bool wl1251_tx_double_buffer_busy(struct wl1251 *wl, u32 data_out_count)
{
int used, data_in_count;
data_in_count = wl->data_in_count;
if (data_in_count < data_out_count)
/* data_in_count has wrapped */
data_in_count += TX_STATUS_DATA_OUT_COUNT_MASK + 1;
used = data_in_count - data_out_count;
WARN_ON(used < 0);
WARN_ON(used > DP_TX_PACKET_RING_CHUNK_NUM);
if (used >= DP_TX_PACKET_RING_CHUNK_NUM)
return true;
else
return false;
}
static int wl1251_tx_path_status(struct wl1251 *wl)
{
u32 status, addr, data_out_count;
bool busy;
addr = wl->data_path->tx_control_addr;
status = wl1251_mem_read32(wl, addr);
data_out_count = status & TX_STATUS_DATA_OUT_COUNT_MASK;
busy = wl1251_tx_double_buffer_busy(wl, data_out_count);
if (busy)
return -EBUSY;
return 0;
}
static int wl1251_tx_id(struct wl1251 *wl, struct sk_buff *skb)
{
int i;
for (i = 0; i < FW_TX_CMPLT_BLOCK_SIZE; i++)
if (wl->tx_frames[i] == NULL) {
wl->tx_frames[i] = skb;
return i;
}
return -EBUSY;
}
static void wl1251_tx_control(struct tx_double_buffer_desc *tx_hdr,
struct ieee80211_tx_info *control, u16 fc)
{
*(u16 *)&tx_hdr->control = 0;
tx_hdr->control.rate_policy = 0;
/* 802.11 packets */
tx_hdr->control.packet_type = 0;
if (control->flags & IEEE80211_TX_CTL_NO_ACK)
tx_hdr->control.ack_policy = 1;
tx_hdr->control.tx_complete = 1;
if ((fc & IEEE80211_FTYPE_DATA) &&
((fc & IEEE80211_STYPE_QOS_DATA) ||
(fc & IEEE80211_STYPE_QOS_NULLFUNC)))
tx_hdr->control.qos = 1;
}
/* RSN + MIC = 8 + 8 = 16 bytes (worst case - AES). */
#define MAX_MSDU_SECURITY_LENGTH 16
#define MAX_MPDU_SECURITY_LENGTH 16
#define WLAN_QOS_HDR_LEN 26
#define MAX_MPDU_HEADER_AND_SECURITY (MAX_MPDU_SECURITY_LENGTH + \
WLAN_QOS_HDR_LEN)
#define HW_BLOCK_SIZE 252
static void wl1251_tx_frag_block_num(struct tx_double_buffer_desc *tx_hdr)
{
u16 payload_len, frag_threshold, mem_blocks;
u16 num_mpdus, mem_blocks_per_frag;
frag_threshold = IEEE80211_MAX_FRAG_THRESHOLD;
tx_hdr->frag_threshold = cpu_to_le16(frag_threshold);
payload_len = le16_to_cpu(tx_hdr->length) + MAX_MSDU_SECURITY_LENGTH;
if (payload_len > frag_threshold) {
mem_blocks_per_frag =
((frag_threshold + MAX_MPDU_HEADER_AND_SECURITY) /
HW_BLOCK_SIZE) + 1;
num_mpdus = payload_len / frag_threshold;
mem_blocks = num_mpdus * mem_blocks_per_frag;
payload_len -= num_mpdus * frag_threshold;
num_mpdus++;
} else {
mem_blocks_per_frag = 0;
mem_blocks = 0;
num_mpdus = 1;
}
mem_blocks += (payload_len / HW_BLOCK_SIZE) + 1;
if (num_mpdus > 1)
mem_blocks += min(num_mpdus, mem_blocks_per_frag);
tx_hdr->num_mem_blocks = mem_blocks;
}
static int wl1251_tx_fill_hdr(struct wl1251 *wl, struct sk_buff *skb,
struct ieee80211_tx_info *control)
{
struct tx_double_buffer_desc *tx_hdr;
struct ieee80211_rate *rate;
int id;
u16 fc;
if (!skb)
return -EINVAL;
id = wl1251_tx_id(wl, skb);
if (id < 0)
return id;
fc = *(u16 *)skb->data;
tx_hdr = (struct tx_double_buffer_desc *) skb_push(skb,
sizeof(*tx_hdr));
tx_hdr->length = cpu_to_le16(skb->len - sizeof(*tx_hdr));
rate = ieee80211_get_tx_rate(wl->hw, control);
tx_hdr->rate = cpu_to_le16(rate->hw_value);
tx_hdr->expiry_time = cpu_to_le32(1 << 16);
tx_hdr->id = id;
tx_hdr->xmit_queue = wl1251_tx_get_queue(skb_get_queue_mapping(skb));
wl1251_tx_control(tx_hdr, control, fc);
wl1251_tx_frag_block_num(tx_hdr);
return 0;
}
/* We copy the packet to the target */
static int wl1251_tx_send_packet(struct wl1251 *wl, struct sk_buff *skb,
struct ieee80211_tx_info *control)
{
struct tx_double_buffer_desc *tx_hdr;
int len;
u32 addr;
if (!skb)
return -EINVAL;
tx_hdr = (struct tx_double_buffer_desc *) skb->data;
if (control->control.hw_key &&
control->control.hw_key->cipher == WLAN_CIPHER_SUITE_TKIP) {
int hdrlen;
__le16 fc;
u16 length;
u8 *pos;
fc = *(__le16 *)(skb->data + sizeof(*tx_hdr));
length = le16_to_cpu(tx_hdr->length) + WL1251_TKIP_IV_SPACE;
tx_hdr->length = cpu_to_le16(length);
hdrlen = ieee80211_hdrlen(fc);
pos = skb_push(skb, WL1251_TKIP_IV_SPACE);
memmove(pos, pos + WL1251_TKIP_IV_SPACE,
sizeof(*tx_hdr) + hdrlen);
}
/* Revisit. This is a workaround for getting non-aligned packets.
This happens at least with EAPOL packets from the user space.
Our DMA requires packets to be aligned on a 4-byte boundary.
*/
if (unlikely((long)skb->data & 0x03)) {
int offset = (4 - (long)skb->data) & 0x03;
wl1251_debug(DEBUG_TX, "skb offset %d", offset);
/* check whether the current skb can be used */
if (skb_cloned(skb) || (skb_tailroom(skb) < offset)) {
struct sk_buff *newskb = skb_copy_expand(skb, 0, 3,
GFP_KERNEL);
if (unlikely(newskb == NULL)) {
wl1251_error("Can't allocate skb!");
return -EINVAL;
}
tx_hdr = (struct tx_double_buffer_desc *) newskb->data;
dev_kfree_skb_any(skb);
wl->tx_frames[tx_hdr->id] = skb = newskb;
offset = (4 - (long)skb->data) & 0x03;
wl1251_debug(DEBUG_TX, "new skb offset %d", offset);
}
/* align the buffer on a 4-byte boundary */
if (offset) {
unsigned char *src = skb->data;
skb_reserve(skb, offset);
memmove(skb->data, src, skb->len);
tx_hdr = (struct tx_double_buffer_desc *) skb->data;
}
}
/* Our skb->data at this point includes the HW header */
len = WL1251_TX_ALIGN(skb->len);
if (wl->data_in_count & 0x1)
addr = wl->data_path->tx_packet_ring_addr +
wl->data_path->tx_packet_ring_chunk_size;
else
addr = wl->data_path->tx_packet_ring_addr;
wl1251_mem_write(wl, addr, skb->data, len);
wl1251_debug(DEBUG_TX, "tx id %u skb 0x%p payload %u rate 0x%x "
"queue %d", tx_hdr->id, skb, tx_hdr->length,
tx_hdr->rate, tx_hdr->xmit_queue);
return 0;
}
static void wl1251_tx_trigger(struct wl1251 *wl)
{
u32 data, addr;
if (wl->data_in_count & 0x1) {
addr = ACX_REG_INTERRUPT_TRIG_H;
data = INTR_TRIG_TX_PROC1;
} else {
addr = ACX_REG_INTERRUPT_TRIG;
data = INTR_TRIG_TX_PROC0;
}
wl1251_reg_write32(wl, addr, data);
/* Bumping data in */
wl->data_in_count = (wl->data_in_count + 1) &
TX_STATUS_DATA_OUT_COUNT_MASK;
}
/* caller must hold wl->mutex */
static int wl1251_tx_frame(struct wl1251 *wl, struct sk_buff *skb)
{
struct ieee80211_tx_info *info;
int ret = 0;
u8 idx;
info = IEEE80211_SKB_CB(skb);
if (info->control.hw_key) {
idx = info->control.hw_key->hw_key_idx;
if (unlikely(wl->default_key != idx)) {
ret = wl1251_acx_default_key(wl, idx);
if (ret < 0)
return ret;
}
}
ret = wl1251_tx_path_status(wl);
if (ret < 0)
return ret;
ret = wl1251_tx_fill_hdr(wl, skb, info);
if (ret < 0)
return ret;
ret = wl1251_tx_send_packet(wl, skb, info);
if (ret < 0)
return ret;
wl1251_tx_trigger(wl);
return ret;
}
void wl1251_tx_work(struct work_struct *work)
{
struct wl1251 *wl = container_of(work, struct wl1251, tx_work);
struct sk_buff *skb;
bool woken_up = false;
int ret;
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1251_STATE_OFF))
goto out;
while ((skb = skb_dequeue(&wl->tx_queue))) {
if (!woken_up) {
ret = wl1251_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
woken_up = true;
}
ret = wl1251_tx_frame(wl, skb);
if (ret == -EBUSY) {
skb_queue_head(&wl->tx_queue, skb);
goto out;
} else if (ret < 0) {
dev_kfree_skb(skb);
goto out;
}
}
out:
if (woken_up)
wl1251_ps_elp_sleep(wl);
mutex_unlock(&wl->mutex);
}
static const char *wl1251_tx_parse_status(u8 status)
{
/* 8 bit status field, one character per bit plus null */
static char buf[9];
int i = 0;
memset(buf, 0, sizeof(buf));
if (status & TX_DMA_ERROR)
buf[i++] = 'm';
if (status & TX_DISABLED)
buf[i++] = 'd';
if (status & TX_RETRY_EXCEEDED)
buf[i++] = 'r';
if (status & TX_TIMEOUT)
buf[i++] = 't';
if (status & TX_KEY_NOT_FOUND)
buf[i++] = 'k';
if (status & TX_ENCRYPT_FAIL)
buf[i++] = 'e';
if (status & TX_UNAVAILABLE_PRIORITY)
buf[i++] = 'p';
/* bit 0 is unused apparently */
return buf;
}
static void wl1251_tx_packet_cb(struct wl1251 *wl,
struct tx_result *result)
{
struct ieee80211_tx_info *info;
struct sk_buff *skb;
int hdrlen;
u8 *frame;
skb = wl->tx_frames[result->id];
if (skb == NULL) {
wl1251_error("SKB for packet %d is NULL", result->id);
return;
}
info = IEEE80211_SKB_CB(skb);
if (!(info->flags & IEEE80211_TX_CTL_NO_ACK) &&
(result->status == TX_SUCCESS))
info->flags |= IEEE80211_TX_STAT_ACK;
info->status.rates[0].count = result->ack_failures + 1;
wl->stats.retry_count += result->ack_failures;
/*
* We have to remove our private TX header before pushing
* the skb back to mac80211.
*/
frame = skb_pull(skb, sizeof(struct tx_double_buffer_desc));
if (info->control.hw_key &&
info->control.hw_key->cipher == WLAN_CIPHER_SUITE_TKIP) {
hdrlen = ieee80211_get_hdrlen_from_skb(skb);
memmove(frame + WL1251_TKIP_IV_SPACE, frame, hdrlen);
skb_pull(skb, WL1251_TKIP_IV_SPACE);
}
wl1251_debug(DEBUG_TX, "tx status id %u skb 0x%p failures %u rate 0x%x"
" status 0x%x (%s)",
result->id, skb, result->ack_failures, result->rate,
result->status, wl1251_tx_parse_status(result->status));
ieee80211_tx_status(wl->hw, skb);
wl->tx_frames[result->id] = NULL;
}
/* Called upon reception of a TX complete interrupt */
void wl1251_tx_complete(struct wl1251 *wl)
{
int i, result_index, num_complete = 0, queue_len;
struct tx_result result[FW_TX_CMPLT_BLOCK_SIZE], *result_ptr;
unsigned long flags;
if (unlikely(wl->state != WL1251_STATE_ON))
return;
/* First we read the result */
wl1251_mem_read(wl, wl->data_path->tx_complete_addr,
result, sizeof(result));
result_index = wl->next_tx_complete;
for (i = 0; i < ARRAY_SIZE(result); i++) {
result_ptr = &result[result_index];
if (result_ptr->done_1 == 1 &&
result_ptr->done_2 == 1) {
wl1251_tx_packet_cb(wl, result_ptr);
result_ptr->done_1 = 0;
result_ptr->done_2 = 0;
result_index = (result_index + 1) &
(FW_TX_CMPLT_BLOCK_SIZE - 1);
num_complete++;
} else {
break;
}
}
queue_len = skb_queue_len(&wl->tx_queue);
if ((num_complete > 0) && (queue_len > 0)) {
/* firmware buffer has space, reschedule tx_work */
wl1251_debug(DEBUG_TX, "tx_complete: reschedule tx_work");
ieee80211_queue_work(wl->hw, &wl->tx_work);
}
if (wl->tx_queue_stopped &&
queue_len <= WL1251_TX_QUEUE_LOW_WATERMARK) {
/* tx_queue has space, restart queues */
wl1251_debug(DEBUG_TX, "tx_complete: waking queues");
spin_lock_irqsave(&wl->wl_lock, flags);
ieee80211_wake_queues(wl->hw);
wl->tx_queue_stopped = false;
spin_unlock_irqrestore(&wl->wl_lock, flags);
}
/* Every completed frame needs to be acknowledged */
if (num_complete) {
/*
* If we've wrapped, we have to clear
* the results in 2 steps.
*/
if (result_index > wl->next_tx_complete) {
/* Only 1 write is needed */
wl1251_mem_write(wl,
wl->data_path->tx_complete_addr +
(wl->next_tx_complete *
sizeof(struct tx_result)),
&result[wl->next_tx_complete],
num_complete *
sizeof(struct tx_result));
} else if (result_index < wl->next_tx_complete) {
/* 2 writes are needed */
wl1251_mem_write(wl,
wl->data_path->tx_complete_addr +
(wl->next_tx_complete *
sizeof(struct tx_result)),
&result[wl->next_tx_complete],
(FW_TX_CMPLT_BLOCK_SIZE -
wl->next_tx_complete) *
sizeof(struct tx_result));
wl1251_mem_write(wl,
wl->data_path->tx_complete_addr,
result,
(num_complete -
FW_TX_CMPLT_BLOCK_SIZE +
wl->next_tx_complete) *
sizeof(struct tx_result));
} else {
/* We have to write the whole array */
wl1251_mem_write(wl,
wl->data_path->tx_complete_addr,
result,
FW_TX_CMPLT_BLOCK_SIZE *
sizeof(struct tx_result));
}
}
wl->next_tx_complete = result_index;
}
/* caller must hold wl->mutex */
void wl1251_tx_flush(struct wl1251 *wl)
{
int i;
struct sk_buff *skb;
struct ieee80211_tx_info *info;
/* TX failure */
/* control->flags = 0; FIXME */
while ((skb = skb_dequeue(&wl->tx_queue))) {
info = IEEE80211_SKB_CB(skb);
wl1251_debug(DEBUG_TX, "flushing skb 0x%p", skb);
if (!(info->flags & IEEE80211_TX_CTL_REQ_TX_STATUS))
continue;
ieee80211_tx_status(wl->hw, skb);
}
for (i = 0; i < FW_TX_CMPLT_BLOCK_SIZE; i++)
if (wl->tx_frames[i] != NULL) {
skb = wl->tx_frames[i];
info = IEEE80211_SKB_CB(skb);
if (!(info->flags & IEEE80211_TX_CTL_REQ_TX_STATUS))
continue;
ieee80211_tx_status(wl->hw, skb);
wl->tx_frames[i] = NULL;
}
}
| gpl-2.0 |
kamarush/android_kernel_sony_yuga_lp | arch/mips/kernel/smp-up.c | 11127 | 1695 | /*
* 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) 2006, 07 by Ralf Baechle (ralf@linux-mips.org)
*
* Symmetric Uniprocessor (TM) Support
*/
#include <linux/kernel.h>
#include <linux/sched.h>
/*
* Send inter-processor interrupt
*/
static void up_send_ipi_single(int cpu, unsigned int action)
{
panic(KERN_ERR "%s called", __func__);
}
static inline void up_send_ipi_mask(const struct cpumask *mask,
unsigned int action)
{
panic(KERN_ERR "%s called", __func__);
}
/*
* After we've done initial boot, this function is called to allow the
* board code to clean up state, if needed
*/
static void __cpuinit up_init_secondary(void)
{
}
static void __cpuinit up_smp_finish(void)
{
}
/* Hook for after all CPUs are online */
static void up_cpus_done(void)
{
}
/*
* Firmware CPU startup hook
*/
static void __cpuinit up_boot_secondary(int cpu, struct task_struct *idle)
{
}
static void __init up_smp_setup(void)
{
}
static void __init up_prepare_cpus(unsigned int max_cpus)
{
}
#ifdef CONFIG_HOTPLUG_CPU
static int up_cpu_disable(void)
{
return -ENOSYS;
}
static void up_cpu_die(unsigned int cpu)
{
BUG();
}
#endif
struct plat_smp_ops up_smp_ops = {
.send_ipi_single = up_send_ipi_single,
.send_ipi_mask = up_send_ipi_mask,
.init_secondary = up_init_secondary,
.smp_finish = up_smp_finish,
.cpus_done = up_cpus_done,
.boot_secondary = up_boot_secondary,
.smp_setup = up_smp_setup,
.prepare_cpus = up_prepare_cpus,
#ifdef CONFIG_HOTPLUG_CPU
.cpu_disable = up_cpu_disable,
.cpu_die = up_cpu_die,
#endif
};
| gpl-2.0 |
neohung/am335 | sound/soc/soc-dapm.c | 120 | 75268 | /*
* soc-dapm.c -- ALSA SoC Dynamic Audio Power Management
*
* Copyright 2005 Wolfson Microelectronics PLC.
* Author: Liam Girdwood <lrg@slimlogic.co.uk>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* Features:
* o Changes power status of internal codec blocks depending on the
* dynamic configuration of codec internal audio paths and active
* DACs/ADCs.
* o Platform power domain - can support external components i.e. amps and
* mic/meadphone insertion events.
* o Automatic Mic Bias support
* o Jack insertion power event initiation - e.g. hp insertion will enable
* sinks, dacs, etc
* o Delayed powerdown of audio susbsystem to reduce pops between a quick
* device reopen.
*
* Todo:
* o DAPM power change sequencing - allow for configurable per
* codec sequences.
* o Support for analogue bias optimisation.
* o Support for reduced codec oversampling rates.
* o Support for reduced codec bias currents.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/async.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/bitops.h>
#include <linux/platform_device.h>
#include <linux/jiffies.h>
#include <linux/debugfs.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/initval.h>
#include <trace/events/asoc.h>
#define DAPM_UPDATE_STAT(widget, val) widget->dapm->card->dapm_stats.val++;
/* dapm power sequences - make this per codec in the future */
static int dapm_up_seq[] = {
[snd_soc_dapm_pre] = 0,
[snd_soc_dapm_supply] = 1,
[snd_soc_dapm_micbias] = 2,
[snd_soc_dapm_aif_in] = 3,
[snd_soc_dapm_aif_out] = 3,
[snd_soc_dapm_mic] = 4,
[snd_soc_dapm_mux] = 5,
[snd_soc_dapm_virt_mux] = 5,
[snd_soc_dapm_value_mux] = 5,
[snd_soc_dapm_dac] = 6,
[snd_soc_dapm_mixer] = 7,
[snd_soc_dapm_mixer_named_ctl] = 7,
[snd_soc_dapm_pga] = 8,
[snd_soc_dapm_adc] = 9,
[snd_soc_dapm_out_drv] = 10,
[snd_soc_dapm_hp] = 10,
[snd_soc_dapm_spk] = 10,
[snd_soc_dapm_post] = 11,
};
static int dapm_down_seq[] = {
[snd_soc_dapm_pre] = 0,
[snd_soc_dapm_adc] = 1,
[snd_soc_dapm_hp] = 2,
[snd_soc_dapm_spk] = 2,
[snd_soc_dapm_out_drv] = 2,
[snd_soc_dapm_pga] = 4,
[snd_soc_dapm_mixer_named_ctl] = 5,
[snd_soc_dapm_mixer] = 5,
[snd_soc_dapm_dac] = 6,
[snd_soc_dapm_mic] = 7,
[snd_soc_dapm_micbias] = 8,
[snd_soc_dapm_mux] = 9,
[snd_soc_dapm_virt_mux] = 9,
[snd_soc_dapm_value_mux] = 9,
[snd_soc_dapm_aif_in] = 10,
[snd_soc_dapm_aif_out] = 10,
[snd_soc_dapm_supply] = 11,
[snd_soc_dapm_post] = 12,
};
static void pop_wait(u32 pop_time)
{
if (pop_time)
schedule_timeout_uninterruptible(msecs_to_jiffies(pop_time));
}
static void pop_dbg(struct device *dev, u32 pop_time, const char *fmt, ...)
{
va_list args;
char *buf;
if (!pop_time)
return;
buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
if (buf == NULL)
return;
va_start(args, fmt);
vsnprintf(buf, PAGE_SIZE, fmt, args);
dev_info(dev, "%s", buf);
va_end(args);
kfree(buf);
}
static bool dapm_dirty_widget(struct snd_soc_dapm_widget *w)
{
return !list_empty(&w->dirty);
}
void dapm_mark_dirty(struct snd_soc_dapm_widget *w, const char *reason)
{
if (!dapm_dirty_widget(w)) {
dev_vdbg(w->dapm->dev, "Marking %s dirty due to %s\n",
w->name, reason);
list_add_tail(&w->dirty, &w->dapm->card->dapm_dirty);
}
}
EXPORT_SYMBOL_GPL(dapm_mark_dirty);
/* create a new dapm widget */
static inline struct snd_soc_dapm_widget *dapm_cnew_widget(
const struct snd_soc_dapm_widget *_widget)
{
return kmemdup(_widget, sizeof(*_widget), GFP_KERNEL);
}
/* get snd_card from DAPM context */
static inline struct snd_card *dapm_get_snd_card(
struct snd_soc_dapm_context *dapm)
{
if (dapm->codec)
return dapm->codec->card->snd_card;
else if (dapm->platform)
return dapm->platform->card->snd_card;
else
BUG();
/* unreachable */
return NULL;
}
/* get soc_card from DAPM context */
static inline struct snd_soc_card *dapm_get_soc_card(
struct snd_soc_dapm_context *dapm)
{
if (dapm->codec)
return dapm->codec->card;
else if (dapm->platform)
return dapm->platform->card;
else
BUG();
/* unreachable */
return NULL;
}
static int soc_widget_read(struct snd_soc_dapm_widget *w, int reg)
{
if (w->codec)
return snd_soc_read(w->codec, reg);
else if (w->platform)
return snd_soc_platform_read(w->platform, reg);
dev_err(w->dapm->dev, "no valid widget read method\n");
return -1;
}
static int soc_widget_write(struct snd_soc_dapm_widget *w, int reg, int val)
{
if (w->codec)
return snd_soc_write(w->codec, reg, val);
else if (w->platform)
return snd_soc_platform_write(w->platform, reg, val);
dev_err(w->dapm->dev, "no valid widget write method\n");
return -1;
}
static int soc_widget_update_bits(struct snd_soc_dapm_widget *w,
unsigned short reg, unsigned int mask, unsigned int value)
{
int change;
unsigned int old, new;
int ret;
ret = soc_widget_read(w, reg);
if (ret < 0)
return ret;
old = ret;
new = (old & ~mask) | (value & mask);
change = old != new;
if (change) {
ret = soc_widget_write(w, reg, new);
if (ret < 0)
return ret;
}
return change;
}
/**
* snd_soc_dapm_set_bias_level - set the bias level for the system
* @dapm: DAPM context
* @level: level to configure
*
* Configure the bias (power) levels for the SoC audio device.
*
* Returns 0 for success else error.
*/
static int snd_soc_dapm_set_bias_level(struct snd_soc_dapm_context *dapm,
enum snd_soc_bias_level level)
{
struct snd_soc_card *card = dapm->card;
int ret = 0;
trace_snd_soc_bias_level_start(card, level);
if (card && card->set_bias_level)
ret = card->set_bias_level(card, dapm, level);
if (ret != 0)
goto out;
if (dapm->codec) {
if (dapm->codec->driver->set_bias_level)
ret = dapm->codec->driver->set_bias_level(dapm->codec,
level);
else
dapm->bias_level = level;
}
if (ret != 0)
goto out;
if (card && card->set_bias_level_post)
ret = card->set_bias_level_post(card, dapm, level);
out:
trace_snd_soc_bias_level_done(card, level);
return ret;
}
/* set up initial codec paths */
static void dapm_set_path_status(struct snd_soc_dapm_widget *w,
struct snd_soc_dapm_path *p, int i)
{
switch (w->id) {
case snd_soc_dapm_switch:
case snd_soc_dapm_mixer:
case snd_soc_dapm_mixer_named_ctl: {
int val;
struct soc_mixer_control *mc = (struct soc_mixer_control *)
w->kcontrol_news[i].private_value;
unsigned int reg = mc->reg;
unsigned int shift = mc->shift;
int max = mc->max;
unsigned int mask = (1 << fls(max)) - 1;
unsigned int invert = mc->invert;
val = soc_widget_read(w, reg);
val = (val >> shift) & mask;
if ((invert && !val) || (!invert && val))
p->connect = 1;
else
p->connect = 0;
}
break;
case snd_soc_dapm_mux: {
struct soc_enum *e = (struct soc_enum *)
w->kcontrol_news[i].private_value;
int val, item, bitmask;
for (bitmask = 1; bitmask < e->max; bitmask <<= 1)
;
val = soc_widget_read(w, e->reg);
item = (val >> e->shift_l) & (bitmask - 1);
p->connect = 0;
for (i = 0; i < e->max; i++) {
if (!(strcmp(p->name, e->texts[i])) && item == i)
p->connect = 1;
}
}
break;
case snd_soc_dapm_virt_mux: {
struct soc_enum *e = (struct soc_enum *)
w->kcontrol_news[i].private_value;
p->connect = 0;
/* since a virtual mux has no backing registers to
* decide which path to connect, it will try to match
* with the first enumeration. This is to ensure
* that the default mux choice (the first) will be
* correctly powered up during initialization.
*/
if (!strcmp(p->name, e->texts[0]))
p->connect = 1;
}
break;
case snd_soc_dapm_value_mux: {
struct soc_enum *e = (struct soc_enum *)
w->kcontrol_news[i].private_value;
int val, item;
val = soc_widget_read(w, e->reg);
val = (val >> e->shift_l) & e->mask;
for (item = 0; item < e->max; item++) {
if (val == e->values[item])
break;
}
p->connect = 0;
for (i = 0; i < e->max; i++) {
if (!(strcmp(p->name, e->texts[i])) && item == i)
p->connect = 1;
}
}
break;
/* does not affect routing - always connected */
case snd_soc_dapm_pga:
case snd_soc_dapm_out_drv:
case snd_soc_dapm_output:
case snd_soc_dapm_adc:
case snd_soc_dapm_input:
case snd_soc_dapm_dac:
case snd_soc_dapm_micbias:
case snd_soc_dapm_vmid:
case snd_soc_dapm_supply:
case snd_soc_dapm_aif_in:
case snd_soc_dapm_aif_out:
case snd_soc_dapm_hp:
case snd_soc_dapm_mic:
case snd_soc_dapm_spk:
case snd_soc_dapm_line:
p->connect = 1;
break;
/* does affect routing - dynamically connected */
case snd_soc_dapm_pre:
case snd_soc_dapm_post:
p->connect = 0;
break;
}
}
/* connect mux widget to its interconnecting audio paths */
static int dapm_connect_mux(struct snd_soc_dapm_context *dapm,
struct snd_soc_dapm_widget *src, struct snd_soc_dapm_widget *dest,
struct snd_soc_dapm_path *path, const char *control_name,
const struct snd_kcontrol_new *kcontrol)
{
struct soc_enum *e = (struct soc_enum *)kcontrol->private_value;
int i;
for (i = 0; i < e->max; i++) {
if (!(strcmp(control_name, e->texts[i]))) {
list_add(&path->list, &dapm->card->paths);
list_add(&path->list_sink, &dest->sources);
list_add(&path->list_source, &src->sinks);
path->name = (char*)e->texts[i];
dapm_set_path_status(dest, path, 0);
return 0;
}
}
return -ENODEV;
}
/* connect mixer widget to its interconnecting audio paths */
static int dapm_connect_mixer(struct snd_soc_dapm_context *dapm,
struct snd_soc_dapm_widget *src, struct snd_soc_dapm_widget *dest,
struct snd_soc_dapm_path *path, const char *control_name)
{
int i;
/* search for mixer kcontrol */
for (i = 0; i < dest->num_kcontrols; i++) {
if (!strcmp(control_name, dest->kcontrol_news[i].name)) {
list_add(&path->list, &dapm->card->paths);
list_add(&path->list_sink, &dest->sources);
list_add(&path->list_source, &src->sinks);
path->name = dest->kcontrol_news[i].name;
dapm_set_path_status(dest, path, i);
return 0;
}
}
return -ENODEV;
}
static int dapm_is_shared_kcontrol(struct snd_soc_dapm_context *dapm,
struct snd_soc_dapm_widget *kcontrolw,
const struct snd_kcontrol_new *kcontrol_new,
struct snd_kcontrol **kcontrol)
{
struct snd_soc_dapm_widget *w;
int i;
*kcontrol = NULL;
list_for_each_entry(w, &dapm->card->widgets, list) {
if (w == kcontrolw || w->dapm != kcontrolw->dapm)
continue;
for (i = 0; i < w->num_kcontrols; i++) {
if (&w->kcontrol_news[i] == kcontrol_new) {
if (w->kcontrols)
*kcontrol = w->kcontrols[i];
return 1;
}
}
}
return 0;
}
/* create new dapm mixer control */
static int dapm_new_mixer(struct snd_soc_dapm_widget *w)
{
struct snd_soc_dapm_context *dapm = w->dapm;
int i, ret = 0;
size_t name_len, prefix_len;
struct snd_soc_dapm_path *path;
struct snd_card *card = dapm->card->snd_card;
const char *prefix;
struct snd_soc_dapm_widget_list *wlist;
size_t wlistsize;
if (dapm->codec)
prefix = dapm->codec->name_prefix;
else
prefix = NULL;
if (prefix)
prefix_len = strlen(prefix) + 1;
else
prefix_len = 0;
/* add kcontrol */
for (i = 0; i < w->num_kcontrols; i++) {
/* match name */
list_for_each_entry(path, &w->sources, list_sink) {
/* mixer/mux paths name must match control name */
if (path->name != (char *)w->kcontrol_news[i].name)
continue;
if (w->kcontrols[i]) {
path->kcontrol = w->kcontrols[i];
continue;
}
wlistsize = sizeof(struct snd_soc_dapm_widget_list) +
sizeof(struct snd_soc_dapm_widget *),
wlist = kzalloc(wlistsize, GFP_KERNEL);
if (wlist == NULL) {
dev_err(dapm->dev,
"asoc: can't allocate widget list for %s\n",
w->name);
return -ENOMEM;
}
wlist->num_widgets = 1;
wlist->widgets[0] = w;
/* add dapm control with long name.
* for dapm_mixer this is the concatenation of the
* mixer and kcontrol name.
* for dapm_mixer_named_ctl this is simply the
* kcontrol name.
*/
name_len = strlen(w->kcontrol_news[i].name) + 1;
if (w->id != snd_soc_dapm_mixer_named_ctl)
name_len += 1 + strlen(w->name);
path->long_name = kmalloc(name_len, GFP_KERNEL);
if (path->long_name == NULL) {
kfree(wlist);
return -ENOMEM;
}
switch (w->id) {
default:
/* The control will get a prefix from
* the control creation process but
* we're also using the same prefix
* for widgets so cut the prefix off
* the front of the widget name.
*/
snprintf(path->long_name, name_len, "%s %s",
w->name + prefix_len,
w->kcontrol_news[i].name);
break;
case snd_soc_dapm_mixer_named_ctl:
snprintf(path->long_name, name_len, "%s",
w->kcontrol_news[i].name);
break;
}
path->long_name[name_len - 1] = '\0';
path->kcontrol = snd_soc_cnew(&w->kcontrol_news[i],
wlist, path->long_name,
prefix);
ret = snd_ctl_add(card, path->kcontrol);
if (ret < 0) {
dev_err(dapm->dev,
"asoc: failed to add dapm kcontrol %s: %d\n",
path->long_name, ret);
kfree(wlist);
kfree(path->long_name);
path->long_name = NULL;
return ret;
}
w->kcontrols[i] = path->kcontrol;
}
}
return ret;
}
/* create new dapm mux control */
static int dapm_new_mux(struct snd_soc_dapm_widget *w)
{
struct snd_soc_dapm_context *dapm = w->dapm;
struct snd_soc_dapm_path *path = NULL;
struct snd_kcontrol *kcontrol;
struct snd_card *card = dapm->card->snd_card;
const char *prefix;
size_t prefix_len;
int ret;
struct snd_soc_dapm_widget_list *wlist;
int shared, wlistentries;
size_t wlistsize;
char *name;
if (w->num_kcontrols != 1) {
dev_err(dapm->dev,
"asoc: mux %s has incorrect number of controls\n",
w->name);
return -EINVAL;
}
shared = dapm_is_shared_kcontrol(dapm, w, &w->kcontrol_news[0],
&kcontrol);
if (kcontrol) {
wlist = kcontrol->private_data;
wlistentries = wlist->num_widgets + 1;
} else {
wlist = NULL;
wlistentries = 1;
}
wlistsize = sizeof(struct snd_soc_dapm_widget_list) +
wlistentries * sizeof(struct snd_soc_dapm_widget *),
wlist = krealloc(wlist, wlistsize, GFP_KERNEL);
if (wlist == NULL) {
dev_err(dapm->dev,
"asoc: can't allocate widget list for %s\n", w->name);
return -ENOMEM;
}
wlist->num_widgets = wlistentries;
wlist->widgets[wlistentries - 1] = w;
if (!kcontrol) {
if (dapm->codec)
prefix = dapm->codec->name_prefix;
else
prefix = NULL;
if (shared) {
name = w->kcontrol_news[0].name;
prefix_len = 0;
} else {
name = w->name;
if (prefix)
prefix_len = strlen(prefix) + 1;
else
prefix_len = 0;
}
/*
* The control will get a prefix from the control creation
* process but we're also using the same prefix for widgets so
* cut the prefix off the front of the widget name.
*/
kcontrol = snd_soc_cnew(&w->kcontrol_news[0], wlist,
name + prefix_len, prefix);
ret = snd_ctl_add(card, kcontrol);
if (ret < 0) {
dev_err(dapm->dev, "failed to add kcontrol %s: %d\n",
w->name, ret);
kfree(wlist);
return ret;
}
}
kcontrol->private_data = wlist;
w->kcontrols[0] = kcontrol;
list_for_each_entry(path, &w->sources, list_sink)
path->kcontrol = kcontrol;
return 0;
}
/* create new dapm volume control */
static int dapm_new_pga(struct snd_soc_dapm_widget *w)
{
if (w->num_kcontrols)
dev_err(w->dapm->dev,
"asoc: PGA controls not supported: '%s'\n", w->name);
return 0;
}
/* reset 'walked' bit for each dapm path */
static inline void dapm_clear_walk(struct snd_soc_dapm_context *dapm)
{
struct snd_soc_dapm_path *p;
list_for_each_entry(p, &dapm->card->paths, list)
p->walked = 0;
}
/* We implement power down on suspend by checking the power state of
* the ALSA card - when we are suspending the ALSA state for the card
* is set to D3.
*/
static int snd_soc_dapm_suspend_check(struct snd_soc_dapm_widget *widget)
{
int level = snd_power_get_state(widget->dapm->card->snd_card);
switch (level) {
case SNDRV_CTL_POWER_D3hot:
case SNDRV_CTL_POWER_D3cold:
if (widget->ignore_suspend)
dev_dbg(widget->dapm->dev, "%s ignoring suspend\n",
widget->name);
return widget->ignore_suspend;
default:
return 1;
}
}
/*
* Recursively check for a completed path to an active or physically connected
* output widget. Returns number of complete paths.
*/
static int is_connected_output_ep(struct snd_soc_dapm_widget *widget)
{
struct snd_soc_dapm_path *path;
int con = 0;
if (widget->outputs >= 0)
return widget->outputs;
DAPM_UPDATE_STAT(widget, path_checks);
if (widget->id == snd_soc_dapm_supply)
return 0;
switch (widget->id) {
case snd_soc_dapm_adc:
case snd_soc_dapm_aif_out:
if (widget->active) {
widget->outputs = snd_soc_dapm_suspend_check(widget);
return widget->outputs;
}
default:
break;
}
if (widget->connected) {
/* connected pin ? */
if (widget->id == snd_soc_dapm_output && !widget->ext) {
widget->outputs = snd_soc_dapm_suspend_check(widget);
return widget->outputs;
}
/* connected jack or spk ? */
if (widget->id == snd_soc_dapm_hp ||
widget->id == snd_soc_dapm_spk ||
(widget->id == snd_soc_dapm_line &&
!list_empty(&widget->sources))) {
widget->outputs = snd_soc_dapm_suspend_check(widget);
return widget->outputs;
}
}
list_for_each_entry(path, &widget->sinks, list_source) {
DAPM_UPDATE_STAT(widget, neighbour_checks);
if (path->weak)
continue;
if (path->walked)
continue;
if (path->sink && path->connect) {
path->walked = 1;
con += is_connected_output_ep(path->sink);
}
}
widget->outputs = con;
return con;
}
/*
* Recursively check for a completed path to an active or physically connected
* input widget. Returns number of complete paths.
*/
static int is_connected_input_ep(struct snd_soc_dapm_widget *widget)
{
struct snd_soc_dapm_path *path;
int con = 0;
if (widget->inputs >= 0)
return widget->inputs;
DAPM_UPDATE_STAT(widget, path_checks);
if (widget->id == snd_soc_dapm_supply)
return 0;
/* active stream ? */
switch (widget->id) {
case snd_soc_dapm_dac:
case snd_soc_dapm_aif_in:
if (widget->active) {
widget->inputs = snd_soc_dapm_suspend_check(widget);
return widget->inputs;
}
default:
break;
}
if (widget->connected) {
/* connected pin ? */
if (widget->id == snd_soc_dapm_input && !widget->ext) {
widget->inputs = snd_soc_dapm_suspend_check(widget);
return widget->inputs;
}
/* connected VMID/Bias for lower pops */
if (widget->id == snd_soc_dapm_vmid) {
widget->inputs = snd_soc_dapm_suspend_check(widget);
return widget->inputs;
}
/* connected jack ? */
if (widget->id == snd_soc_dapm_mic ||
(widget->id == snd_soc_dapm_line &&
!list_empty(&widget->sinks))) {
widget->inputs = snd_soc_dapm_suspend_check(widget);
return widget->inputs;
}
}
list_for_each_entry(path, &widget->sources, list_sink) {
DAPM_UPDATE_STAT(widget, neighbour_checks);
if (path->weak)
continue;
if (path->walked)
continue;
if (path->source && path->connect) {
path->walked = 1;
con += is_connected_input_ep(path->source);
}
}
widget->inputs = con;
return con;
}
/*
* Handler for generic register modifier widget.
*/
int dapm_reg_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
unsigned int val;
if (SND_SOC_DAPM_EVENT_ON(event))
val = w->on_val;
else
val = w->off_val;
soc_widget_update_bits(w, -(w->reg + 1),
w->mask << w->shift, val << w->shift);
return 0;
}
EXPORT_SYMBOL_GPL(dapm_reg_event);
static int dapm_widget_power_check(struct snd_soc_dapm_widget *w)
{
if (w->power_checked)
return w->new_power;
if (w->force)
w->new_power = 1;
else
w->new_power = w->power_check(w);
w->power_checked = true;
return w->new_power;
}
/* Generic check to see if a widget should be powered.
*/
static int dapm_generic_check_power(struct snd_soc_dapm_widget *w)
{
int in, out;
DAPM_UPDATE_STAT(w, power_checks);
in = is_connected_input_ep(w);
dapm_clear_walk(w->dapm);
out = is_connected_output_ep(w);
dapm_clear_walk(w->dapm);
return out != 0 && in != 0;
}
/* Check to see if an ADC has power */
static int dapm_adc_check_power(struct snd_soc_dapm_widget *w)
{
int in;
DAPM_UPDATE_STAT(w, power_checks);
if (w->active) {
in = is_connected_input_ep(w);
dapm_clear_walk(w->dapm);
return in != 0;
} else {
return dapm_generic_check_power(w);
}
}
/* Check to see if a DAC has power */
static int dapm_dac_check_power(struct snd_soc_dapm_widget *w)
{
int out;
DAPM_UPDATE_STAT(w, power_checks);
if (w->active) {
out = is_connected_output_ep(w);
dapm_clear_walk(w->dapm);
return out != 0;
} else {
return dapm_generic_check_power(w);
}
}
/* Check to see if a power supply is needed */
static int dapm_supply_check_power(struct snd_soc_dapm_widget *w)
{
struct snd_soc_dapm_path *path;
DAPM_UPDATE_STAT(w, power_checks);
/* Check if one of our outputs is connected */
list_for_each_entry(path, &w->sinks, list_source) {
DAPM_UPDATE_STAT(w, neighbour_checks);
if (path->weak)
continue;
if (path->connected &&
!path->connected(path->source, path->sink))
continue;
if (!path->sink)
continue;
if (dapm_widget_power_check(path->sink))
return 1;
}
dapm_clear_walk(w->dapm);
return 0;
}
static int dapm_always_on_check_power(struct snd_soc_dapm_widget *w)
{
return 1;
}
static int dapm_seq_compare(struct snd_soc_dapm_widget *a,
struct snd_soc_dapm_widget *b,
bool power_up)
{
int *sort;
if (power_up)
sort = dapm_up_seq;
else
sort = dapm_down_seq;
if (sort[a->id] != sort[b->id])
return sort[a->id] - sort[b->id];
if (a->subseq != b->subseq) {
if (power_up)
return a->subseq - b->subseq;
else
return b->subseq - a->subseq;
}
if (a->reg != b->reg)
return a->reg - b->reg;
if (a->dapm != b->dapm)
return (unsigned long)a->dapm - (unsigned long)b->dapm;
return 0;
}
/* Insert a widget in order into a DAPM power sequence. */
static void dapm_seq_insert(struct snd_soc_dapm_widget *new_widget,
struct list_head *list,
bool power_up)
{
struct snd_soc_dapm_widget *w;
list_for_each_entry(w, list, power_list)
if (dapm_seq_compare(new_widget, w, power_up) < 0) {
list_add_tail(&new_widget->power_list, &w->power_list);
return;
}
list_add_tail(&new_widget->power_list, list);
}
static void dapm_seq_check_event(struct snd_soc_dapm_context *dapm,
struct snd_soc_dapm_widget *w, int event)
{
struct snd_soc_card *card = dapm->card;
const char *ev_name;
int power, ret;
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
ev_name = "PRE_PMU";
power = 1;
break;
case SND_SOC_DAPM_POST_PMU:
ev_name = "POST_PMU";
power = 1;
break;
case SND_SOC_DAPM_PRE_PMD:
ev_name = "PRE_PMD";
power = 0;
break;
case SND_SOC_DAPM_POST_PMD:
ev_name = "POST_PMD";
power = 0;
break;
default:
BUG();
return;
}
if (w->power != power)
return;
if (w->event && (w->event_flags & event)) {
pop_dbg(dapm->dev, card->pop_time, "pop test : %s %s\n",
w->name, ev_name);
trace_snd_soc_dapm_widget_event_start(w, event);
ret = w->event(w, NULL, event);
trace_snd_soc_dapm_widget_event_done(w, event);
if (ret < 0)
pr_err("%s: %s event failed: %d\n",
ev_name, w->name, ret);
}
}
/* Apply the coalesced changes from a DAPM sequence */
static void dapm_seq_run_coalesced(struct snd_soc_dapm_context *dapm,
struct list_head *pending)
{
struct snd_soc_card *card = dapm->card;
struct snd_soc_dapm_widget *w;
int reg, power;
unsigned int value = 0;
unsigned int mask = 0;
unsigned int cur_mask;
reg = list_first_entry(pending, struct snd_soc_dapm_widget,
power_list)->reg;
list_for_each_entry(w, pending, power_list) {
cur_mask = 1 << w->shift;
BUG_ON(reg != w->reg);
if (w->invert)
power = !w->power;
else
power = w->power;
mask |= cur_mask;
if (power)
value |= cur_mask;
pop_dbg(dapm->dev, card->pop_time,
"pop test : Queue %s: reg=0x%x, 0x%x/0x%x\n",
w->name, reg, value, mask);
/* Check for events */
dapm_seq_check_event(dapm, w, SND_SOC_DAPM_PRE_PMU);
dapm_seq_check_event(dapm, w, SND_SOC_DAPM_PRE_PMD);
}
if (reg >= 0) {
/* Any widget will do, they should all be updating the
* same register.
*/
w = list_first_entry(pending, struct snd_soc_dapm_widget,
power_list);
pop_dbg(dapm->dev, card->pop_time,
"pop test : Applying 0x%x/0x%x to %x in %dms\n",
value, mask, reg, card->pop_time);
pop_wait(card->pop_time);
soc_widget_update_bits(w, reg, mask, value);
}
list_for_each_entry(w, pending, power_list) {
dapm_seq_check_event(dapm, w, SND_SOC_DAPM_POST_PMU);
dapm_seq_check_event(dapm, w, SND_SOC_DAPM_POST_PMD);
}
}
/* Apply a DAPM power sequence.
*
* We walk over a pre-sorted list of widgets to apply power to. In
* order to minimise the number of writes to the device required
* multiple widgets will be updated in a single write where possible.
* Currently anything that requires more than a single write is not
* handled.
*/
static void dapm_seq_run(struct snd_soc_dapm_context *dapm,
struct list_head *list, int event, bool power_up)
{
struct snd_soc_dapm_widget *w, *n;
LIST_HEAD(pending);
int cur_sort = -1;
int cur_subseq = -1;
int cur_reg = SND_SOC_NOPM;
struct snd_soc_dapm_context *cur_dapm = NULL;
int ret, i;
int *sort;
if (power_up)
sort = dapm_up_seq;
else
sort = dapm_down_seq;
list_for_each_entry_safe(w, n, list, power_list) {
ret = 0;
/* Do we need to apply any queued changes? */
if (sort[w->id] != cur_sort || w->reg != cur_reg ||
w->dapm != cur_dapm || w->subseq != cur_subseq) {
if (!list_empty(&pending))
dapm_seq_run_coalesced(cur_dapm, &pending);
if (cur_dapm && cur_dapm->seq_notifier) {
for (i = 0; i < ARRAY_SIZE(dapm_up_seq); i++)
if (sort[i] == cur_sort)
cur_dapm->seq_notifier(cur_dapm,
i,
cur_subseq);
}
INIT_LIST_HEAD(&pending);
cur_sort = -1;
cur_subseq = INT_MIN;
cur_reg = SND_SOC_NOPM;
cur_dapm = NULL;
}
switch (w->id) {
case snd_soc_dapm_pre:
if (!w->event)
list_for_each_entry_safe_continue(w, n, list,
power_list);
if (event == SND_SOC_DAPM_STREAM_START)
ret = w->event(w,
NULL, SND_SOC_DAPM_PRE_PMU);
else if (event == SND_SOC_DAPM_STREAM_STOP)
ret = w->event(w,
NULL, SND_SOC_DAPM_PRE_PMD);
break;
case snd_soc_dapm_post:
if (!w->event)
list_for_each_entry_safe_continue(w, n, list,
power_list);
if (event == SND_SOC_DAPM_STREAM_START)
ret = w->event(w,
NULL, SND_SOC_DAPM_POST_PMU);
else if (event == SND_SOC_DAPM_STREAM_STOP)
ret = w->event(w,
NULL, SND_SOC_DAPM_POST_PMD);
break;
default:
/* Queue it up for application */
cur_sort = sort[w->id];
cur_subseq = w->subseq;
cur_reg = w->reg;
cur_dapm = w->dapm;
list_move(&w->power_list, &pending);
break;
}
if (ret < 0)
dev_err(w->dapm->dev,
"Failed to apply widget power: %d\n", ret);
}
if (!list_empty(&pending))
dapm_seq_run_coalesced(cur_dapm, &pending);
if (cur_dapm && cur_dapm->seq_notifier) {
for (i = 0; i < ARRAY_SIZE(dapm_up_seq); i++)
if (sort[i] == cur_sort)
cur_dapm->seq_notifier(cur_dapm,
i, cur_subseq);
}
}
static void dapm_widget_update(struct snd_soc_dapm_context *dapm)
{
struct snd_soc_dapm_update *update = dapm->update;
struct snd_soc_dapm_widget *w;
int ret;
if (!update)
return;
w = update->widget;
if (w->event &&
(w->event_flags & SND_SOC_DAPM_PRE_REG)) {
ret = w->event(w, update->kcontrol, SND_SOC_DAPM_PRE_REG);
if (ret != 0)
pr_err("%s DAPM pre-event failed: %d\n",
w->name, ret);
}
ret = snd_soc_update_bits(w->codec, update->reg, update->mask,
update->val);
if (ret < 0)
pr_err("%s DAPM update failed: %d\n", w->name, ret);
if (w->event &&
(w->event_flags & SND_SOC_DAPM_POST_REG)) {
ret = w->event(w, update->kcontrol, SND_SOC_DAPM_POST_REG);
if (ret != 0)
pr_err("%s DAPM post-event failed: %d\n",
w->name, ret);
}
}
/* Async callback run prior to DAPM sequences - brings to _PREPARE if
* they're changing state.
*/
static void dapm_pre_sequence_async(void *data, async_cookie_t cookie)
{
struct snd_soc_dapm_context *d = data;
int ret;
/* If we're off and we're not supposed to be go into STANDBY */
if (d->bias_level == SND_SOC_BIAS_OFF &&
d->target_bias_level != SND_SOC_BIAS_OFF) {
ret = snd_soc_dapm_set_bias_level(d, SND_SOC_BIAS_STANDBY);
if (ret != 0)
dev_err(d->dev,
"Failed to turn on bias: %d\n", ret);
}
/* Prepare for a STADDBY->ON or ON->STANDBY transition */
if (d->bias_level != d->target_bias_level) {
ret = snd_soc_dapm_set_bias_level(d, SND_SOC_BIAS_PREPARE);
if (ret != 0)
dev_err(d->dev,
"Failed to prepare bias: %d\n", ret);
}
}
/* Async callback run prior to DAPM sequences - brings to their final
* state.
*/
static void dapm_post_sequence_async(void *data, async_cookie_t cookie)
{
struct snd_soc_dapm_context *d = data;
int ret;
/* If we just powered the last thing off drop to standby bias */
if (d->bias_level == SND_SOC_BIAS_PREPARE &&
(d->target_bias_level == SND_SOC_BIAS_STANDBY ||
d->target_bias_level == SND_SOC_BIAS_OFF)) {
ret = snd_soc_dapm_set_bias_level(d, SND_SOC_BIAS_STANDBY);
if (ret != 0)
dev_err(d->dev, "Failed to apply standby bias: %d\n",
ret);
}
/* If we're in standby and can support bias off then do that */
if (d->bias_level == SND_SOC_BIAS_STANDBY &&
d->target_bias_level == SND_SOC_BIAS_OFF) {
ret = snd_soc_dapm_set_bias_level(d, SND_SOC_BIAS_OFF);
if (ret != 0)
dev_err(d->dev, "Failed to turn off bias: %d\n", ret);
}
/* If we just powered up then move to active bias */
if (d->bias_level == SND_SOC_BIAS_PREPARE &&
d->target_bias_level == SND_SOC_BIAS_ON) {
ret = snd_soc_dapm_set_bias_level(d, SND_SOC_BIAS_ON);
if (ret != 0)
dev_err(d->dev, "Failed to apply active bias: %d\n",
ret);
}
}
static void dapm_widget_set_peer_power(struct snd_soc_dapm_widget *peer,
bool power, bool connect)
{
/* If a connection is being made or broken then that update
* will have marked the peer dirty, otherwise the widgets are
* not connected and this update has no impact. */
if (!connect)
return;
/* If the peer is already in the state we're moving to then we
* won't have an impact on it. */
if (power != peer->power)
dapm_mark_dirty(peer, "peer state change");
}
static void dapm_widget_set_power(struct snd_soc_dapm_widget *w, bool power,
struct list_head *up_list,
struct list_head *down_list)
{
struct snd_soc_dapm_path *path;
if (w->power == power)
return;
trace_snd_soc_dapm_widget_power(w, power);
/* If we changed our power state perhaps our neigbours changed
* also.
*/
list_for_each_entry(path, &w->sources, list_sink) {
if (path->source) {
dapm_widget_set_peer_power(path->source, power,
path->connect);
}
}
switch (w->id) {
case snd_soc_dapm_supply:
/* Supplies can't affect their outputs, only their inputs */
break;
default:
list_for_each_entry(path, &w->sinks, list_source) {
if (path->sink) {
dapm_widget_set_peer_power(path->sink, power,
path->connect);
}
}
break;
}
if (power)
dapm_seq_insert(w, up_list, true);
else
dapm_seq_insert(w, down_list, false);
w->power = power;
}
static void dapm_power_one_widget(struct snd_soc_dapm_widget *w,
struct list_head *up_list,
struct list_head *down_list)
{
int power;
switch (w->id) {
case snd_soc_dapm_pre:
dapm_seq_insert(w, down_list, false);
break;
case snd_soc_dapm_post:
dapm_seq_insert(w, up_list, true);
break;
default:
power = dapm_widget_power_check(w);
dapm_widget_set_power(w, power, up_list, down_list);
break;
}
}
/*
* Scan each dapm widget for complete audio path.
* A complete path is a route that has valid endpoints i.e.:-
*
* o DAC to output pin.
* o Input Pin to ADC.
* o Input pin to Output pin (bypass, sidetone)
* o DAC to ADC (loopback).
*/
static int dapm_power_widgets(struct snd_soc_dapm_context *dapm, int event)
{
struct snd_soc_card *card = dapm->card;
struct snd_soc_dapm_widget *w;
struct snd_soc_dapm_context *d;
LIST_HEAD(up_list);
LIST_HEAD(down_list);
LIST_HEAD(async_domain);
enum snd_soc_bias_level bias;
trace_snd_soc_dapm_start(card);
list_for_each_entry(d, &card->dapm_list, list) {
if (d->n_widgets || d->codec == NULL) {
if (d->idle_bias_off)
d->target_bias_level = SND_SOC_BIAS_OFF;
else
d->target_bias_level = SND_SOC_BIAS_STANDBY;
}
}
memset(&card->dapm_stats, 0, sizeof(card->dapm_stats));
list_for_each_entry(w, &card->widgets, list) {
w->power_checked = false;
w->inputs = -1;
w->outputs = -1;
}
/* Check which widgets we need to power and store them in
* lists indicating if they should be powered up or down. We
* only check widgets that have been flagged as dirty but note
* that new widgets may be added to the dirty list while we
* iterate.
*/
list_for_each_entry(w, &card->dapm_dirty, dirty) {
dapm_power_one_widget(w, &up_list, &down_list);
}
list_for_each_entry(w, &card->widgets, list) {
list_del_init(&w->dirty);
if (w->power) {
d = w->dapm;
/* Supplies and micbiases only bring the
* context up to STANDBY as unless something
* else is active and passing audio they
* generally don't require full power.
*/
switch (w->id) {
case snd_soc_dapm_supply:
case snd_soc_dapm_micbias:
if (d->target_bias_level < SND_SOC_BIAS_STANDBY)
d->target_bias_level = SND_SOC_BIAS_STANDBY;
break;
default:
d->target_bias_level = SND_SOC_BIAS_ON;
break;
}
}
}
/* If there are no DAPM widgets then try to figure out power from the
* event type.
*/
if (!dapm->n_widgets) {
switch (event) {
case SND_SOC_DAPM_STREAM_START:
case SND_SOC_DAPM_STREAM_RESUME:
dapm->target_bias_level = SND_SOC_BIAS_ON;
break;
case SND_SOC_DAPM_STREAM_STOP:
if (dapm->codec->active)
dapm->target_bias_level = SND_SOC_BIAS_ON;
else
dapm->target_bias_level = SND_SOC_BIAS_STANDBY;
break;
case SND_SOC_DAPM_STREAM_SUSPEND:
dapm->target_bias_level = SND_SOC_BIAS_STANDBY;
break;
case SND_SOC_DAPM_STREAM_NOP:
dapm->target_bias_level = dapm->bias_level;
break;
default:
break;
}
}
/* Force all contexts in the card to the same bias state if
* they're not ground referenced.
*/
bias = SND_SOC_BIAS_OFF;
list_for_each_entry(d, &card->dapm_list, list)
if (d->target_bias_level > bias)
bias = d->target_bias_level;
list_for_each_entry(d, &card->dapm_list, list)
if (!d->idle_bias_off)
d->target_bias_level = bias;
trace_snd_soc_dapm_walk_done(card);
/* Run all the bias changes in parallel */
list_for_each_entry(d, &dapm->card->dapm_list, list)
async_schedule_domain(dapm_pre_sequence_async, d,
&async_domain);
async_synchronize_full_domain(&async_domain);
/* Power down widgets first; try to avoid amplifying pops. */
dapm_seq_run(dapm, &down_list, event, false);
dapm_widget_update(dapm);
/* Now power up. */
dapm_seq_run(dapm, &up_list, event, true);
/* Run all the bias changes in parallel */
list_for_each_entry(d, &dapm->card->dapm_list, list)
async_schedule_domain(dapm_post_sequence_async, d,
&async_domain);
async_synchronize_full_domain(&async_domain);
pop_dbg(dapm->dev, card->pop_time,
"DAPM sequencing finished, waiting %dms\n", card->pop_time);
pop_wait(card->pop_time);
trace_snd_soc_dapm_done(card);
return 0;
}
#ifdef CONFIG_DEBUG_FS
static int dapm_widget_power_open_file(struct inode *inode, struct file *file)
{
file->private_data = inode->i_private;
return 0;
}
static ssize_t dapm_widget_power_read_file(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
struct snd_soc_dapm_widget *w = file->private_data;
char *buf;
int in, out;
ssize_t ret;
struct snd_soc_dapm_path *p = NULL;
buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
if (!buf)
return -ENOMEM;
in = is_connected_input_ep(w);
dapm_clear_walk(w->dapm);
out = is_connected_output_ep(w);
dapm_clear_walk(w->dapm);
ret = snprintf(buf, PAGE_SIZE, "%s: %s in %d out %d",
w->name, w->power ? "On" : "Off", in, out);
if (w->reg >= 0)
ret += snprintf(buf + ret, PAGE_SIZE - ret,
" - R%d(0x%x) bit %d",
w->reg, w->reg, w->shift);
ret += snprintf(buf + ret, PAGE_SIZE - ret, "\n");
if (w->sname)
ret += snprintf(buf + ret, PAGE_SIZE - ret, " stream %s %s\n",
w->sname,
w->active ? "active" : "inactive");
list_for_each_entry(p, &w->sources, list_sink) {
if (p->connected && !p->connected(w, p->sink))
continue;
if (p->connect)
ret += snprintf(buf + ret, PAGE_SIZE - ret,
" in \"%s\" \"%s\"\n",
p->name ? p->name : "static",
p->source->name);
}
list_for_each_entry(p, &w->sinks, list_source) {
if (p->connected && !p->connected(w, p->sink))
continue;
if (p->connect)
ret += snprintf(buf + ret, PAGE_SIZE - ret,
" out \"%s\" \"%s\"\n",
p->name ? p->name : "static",
p->sink->name);
}
ret = simple_read_from_buffer(user_buf, count, ppos, buf, ret);
kfree(buf);
return ret;
}
static const struct file_operations dapm_widget_power_fops = {
.open = dapm_widget_power_open_file,
.read = dapm_widget_power_read_file,
.llseek = default_llseek,
};
static int dapm_bias_open_file(struct inode *inode, struct file *file)
{
file->private_data = inode->i_private;
return 0;
}
static ssize_t dapm_bias_read_file(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct snd_soc_dapm_context *dapm = file->private_data;
char *level;
switch (dapm->bias_level) {
case SND_SOC_BIAS_ON:
level = "On\n";
break;
case SND_SOC_BIAS_PREPARE:
level = "Prepare\n";
break;
case SND_SOC_BIAS_STANDBY:
level = "Standby\n";
break;
case SND_SOC_BIAS_OFF:
level = "Off\n";
break;
default:
BUG();
level = "Unknown\n";
break;
}
return simple_read_from_buffer(user_buf, count, ppos, level,
strlen(level));
}
static const struct file_operations dapm_bias_fops = {
.open = dapm_bias_open_file,
.read = dapm_bias_read_file,
.llseek = default_llseek,
};
void snd_soc_dapm_debugfs_init(struct snd_soc_dapm_context *dapm,
struct dentry *parent)
{
struct dentry *d;
dapm->debugfs_dapm = debugfs_create_dir("dapm", parent);
if (!dapm->debugfs_dapm) {
printk(KERN_WARNING
"Failed to create DAPM debugfs directory\n");
return;
}
d = debugfs_create_file("bias_level", 0444,
dapm->debugfs_dapm, dapm,
&dapm_bias_fops);
if (!d)
dev_warn(dapm->dev,
"ASoC: Failed to create bias level debugfs file\n");
}
static void dapm_debugfs_add_widget(struct snd_soc_dapm_widget *w)
{
struct snd_soc_dapm_context *dapm = w->dapm;
struct dentry *d;
if (!dapm->debugfs_dapm || !w->name)
return;
d = debugfs_create_file(w->name, 0444,
dapm->debugfs_dapm, w,
&dapm_widget_power_fops);
if (!d)
dev_warn(w->dapm->dev,
"ASoC: Failed to create %s debugfs file\n",
w->name);
}
static void dapm_debugfs_cleanup(struct snd_soc_dapm_context *dapm)
{
debugfs_remove_recursive(dapm->debugfs_dapm);
}
#else
void snd_soc_dapm_debugfs_init(struct snd_soc_dapm_context *dapm,
struct dentry *parent)
{
}
static inline void dapm_debugfs_add_widget(struct snd_soc_dapm_widget *w)
{
}
static inline void dapm_debugfs_cleanup(struct snd_soc_dapm_context *dapm)
{
}
#endif
/* test and update the power status of a mux widget */
static int dapm_mux_update_power(struct snd_soc_dapm_widget *widget,
struct snd_kcontrol *kcontrol, int change,
int mux, struct soc_enum *e)
{
struct snd_soc_dapm_path *path;
int found = 0;
if (widget->id != snd_soc_dapm_mux &&
widget->id != snd_soc_dapm_virt_mux &&
widget->id != snd_soc_dapm_value_mux)
return -ENODEV;
if (!change)
return 0;
/* find dapm widget path assoc with kcontrol */
list_for_each_entry(path, &widget->dapm->card->paths, list) {
if (path->kcontrol != kcontrol)
continue;
if (!path->name || !e->texts[mux])
continue;
found = 1;
/* we now need to match the string in the enum to the path */
if (!(strcmp(path->name, e->texts[mux]))) {
path->connect = 1; /* new connection */
dapm_mark_dirty(path->source, "mux connection");
} else {
if (path->connect)
dapm_mark_dirty(path->source,
"mux disconnection");
path->connect = 0; /* old connection must be powered down */
}
}
if (found) {
dapm_mark_dirty(widget, "mux change");
dapm_power_widgets(widget->dapm, SND_SOC_DAPM_STREAM_NOP);
}
return 0;
}
/* test and update the power status of a mixer or switch widget */
static int dapm_mixer_update_power(struct snd_soc_dapm_widget *widget,
struct snd_kcontrol *kcontrol, int connect)
{
struct snd_soc_dapm_path *path;
int found = 0;
if (widget->id != snd_soc_dapm_mixer &&
widget->id != snd_soc_dapm_mixer_named_ctl &&
widget->id != snd_soc_dapm_switch)
return -ENODEV;
/* find dapm widget path assoc with kcontrol */
list_for_each_entry(path, &widget->dapm->card->paths, list) {
if (path->kcontrol != kcontrol)
continue;
/* found, now check type */
found = 1;
path->connect = connect;
dapm_mark_dirty(path->source, "mixer connection");
}
if (found) {
dapm_mark_dirty(widget, "mixer update");
dapm_power_widgets(widget->dapm, SND_SOC_DAPM_STREAM_NOP);
}
return 0;
}
/* show dapm widget status in sys fs */
static ssize_t dapm_widget_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct snd_soc_pcm_runtime *rtd =
container_of(dev, struct snd_soc_pcm_runtime, dev);
struct snd_soc_codec *codec =rtd->codec;
struct snd_soc_dapm_widget *w;
int count = 0;
char *state = "not set";
list_for_each_entry(w, &codec->card->widgets, list) {
if (w->dapm != &codec->dapm)
continue;
/* only display widgets that burnm power */
switch (w->id) {
case snd_soc_dapm_hp:
case snd_soc_dapm_mic:
case snd_soc_dapm_spk:
case snd_soc_dapm_line:
case snd_soc_dapm_micbias:
case snd_soc_dapm_dac:
case snd_soc_dapm_adc:
case snd_soc_dapm_pga:
case snd_soc_dapm_out_drv:
case snd_soc_dapm_mixer:
case snd_soc_dapm_mixer_named_ctl:
case snd_soc_dapm_supply:
if (w->name)
count += sprintf(buf + count, "%s: %s\n",
w->name, w->power ? "On":"Off");
break;
default:
break;
}
}
switch (codec->dapm.bias_level) {
case SND_SOC_BIAS_ON:
state = "On";
break;
case SND_SOC_BIAS_PREPARE:
state = "Prepare";
break;
case SND_SOC_BIAS_STANDBY:
state = "Standby";
break;
case SND_SOC_BIAS_OFF:
state = "Off";
break;
}
count += sprintf(buf + count, "PM State: %s\n", state);
return count;
}
static DEVICE_ATTR(dapm_widget, 0444, dapm_widget_show, NULL);
int snd_soc_dapm_sys_add(struct device *dev)
{
return device_create_file(dev, &dev_attr_dapm_widget);
}
static void snd_soc_dapm_sys_remove(struct device *dev)
{
device_remove_file(dev, &dev_attr_dapm_widget);
}
/* free all dapm widgets and resources */
static void dapm_free_widgets(struct snd_soc_dapm_context *dapm)
{
struct snd_soc_dapm_widget *w, *next_w;
struct snd_soc_dapm_path *p, *next_p;
list_for_each_entry_safe(w, next_w, &dapm->card->widgets, list) {
if (w->dapm != dapm)
continue;
list_del(&w->list);
/*
* remove source and sink paths associated to this widget.
* While removing the path, remove reference to it from both
* source and sink widgets so that path is removed only once.
*/
list_for_each_entry_safe(p, next_p, &w->sources, list_sink) {
list_del(&p->list_sink);
list_del(&p->list_source);
list_del(&p->list);
kfree(p->long_name);
kfree(p);
}
list_for_each_entry_safe(p, next_p, &w->sinks, list_source) {
list_del(&p->list_sink);
list_del(&p->list_source);
list_del(&p->list);
kfree(p->long_name);
kfree(p);
}
kfree(w->kcontrols);
kfree(w->name);
kfree(w);
}
}
static struct snd_soc_dapm_widget *dapm_find_widget(
struct snd_soc_dapm_context *dapm, const char *pin,
bool search_other_contexts)
{
struct snd_soc_dapm_widget *w;
struct snd_soc_dapm_widget *fallback = NULL;
list_for_each_entry(w, &dapm->card->widgets, list) {
if (!strcmp(w->name, pin)) {
if (w->dapm == dapm)
return w;
else
fallback = w;
}
}
if (search_other_contexts)
return fallback;
return NULL;
}
static int snd_soc_dapm_set_pin(struct snd_soc_dapm_context *dapm,
const char *pin, int status)
{
struct snd_soc_dapm_widget *w = dapm_find_widget(dapm, pin, true);
if (!w) {
dev_err(dapm->dev, "dapm: unknown pin %s\n", pin);
return -EINVAL;
}
w->connected = status;
if (status == 0)
w->force = 0;
dapm_mark_dirty(w, "pin configuration");
return 0;
}
/**
* snd_soc_dapm_sync - scan and power dapm paths
* @dapm: DAPM context
*
* Walks all dapm audio paths and powers widgets according to their
* stream or path usage.
*
* Returns 0 for success.
*/
int snd_soc_dapm_sync(struct snd_soc_dapm_context *dapm)
{
/*
* Suppress early reports (eg, jacks syncing their state) to avoid
* silly DAPM runs during card startup.
*/
if (!dapm->card || !dapm->card->instantiated)
return 0;
return dapm_power_widgets(dapm, SND_SOC_DAPM_STREAM_NOP);
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_sync);
static int snd_soc_dapm_add_route(struct snd_soc_dapm_context *dapm,
const struct snd_soc_dapm_route *route)
{
struct snd_soc_dapm_path *path;
struct snd_soc_dapm_widget *wsource = NULL, *wsink = NULL, *w;
struct snd_soc_dapm_widget *wtsource = NULL, *wtsink = NULL;
const char *sink;
const char *control = route->control;
const char *source;
char prefixed_sink[80];
char prefixed_source[80];
int ret = 0;
if (dapm->codec && dapm->codec->name_prefix) {
snprintf(prefixed_sink, sizeof(prefixed_sink), "%s %s",
dapm->codec->name_prefix, route->sink);
sink = prefixed_sink;
snprintf(prefixed_source, sizeof(prefixed_source), "%s %s",
dapm->codec->name_prefix, route->source);
source = prefixed_source;
} else {
sink = route->sink;
source = route->source;
}
/*
* find src and dest widgets over all widgets but favor a widget from
* current DAPM context
*/
list_for_each_entry(w, &dapm->card->widgets, list) {
if (!wsink && !(strcmp(w->name, sink))) {
wtsink = w;
if (w->dapm == dapm)
wsink = w;
continue;
}
if (!wsource && !(strcmp(w->name, source))) {
wtsource = w;
if (w->dapm == dapm)
wsource = w;
}
}
/* use widget from another DAPM context if not found from this */
if (!wsink)
wsink = wtsink;
if (!wsource)
wsource = wtsource;
if (wsource == NULL || wsink == NULL)
return -ENODEV;
path = kzalloc(sizeof(struct snd_soc_dapm_path), GFP_KERNEL);
if (!path)
return -ENOMEM;
path->source = wsource;
path->sink = wsink;
path->connected = route->connected;
INIT_LIST_HEAD(&path->list);
INIT_LIST_HEAD(&path->list_source);
INIT_LIST_HEAD(&path->list_sink);
/* check for external widgets */
if (wsink->id == snd_soc_dapm_input) {
if (wsource->id == snd_soc_dapm_micbias ||
wsource->id == snd_soc_dapm_mic ||
wsource->id == snd_soc_dapm_line ||
wsource->id == snd_soc_dapm_output)
wsink->ext = 1;
}
if (wsource->id == snd_soc_dapm_output) {
if (wsink->id == snd_soc_dapm_spk ||
wsink->id == snd_soc_dapm_hp ||
wsink->id == snd_soc_dapm_line ||
wsink->id == snd_soc_dapm_input)
wsource->ext = 1;
}
/* connect static paths */
if (control == NULL) {
list_add(&path->list, &dapm->card->paths);
list_add(&path->list_sink, &wsink->sources);
list_add(&path->list_source, &wsource->sinks);
path->connect = 1;
return 0;
}
/* connect dynamic paths */
switch (wsink->id) {
case snd_soc_dapm_adc:
case snd_soc_dapm_dac:
case snd_soc_dapm_pga:
case snd_soc_dapm_out_drv:
case snd_soc_dapm_input:
case snd_soc_dapm_output:
case snd_soc_dapm_micbias:
case snd_soc_dapm_vmid:
case snd_soc_dapm_pre:
case snd_soc_dapm_post:
case snd_soc_dapm_supply:
case snd_soc_dapm_aif_in:
case snd_soc_dapm_aif_out:
list_add(&path->list, &dapm->card->paths);
list_add(&path->list_sink, &wsink->sources);
list_add(&path->list_source, &wsource->sinks);
path->connect = 1;
return 0;
case snd_soc_dapm_mux:
case snd_soc_dapm_virt_mux:
case snd_soc_dapm_value_mux:
ret = dapm_connect_mux(dapm, wsource, wsink, path, control,
&wsink->kcontrol_news[0]);
if (ret != 0)
goto err;
break;
case snd_soc_dapm_switch:
case snd_soc_dapm_mixer:
case snd_soc_dapm_mixer_named_ctl:
ret = dapm_connect_mixer(dapm, wsource, wsink, path, control);
if (ret != 0)
goto err;
break;
case snd_soc_dapm_hp:
case snd_soc_dapm_mic:
case snd_soc_dapm_line:
case snd_soc_dapm_spk:
list_add(&path->list, &dapm->card->paths);
list_add(&path->list_sink, &wsink->sources);
list_add(&path->list_source, &wsource->sinks);
path->connect = 0;
return 0;
}
return 0;
err:
dev_warn(dapm->dev, "asoc: no dapm match for %s --> %s --> %s\n",
source, control, sink);
kfree(path);
return ret;
}
/**
* snd_soc_dapm_add_routes - Add routes between DAPM widgets
* @dapm: DAPM context
* @route: audio routes
* @num: number of routes
*
* Connects 2 dapm widgets together via a named audio path. The sink is
* the widget receiving the audio signal, whilst the source is the sender
* of the audio signal.
*
* Returns 0 for success else error. On error all resources can be freed
* with a call to snd_soc_card_free().
*/
int snd_soc_dapm_add_routes(struct snd_soc_dapm_context *dapm,
const struct snd_soc_dapm_route *route, int num)
{
int i, ret;
for (i = 0; i < num; i++) {
ret = snd_soc_dapm_add_route(dapm, route);
if (ret < 0) {
dev_err(dapm->dev, "Failed to add route %s->%s\n",
route->source, route->sink);
return ret;
}
route++;
}
return 0;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_add_routes);
static int snd_soc_dapm_weak_route(struct snd_soc_dapm_context *dapm,
const struct snd_soc_dapm_route *route)
{
struct snd_soc_dapm_widget *source = dapm_find_widget(dapm,
route->source,
true);
struct snd_soc_dapm_widget *sink = dapm_find_widget(dapm,
route->sink,
true);
struct snd_soc_dapm_path *path;
int count = 0;
if (!source) {
dev_err(dapm->dev, "Unable to find source %s for weak route\n",
route->source);
return -ENODEV;
}
if (!sink) {
dev_err(dapm->dev, "Unable to find sink %s for weak route\n",
route->sink);
return -ENODEV;
}
if (route->control || route->connected)
dev_warn(dapm->dev, "Ignoring control for weak route %s->%s\n",
route->source, route->sink);
list_for_each_entry(path, &source->sinks, list_source) {
if (path->sink == sink) {
path->weak = 1;
count++;
}
}
if (count == 0)
dev_err(dapm->dev, "No path found for weak route %s->%s\n",
route->source, route->sink);
if (count > 1)
dev_warn(dapm->dev, "%d paths found for weak route %s->%s\n",
count, route->source, route->sink);
return 0;
}
/**
* snd_soc_dapm_weak_routes - Mark routes between DAPM widgets as weak
* @dapm: DAPM context
* @route: audio routes
* @num: number of routes
*
* Mark existing routes matching those specified in the passed array
* as being weak, meaning that they are ignored for the purpose of
* power decisions. The main intended use case is for sidetone paths
* which couple audio between other independent paths if they are both
* active in order to make the combination work better at the user
* level but which aren't intended to be "used".
*
* Note that CODEC drivers should not use this as sidetone type paths
* can frequently also be used as bypass paths.
*/
int snd_soc_dapm_weak_routes(struct snd_soc_dapm_context *dapm,
const struct snd_soc_dapm_route *route, int num)
{
int i, err;
int ret = 0;
for (i = 0; i < num; i++) {
err = snd_soc_dapm_weak_route(dapm, route);
if (err)
ret = err;
route++;
}
return ret;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_weak_routes);
/**
* snd_soc_dapm_new_widgets - add new dapm widgets
* @dapm: DAPM context
*
* Checks the codec for any new dapm widgets and creates them if found.
*
* Returns 0 for success.
*/
int snd_soc_dapm_new_widgets(struct snd_soc_dapm_context *dapm)
{
struct snd_soc_dapm_widget *w;
unsigned int val;
list_for_each_entry(w, &dapm->card->widgets, list)
{
if (w->new)
continue;
if (w->num_kcontrols) {
w->kcontrols = kzalloc(w->num_kcontrols *
sizeof(struct snd_kcontrol *),
GFP_KERNEL);
if (!w->kcontrols)
return -ENOMEM;
}
switch(w->id) {
case snd_soc_dapm_switch:
case snd_soc_dapm_mixer:
case snd_soc_dapm_mixer_named_ctl:
dapm_new_mixer(w);
break;
case snd_soc_dapm_mux:
case snd_soc_dapm_virt_mux:
case snd_soc_dapm_value_mux:
dapm_new_mux(w);
break;
case snd_soc_dapm_pga:
case snd_soc_dapm_out_drv:
dapm_new_pga(w);
break;
default:
break;
}
/* Read the initial power state from the device */
if (w->reg >= 0) {
val = soc_widget_read(w, w->reg);
val &= 1 << w->shift;
if (w->invert)
val = !val;
if (val)
w->power = 1;
}
w->new = 1;
dapm_mark_dirty(w, "new widget");
dapm_debugfs_add_widget(w);
}
dapm_power_widgets(dapm, SND_SOC_DAPM_STREAM_NOP);
return 0;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_new_widgets);
/**
* snd_soc_dapm_get_volsw - dapm mixer get callback
* @kcontrol: mixer control
* @ucontrol: control element information
*
* Callback to get the value of a dapm mixer control.
*
* Returns 0 for success.
*/
int snd_soc_dapm_get_volsw(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
struct soc_mixer_control *mc =
(struct soc_mixer_control *)kcontrol->private_value;
unsigned int reg = mc->reg;
unsigned int shift = mc->shift;
unsigned int rshift = mc->rshift;
int max = mc->max;
unsigned int invert = mc->invert;
unsigned int mask = (1 << fls(max)) - 1;
ucontrol->value.integer.value[0] =
(snd_soc_read(widget->codec, reg) >> shift) & mask;
if (shift != rshift)
ucontrol->value.integer.value[1] =
(snd_soc_read(widget->codec, reg) >> rshift) & mask;
if (invert) {
ucontrol->value.integer.value[0] =
max - ucontrol->value.integer.value[0];
if (shift != rshift)
ucontrol->value.integer.value[1] =
max - ucontrol->value.integer.value[1];
}
return 0;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_get_volsw);
/**
* snd_soc_dapm_put_volsw - dapm mixer set callback
* @kcontrol: mixer control
* @ucontrol: control element information
*
* Callback to set the value of a dapm mixer control.
*
* Returns 0 for success.
*/
int snd_soc_dapm_put_volsw(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
struct snd_soc_codec *codec = widget->codec;
struct soc_mixer_control *mc =
(struct soc_mixer_control *)kcontrol->private_value;
unsigned int reg = mc->reg;
unsigned int shift = mc->shift;
int max = mc->max;
unsigned int mask = (1 << fls(max)) - 1;
unsigned int invert = mc->invert;
unsigned int val;
int connect, change;
struct snd_soc_dapm_update update;
int wi;
val = (ucontrol->value.integer.value[0] & mask);
if (invert)
val = max - val;
mask = mask << shift;
val = val << shift;
if (val)
/* new connection */
connect = invert ? 0 : 1;
else
/* old connection must be powered down */
connect = invert ? 1 : 0;
mutex_lock(&codec->mutex);
change = snd_soc_test_bits(widget->codec, reg, mask, val);
if (change) {
for (wi = 0; wi < wlist->num_widgets; wi++) {
widget = wlist->widgets[wi];
widget->value = val;
update.kcontrol = kcontrol;
update.widget = widget;
update.reg = reg;
update.mask = mask;
update.val = val;
widget->dapm->update = &update;
dapm_mixer_update_power(widget, kcontrol, connect);
widget->dapm->update = NULL;
}
}
mutex_unlock(&codec->mutex);
return 0;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_put_volsw);
/**
* snd_soc_dapm_get_enum_double - dapm enumerated double mixer get callback
* @kcontrol: mixer control
* @ucontrol: control element information
*
* Callback to get the value of a dapm enumerated double mixer control.
*
* Returns 0 for success.
*/
int snd_soc_dapm_get_enum_double(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
struct soc_enum *e = (struct soc_enum *)kcontrol->private_value;
unsigned int val, bitmask;
for (bitmask = 1; bitmask < e->max; bitmask <<= 1)
;
val = snd_soc_read(widget->codec, e->reg);
ucontrol->value.enumerated.item[0] = (val >> e->shift_l) & (bitmask - 1);
if (e->shift_l != e->shift_r)
ucontrol->value.enumerated.item[1] =
(val >> e->shift_r) & (bitmask - 1);
return 0;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_get_enum_double);
/**
* snd_soc_dapm_put_enum_double - dapm enumerated double mixer set callback
* @kcontrol: mixer control
* @ucontrol: control element information
*
* Callback to set the value of a dapm enumerated double mixer control.
*
* Returns 0 for success.
*/
int snd_soc_dapm_put_enum_double(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
struct snd_soc_codec *codec = widget->codec;
struct soc_enum *e = (struct soc_enum *)kcontrol->private_value;
unsigned int val, mux, change;
unsigned int mask, bitmask;
struct snd_soc_dapm_update update;
int wi;
for (bitmask = 1; bitmask < e->max; bitmask <<= 1)
;
if (ucontrol->value.enumerated.item[0] > e->max - 1)
return -EINVAL;
mux = ucontrol->value.enumerated.item[0];
val = mux << e->shift_l;
mask = (bitmask - 1) << e->shift_l;
if (e->shift_l != e->shift_r) {
if (ucontrol->value.enumerated.item[1] > e->max - 1)
return -EINVAL;
val |= ucontrol->value.enumerated.item[1] << e->shift_r;
mask |= (bitmask - 1) << e->shift_r;
}
mutex_lock(&codec->mutex);
change = snd_soc_test_bits(widget->codec, e->reg, mask, val);
if (change) {
for (wi = 0; wi < wlist->num_widgets; wi++) {
widget = wlist->widgets[wi];
widget->value = val;
update.kcontrol = kcontrol;
update.widget = widget;
update.reg = e->reg;
update.mask = mask;
update.val = val;
widget->dapm->update = &update;
dapm_mux_update_power(widget, kcontrol, change, mux, e);
widget->dapm->update = NULL;
}
}
mutex_unlock(&codec->mutex);
return change;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_put_enum_double);
/**
* snd_soc_dapm_get_enum_virt - Get virtual DAPM mux
* @kcontrol: mixer control
* @ucontrol: control element information
*
* Returns 0 for success.
*/
int snd_soc_dapm_get_enum_virt(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
ucontrol->value.enumerated.item[0] = widget->value;
return 0;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_get_enum_virt);
/**
* snd_soc_dapm_put_enum_virt - Set virtual DAPM mux
* @kcontrol: mixer control
* @ucontrol: control element information
*
* Returns 0 for success.
*/
int snd_soc_dapm_put_enum_virt(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
struct snd_soc_codec *codec = widget->codec;
struct soc_enum *e =
(struct soc_enum *)kcontrol->private_value;
int change;
int ret = 0;
int wi;
if (ucontrol->value.enumerated.item[0] >= e->max)
return -EINVAL;
mutex_lock(&codec->mutex);
change = widget->value != ucontrol->value.enumerated.item[0];
if (change) {
for (wi = 0; wi < wlist->num_widgets; wi++) {
widget = wlist->widgets[wi];
widget->value = ucontrol->value.enumerated.item[0];
dapm_mux_update_power(widget, kcontrol, change,
widget->value, e);
}
}
mutex_unlock(&codec->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_put_enum_virt);
/**
* snd_soc_dapm_get_value_enum_double - dapm semi enumerated double mixer get
* callback
* @kcontrol: mixer control
* @ucontrol: control element information
*
* Callback to get the value of a dapm semi enumerated double mixer control.
*
* Semi enumerated mixer: the enumerated items are referred as values. Can be
* used for handling bitfield coded enumeration for example.
*
* Returns 0 for success.
*/
int snd_soc_dapm_get_value_enum_double(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
struct soc_enum *e = (struct soc_enum *)kcontrol->private_value;
unsigned int reg_val, val, mux;
reg_val = snd_soc_read(widget->codec, e->reg);
val = (reg_val >> e->shift_l) & e->mask;
for (mux = 0; mux < e->max; mux++) {
if (val == e->values[mux])
break;
}
ucontrol->value.enumerated.item[0] = mux;
if (e->shift_l != e->shift_r) {
val = (reg_val >> e->shift_r) & e->mask;
for (mux = 0; mux < e->max; mux++) {
if (val == e->values[mux])
break;
}
ucontrol->value.enumerated.item[1] = mux;
}
return 0;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_get_value_enum_double);
/**
* snd_soc_dapm_put_value_enum_double - dapm semi enumerated double mixer set
* callback
* @kcontrol: mixer control
* @ucontrol: control element information
*
* Callback to set the value of a dapm semi enumerated double mixer control.
*
* Semi enumerated mixer: the enumerated items are referred as values. Can be
* used for handling bitfield coded enumeration for example.
*
* Returns 0 for success.
*/
int snd_soc_dapm_put_value_enum_double(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
struct snd_soc_codec *codec = widget->codec;
struct soc_enum *e = (struct soc_enum *)kcontrol->private_value;
unsigned int val, mux, change;
unsigned int mask;
struct snd_soc_dapm_update update;
int wi;
if (ucontrol->value.enumerated.item[0] > e->max - 1)
return -EINVAL;
mux = ucontrol->value.enumerated.item[0];
val = e->values[ucontrol->value.enumerated.item[0]] << e->shift_l;
mask = e->mask << e->shift_l;
if (e->shift_l != e->shift_r) {
if (ucontrol->value.enumerated.item[1] > e->max - 1)
return -EINVAL;
val |= e->values[ucontrol->value.enumerated.item[1]] << e->shift_r;
mask |= e->mask << e->shift_r;
}
mutex_lock(&codec->mutex);
change = snd_soc_test_bits(widget->codec, e->reg, mask, val);
if (change) {
for (wi = 0; wi < wlist->num_widgets; wi++) {
widget = wlist->widgets[wi];
widget->value = val;
update.kcontrol = kcontrol;
update.widget = widget;
update.reg = e->reg;
update.mask = mask;
update.val = val;
widget->dapm->update = &update;
dapm_mux_update_power(widget, kcontrol, change, mux, e);
widget->dapm->update = NULL;
}
}
mutex_unlock(&codec->mutex);
return change;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_put_value_enum_double);
/**
* snd_soc_dapm_info_pin_switch - Info for a pin switch
*
* @kcontrol: mixer control
* @uinfo: control element information
*
* Callback to provide information about a pin switch control.
*/
int snd_soc_dapm_info_pin_switch(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
uinfo->count = 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 1;
return 0;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_info_pin_switch);
/**
* snd_soc_dapm_get_pin_switch - Get information for a pin switch
*
* @kcontrol: mixer control
* @ucontrol: Value
*/
int snd_soc_dapm_get_pin_switch(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
const char *pin = (const char *)kcontrol->private_value;
mutex_lock(&codec->mutex);
ucontrol->value.integer.value[0] =
snd_soc_dapm_get_pin_status(&codec->dapm, pin);
mutex_unlock(&codec->mutex);
return 0;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_get_pin_switch);
/**
* snd_soc_dapm_put_pin_switch - Set information for a pin switch
*
* @kcontrol: mixer control
* @ucontrol: Value
*/
int snd_soc_dapm_put_pin_switch(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
const char *pin = (const char *)kcontrol->private_value;
mutex_lock(&codec->mutex);
if (ucontrol->value.integer.value[0])
snd_soc_dapm_enable_pin(&codec->dapm, pin);
else
snd_soc_dapm_disable_pin(&codec->dapm, pin);
snd_soc_dapm_sync(&codec->dapm);
mutex_unlock(&codec->mutex);
return 0;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_put_pin_switch);
/**
* snd_soc_dapm_new_control - create new dapm control
* @dapm: DAPM context
* @widget: widget template
*
* Creates a new dapm control based upon the template.
*
* Returns 0 for success else error.
*/
int snd_soc_dapm_new_control(struct snd_soc_dapm_context *dapm,
const struct snd_soc_dapm_widget *widget)
{
struct snd_soc_dapm_widget *w;
size_t name_len;
if ((w = dapm_cnew_widget(widget)) == NULL)
return -ENOMEM;
name_len = strlen(widget->name) + 1;
if (dapm->codec && dapm->codec->name_prefix)
name_len += 1 + strlen(dapm->codec->name_prefix);
w->name = kmalloc(name_len, GFP_KERNEL);
if (w->name == NULL) {
kfree(w);
return -ENOMEM;
}
if (dapm->codec && dapm->codec->name_prefix)
snprintf(w->name, name_len, "%s %s",
dapm->codec->name_prefix, widget->name);
else
snprintf(w->name, name_len, "%s", widget->name);
switch (w->id) {
case snd_soc_dapm_switch:
case snd_soc_dapm_mixer:
case snd_soc_dapm_mixer_named_ctl:
w->power_check = dapm_generic_check_power;
break;
case snd_soc_dapm_mux:
case snd_soc_dapm_virt_mux:
case snd_soc_dapm_value_mux:
w->power_check = dapm_generic_check_power;
break;
case snd_soc_dapm_adc:
case snd_soc_dapm_aif_out:
w->power_check = dapm_adc_check_power;
break;
case snd_soc_dapm_dac:
case snd_soc_dapm_aif_in:
w->power_check = dapm_dac_check_power;
break;
case snd_soc_dapm_pga:
case snd_soc_dapm_out_drv:
case snd_soc_dapm_input:
case snd_soc_dapm_output:
case snd_soc_dapm_micbias:
case snd_soc_dapm_spk:
case snd_soc_dapm_hp:
case snd_soc_dapm_mic:
case snd_soc_dapm_line:
w->power_check = dapm_generic_check_power;
break;
case snd_soc_dapm_supply:
w->power_check = dapm_supply_check_power;
break;
default:
w->power_check = dapm_always_on_check_power;
break;
}
dapm->n_widgets++;
w->dapm = dapm;
w->codec = dapm->codec;
w->platform = dapm->platform;
INIT_LIST_HEAD(&w->sources);
INIT_LIST_HEAD(&w->sinks);
INIT_LIST_HEAD(&w->list);
INIT_LIST_HEAD(&w->dirty);
list_add(&w->list, &dapm->card->widgets);
/* machine layer set ups unconnected pins and insertions */
w->connected = 1;
return 0;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_new_control);
/**
* snd_soc_dapm_new_controls - create new dapm controls
* @dapm: DAPM context
* @widget: widget array
* @num: number of widgets
*
* Creates new DAPM controls based upon the templates.
*
* Returns 0 for success else error.
*/
int snd_soc_dapm_new_controls(struct snd_soc_dapm_context *dapm,
const struct snd_soc_dapm_widget *widget,
int num)
{
int i, ret;
for (i = 0; i < num; i++) {
ret = snd_soc_dapm_new_control(dapm, widget);
if (ret < 0) {
dev_err(dapm->dev,
"ASoC: Failed to create DAPM control %s: %d\n",
widget->name, ret);
return ret;
}
widget++;
}
return 0;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_new_controls);
static void soc_dapm_stream_event(struct snd_soc_dapm_context *dapm,
const char *stream, int event)
{
struct snd_soc_dapm_widget *w;
list_for_each_entry(w, &dapm->card->widgets, list)
{
if (!w->sname || w->dapm != dapm)
continue;
dev_vdbg(w->dapm->dev, "widget %s\n %s stream %s event %d\n",
w->name, w->sname, stream, event);
if (strstr(w->sname, stream)) {
dapm_mark_dirty(w, "stream event");
switch(event) {
case SND_SOC_DAPM_STREAM_START:
w->active = 1;
break;
case SND_SOC_DAPM_STREAM_STOP:
w->active = 0;
break;
case SND_SOC_DAPM_STREAM_SUSPEND:
case SND_SOC_DAPM_STREAM_RESUME:
case SND_SOC_DAPM_STREAM_PAUSE_PUSH:
case SND_SOC_DAPM_STREAM_PAUSE_RELEASE:
break;
}
}
}
dapm_power_widgets(dapm, event);
/* do we need to notify any clients that DAPM stream is complete */
if (dapm->stream_event)
dapm->stream_event(dapm, event);
}
/**
* snd_soc_dapm_stream_event - send a stream event to the dapm core
* @rtd: PCM runtime data
* @stream: stream name
* @event: stream event
*
* Sends a stream event to the dapm core. The core then makes any
* necessary widget power changes.
*
* Returns 0 for success else error.
*/
int snd_soc_dapm_stream_event(struct snd_soc_pcm_runtime *rtd,
const char *stream, int event)
{
struct snd_soc_codec *codec = rtd->codec;
if (stream == NULL)
return 0;
mutex_lock(&codec->mutex);
soc_dapm_stream_event(&codec->dapm, stream, event);
mutex_unlock(&codec->mutex);
return 0;
}
/**
* snd_soc_dapm_enable_pin - enable pin.
* @dapm: DAPM context
* @pin: pin name
*
* Enables input/output pin and its parents or children widgets iff there is
* a valid audio route and active audio stream.
* NOTE: snd_soc_dapm_sync() needs to be called after this for DAPM to
* do any widget power switching.
*/
int snd_soc_dapm_enable_pin(struct snd_soc_dapm_context *dapm, const char *pin)
{
return snd_soc_dapm_set_pin(dapm, pin, 1);
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_enable_pin);
/**
* snd_soc_dapm_force_enable_pin - force a pin to be enabled
* @dapm: DAPM context
* @pin: pin name
*
* Enables input/output pin regardless of any other state. This is
* intended for use with microphone bias supplies used in microphone
* jack detection.
*
* NOTE: snd_soc_dapm_sync() needs to be called after this for DAPM to
* do any widget power switching.
*/
int snd_soc_dapm_force_enable_pin(struct snd_soc_dapm_context *dapm,
const char *pin)
{
struct snd_soc_dapm_widget *w = dapm_find_widget(dapm, pin, true);
if (!w) {
dev_err(dapm->dev, "dapm: unknown pin %s\n", pin);
return -EINVAL;
}
dev_dbg(w->dapm->dev, "dapm: force enable pin %s\n", pin);
w->connected = 1;
w->force = 1;
dapm_mark_dirty(w, "force enable");
return 0;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_force_enable_pin);
/**
* snd_soc_dapm_disable_pin - disable pin.
* @dapm: DAPM context
* @pin: pin name
*
* Disables input/output pin and its parents or children widgets.
* NOTE: snd_soc_dapm_sync() needs to be called after this for DAPM to
* do any widget power switching.
*/
int snd_soc_dapm_disable_pin(struct snd_soc_dapm_context *dapm,
const char *pin)
{
return snd_soc_dapm_set_pin(dapm, pin, 0);
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_disable_pin);
/**
* snd_soc_dapm_nc_pin - permanently disable pin.
* @dapm: DAPM context
* @pin: pin name
*
* Marks the specified pin as being not connected, disabling it along
* any parent or child widgets. At present this is identical to
* snd_soc_dapm_disable_pin() but in future it will be extended to do
* additional things such as disabling controls which only affect
* paths through the pin.
*
* NOTE: snd_soc_dapm_sync() needs to be called after this for DAPM to
* do any widget power switching.
*/
int snd_soc_dapm_nc_pin(struct snd_soc_dapm_context *dapm, const char *pin)
{
return snd_soc_dapm_set_pin(dapm, pin, 0);
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_nc_pin);
/**
* snd_soc_dapm_get_pin_status - get audio pin status
* @dapm: DAPM context
* @pin: audio signal pin endpoint (or start point)
*
* Get audio pin status - connected or disconnected.
*
* Returns 1 for connected otherwise 0.
*/
int snd_soc_dapm_get_pin_status(struct snd_soc_dapm_context *dapm,
const char *pin)
{
struct snd_soc_dapm_widget *w = dapm_find_widget(dapm, pin, true);
if (w)
return w->connected;
return 0;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_get_pin_status);
/**
* snd_soc_dapm_ignore_suspend - ignore suspend status for DAPM endpoint
* @dapm: DAPM context
* @pin: audio signal pin endpoint (or start point)
*
* Mark the given endpoint or pin as ignoring suspend. When the
* system is disabled a path between two endpoints flagged as ignoring
* suspend will not be disabled. The path must already be enabled via
* normal means at suspend time, it will not be turned on if it was not
* already enabled.
*/
int snd_soc_dapm_ignore_suspend(struct snd_soc_dapm_context *dapm,
const char *pin)
{
struct snd_soc_dapm_widget *w = dapm_find_widget(dapm, pin, false);
if (!w) {
dev_err(dapm->dev, "dapm: unknown pin %s\n", pin);
return -EINVAL;
}
w->ignore_suspend = 1;
return 0;
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_ignore_suspend);
/**
* snd_soc_dapm_free - free dapm resources
* @dapm: DAPM context
*
* Free all dapm widgets and resources.
*/
void snd_soc_dapm_free(struct snd_soc_dapm_context *dapm)
{
snd_soc_dapm_sys_remove(dapm->dev);
dapm_debugfs_cleanup(dapm);
dapm_free_widgets(dapm);
list_del(&dapm->list);
}
EXPORT_SYMBOL_GPL(snd_soc_dapm_free);
static void soc_dapm_shutdown_codec(struct snd_soc_dapm_context *dapm)
{
struct snd_soc_dapm_widget *w;
LIST_HEAD(down_list);
int powerdown = 0;
list_for_each_entry(w, &dapm->card->widgets, list) {
if (w->dapm != dapm)
continue;
if (w->power) {
dapm_seq_insert(w, &down_list, false);
w->power = 0;
powerdown = 1;
}
}
/* If there were no widgets to power down we're already in
* standby.
*/
if (powerdown) {
snd_soc_dapm_set_bias_level(dapm, SND_SOC_BIAS_PREPARE);
dapm_seq_run(dapm, &down_list, 0, false);
snd_soc_dapm_set_bias_level(dapm, SND_SOC_BIAS_STANDBY);
}
}
/*
* snd_soc_dapm_shutdown - callback for system shutdown
*/
void snd_soc_dapm_shutdown(struct snd_soc_card *card)
{
struct snd_soc_codec *codec;
list_for_each_entry(codec, &card->codec_dev_list, list) {
soc_dapm_shutdown_codec(&codec->dapm);
snd_soc_dapm_set_bias_level(&codec->dapm, SND_SOC_BIAS_OFF);
}
}
/* Module information */
MODULE_AUTHOR("Liam Girdwood, lrg@slimlogic.co.uk");
MODULE_DESCRIPTION("Dynamic Audio Power Management core for ALSA SoC");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Hardslog/grimlock_kernel_asus_tegra3_unified | net/l2tp/l2tp_core.c | 376 | 47246 | /*
* L2TP core.
*
* Copyright (c) 2008,2009,2010 Katalix Systems Ltd
*
* This file contains some code of the original L2TPv2 pppol2tp
* driver, which has the following copyright:
*
* Authors: Martijn van Oosterhout <kleptog@svana.org>
* James Chapman (jchapman@katalix.com)
* Contributors:
* Michal Ostrowski <mostrows@speakeasy.net>
* Arnaldo Carvalho de Melo <acme@xconectiva.com.br>
* David S. Miller (davem@redhat.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/string.h>
#include <linux/list.h>
#include <linux/rculist.h>
#include <linux/uaccess.h>
#include <linux/kernel.h>
#include <linux/spinlock.h>
#include <linux/kthread.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/jiffies.h>
#include <linux/netdevice.h>
#include <linux/net.h>
#include <linux/inetdevice.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/udp.h>
#include <linux/l2tp.h>
#include <linux/hash.h>
#include <linux/sort.h>
#include <linux/file.h>
#include <linux/nsproxy.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include <net/dst.h>
#include <net/ip.h>
#include <net/udp.h>
#include <net/inet_common.h>
#include <net/xfrm.h>
#include <net/protocol.h>
#include <asm/byteorder.h>
#include <linux/atomic.h>
#include "l2tp_core.h"
#define L2TP_DRV_VERSION "V2.0"
/* L2TP header constants */
#define L2TP_HDRFLAG_T 0x8000
#define L2TP_HDRFLAG_L 0x4000
#define L2TP_HDRFLAG_S 0x0800
#define L2TP_HDRFLAG_O 0x0200
#define L2TP_HDRFLAG_P 0x0100
#define L2TP_HDR_VER_MASK 0x000F
#define L2TP_HDR_VER_2 0x0002
#define L2TP_HDR_VER_3 0x0003
/* L2TPv3 default L2-specific sublayer */
#define L2TP_SLFLAG_S 0x40000000
#define L2TP_SL_SEQ_MASK 0x00ffffff
#define L2TP_HDR_SIZE_SEQ 10
#define L2TP_HDR_SIZE_NOSEQ 6
/* Default trace flags */
#define L2TP_DEFAULT_DEBUG_FLAGS 0
#define PRINTK(_mask, _type, _lvl, _fmt, args...) \
do { \
if ((_mask) & (_type)) \
printk(_lvl "L2TP: " _fmt, ##args); \
} while (0)
/* Private data stored for received packets in the skb.
*/
struct l2tp_skb_cb {
u32 ns;
u16 has_seq;
u16 length;
unsigned long expires;
};
#define L2TP_SKB_CB(skb) ((struct l2tp_skb_cb *) &skb->cb[sizeof(struct inet_skb_parm)])
static atomic_t l2tp_tunnel_count;
static atomic_t l2tp_session_count;
/* per-net private data for this module */
static unsigned int l2tp_net_id;
struct l2tp_net {
struct list_head l2tp_tunnel_list;
spinlock_t l2tp_tunnel_list_lock;
struct hlist_head l2tp_session_hlist[L2TP_HASH_SIZE_2];
spinlock_t l2tp_session_hlist_lock;
};
static void l2tp_session_set_header_len(struct l2tp_session *session, int version);
static void l2tp_tunnel_free(struct l2tp_tunnel *tunnel);
static void l2tp_tunnel_closeall(struct l2tp_tunnel *tunnel);
static inline struct l2tp_net *l2tp_pernet(struct net *net)
{
BUG_ON(!net);
return net_generic(net, l2tp_net_id);
}
/* Tunnel reference counts. Incremented per session that is added to
* the tunnel.
*/
static inline void l2tp_tunnel_inc_refcount_1(struct l2tp_tunnel *tunnel)
{
atomic_inc(&tunnel->ref_count);
}
static inline void l2tp_tunnel_dec_refcount_1(struct l2tp_tunnel *tunnel)
{
if (atomic_dec_and_test(&tunnel->ref_count))
l2tp_tunnel_free(tunnel);
}
#ifdef L2TP_REFCNT_DEBUG
#define l2tp_tunnel_inc_refcount(_t) do { \
printk(KERN_DEBUG "l2tp_tunnel_inc_refcount: %s:%d %s: cnt=%d\n", __func__, __LINE__, (_t)->name, atomic_read(&_t->ref_count)); \
l2tp_tunnel_inc_refcount_1(_t); \
} while (0)
#define l2tp_tunnel_dec_refcount(_t) do { \
printk(KERN_DEBUG "l2tp_tunnel_dec_refcount: %s:%d %s: cnt=%d\n", __func__, __LINE__, (_t)->name, atomic_read(&_t->ref_count)); \
l2tp_tunnel_dec_refcount_1(_t); \
} while (0)
#else
#define l2tp_tunnel_inc_refcount(t) l2tp_tunnel_inc_refcount_1(t)
#define l2tp_tunnel_dec_refcount(t) l2tp_tunnel_dec_refcount_1(t)
#endif
/* Session hash global list for L2TPv3.
* The session_id SHOULD be random according to RFC3931, but several
* L2TP implementations use incrementing session_ids. So we do a real
* hash on the session_id, rather than a simple bitmask.
*/
static inline struct hlist_head *
l2tp_session_id_hash_2(struct l2tp_net *pn, u32 session_id)
{
return &pn->l2tp_session_hlist[hash_32(session_id, L2TP_HASH_BITS_2)];
}
/* Lookup a session by id in the global session list
*/
static struct l2tp_session *l2tp_session_find_2(struct net *net, u32 session_id)
{
struct l2tp_net *pn = l2tp_pernet(net);
struct hlist_head *session_list =
l2tp_session_id_hash_2(pn, session_id);
struct l2tp_session *session;
struct hlist_node *walk;
rcu_read_lock_bh();
hlist_for_each_entry_rcu(session, walk, session_list, global_hlist) {
if (session->session_id == session_id) {
rcu_read_unlock_bh();
return session;
}
}
rcu_read_unlock_bh();
return NULL;
}
/* Session hash list.
* The session_id SHOULD be random according to RFC2661, but several
* L2TP implementations (Cisco and Microsoft) use incrementing
* session_ids. So we do a real hash on the session_id, rather than a
* simple bitmask.
*/
static inline struct hlist_head *
l2tp_session_id_hash(struct l2tp_tunnel *tunnel, u32 session_id)
{
return &tunnel->session_hlist[hash_32(session_id, L2TP_HASH_BITS)];
}
/* Lookup a session by id
*/
struct l2tp_session *l2tp_session_find(struct net *net, struct l2tp_tunnel *tunnel, u32 session_id)
{
struct hlist_head *session_list;
struct l2tp_session *session;
struct hlist_node *walk;
/* In L2TPv3, session_ids are unique over all tunnels and we
* sometimes need to look them up before we know the
* tunnel.
*/
if (tunnel == NULL)
return l2tp_session_find_2(net, session_id);
session_list = l2tp_session_id_hash(tunnel, session_id);
read_lock_bh(&tunnel->hlist_lock);
hlist_for_each_entry(session, walk, session_list, hlist) {
if (session->session_id == session_id) {
read_unlock_bh(&tunnel->hlist_lock);
return session;
}
}
read_unlock_bh(&tunnel->hlist_lock);
return NULL;
}
EXPORT_SYMBOL_GPL(l2tp_session_find);
struct l2tp_session *l2tp_session_find_nth(struct l2tp_tunnel *tunnel, int nth)
{
int hash;
struct hlist_node *walk;
struct l2tp_session *session;
int count = 0;
read_lock_bh(&tunnel->hlist_lock);
for (hash = 0; hash < L2TP_HASH_SIZE; hash++) {
hlist_for_each_entry(session, walk, &tunnel->session_hlist[hash], hlist) {
if (++count > nth) {
read_unlock_bh(&tunnel->hlist_lock);
return session;
}
}
}
read_unlock_bh(&tunnel->hlist_lock);
return NULL;
}
EXPORT_SYMBOL_GPL(l2tp_session_find_nth);
/* Lookup a session by interface name.
* This is very inefficient but is only used by management interfaces.
*/
struct l2tp_session *l2tp_session_find_by_ifname(struct net *net, char *ifname)
{
struct l2tp_net *pn = l2tp_pernet(net);
int hash;
struct hlist_node *walk;
struct l2tp_session *session;
rcu_read_lock_bh();
for (hash = 0; hash < L2TP_HASH_SIZE_2; hash++) {
hlist_for_each_entry_rcu(session, walk, &pn->l2tp_session_hlist[hash], global_hlist) {
if (!strcmp(session->ifname, ifname)) {
rcu_read_unlock_bh();
return session;
}
}
}
rcu_read_unlock_bh();
return NULL;
}
EXPORT_SYMBOL_GPL(l2tp_session_find_by_ifname);
/* Lookup a tunnel by id
*/
struct l2tp_tunnel *l2tp_tunnel_find(struct net *net, u32 tunnel_id)
{
struct l2tp_tunnel *tunnel;
struct l2tp_net *pn = l2tp_pernet(net);
rcu_read_lock_bh();
list_for_each_entry_rcu(tunnel, &pn->l2tp_tunnel_list, list) {
if (tunnel->tunnel_id == tunnel_id) {
rcu_read_unlock_bh();
return tunnel;
}
}
rcu_read_unlock_bh();
return NULL;
}
EXPORT_SYMBOL_GPL(l2tp_tunnel_find);
struct l2tp_tunnel *l2tp_tunnel_find_nth(struct net *net, int nth)
{
struct l2tp_net *pn = l2tp_pernet(net);
struct l2tp_tunnel *tunnel;
int count = 0;
rcu_read_lock_bh();
list_for_each_entry_rcu(tunnel, &pn->l2tp_tunnel_list, list) {
if (++count > nth) {
rcu_read_unlock_bh();
return tunnel;
}
}
rcu_read_unlock_bh();
return NULL;
}
EXPORT_SYMBOL_GPL(l2tp_tunnel_find_nth);
/*****************************************************************************
* Receive data handling
*****************************************************************************/
/* Queue a skb in order. We come here only if the skb has an L2TP sequence
* number.
*/
static void l2tp_recv_queue_skb(struct l2tp_session *session, struct sk_buff *skb)
{
struct sk_buff *skbp;
struct sk_buff *tmp;
u32 ns = L2TP_SKB_CB(skb)->ns;
spin_lock_bh(&session->reorder_q.lock);
skb_queue_walk_safe(&session->reorder_q, skbp, tmp) {
if (L2TP_SKB_CB(skbp)->ns > ns) {
__skb_queue_before(&session->reorder_q, skbp, skb);
PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
"%s: pkt %hu, inserted before %hu, reorder_q len=%d\n",
session->name, ns, L2TP_SKB_CB(skbp)->ns,
skb_queue_len(&session->reorder_q));
session->stats.rx_oos_packets++;
goto out;
}
}
__skb_queue_tail(&session->reorder_q, skb);
out:
spin_unlock_bh(&session->reorder_q.lock);
}
/* Dequeue a single skb.
*/
static void l2tp_recv_dequeue_skb(struct l2tp_session *session, struct sk_buff *skb)
{
struct l2tp_tunnel *tunnel = session->tunnel;
int length = L2TP_SKB_CB(skb)->length;
/* We're about to requeue the skb, so return resources
* to its current owner (a socket receive buffer).
*/
skb_orphan(skb);
tunnel->stats.rx_packets++;
tunnel->stats.rx_bytes += length;
session->stats.rx_packets++;
session->stats.rx_bytes += length;
if (L2TP_SKB_CB(skb)->has_seq) {
/* Bump our Nr */
session->nr++;
if (tunnel->version == L2TP_HDR_VER_2)
session->nr &= 0xffff;
else
session->nr &= 0xffffff;
PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
"%s: updated nr to %hu\n", session->name, session->nr);
}
/* call private receive handler */
if (session->recv_skb != NULL)
(*session->recv_skb)(session, skb, L2TP_SKB_CB(skb)->length);
else
kfree_skb(skb);
if (session->deref)
(*session->deref)(session);
}
/* Dequeue skbs from the session's reorder_q, subject to packet order.
* Skbs that have been in the queue for too long are simply discarded.
*/
static void l2tp_recv_dequeue(struct l2tp_session *session)
{
struct sk_buff *skb;
struct sk_buff *tmp;
/* If the pkt at the head of the queue has the nr that we
* expect to send up next, dequeue it and any other
* in-sequence packets behind it.
*/
spin_lock_bh(&session->reorder_q.lock);
skb_queue_walk_safe(&session->reorder_q, skb, tmp) {
if (time_after(jiffies, L2TP_SKB_CB(skb)->expires)) {
session->stats.rx_seq_discards++;
session->stats.rx_errors++;
PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
"%s: oos pkt %u len %d discarded (too old), "
"waiting for %u, reorder_q_len=%d\n",
session->name, L2TP_SKB_CB(skb)->ns,
L2TP_SKB_CB(skb)->length, session->nr,
skb_queue_len(&session->reorder_q));
__skb_unlink(skb, &session->reorder_q);
kfree_skb(skb);
if (session->deref)
(*session->deref)(session);
continue;
}
if (L2TP_SKB_CB(skb)->has_seq) {
if (L2TP_SKB_CB(skb)->ns != session->nr) {
PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
"%s: holding oos pkt %u len %d, "
"waiting for %u, reorder_q_len=%d\n",
session->name, L2TP_SKB_CB(skb)->ns,
L2TP_SKB_CB(skb)->length, session->nr,
skb_queue_len(&session->reorder_q));
goto out;
}
}
__skb_unlink(skb, &session->reorder_q);
/* Process the skb. We release the queue lock while we
* do so to let other contexts process the queue.
*/
spin_unlock_bh(&session->reorder_q.lock);
l2tp_recv_dequeue_skb(session, skb);
spin_lock_bh(&session->reorder_q.lock);
}
out:
spin_unlock_bh(&session->reorder_q.lock);
}
static inline int l2tp_verify_udp_checksum(struct sock *sk,
struct sk_buff *skb)
{
struct udphdr *uh = udp_hdr(skb);
u16 ulen = ntohs(uh->len);
struct inet_sock *inet;
__wsum psum;
if (sk->sk_no_check || skb_csum_unnecessary(skb) || !uh->check)
return 0;
inet = inet_sk(sk);
psum = csum_tcpudp_nofold(inet->inet_saddr, inet->inet_daddr, ulen,
IPPROTO_UDP, 0);
if ((skb->ip_summed == CHECKSUM_COMPLETE) &&
!csum_fold(csum_add(psum, skb->csum)))
return 0;
skb->csum = psum;
return __skb_checksum_complete(skb);
}
/* Do receive processing of L2TP data frames. We handle both L2TPv2
* and L2TPv3 data frames here.
*
* L2TPv2 Data Message Header
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |T|L|x|x|S|x|O|P|x|x|x|x| Ver | Length (opt) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Tunnel ID | Session ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Ns (opt) | Nr (opt) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Offset Size (opt) | Offset pad... (opt)
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Data frames are marked by T=0. All other fields are the same as
* those in L2TP control frames.
*
* L2TPv3 Data Message Header
*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | L2TP Session Header |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | L2-Specific Sublayer |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Tunnel Payload ...
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* L2TPv3 Session Header Over IP
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Session ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Cookie (optional, maximum 64 bits)...
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* L2TPv3 L2-Specific Sublayer Format
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |x|S|x|x|x|x|x|x| Sequence Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Cookie value, sublayer format and offset (pad) are negotiated with
* the peer when the session is set up. Unlike L2TPv2, we do not need
* to parse the packet header to determine if optional fields are
* present.
*
* Caller must already have parsed the frame and determined that it is
* a data (not control) frame before coming here. Fields up to the
* session-id have already been parsed and ptr points to the data
* after the session-id.
*/
void l2tp_recv_common(struct l2tp_session *session, struct sk_buff *skb,
unsigned char *ptr, unsigned char *optr, u16 hdrflags,
int length, int (*payload_hook)(struct sk_buff *skb))
{
struct l2tp_tunnel *tunnel = session->tunnel;
int offset;
u32 ns, nr;
/* The ref count is increased since we now hold a pointer to
* the session. Take care to decrement the refcnt when exiting
* this function from now on...
*/
l2tp_session_inc_refcount(session);
if (session->ref)
(*session->ref)(session);
/* Parse and check optional cookie */
if (session->peer_cookie_len > 0) {
if (memcmp(ptr, &session->peer_cookie[0], session->peer_cookie_len)) {
PRINTK(tunnel->debug, L2TP_MSG_DATA, KERN_INFO,
"%s: cookie mismatch (%u/%u). Discarding.\n",
tunnel->name, tunnel->tunnel_id, session->session_id);
session->stats.rx_cookie_discards++;
goto discard;
}
ptr += session->peer_cookie_len;
}
/* Handle the optional sequence numbers. Sequence numbers are
* in different places for L2TPv2 and L2TPv3.
*
* If we are the LAC, enable/disable sequence numbers under
* the control of the LNS. If no sequence numbers present but
* we were expecting them, discard frame.
*/
ns = nr = 0;
L2TP_SKB_CB(skb)->has_seq = 0;
if (tunnel->version == L2TP_HDR_VER_2) {
if (hdrflags & L2TP_HDRFLAG_S) {
ns = ntohs(*(__be16 *) ptr);
ptr += 2;
nr = ntohs(*(__be16 *) ptr);
ptr += 2;
/* Store L2TP info in the skb */
L2TP_SKB_CB(skb)->ns = ns;
L2TP_SKB_CB(skb)->has_seq = 1;
PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
"%s: recv data ns=%u, nr=%u, session nr=%u\n",
session->name, ns, nr, session->nr);
}
} else if (session->l2specific_type == L2TP_L2SPECTYPE_DEFAULT) {
u32 l2h = ntohl(*(__be32 *) ptr);
if (l2h & 0x40000000) {
ns = l2h & 0x00ffffff;
/* Store L2TP info in the skb */
L2TP_SKB_CB(skb)->ns = ns;
L2TP_SKB_CB(skb)->has_seq = 1;
PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
"%s: recv data ns=%u, session nr=%u\n",
session->name, ns, session->nr);
}
}
/* Advance past L2-specific header, if present */
ptr += session->l2specific_len;
if (L2TP_SKB_CB(skb)->has_seq) {
/* Received a packet with sequence numbers. If we're the LNS,
* check if we sre sending sequence numbers and if not,
* configure it so.
*/
if ((!session->lns_mode) && (!session->send_seq)) {
PRINTK(session->debug, L2TP_MSG_SEQ, KERN_INFO,
"%s: requested to enable seq numbers by LNS\n",
session->name);
session->send_seq = -1;
l2tp_session_set_header_len(session, tunnel->version);
}
} else {
/* No sequence numbers.
* If user has configured mandatory sequence numbers, discard.
*/
if (session->recv_seq) {
PRINTK(session->debug, L2TP_MSG_SEQ, KERN_WARNING,
"%s: recv data has no seq numbers when required. "
"Discarding\n", session->name);
session->stats.rx_seq_discards++;
goto discard;
}
/* If we're the LAC and we're sending sequence numbers, the
* LNS has requested that we no longer send sequence numbers.
* If we're the LNS and we're sending sequence numbers, the
* LAC is broken. Discard the frame.
*/
if ((!session->lns_mode) && (session->send_seq)) {
PRINTK(session->debug, L2TP_MSG_SEQ, KERN_INFO,
"%s: requested to disable seq numbers by LNS\n",
session->name);
session->send_seq = 0;
l2tp_session_set_header_len(session, tunnel->version);
} else if (session->send_seq) {
PRINTK(session->debug, L2TP_MSG_SEQ, KERN_WARNING,
"%s: recv data has no seq numbers when required. "
"Discarding\n", session->name);
session->stats.rx_seq_discards++;
goto discard;
}
}
/* Session data offset is handled differently for L2TPv2 and
* L2TPv3. For L2TPv2, there is an optional 16-bit value in
* the header. For L2TPv3, the offset is negotiated using AVPs
* in the session setup control protocol.
*/
if (tunnel->version == L2TP_HDR_VER_2) {
/* If offset bit set, skip it. */
if (hdrflags & L2TP_HDRFLAG_O) {
offset = ntohs(*(__be16 *)ptr);
ptr += 2 + offset;
}
} else
ptr += session->offset;
offset = ptr - optr;
if (!pskb_may_pull(skb, offset))
goto discard;
__skb_pull(skb, offset);
/* If caller wants to process the payload before we queue the
* packet, do so now.
*/
if (payload_hook)
if ((*payload_hook)(skb))
goto discard;
/* Prepare skb for adding to the session's reorder_q. Hold
* packets for max reorder_timeout or 1 second if not
* reordering.
*/
L2TP_SKB_CB(skb)->length = length;
L2TP_SKB_CB(skb)->expires = jiffies +
(session->reorder_timeout ? session->reorder_timeout : HZ);
/* Add packet to the session's receive queue. Reordering is done here, if
* enabled. Saved L2TP protocol info is stored in skb->sb[].
*/
if (L2TP_SKB_CB(skb)->has_seq) {
if (session->reorder_timeout != 0) {
/* Packet reordering enabled. Add skb to session's
* reorder queue, in order of ns.
*/
l2tp_recv_queue_skb(session, skb);
} else {
/* Packet reordering disabled. Discard out-of-sequence
* packets
*/
if (L2TP_SKB_CB(skb)->ns != session->nr) {
session->stats.rx_seq_discards++;
PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
"%s: oos pkt %u len %d discarded, "
"waiting for %u, reorder_q_len=%d\n",
session->name, L2TP_SKB_CB(skb)->ns,
L2TP_SKB_CB(skb)->length, session->nr,
skb_queue_len(&session->reorder_q));
goto discard;
}
skb_queue_tail(&session->reorder_q, skb);
}
} else {
/* No sequence numbers. Add the skb to the tail of the
* reorder queue. This ensures that it will be
* delivered after all previous sequenced skbs.
*/
skb_queue_tail(&session->reorder_q, skb);
}
/* Try to dequeue as many skbs from reorder_q as we can. */
l2tp_recv_dequeue(session);
l2tp_session_dec_refcount(session);
return;
discard:
session->stats.rx_errors++;
kfree_skb(skb);
if (session->deref)
(*session->deref)(session);
l2tp_session_dec_refcount(session);
}
EXPORT_SYMBOL(l2tp_recv_common);
/* Internal UDP receive frame. Do the real work of receiving an L2TP data frame
* here. The skb is not on a list when we get here.
* Returns 0 if the packet was a data packet and was successfully passed on.
* Returns 1 if the packet was not a good data packet and could not be
* forwarded. All such packets are passed up to userspace to deal with.
*/
static int l2tp_udp_recv_core(struct l2tp_tunnel *tunnel, struct sk_buff *skb,
int (*payload_hook)(struct sk_buff *skb))
{
struct l2tp_session *session = NULL;
unsigned char *ptr, *optr;
u16 hdrflags;
u32 tunnel_id, session_id;
int offset;
u16 version;
int length;
if (tunnel->sock && l2tp_verify_udp_checksum(tunnel->sock, skb))
goto discard_bad_csum;
/* UDP always verifies the packet length. */
__skb_pull(skb, sizeof(struct udphdr));
/* Short packet? */
if (!pskb_may_pull(skb, L2TP_HDR_SIZE_SEQ)) {
PRINTK(tunnel->debug, L2TP_MSG_DATA, KERN_INFO,
"%s: recv short packet (len=%d)\n", tunnel->name, skb->len);
goto error;
}
/* Point to L2TP header */
optr = ptr = skb->data;
/* Trace packet contents, if enabled */
if (tunnel->debug & L2TP_MSG_DATA) {
length = min(32u, skb->len);
if (!pskb_may_pull(skb, length))
goto error;
printk(KERN_DEBUG "%s: recv: ", tunnel->name);
offset = 0;
do {
printk(" %02X", ptr[offset]);
} while (++offset < length);
printk("\n");
}
/* Get L2TP header flags */
hdrflags = ntohs(*(__be16 *) ptr);
/* Check protocol version */
version = hdrflags & L2TP_HDR_VER_MASK;
if (version != tunnel->version) {
PRINTK(tunnel->debug, L2TP_MSG_DATA, KERN_INFO,
"%s: recv protocol version mismatch: got %d expected %d\n",
tunnel->name, version, tunnel->version);
goto error;
}
/* Get length of L2TP packet */
length = skb->len;
/* If type is control packet, it is handled by userspace. */
if (hdrflags & L2TP_HDRFLAG_T) {
PRINTK(tunnel->debug, L2TP_MSG_DATA, KERN_DEBUG,
"%s: recv control packet, len=%d\n", tunnel->name, length);
goto error;
}
/* Skip flags */
ptr += 2;
if (tunnel->version == L2TP_HDR_VER_2) {
/* If length is present, skip it */
if (hdrflags & L2TP_HDRFLAG_L)
ptr += 2;
/* Extract tunnel and session ID */
tunnel_id = ntohs(*(__be16 *) ptr);
ptr += 2;
session_id = ntohs(*(__be16 *) ptr);
ptr += 2;
} else {
ptr += 2; /* skip reserved bits */
tunnel_id = tunnel->tunnel_id;
session_id = ntohl(*(__be32 *) ptr);
ptr += 4;
}
/* Find the session context */
session = l2tp_session_find(tunnel->l2tp_net, tunnel, session_id);
if (!session || !session->recv_skb) {
/* Not found? Pass to userspace to deal with */
PRINTK(tunnel->debug, L2TP_MSG_DATA, KERN_INFO,
"%s: no session found (%u/%u). Passing up.\n",
tunnel->name, tunnel_id, session_id);
goto error;
}
l2tp_recv_common(session, skb, ptr, optr, hdrflags, length, payload_hook);
return 0;
discard_bad_csum:
LIMIT_NETDEBUG("%s: UDP: bad checksum\n", tunnel->name);
UDP_INC_STATS_USER(tunnel->l2tp_net, UDP_MIB_INERRORS, 0);
tunnel->stats.rx_errors++;
kfree_skb(skb);
return 0;
error:
/* Put UDP header back */
__skb_push(skb, sizeof(struct udphdr));
return 1;
}
/* UDP encapsulation receive handler. See net/ipv4/udp.c.
* Return codes:
* 0 : success.
* <0: error
* >0: skb should be passed up to userspace as UDP.
*/
int l2tp_udp_encap_recv(struct sock *sk, struct sk_buff *skb)
{
struct l2tp_tunnel *tunnel;
tunnel = l2tp_sock_to_tunnel(sk);
if (tunnel == NULL)
goto pass_up;
PRINTK(tunnel->debug, L2TP_MSG_DATA, KERN_DEBUG,
"%s: received %d bytes\n", tunnel->name, skb->len);
if (l2tp_udp_recv_core(tunnel, skb, tunnel->recv_payload_hook))
goto pass_up_put;
sock_put(sk);
return 0;
pass_up_put:
sock_put(sk);
pass_up:
return 1;
}
EXPORT_SYMBOL_GPL(l2tp_udp_encap_recv);
/************************************************************************
* Transmit handling
***********************************************************************/
/* Build an L2TP header for the session into the buffer provided.
*/
static int l2tp_build_l2tpv2_header(struct l2tp_session *session, void *buf)
{
struct l2tp_tunnel *tunnel = session->tunnel;
__be16 *bufp = buf;
__be16 *optr = buf;
u16 flags = L2TP_HDR_VER_2;
u32 tunnel_id = tunnel->peer_tunnel_id;
u32 session_id = session->peer_session_id;
if (session->send_seq)
flags |= L2TP_HDRFLAG_S;
/* Setup L2TP header. */
*bufp++ = htons(flags);
*bufp++ = htons(tunnel_id);
*bufp++ = htons(session_id);
if (session->send_seq) {
*bufp++ = htons(session->ns);
*bufp++ = 0;
session->ns++;
session->ns &= 0xffff;
PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
"%s: updated ns to %u\n", session->name, session->ns);
}
return bufp - optr;
}
static int l2tp_build_l2tpv3_header(struct l2tp_session *session, void *buf)
{
struct l2tp_tunnel *tunnel = session->tunnel;
char *bufp = buf;
char *optr = bufp;
/* Setup L2TP header. The header differs slightly for UDP and
* IP encapsulations. For UDP, there is 4 bytes of flags.
*/
if (tunnel->encap == L2TP_ENCAPTYPE_UDP) {
u16 flags = L2TP_HDR_VER_3;
*((__be16 *) bufp) = htons(flags);
bufp += 2;
*((__be16 *) bufp) = 0;
bufp += 2;
}
*((__be32 *) bufp) = htonl(session->peer_session_id);
bufp += 4;
if (session->cookie_len) {
memcpy(bufp, &session->cookie[0], session->cookie_len);
bufp += session->cookie_len;
}
if (session->l2specific_len) {
if (session->l2specific_type == L2TP_L2SPECTYPE_DEFAULT) {
u32 l2h = 0;
if (session->send_seq) {
l2h = 0x40000000 | session->ns;
session->ns++;
session->ns &= 0xffffff;
PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
"%s: updated ns to %u\n", session->name, session->ns);
}
*((__be32 *) bufp) = htonl(l2h);
}
bufp += session->l2specific_len;
}
if (session->offset)
bufp += session->offset;
return bufp - optr;
}
static int l2tp_xmit_core(struct l2tp_session *session, struct sk_buff *skb,
struct flowi *fl, size_t data_len)
{
struct l2tp_tunnel *tunnel = session->tunnel;
unsigned int len = skb->len;
int error;
/* Debug */
if (session->send_seq)
PRINTK(session->debug, L2TP_MSG_DATA, KERN_DEBUG,
"%s: send %Zd bytes, ns=%u\n", session->name,
data_len, session->ns - 1);
else
PRINTK(session->debug, L2TP_MSG_DATA, KERN_DEBUG,
"%s: send %Zd bytes\n", session->name, data_len);
if (session->debug & L2TP_MSG_DATA) {
int i;
int uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(struct udphdr) : 0;
unsigned char *datap = skb->data + uhlen;
printk(KERN_DEBUG "%s: xmit:", session->name);
for (i = 0; i < (len - uhlen); i++) {
printk(" %02X", *datap++);
if (i == 31) {
printk(" ...");
break;
}
}
printk("\n");
}
/* Queue the packet to IP for output */
skb->local_df = 1;
error = ip_queue_xmit(skb, fl);
/* Update stats */
if (error >= 0) {
tunnel->stats.tx_packets++;
tunnel->stats.tx_bytes += len;
session->stats.tx_packets++;
session->stats.tx_bytes += len;
} else {
tunnel->stats.tx_errors++;
session->stats.tx_errors++;
}
return 0;
}
/* Automatically called when the skb is freed.
*/
static void l2tp_sock_wfree(struct sk_buff *skb)
{
sock_put(skb->sk);
}
/* For data skbs that we transmit, we associate with the tunnel socket
* but don't do accounting.
*/
static inline void l2tp_skb_set_owner_w(struct sk_buff *skb, struct sock *sk)
{
sock_hold(sk);
skb->sk = sk;
skb->destructor = l2tp_sock_wfree;
}
/* If caller requires the skb to have a ppp header, the header must be
* inserted in the skb data before calling this function.
*/
int l2tp_xmit_skb(struct l2tp_session *session, struct sk_buff *skb, int hdr_len)
{
int data_len = skb->len;
struct l2tp_tunnel *tunnel = session->tunnel;
struct sock *sk = tunnel->sock;
struct flowi *fl;
struct udphdr *uh;
struct inet_sock *inet;
__wsum csum;
int old_headroom;
int new_headroom;
int headroom;
int uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(struct udphdr) : 0;
int udp_len;
/* Check that there's enough headroom in the skb to insert IP,
* UDP and L2TP headers. If not enough, expand it to
* make room. Adjust truesize.
*/
headroom = NET_SKB_PAD + sizeof(struct iphdr) +
uhlen + hdr_len;
old_headroom = skb_headroom(skb);
if (skb_cow_head(skb, headroom)) {
dev_kfree_skb(skb);
goto abort;
}
new_headroom = skb_headroom(skb);
skb_orphan(skb);
skb->truesize += new_headroom - old_headroom;
/* Setup L2TP header */
session->build_header(session, __skb_push(skb, hdr_len));
/* Reset skb netfilter state */
memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt));
IPCB(skb)->flags &= ~(IPSKB_XFRM_TUNNEL_SIZE | IPSKB_XFRM_TRANSFORMED |
IPSKB_REROUTED);
nf_reset(skb);
bh_lock_sock(sk);
if (sock_owned_by_user(sk)) {
dev_kfree_skb(skb);
goto out_unlock;
}
/* Get routing info from the tunnel socket */
skb_dst_drop(skb);
skb_dst_set(skb, dst_clone(__sk_dst_get(sk)));
inet = inet_sk(sk);
fl = &inet->cork.fl;
switch (tunnel->encap) {
case L2TP_ENCAPTYPE_UDP:
/* Setup UDP header */
__skb_push(skb, sizeof(*uh));
skb_reset_transport_header(skb);
uh = udp_hdr(skb);
uh->source = inet->inet_sport;
uh->dest = inet->inet_dport;
udp_len = uhlen + hdr_len + data_len;
uh->len = htons(udp_len);
uh->check = 0;
/* Calculate UDP checksum if configured to do so */
if (sk->sk_no_check == UDP_CSUM_NOXMIT)
skb->ip_summed = CHECKSUM_NONE;
else if ((skb_dst(skb) && skb_dst(skb)->dev) &&
(!(skb_dst(skb)->dev->features & NETIF_F_V4_CSUM))) {
skb->ip_summed = CHECKSUM_COMPLETE;
csum = skb_checksum(skb, 0, udp_len, 0);
uh->check = csum_tcpudp_magic(inet->inet_saddr,
inet->inet_daddr,
udp_len, IPPROTO_UDP, csum);
if (uh->check == 0)
uh->check = CSUM_MANGLED_0;
} else {
skb->ip_summed = CHECKSUM_PARTIAL;
skb->csum_start = skb_transport_header(skb) - skb->head;
skb->csum_offset = offsetof(struct udphdr, check);
uh->check = ~csum_tcpudp_magic(inet->inet_saddr,
inet->inet_daddr,
udp_len, IPPROTO_UDP, 0);
}
break;
case L2TP_ENCAPTYPE_IP:
break;
}
l2tp_skb_set_owner_w(skb, sk);
l2tp_xmit_core(session, skb, fl, data_len);
out_unlock:
bh_unlock_sock(sk);
abort:
return 0;
}
EXPORT_SYMBOL_GPL(l2tp_xmit_skb);
/*****************************************************************************
* Tinnel and session create/destroy.
*****************************************************************************/
/* Tunnel socket destruct hook.
* The tunnel context is deleted only when all session sockets have been
* closed.
*/
static void l2tp_tunnel_destruct(struct sock *sk)
{
struct l2tp_tunnel *tunnel;
tunnel = sk->sk_user_data;
if (tunnel == NULL)
goto end;
PRINTK(tunnel->debug, L2TP_MSG_CONTROL, KERN_INFO,
"%s: closing...\n", tunnel->name);
/* Close all sessions */
l2tp_tunnel_closeall(tunnel);
switch (tunnel->encap) {
case L2TP_ENCAPTYPE_UDP:
/* No longer an encapsulation socket. See net/ipv4/udp.c */
(udp_sk(sk))->encap_type = 0;
(udp_sk(sk))->encap_rcv = NULL;
break;
case L2TP_ENCAPTYPE_IP:
break;
}
/* Remove hooks into tunnel socket */
tunnel->sock = NULL;
sk->sk_destruct = tunnel->old_sk_destruct;
sk->sk_user_data = NULL;
/* Call the original destructor */
if (sk->sk_destruct)
(*sk->sk_destruct)(sk);
/* We're finished with the socket */
l2tp_tunnel_dec_refcount(tunnel);
end:
return;
}
/* When the tunnel is closed, all the attached sessions need to go too.
*/
static void l2tp_tunnel_closeall(struct l2tp_tunnel *tunnel)
{
int hash;
struct hlist_node *walk;
struct hlist_node *tmp;
struct l2tp_session *session;
BUG_ON(tunnel == NULL);
PRINTK(tunnel->debug, L2TP_MSG_CONTROL, KERN_INFO,
"%s: closing all sessions...\n", tunnel->name);
write_lock_bh(&tunnel->hlist_lock);
for (hash = 0; hash < L2TP_HASH_SIZE; hash++) {
again:
hlist_for_each_safe(walk, tmp, &tunnel->session_hlist[hash]) {
session = hlist_entry(walk, struct l2tp_session, hlist);
PRINTK(session->debug, L2TP_MSG_CONTROL, KERN_INFO,
"%s: closing session\n", session->name);
hlist_del_init(&session->hlist);
/* Since we should hold the sock lock while
* doing any unbinding, we need to release the
* lock we're holding before taking that lock.
* Hold a reference to the sock so it doesn't
* disappear as we're jumping between locks.
*/
if (session->ref != NULL)
(*session->ref)(session);
write_unlock_bh(&tunnel->hlist_lock);
if (tunnel->version != L2TP_HDR_VER_2) {
struct l2tp_net *pn = l2tp_pernet(tunnel->l2tp_net);
spin_lock_bh(&pn->l2tp_session_hlist_lock);
hlist_del_init_rcu(&session->global_hlist);
spin_unlock_bh(&pn->l2tp_session_hlist_lock);
synchronize_rcu();
}
if (session->session_close != NULL)
(*session->session_close)(session);
if (session->deref != NULL)
(*session->deref)(session);
write_lock_bh(&tunnel->hlist_lock);
/* Now restart from the beginning of this hash
* chain. We always remove a session from the
* list so we are guaranteed to make forward
* progress.
*/
goto again;
}
}
write_unlock_bh(&tunnel->hlist_lock);
}
/* Really kill the tunnel.
* Come here only when all sessions have been cleared from the tunnel.
*/
static void l2tp_tunnel_free(struct l2tp_tunnel *tunnel)
{
struct l2tp_net *pn = l2tp_pernet(tunnel->l2tp_net);
BUG_ON(atomic_read(&tunnel->ref_count) != 0);
BUG_ON(tunnel->sock != NULL);
PRINTK(tunnel->debug, L2TP_MSG_CONTROL, KERN_INFO,
"%s: free...\n", tunnel->name);
/* Remove from tunnel list */
spin_lock_bh(&pn->l2tp_tunnel_list_lock);
list_del_rcu(&tunnel->list);
spin_unlock_bh(&pn->l2tp_tunnel_list_lock);
synchronize_rcu();
atomic_dec(&l2tp_tunnel_count);
kfree(tunnel);
}
/* Create a socket for the tunnel, if one isn't set up by
* userspace. This is used for static tunnels where there is no
* managing L2TP daemon.
*/
static int l2tp_tunnel_sock_create(u32 tunnel_id, u32 peer_tunnel_id, struct l2tp_tunnel_cfg *cfg, struct socket **sockp)
{
int err = -EINVAL;
struct sockaddr_in udp_addr;
struct sockaddr_l2tpip ip_addr;
struct socket *sock = NULL;
switch (cfg->encap) {
case L2TP_ENCAPTYPE_UDP:
err = sock_create(AF_INET, SOCK_DGRAM, 0, sockp);
if (err < 0)
goto out;
sock = *sockp;
memset(&udp_addr, 0, sizeof(udp_addr));
udp_addr.sin_family = AF_INET;
udp_addr.sin_addr = cfg->local_ip;
udp_addr.sin_port = htons(cfg->local_udp_port);
err = kernel_bind(sock, (struct sockaddr *) &udp_addr, sizeof(udp_addr));
if (err < 0)
goto out;
udp_addr.sin_family = AF_INET;
udp_addr.sin_addr = cfg->peer_ip;
udp_addr.sin_port = htons(cfg->peer_udp_port);
err = kernel_connect(sock, (struct sockaddr *) &udp_addr, sizeof(udp_addr), 0);
if (err < 0)
goto out;
if (!cfg->use_udp_checksums)
sock->sk->sk_no_check = UDP_CSUM_NOXMIT;
break;
case L2TP_ENCAPTYPE_IP:
err = sock_create(AF_INET, SOCK_DGRAM, IPPROTO_L2TP, sockp);
if (err < 0)
goto out;
sock = *sockp;
memset(&ip_addr, 0, sizeof(ip_addr));
ip_addr.l2tp_family = AF_INET;
ip_addr.l2tp_addr = cfg->local_ip;
ip_addr.l2tp_conn_id = tunnel_id;
err = kernel_bind(sock, (struct sockaddr *) &ip_addr, sizeof(ip_addr));
if (err < 0)
goto out;
ip_addr.l2tp_family = AF_INET;
ip_addr.l2tp_addr = cfg->peer_ip;
ip_addr.l2tp_conn_id = peer_tunnel_id;
err = kernel_connect(sock, (struct sockaddr *) &ip_addr, sizeof(ip_addr), 0);
if (err < 0)
goto out;
break;
default:
goto out;
}
out:
if ((err < 0) && sock) {
sock_release(sock);
*sockp = NULL;
}
return err;
}
int l2tp_tunnel_create(struct net *net, int fd, int version, u32 tunnel_id, u32 peer_tunnel_id, struct l2tp_tunnel_cfg *cfg, struct l2tp_tunnel **tunnelp)
{
struct l2tp_tunnel *tunnel = NULL;
int err;
struct socket *sock = NULL;
struct sock *sk = NULL;
struct l2tp_net *pn;
enum l2tp_encap_type encap = L2TP_ENCAPTYPE_UDP;
/* Get the tunnel socket from the fd, which was opened by
* the userspace L2TP daemon. If not specified, create a
* kernel socket.
*/
if (fd < 0) {
err = l2tp_tunnel_sock_create(tunnel_id, peer_tunnel_id, cfg, &sock);
if (err < 0)
goto err;
} else {
err = -EBADF;
sock = sockfd_lookup(fd, &err);
if (!sock) {
printk(KERN_ERR "tunl %hu: sockfd_lookup(fd=%d) returned %d\n",
tunnel_id, fd, err);
goto err;
}
}
sk = sock->sk;
if (cfg != NULL)
encap = cfg->encap;
/* Quick sanity checks */
switch (encap) {
case L2TP_ENCAPTYPE_UDP:
err = -EPROTONOSUPPORT;
if (sk->sk_protocol != IPPROTO_UDP) {
printk(KERN_ERR "tunl %hu: fd %d wrong protocol, got %d, expected %d\n",
tunnel_id, fd, sk->sk_protocol, IPPROTO_UDP);
goto err;
}
break;
case L2TP_ENCAPTYPE_IP:
err = -EPROTONOSUPPORT;
if (sk->sk_protocol != IPPROTO_L2TP) {
printk(KERN_ERR "tunl %hu: fd %d wrong protocol, got %d, expected %d\n",
tunnel_id, fd, sk->sk_protocol, IPPROTO_L2TP);
goto err;
}
break;
}
/* Check if this socket has already been prepped */
tunnel = (struct l2tp_tunnel *)sk->sk_user_data;
if (tunnel != NULL) {
/* This socket has already been prepped */
err = -EBUSY;
goto err;
}
tunnel = kzalloc(sizeof(struct l2tp_tunnel), GFP_KERNEL);
if (tunnel == NULL) {
err = -ENOMEM;
goto err;
}
tunnel->version = version;
tunnel->tunnel_id = tunnel_id;
tunnel->peer_tunnel_id = peer_tunnel_id;
tunnel->debug = L2TP_DEFAULT_DEBUG_FLAGS;
tunnel->magic = L2TP_TUNNEL_MAGIC;
sprintf(&tunnel->name[0], "tunl %u", tunnel_id);
rwlock_init(&tunnel->hlist_lock);
/* The net we belong to */
tunnel->l2tp_net = net;
pn = l2tp_pernet(net);
if (cfg != NULL)
tunnel->debug = cfg->debug;
/* Mark socket as an encapsulation socket. See net/ipv4/udp.c */
tunnel->encap = encap;
if (encap == L2TP_ENCAPTYPE_UDP) {
/* Mark socket as an encapsulation socket. See net/ipv4/udp.c */
udp_sk(sk)->encap_type = UDP_ENCAP_L2TPINUDP;
udp_sk(sk)->encap_rcv = l2tp_udp_encap_recv;
}
sk->sk_user_data = tunnel;
/* Hook on the tunnel socket destructor so that we can cleanup
* if the tunnel socket goes away.
*/
tunnel->old_sk_destruct = sk->sk_destruct;
sk->sk_destruct = &l2tp_tunnel_destruct;
tunnel->sock = sk;
sk->sk_allocation = GFP_ATOMIC;
/* Add tunnel to our list */
INIT_LIST_HEAD(&tunnel->list);
atomic_inc(&l2tp_tunnel_count);
/* Bump the reference count. The tunnel context is deleted
* only when this drops to zero. Must be done before list insertion
*/
l2tp_tunnel_inc_refcount(tunnel);
spin_lock_bh(&pn->l2tp_tunnel_list_lock);
list_add_rcu(&tunnel->list, &pn->l2tp_tunnel_list);
spin_unlock_bh(&pn->l2tp_tunnel_list_lock);
err = 0;
err:
if (tunnelp)
*tunnelp = tunnel;
/* If tunnel's socket was created by the kernel, it doesn't
* have a file.
*/
if (sock && sock->file)
sockfd_put(sock);
return err;
}
EXPORT_SYMBOL_GPL(l2tp_tunnel_create);
/* This function is used by the netlink TUNNEL_DELETE command.
*/
int l2tp_tunnel_delete(struct l2tp_tunnel *tunnel)
{
int err = 0;
struct socket *sock = tunnel->sock ? tunnel->sock->sk_socket : NULL;
/* Force the tunnel socket to close. This will eventually
* cause the tunnel to be deleted via the normal socket close
* mechanisms when userspace closes the tunnel socket.
*/
if (sock != NULL) {
err = inet_shutdown(sock, 2);
/* If the tunnel's socket was created by the kernel,
* close the socket here since the socket was not
* created by userspace.
*/
if (sock->file == NULL)
err = inet_release(sock);
}
return err;
}
EXPORT_SYMBOL_GPL(l2tp_tunnel_delete);
/* Really kill the session.
*/
void l2tp_session_free(struct l2tp_session *session)
{
struct l2tp_tunnel *tunnel;
BUG_ON(atomic_read(&session->ref_count) != 0);
tunnel = session->tunnel;
if (tunnel != NULL) {
BUG_ON(tunnel->magic != L2TP_TUNNEL_MAGIC);
/* Delete the session from the hash */
write_lock_bh(&tunnel->hlist_lock);
hlist_del_init(&session->hlist);
write_unlock_bh(&tunnel->hlist_lock);
/* Unlink from the global hash if not L2TPv2 */
if (tunnel->version != L2TP_HDR_VER_2) {
struct l2tp_net *pn = l2tp_pernet(tunnel->l2tp_net);
spin_lock_bh(&pn->l2tp_session_hlist_lock);
hlist_del_init_rcu(&session->global_hlist);
spin_unlock_bh(&pn->l2tp_session_hlist_lock);
synchronize_rcu();
}
if (session->session_id != 0)
atomic_dec(&l2tp_session_count);
sock_put(tunnel->sock);
/* This will delete the tunnel context if this
* is the last session on the tunnel.
*/
session->tunnel = NULL;
l2tp_tunnel_dec_refcount(tunnel);
}
kfree(session);
return;
}
EXPORT_SYMBOL_GPL(l2tp_session_free);
/* This function is used by the netlink SESSION_DELETE command and by
pseudowire modules.
*/
int l2tp_session_delete(struct l2tp_session *session)
{
if (session->session_close != NULL)
(*session->session_close)(session);
l2tp_session_dec_refcount(session);
return 0;
}
EXPORT_SYMBOL_GPL(l2tp_session_delete);
/* We come here whenever a session's send_seq, cookie_len or
* l2specific_len parameters are set.
*/
static void l2tp_session_set_header_len(struct l2tp_session *session, int version)
{
if (version == L2TP_HDR_VER_2) {
session->hdr_len = 6;
if (session->send_seq)
session->hdr_len += 4;
} else {
session->hdr_len = 4 + session->cookie_len + session->l2specific_len + session->offset;
if (session->tunnel->encap == L2TP_ENCAPTYPE_UDP)
session->hdr_len += 4;
}
}
struct l2tp_session *l2tp_session_create(int priv_size, struct l2tp_tunnel *tunnel, u32 session_id, u32 peer_session_id, struct l2tp_session_cfg *cfg)
{
struct l2tp_session *session;
session = kzalloc(sizeof(struct l2tp_session) + priv_size, GFP_KERNEL);
if (session != NULL) {
session->magic = L2TP_SESSION_MAGIC;
session->tunnel = tunnel;
session->session_id = session_id;
session->peer_session_id = peer_session_id;
session->nr = 1;
sprintf(&session->name[0], "sess %u/%u",
tunnel->tunnel_id, session->session_id);
skb_queue_head_init(&session->reorder_q);
INIT_HLIST_NODE(&session->hlist);
INIT_HLIST_NODE(&session->global_hlist);
/* Inherit debug options from tunnel */
session->debug = tunnel->debug;
if (cfg) {
session->pwtype = cfg->pw_type;
session->debug = cfg->debug;
session->mtu = cfg->mtu;
session->mru = cfg->mru;
session->send_seq = cfg->send_seq;
session->recv_seq = cfg->recv_seq;
session->lns_mode = cfg->lns_mode;
session->reorder_timeout = cfg->reorder_timeout;
session->offset = cfg->offset;
session->l2specific_type = cfg->l2specific_type;
session->l2specific_len = cfg->l2specific_len;
session->cookie_len = cfg->cookie_len;
memcpy(&session->cookie[0], &cfg->cookie[0], cfg->cookie_len);
session->peer_cookie_len = cfg->peer_cookie_len;
memcpy(&session->peer_cookie[0], &cfg->peer_cookie[0], cfg->peer_cookie_len);
}
if (tunnel->version == L2TP_HDR_VER_2)
session->build_header = l2tp_build_l2tpv2_header;
else
session->build_header = l2tp_build_l2tpv3_header;
l2tp_session_set_header_len(session, tunnel->version);
/* Bump the reference count. The session context is deleted
* only when this drops to zero.
*/
l2tp_session_inc_refcount(session);
l2tp_tunnel_inc_refcount(tunnel);
/* Ensure tunnel socket isn't deleted */
sock_hold(tunnel->sock);
/* Add session to the tunnel's hash list */
write_lock_bh(&tunnel->hlist_lock);
hlist_add_head(&session->hlist,
l2tp_session_id_hash(tunnel, session_id));
write_unlock_bh(&tunnel->hlist_lock);
/* And to the global session list if L2TPv3 */
if (tunnel->version != L2TP_HDR_VER_2) {
struct l2tp_net *pn = l2tp_pernet(tunnel->l2tp_net);
spin_lock_bh(&pn->l2tp_session_hlist_lock);
hlist_add_head_rcu(&session->global_hlist,
l2tp_session_id_hash_2(pn, session_id));
spin_unlock_bh(&pn->l2tp_session_hlist_lock);
}
/* Ignore management session in session count value */
if (session->session_id != 0)
atomic_inc(&l2tp_session_count);
}
return session;
}
EXPORT_SYMBOL_GPL(l2tp_session_create);
/*****************************************************************************
* Init and cleanup
*****************************************************************************/
static __net_init int l2tp_init_net(struct net *net)
{
struct l2tp_net *pn = net_generic(net, l2tp_net_id);
int hash;
INIT_LIST_HEAD(&pn->l2tp_tunnel_list);
spin_lock_init(&pn->l2tp_tunnel_list_lock);
for (hash = 0; hash < L2TP_HASH_SIZE_2; hash++)
INIT_HLIST_HEAD(&pn->l2tp_session_hlist[hash]);
spin_lock_init(&pn->l2tp_session_hlist_lock);
return 0;
}
static struct pernet_operations l2tp_net_ops = {
.init = l2tp_init_net,
.id = &l2tp_net_id,
.size = sizeof(struct l2tp_net),
};
static int __init l2tp_init(void)
{
int rc = 0;
rc = register_pernet_device(&l2tp_net_ops);
if (rc)
goto out;
printk(KERN_INFO "L2TP core driver, %s\n", L2TP_DRV_VERSION);
out:
return rc;
}
static void __exit l2tp_exit(void)
{
unregister_pernet_device(&l2tp_net_ops);
}
module_init(l2tp_init);
module_exit(l2tp_exit);
MODULE_AUTHOR("James Chapman <jchapman@katalix.com>");
MODULE_DESCRIPTION("L2TP core");
MODULE_LICENSE("GPL");
MODULE_VERSION(L2TP_DRV_VERSION);
| gpl-2.0 |
fmaker/kernel_msm | drivers/net/wan/lapbether.c | 888 | 10364 | /*
* "LAPB via ethernet" driver release 001
*
* This code REQUIRES 2.1.15 or higher/ NET3.038
*
* This module:
* This module is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* This is a "pseudo" network driver to allow LAPB over Ethernet.
*
* This driver can use any ethernet destination address, and can be
* limited to accept frames from one dedicated ethernet card only.
*
* History
* LAPBETH 001 Jonathan Naylor Cloned from bpqether.c
* 2000-10-29 Henner Eisen lapb_data_indication() return status.
* 2000-11-14 Henner Eisen dev_hold/put, NETDEV_GOING_DOWN support
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/net.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/notifier.h>
#include <linux/stat.h>
#include <linux/netfilter.h>
#include <linux/module.h>
#include <linux/lapb.h>
#include <linux/init.h>
#include <net/x25device.h>
static char bcast_addr[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
/* If this number is made larger, check that the temporary string buffer
* in lapbeth_new_device is large enough to store the probe device name.*/
#define MAXLAPBDEV 100
struct lapbethdev {
struct list_head node;
struct net_device *ethdev; /* link to ethernet device */
struct net_device *axdev; /* lapbeth device (lapb#) */
};
static LIST_HEAD(lapbeth_devices);
/* ------------------------------------------------------------------------ */
/*
* Get the LAPB device for the ethernet device
*/
static struct lapbethdev *lapbeth_get_x25_dev(struct net_device *dev)
{
struct lapbethdev *lapbeth;
list_for_each_entry_rcu(lapbeth, &lapbeth_devices, node) {
if (lapbeth->ethdev == dev)
return lapbeth;
}
return NULL;
}
static __inline__ int dev_is_ethdev(struct net_device *dev)
{
return dev->type == ARPHRD_ETHER && strncmp(dev->name, "dummy", 5);
}
/* ------------------------------------------------------------------------ */
/*
* Receive a LAPB frame via an ethernet interface.
*/
static int lapbeth_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *ptype, struct net_device *orig_dev)
{
int len, err;
struct lapbethdev *lapbeth;
if (dev_net(dev) != &init_net)
goto drop;
if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL)
return NET_RX_DROP;
if (!pskb_may_pull(skb, 2))
goto drop;
rcu_read_lock();
lapbeth = lapbeth_get_x25_dev(dev);
if (!lapbeth)
goto drop_unlock;
if (!netif_running(lapbeth->axdev))
goto drop_unlock;
len = skb->data[0] + skb->data[1] * 256;
dev->stats.rx_packets++;
dev->stats.rx_bytes += len;
skb_pull(skb, 2); /* Remove the length bytes */
skb_trim(skb, len); /* Set the length of the data */
if ((err = lapb_data_received(lapbeth->axdev, skb)) != LAPB_OK) {
printk(KERN_DEBUG "lapbether: lapb_data_received err - %d\n", err);
goto drop_unlock;
}
out:
rcu_read_unlock();
return 0;
drop_unlock:
kfree_skb(skb);
goto out;
drop:
kfree_skb(skb);
return 0;
}
static int lapbeth_data_indication(struct net_device *dev, struct sk_buff *skb)
{
unsigned char *ptr;
skb_push(skb, 1);
if (skb_cow(skb, 1))
return NET_RX_DROP;
ptr = skb->data;
*ptr = X25_IFACE_DATA;
skb->protocol = x25_type_trans(skb, dev);
return netif_rx(skb);
}
/*
* Send a LAPB frame via an ethernet interface
*/
static netdev_tx_t lapbeth_xmit(struct sk_buff *skb,
struct net_device *dev)
{
int err;
/*
* Just to be *really* sure not to send anything if the interface
* is down, the ethernet device may have gone.
*/
if (!netif_running(dev))
goto drop;
switch (skb->data[0]) {
case X25_IFACE_DATA:
break;
case X25_IFACE_CONNECT:
if ((err = lapb_connect_request(dev)) != LAPB_OK)
printk(KERN_ERR "lapbeth: lapb_connect_request "
"error: %d\n", err);
goto drop;
case X25_IFACE_DISCONNECT:
if ((err = lapb_disconnect_request(dev)) != LAPB_OK)
printk(KERN_ERR "lapbeth: lapb_disconnect_request "
"err: %d\n", err);
/* Fall thru */
default:
goto drop;
}
skb_pull(skb, 1);
if ((err = lapb_data_request(dev, skb)) != LAPB_OK) {
printk(KERN_ERR "lapbeth: lapb_data_request error - %d\n", err);
goto drop;
}
out:
return NETDEV_TX_OK;
drop:
kfree_skb(skb);
goto out;
}
static void lapbeth_data_transmit(struct net_device *ndev, struct sk_buff *skb)
{
struct lapbethdev *lapbeth = netdev_priv(ndev);
unsigned char *ptr;
struct net_device *dev;
int size = skb->len;
skb->protocol = htons(ETH_P_X25);
ptr = skb_push(skb, 2);
*ptr++ = size % 256;
*ptr++ = size / 256;
ndev->stats.tx_packets++;
ndev->stats.tx_bytes += size;
skb->dev = dev = lapbeth->ethdev;
dev_hard_header(skb, dev, ETH_P_DEC, bcast_addr, NULL, 0);
dev_queue_xmit(skb);
}
static void lapbeth_connected(struct net_device *dev, int reason)
{
unsigned char *ptr;
struct sk_buff *skb = dev_alloc_skb(1);
if (!skb) {
printk(KERN_ERR "lapbeth: out of memory\n");
return;
}
ptr = skb_put(skb, 1);
*ptr = X25_IFACE_CONNECT;
skb->protocol = x25_type_trans(skb, dev);
netif_rx(skb);
}
static void lapbeth_disconnected(struct net_device *dev, int reason)
{
unsigned char *ptr;
struct sk_buff *skb = dev_alloc_skb(1);
if (!skb) {
printk(KERN_ERR "lapbeth: out of memory\n");
return;
}
ptr = skb_put(skb, 1);
*ptr = X25_IFACE_DISCONNECT;
skb->protocol = x25_type_trans(skb, dev);
netif_rx(skb);
}
/*
* Set AX.25 callsign
*/
static int lapbeth_set_mac_address(struct net_device *dev, void *addr)
{
struct sockaddr *sa = addr;
memcpy(dev->dev_addr, sa->sa_data, dev->addr_len);
return 0;
}
static struct lapb_register_struct lapbeth_callbacks = {
.connect_confirmation = lapbeth_connected,
.connect_indication = lapbeth_connected,
.disconnect_confirmation = lapbeth_disconnected,
.disconnect_indication = lapbeth_disconnected,
.data_indication = lapbeth_data_indication,
.data_transmit = lapbeth_data_transmit,
};
/*
* open/close a device
*/
static int lapbeth_open(struct net_device *dev)
{
int err;
if ((err = lapb_register(dev, &lapbeth_callbacks)) != LAPB_OK) {
printk(KERN_ERR "lapbeth: lapb_register error - %d\n", err);
return -ENODEV;
}
netif_start_queue(dev);
return 0;
}
static int lapbeth_close(struct net_device *dev)
{
int err;
netif_stop_queue(dev);
if ((err = lapb_unregister(dev)) != LAPB_OK)
printk(KERN_ERR "lapbeth: lapb_unregister error - %d\n", err);
return 0;
}
/* ------------------------------------------------------------------------ */
static const struct net_device_ops lapbeth_netdev_ops = {
.ndo_open = lapbeth_open,
.ndo_stop = lapbeth_close,
.ndo_start_xmit = lapbeth_xmit,
.ndo_set_mac_address = lapbeth_set_mac_address,
};
static void lapbeth_setup(struct net_device *dev)
{
dev->netdev_ops = &lapbeth_netdev_ops;
dev->destructor = free_netdev;
dev->type = ARPHRD_X25;
dev->hard_header_len = 3;
dev->mtu = 1000;
dev->addr_len = 0;
}
/*
* Setup a new device.
*/
static int lapbeth_new_device(struct net_device *dev)
{
struct net_device *ndev;
struct lapbethdev *lapbeth;
int rc = -ENOMEM;
ASSERT_RTNL();
ndev = alloc_netdev(sizeof(*lapbeth), "lapb%d",
lapbeth_setup);
if (!ndev)
goto out;
lapbeth = netdev_priv(ndev);
lapbeth->axdev = ndev;
dev_hold(dev);
lapbeth->ethdev = dev;
rc = dev_alloc_name(ndev, ndev->name);
if (rc < 0)
goto fail;
rc = -EIO;
if (register_netdevice(ndev))
goto fail;
list_add_rcu(&lapbeth->node, &lapbeth_devices);
rc = 0;
out:
return rc;
fail:
dev_put(dev);
free_netdev(ndev);
kfree(lapbeth);
goto out;
}
/*
* Free a lapb network device.
*/
static void lapbeth_free_device(struct lapbethdev *lapbeth)
{
dev_put(lapbeth->ethdev);
list_del_rcu(&lapbeth->node);
unregister_netdevice(lapbeth->axdev);
}
/*
* Handle device status changes.
*
* Called from notifier with RTNL held.
*/
static int lapbeth_device_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct lapbethdev *lapbeth;
struct net_device *dev = ptr;
if (dev_net(dev) != &init_net)
return NOTIFY_DONE;
if (!dev_is_ethdev(dev))
return NOTIFY_DONE;
switch (event) {
case NETDEV_UP:
/* New ethernet device -> new LAPB interface */
if (lapbeth_get_x25_dev(dev) == NULL)
lapbeth_new_device(dev);
break;
case NETDEV_DOWN:
/* ethernet device closed -> close LAPB interface */
lapbeth = lapbeth_get_x25_dev(dev);
if (lapbeth)
dev_close(lapbeth->axdev);
break;
case NETDEV_UNREGISTER:
/* ethernet device disappears -> remove LAPB interface */
lapbeth = lapbeth_get_x25_dev(dev);
if (lapbeth)
lapbeth_free_device(lapbeth);
break;
}
return NOTIFY_DONE;
}
/* ------------------------------------------------------------------------ */
static struct packet_type lapbeth_packet_type __read_mostly = {
.type = cpu_to_be16(ETH_P_DEC),
.func = lapbeth_rcv,
};
static struct notifier_block lapbeth_dev_notifier = {
.notifier_call = lapbeth_device_event,
};
static const char banner[] __initconst =
KERN_INFO "LAPB Ethernet driver version 0.02\n";
static int __init lapbeth_init_driver(void)
{
dev_add_pack(&lapbeth_packet_type);
register_netdevice_notifier(&lapbeth_dev_notifier);
printk(banner);
return 0;
}
module_init(lapbeth_init_driver);
static void __exit lapbeth_cleanup_driver(void)
{
struct lapbethdev *lapbeth;
struct list_head *entry, *tmp;
dev_remove_pack(&lapbeth_packet_type);
unregister_netdevice_notifier(&lapbeth_dev_notifier);
rtnl_lock();
list_for_each_safe(entry, tmp, &lapbeth_devices) {
lapbeth = list_entry(entry, struct lapbethdev, node);
dev_put(lapbeth->ethdev);
unregister_netdevice(lapbeth->axdev);
}
rtnl_unlock();
}
module_exit(lapbeth_cleanup_driver);
MODULE_AUTHOR("Jonathan Naylor <g4klx@g4klx.demon.co.uk>");
MODULE_DESCRIPTION("The unofficial LAPB over Ethernet driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
learningendless/linux-xlnx | crypto/842.c | 1400 | 4705 | /*
* Cryptographic API for the 842 compression algorithm.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Copyright (C) IBM Corporation, 2011
*
* Authors: Robert Jennings <rcj@linux.vnet.ibm.com>
* Seth Jennings <sjenning@linux.vnet.ibm.com>
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/crypto.h>
#include <linux/vmalloc.h>
#include <linux/nx842.h>
#include <linux/lzo.h>
#include <linux/timer.h>
static int nx842_uselzo;
struct nx842_ctx {
void *nx842_wmem; /* working memory for 842/lzo */
};
enum nx842_crypto_type {
NX842_CRYPTO_TYPE_842,
NX842_CRYPTO_TYPE_LZO
};
#define NX842_SENTINEL 0xdeadbeef
struct nx842_crypto_header {
unsigned int sentinel; /* debug */
enum nx842_crypto_type type;
};
static int nx842_init(struct crypto_tfm *tfm)
{
struct nx842_ctx *ctx = crypto_tfm_ctx(tfm);
int wmemsize;
wmemsize = max_t(int, nx842_get_workmem_size(), LZO1X_MEM_COMPRESS);
ctx->nx842_wmem = kmalloc(wmemsize, GFP_NOFS);
if (!ctx->nx842_wmem)
return -ENOMEM;
return 0;
}
static void nx842_exit(struct crypto_tfm *tfm)
{
struct nx842_ctx *ctx = crypto_tfm_ctx(tfm);
kfree(ctx->nx842_wmem);
}
static void nx842_reset_uselzo(unsigned long data)
{
nx842_uselzo = 0;
}
static DEFINE_TIMER(failover_timer, nx842_reset_uselzo, 0, 0);
static int nx842_crypto_compress(struct crypto_tfm *tfm, const u8 *src,
unsigned int slen, u8 *dst, unsigned int *dlen)
{
struct nx842_ctx *ctx = crypto_tfm_ctx(tfm);
struct nx842_crypto_header *hdr;
unsigned int tmp_len = *dlen;
size_t lzodlen; /* needed for lzo */
int err;
*dlen = 0;
hdr = (struct nx842_crypto_header *)dst;
hdr->sentinel = NX842_SENTINEL; /* debug */
dst += sizeof(struct nx842_crypto_header);
tmp_len -= sizeof(struct nx842_crypto_header);
lzodlen = tmp_len;
if (likely(!nx842_uselzo)) {
err = nx842_compress(src, slen, dst, &tmp_len, ctx->nx842_wmem);
if (likely(!err)) {
hdr->type = NX842_CRYPTO_TYPE_842;
*dlen = tmp_len + sizeof(struct nx842_crypto_header);
return 0;
}
/* hardware failed */
nx842_uselzo = 1;
/* set timer to check for hardware again in 1 second */
mod_timer(&failover_timer, jiffies + msecs_to_jiffies(1000));
}
/* no hardware, use lzo */
err = lzo1x_1_compress(src, slen, dst, &lzodlen, ctx->nx842_wmem);
if (err != LZO_E_OK)
return -EINVAL;
hdr->type = NX842_CRYPTO_TYPE_LZO;
*dlen = lzodlen + sizeof(struct nx842_crypto_header);
return 0;
}
static int nx842_crypto_decompress(struct crypto_tfm *tfm, const u8 *src,
unsigned int slen, u8 *dst, unsigned int *dlen)
{
struct nx842_ctx *ctx = crypto_tfm_ctx(tfm);
struct nx842_crypto_header *hdr;
unsigned int tmp_len = *dlen;
size_t lzodlen; /* needed for lzo */
int err;
*dlen = 0;
hdr = (struct nx842_crypto_header *)src;
if (unlikely(hdr->sentinel != NX842_SENTINEL))
return -EINVAL;
src += sizeof(struct nx842_crypto_header);
slen -= sizeof(struct nx842_crypto_header);
if (likely(hdr->type == NX842_CRYPTO_TYPE_842)) {
err = nx842_decompress(src, slen, dst, &tmp_len,
ctx->nx842_wmem);
if (err)
return -EINVAL;
*dlen = tmp_len;
} else if (hdr->type == NX842_CRYPTO_TYPE_LZO) {
lzodlen = tmp_len;
err = lzo1x_decompress_safe(src, slen, dst, &lzodlen);
if (err != LZO_E_OK)
return -EINVAL;
*dlen = lzodlen;
} else
return -EINVAL;
return 0;
}
static struct crypto_alg alg = {
.cra_name = "842",
.cra_flags = CRYPTO_ALG_TYPE_COMPRESS,
.cra_ctxsize = sizeof(struct nx842_ctx),
.cra_module = THIS_MODULE,
.cra_init = nx842_init,
.cra_exit = nx842_exit,
.cra_u = { .compress = {
.coa_compress = nx842_crypto_compress,
.coa_decompress = nx842_crypto_decompress } }
};
static int __init nx842_mod_init(void)
{
del_timer(&failover_timer);
return crypto_register_alg(&alg);
}
static void __exit nx842_mod_exit(void)
{
crypto_unregister_alg(&alg);
}
module_init(nx842_mod_init);
module_exit(nx842_mod_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("842 Compression Algorithm");
MODULE_ALIAS_CRYPTO("842");
| gpl-2.0 |
weimenlove/linux-2.6.37-real6410 | drivers/hid/hid-chicony.c | 3192 | 2187 | /*
* HID driver for some chicony "special" devices
*
* Copyright (c) 1999 Andreas Gal
* Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz>
* Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc
* Copyright (c) 2006-2007 Jiri Kosina
* Copyright (c) 2007 Paul Walmsley
* Copyright (c) 2008 Jiri Slaby
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*/
#include <linux/device.h>
#include <linux/input.h>
#include <linux/hid.h>
#include <linux/module.h>
#include "hid-ids.h"
#define ch_map_key_clear(c) hid_map_usage_clear(hi, usage, bit, max, \
EV_KEY, (c))
static int ch_input_mapping(struct hid_device *hdev, struct hid_input *hi,
struct hid_field *field, struct hid_usage *usage,
unsigned long **bit, int *max)
{
if ((usage->hid & HID_USAGE_PAGE) != HID_UP_MSVENDOR)
return 0;
set_bit(EV_REP, hi->input->evbit);
switch (usage->hid & HID_USAGE) {
case 0xff01: ch_map_key_clear(BTN_1); break;
case 0xff02: ch_map_key_clear(BTN_2); break;
case 0xff03: ch_map_key_clear(BTN_3); break;
case 0xff04: ch_map_key_clear(BTN_4); break;
case 0xff05: ch_map_key_clear(BTN_5); break;
case 0xff06: ch_map_key_clear(BTN_6); break;
case 0xff07: ch_map_key_clear(BTN_7); break;
case 0xff08: ch_map_key_clear(BTN_8); break;
case 0xff09: ch_map_key_clear(BTN_9); break;
case 0xff0a: ch_map_key_clear(BTN_A); break;
case 0xff0b: ch_map_key_clear(BTN_B); break;
default:
return 0;
}
return 1;
}
static const struct hid_device_id ch_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_CHICONY, USB_DEVICE_ID_CHICONY_TACTICAL_PAD) },
{ }
};
MODULE_DEVICE_TABLE(hid, ch_devices);
static struct hid_driver ch_driver = {
.name = "chicony",
.id_table = ch_devices,
.input_mapping = ch_input_mapping,
};
static int __init ch_init(void)
{
return hid_register_driver(&ch_driver);
}
static void __exit ch_exit(void)
{
hid_unregister_driver(&ch_driver);
}
module_init(ch_init);
module_exit(ch_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
fortunaFiWn/android_kernel_samsung_fortuna | arch/arm/mach-ixp4xx/gateway7001-setup.c | 4472 | 2642 | /*
* arch/arm/mach-ixp4xx/gateway7001-setup.c
*
* Board setup for the Gateway 7001 board
*
* Copyright (C) 2007 Imre Kaloz <kaloz@openwrt.org>
*
* based on coyote-setup.c:
* Copyright (C) 2003-2005 MontaVista Software, Inc.
*
* Author: Imre Kaloz <Kaloz@openwrt.org>
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/serial.h>
#include <linux/tty.h>
#include <linux/serial_8250.h>
#include <asm/types.h>
#include <asm/setup.h>
#include <asm/memory.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/flash.h>
static struct flash_platform_data gateway7001_flash_data = {
.map_name = "cfi_probe",
.width = 2,
};
static struct resource gateway7001_flash_resource = {
.flags = IORESOURCE_MEM,
};
static struct platform_device gateway7001_flash = {
.name = "IXP4XX-Flash",
.id = 0,
.dev = {
.platform_data = &gateway7001_flash_data,
},
.num_resources = 1,
.resource = &gateway7001_flash_resource,
};
static struct resource gateway7001_uart_resource = {
.start = IXP4XX_UART2_BASE_PHYS,
.end = IXP4XX_UART2_BASE_PHYS + 0x0fff,
.flags = IORESOURCE_MEM,
};
static struct plat_serial8250_port gateway7001_uart_data[] = {
{
.mapbase = IXP4XX_UART2_BASE_PHYS,
.membase = (char *)IXP4XX_UART2_BASE_VIRT + REG_OFFSET,
.irq = IRQ_IXP4XX_UART2,
.flags = UPF_BOOT_AUTOCONF | UPF_SKIP_TEST,
.iotype = UPIO_MEM,
.regshift = 2,
.uartclk = IXP4XX_UART_XTAL,
},
{ },
};
static struct platform_device gateway7001_uart = {
.name = "serial8250",
.id = PLAT8250_DEV_PLATFORM,
.dev = {
.platform_data = gateway7001_uart_data,
},
.num_resources = 1,
.resource = &gateway7001_uart_resource,
};
static struct platform_device *gateway7001_devices[] __initdata = {
&gateway7001_flash,
&gateway7001_uart
};
static void __init gateway7001_init(void)
{
ixp4xx_sys_init();
gateway7001_flash_resource.start = IXP4XX_EXP_BUS_BASE(0);
gateway7001_flash_resource.end = IXP4XX_EXP_BUS_BASE(0) + SZ_32M - 1;
*IXP4XX_EXP_CS0 |= IXP4XX_FLASH_WRITABLE;
*IXP4XX_EXP_CS1 = *IXP4XX_EXP_CS0;
platform_add_devices(gateway7001_devices, ARRAY_SIZE(gateway7001_devices));
}
#ifdef CONFIG_MACH_GATEWAY7001
MACHINE_START(GATEWAY7001, "Gateway 7001 AP")
/* Maintainer: Imre Kaloz <kaloz@openwrt.org> */
.map_io = ixp4xx_map_io,
.init_early = ixp4xx_init_early,
.init_irq = ixp4xx_init_irq,
.init_time = ixp4xx_timer_init,
.atag_offset = 0x100,
.init_machine = gateway7001_init,
#if defined(CONFIG_PCI)
.dma_zone_size = SZ_64M,
#endif
.restart = ixp4xx_restart,
MACHINE_END
#endif
| gpl-2.0 |
theboleslaw/hammerhead_kernel | drivers/usb/serial/digi_acceleport.c | 4728 | 45694 | /*
* Digi AccelePort USB-4 and USB-2 Serial Converters
*
* Copyright 2000 by Digi International
*
* 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.
*
* Shamelessly based on Brian Warner's keyspan_pda.c and Greg Kroah-Hartman's
* usb-serial driver.
*
* Peter Berger (pberger@brimson.com)
* Al Borchers (borchers@steinerpoint.com)
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/workqueue.h>
#include <linux/uaccess.h>
#include <linux/usb.h>
#include <linux/wait.h>
#include <linux/usb/serial.h>
/* Defines */
/*
* Version Information
*/
#define DRIVER_VERSION "v1.80.1.2"
#define DRIVER_AUTHOR "Peter Berger <pberger@brimson.com>, Al Borchers <borchers@steinerpoint.com>"
#define DRIVER_DESC "Digi AccelePort USB-2/USB-4 Serial Converter driver"
/* port output buffer length -- must be <= transfer buffer length - 2 */
/* so we can be sure to send the full buffer in one urb */
#define DIGI_OUT_BUF_SIZE 8
/* port input buffer length -- must be >= transfer buffer length - 3 */
/* so we can be sure to hold at least one full buffer from one urb */
#define DIGI_IN_BUF_SIZE 64
/* retry timeout while sleeping */
#define DIGI_RETRY_TIMEOUT (HZ/10)
/* timeout while waiting for tty output to drain in close */
/* this delay is used twice in close, so the total delay could */
/* be twice this value */
#define DIGI_CLOSE_TIMEOUT (5*HZ)
/* AccelePort USB Defines */
/* ids */
#define DIGI_VENDOR_ID 0x05c5
#define DIGI_2_ID 0x0002 /* USB-2 */
#define DIGI_4_ID 0x0004 /* USB-4 */
/* commands
* "INB": can be used on the in-band endpoint
* "OOB": can be used on the out-of-band endpoint
*/
#define DIGI_CMD_SET_BAUD_RATE 0 /* INB, OOB */
#define DIGI_CMD_SET_WORD_SIZE 1 /* INB, OOB */
#define DIGI_CMD_SET_PARITY 2 /* INB, OOB */
#define DIGI_CMD_SET_STOP_BITS 3 /* INB, OOB */
#define DIGI_CMD_SET_INPUT_FLOW_CONTROL 4 /* INB, OOB */
#define DIGI_CMD_SET_OUTPUT_FLOW_CONTROL 5 /* INB, OOB */
#define DIGI_CMD_SET_DTR_SIGNAL 6 /* INB, OOB */
#define DIGI_CMD_SET_RTS_SIGNAL 7 /* INB, OOB */
#define DIGI_CMD_READ_INPUT_SIGNALS 8 /* OOB */
#define DIGI_CMD_IFLUSH_FIFO 9 /* OOB */
#define DIGI_CMD_RECEIVE_ENABLE 10 /* INB, OOB */
#define DIGI_CMD_BREAK_CONTROL 11 /* INB, OOB */
#define DIGI_CMD_LOCAL_LOOPBACK 12 /* INB, OOB */
#define DIGI_CMD_TRANSMIT_IDLE 13 /* INB, OOB */
#define DIGI_CMD_READ_UART_REGISTER 14 /* OOB */
#define DIGI_CMD_WRITE_UART_REGISTER 15 /* INB, OOB */
#define DIGI_CMD_AND_UART_REGISTER 16 /* INB, OOB */
#define DIGI_CMD_OR_UART_REGISTER 17 /* INB, OOB */
#define DIGI_CMD_SEND_DATA 18 /* INB */
#define DIGI_CMD_RECEIVE_DATA 19 /* INB */
#define DIGI_CMD_RECEIVE_DISABLE 20 /* INB */
#define DIGI_CMD_GET_PORT_TYPE 21 /* OOB */
/* baud rates */
#define DIGI_BAUD_50 0
#define DIGI_BAUD_75 1
#define DIGI_BAUD_110 2
#define DIGI_BAUD_150 3
#define DIGI_BAUD_200 4
#define DIGI_BAUD_300 5
#define DIGI_BAUD_600 6
#define DIGI_BAUD_1200 7
#define DIGI_BAUD_1800 8
#define DIGI_BAUD_2400 9
#define DIGI_BAUD_4800 10
#define DIGI_BAUD_7200 11
#define DIGI_BAUD_9600 12
#define DIGI_BAUD_14400 13
#define DIGI_BAUD_19200 14
#define DIGI_BAUD_28800 15
#define DIGI_BAUD_38400 16
#define DIGI_BAUD_57600 17
#define DIGI_BAUD_76800 18
#define DIGI_BAUD_115200 19
#define DIGI_BAUD_153600 20
#define DIGI_BAUD_230400 21
#define DIGI_BAUD_460800 22
/* arguments */
#define DIGI_WORD_SIZE_5 0
#define DIGI_WORD_SIZE_6 1
#define DIGI_WORD_SIZE_7 2
#define DIGI_WORD_SIZE_8 3
#define DIGI_PARITY_NONE 0
#define DIGI_PARITY_ODD 1
#define DIGI_PARITY_EVEN 2
#define DIGI_PARITY_MARK 3
#define DIGI_PARITY_SPACE 4
#define DIGI_STOP_BITS_1 0
#define DIGI_STOP_BITS_2 1
#define DIGI_INPUT_FLOW_CONTROL_XON_XOFF 1
#define DIGI_INPUT_FLOW_CONTROL_RTS 2
#define DIGI_INPUT_FLOW_CONTROL_DTR 4
#define DIGI_OUTPUT_FLOW_CONTROL_XON_XOFF 1
#define DIGI_OUTPUT_FLOW_CONTROL_CTS 2
#define DIGI_OUTPUT_FLOW_CONTROL_DSR 4
#define DIGI_DTR_INACTIVE 0
#define DIGI_DTR_ACTIVE 1
#define DIGI_DTR_INPUT_FLOW_CONTROL 2
#define DIGI_RTS_INACTIVE 0
#define DIGI_RTS_ACTIVE 1
#define DIGI_RTS_INPUT_FLOW_CONTROL 2
#define DIGI_RTS_TOGGLE 3
#define DIGI_FLUSH_TX 1
#define DIGI_FLUSH_RX 2
#define DIGI_RESUME_TX 4 /* clears xoff condition */
#define DIGI_TRANSMIT_NOT_IDLE 0
#define DIGI_TRANSMIT_IDLE 1
#define DIGI_DISABLE 0
#define DIGI_ENABLE 1
#define DIGI_DEASSERT 0
#define DIGI_ASSERT 1
/* in band status codes */
#define DIGI_OVERRUN_ERROR 4
#define DIGI_PARITY_ERROR 8
#define DIGI_FRAMING_ERROR 16
#define DIGI_BREAK_ERROR 32
/* out of band status */
#define DIGI_NO_ERROR 0
#define DIGI_BAD_FIRST_PARAMETER 1
#define DIGI_BAD_SECOND_PARAMETER 2
#define DIGI_INVALID_LINE 3
#define DIGI_INVALID_OPCODE 4
/* input signals */
#define DIGI_READ_INPUT_SIGNALS_SLOT 1
#define DIGI_READ_INPUT_SIGNALS_ERR 2
#define DIGI_READ_INPUT_SIGNALS_BUSY 4
#define DIGI_READ_INPUT_SIGNALS_PE 8
#define DIGI_READ_INPUT_SIGNALS_CTS 16
#define DIGI_READ_INPUT_SIGNALS_DSR 32
#define DIGI_READ_INPUT_SIGNALS_RI 64
#define DIGI_READ_INPUT_SIGNALS_DCD 128
/* Structures */
struct digi_serial {
spinlock_t ds_serial_lock;
struct usb_serial_port *ds_oob_port; /* out-of-band port */
int ds_oob_port_num; /* index of out-of-band port */
int ds_device_started;
};
struct digi_port {
spinlock_t dp_port_lock;
int dp_port_num;
int dp_out_buf_len;
unsigned char dp_out_buf[DIGI_OUT_BUF_SIZE];
int dp_write_urb_in_use;
unsigned int dp_modem_signals;
wait_queue_head_t dp_modem_change_wait;
int dp_transmit_idle;
wait_queue_head_t dp_transmit_idle_wait;
int dp_throttled;
int dp_throttle_restart;
wait_queue_head_t dp_flush_wait;
wait_queue_head_t dp_close_wait; /* wait queue for close */
struct work_struct dp_wakeup_work;
struct usb_serial_port *dp_port;
};
/* Local Function Declarations */
static void digi_wakeup_write(struct usb_serial_port *port);
static void digi_wakeup_write_lock(struct work_struct *work);
static int digi_write_oob_command(struct usb_serial_port *port,
unsigned char *buf, int count, int interruptible);
static int digi_write_inb_command(struct usb_serial_port *port,
unsigned char *buf, int count, unsigned long timeout);
static int digi_set_modem_signals(struct usb_serial_port *port,
unsigned int modem_signals, int interruptible);
static int digi_transmit_idle(struct usb_serial_port *port,
unsigned long timeout);
static void digi_rx_throttle(struct tty_struct *tty);
static void digi_rx_unthrottle(struct tty_struct *tty);
static void digi_set_termios(struct tty_struct *tty,
struct usb_serial_port *port, struct ktermios *old_termios);
static void digi_break_ctl(struct tty_struct *tty, int break_state);
static int digi_tiocmget(struct tty_struct *tty);
static int digi_tiocmset(struct tty_struct *tty, unsigned int set,
unsigned int clear);
static int digi_write(struct tty_struct *tty, struct usb_serial_port *port,
const unsigned char *buf, int count);
static void digi_write_bulk_callback(struct urb *urb);
static int digi_write_room(struct tty_struct *tty);
static int digi_chars_in_buffer(struct tty_struct *tty);
static int digi_open(struct tty_struct *tty, struct usb_serial_port *port);
static void digi_close(struct usb_serial_port *port);
static void digi_dtr_rts(struct usb_serial_port *port, int on);
static int digi_startup_device(struct usb_serial *serial);
static int digi_startup(struct usb_serial *serial);
static void digi_disconnect(struct usb_serial *serial);
static void digi_release(struct usb_serial *serial);
static void digi_read_bulk_callback(struct urb *urb);
static int digi_read_inb_callback(struct urb *urb);
static int digi_read_oob_callback(struct urb *urb);
/* Statics */
static bool debug;
static const struct usb_device_id id_table_combined[] = {
{ USB_DEVICE(DIGI_VENDOR_ID, DIGI_2_ID) },
{ USB_DEVICE(DIGI_VENDOR_ID, DIGI_4_ID) },
{ } /* Terminating entry */
};
static const struct usb_device_id id_table_2[] = {
{ USB_DEVICE(DIGI_VENDOR_ID, DIGI_2_ID) },
{ } /* Terminating entry */
};
static const struct usb_device_id id_table_4[] = {
{ USB_DEVICE(DIGI_VENDOR_ID, DIGI_4_ID) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, id_table_combined);
static struct usb_driver digi_driver = {
.name = "digi_acceleport",
.probe = usb_serial_probe,
.disconnect = usb_serial_disconnect,
.id_table = id_table_combined,
};
/* device info needed for the Digi serial converter */
static struct usb_serial_driver digi_acceleport_2_device = {
.driver = {
.owner = THIS_MODULE,
.name = "digi_2",
},
.description = "Digi 2 port USB adapter",
.id_table = id_table_2,
.num_ports = 3,
.open = digi_open,
.close = digi_close,
.dtr_rts = digi_dtr_rts,
.write = digi_write,
.write_room = digi_write_room,
.write_bulk_callback = digi_write_bulk_callback,
.read_bulk_callback = digi_read_bulk_callback,
.chars_in_buffer = digi_chars_in_buffer,
.throttle = digi_rx_throttle,
.unthrottle = digi_rx_unthrottle,
.set_termios = digi_set_termios,
.break_ctl = digi_break_ctl,
.tiocmget = digi_tiocmget,
.tiocmset = digi_tiocmset,
.attach = digi_startup,
.disconnect = digi_disconnect,
.release = digi_release,
};
static struct usb_serial_driver digi_acceleport_4_device = {
.driver = {
.owner = THIS_MODULE,
.name = "digi_4",
},
.description = "Digi 4 port USB adapter",
.id_table = id_table_4,
.num_ports = 4,
.open = digi_open,
.close = digi_close,
.write = digi_write,
.write_room = digi_write_room,
.write_bulk_callback = digi_write_bulk_callback,
.read_bulk_callback = digi_read_bulk_callback,
.chars_in_buffer = digi_chars_in_buffer,
.throttle = digi_rx_throttle,
.unthrottle = digi_rx_unthrottle,
.set_termios = digi_set_termios,
.break_ctl = digi_break_ctl,
.tiocmget = digi_tiocmget,
.tiocmset = digi_tiocmset,
.attach = digi_startup,
.disconnect = digi_disconnect,
.release = digi_release,
};
static struct usb_serial_driver * const serial_drivers[] = {
&digi_acceleport_2_device, &digi_acceleport_4_device, NULL
};
/* Functions */
/*
* Cond Wait Interruptible Timeout Irqrestore
*
* Do spin_unlock_irqrestore and interruptible_sleep_on_timeout
* so that wake ups are not lost if they occur between the unlock
* and the sleep. In other words, spin_unlock_irqrestore and
* interruptible_sleep_on_timeout are "atomic" with respect to
* wake ups. This is used to implement condition variables.
*
* interruptible_sleep_on_timeout is deprecated and has been replaced
* with the equivalent code.
*/
static long cond_wait_interruptible_timeout_irqrestore(
wait_queue_head_t *q, long timeout,
spinlock_t *lock, unsigned long flags)
__releases(lock)
{
DEFINE_WAIT(wait);
prepare_to_wait(q, &wait, TASK_INTERRUPTIBLE);
spin_unlock_irqrestore(lock, flags);
timeout = schedule_timeout(timeout);
finish_wait(q, &wait);
return timeout;
}
/*
* Digi Wakeup Write
*
* Wake up port, line discipline, and tty processes sleeping
* on writes.
*/
static void digi_wakeup_write_lock(struct work_struct *work)
{
struct digi_port *priv =
container_of(work, struct digi_port, dp_wakeup_work);
struct usb_serial_port *port = priv->dp_port;
unsigned long flags;
spin_lock_irqsave(&priv->dp_port_lock, flags);
digi_wakeup_write(port);
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
}
static void digi_wakeup_write(struct usb_serial_port *port)
{
struct tty_struct *tty = tty_port_tty_get(&port->port);
if (tty) {
tty_wakeup(tty);
tty_kref_put(tty);
}
}
/*
* Digi Write OOB Command
*
* Write commands on the out of band port. Commands are 4
* bytes each, multiple commands can be sent at once, and
* no command will be split across USB packets. Returns 0
* if successful, -EINTR if interrupted while sleeping and
* the interruptible flag is true, or a negative error
* returned by usb_submit_urb.
*/
static int digi_write_oob_command(struct usb_serial_port *port,
unsigned char *buf, int count, int interruptible)
{
int ret = 0;
int len;
struct usb_serial_port *oob_port = (struct usb_serial_port *)((struct digi_serial *)(usb_get_serial_data(port->serial)))->ds_oob_port;
struct digi_port *oob_priv = usb_get_serial_port_data(oob_port);
unsigned long flags = 0;
dbg("digi_write_oob_command: TOP: port=%d, count=%d", oob_priv->dp_port_num, count);
spin_lock_irqsave(&oob_priv->dp_port_lock, flags);
while (count > 0) {
while (oob_priv->dp_write_urb_in_use) {
cond_wait_interruptible_timeout_irqrestore(
&oob_port->write_wait, DIGI_RETRY_TIMEOUT,
&oob_priv->dp_port_lock, flags);
if (interruptible && signal_pending(current))
return -EINTR;
spin_lock_irqsave(&oob_priv->dp_port_lock, flags);
}
/* len must be a multiple of 4, so commands are not split */
len = min(count, oob_port->bulk_out_size);
if (len > 4)
len &= ~3;
memcpy(oob_port->write_urb->transfer_buffer, buf, len);
oob_port->write_urb->transfer_buffer_length = len;
ret = usb_submit_urb(oob_port->write_urb, GFP_ATOMIC);
if (ret == 0) {
oob_priv->dp_write_urb_in_use = 1;
count -= len;
buf += len;
}
}
spin_unlock_irqrestore(&oob_priv->dp_port_lock, flags);
if (ret)
dev_err(&port->dev, "%s: usb_submit_urb failed, ret=%d\n",
__func__, ret);
return ret;
}
/*
* Digi Write In Band Command
*
* Write commands on the given port. Commands are 4
* bytes each, multiple commands can be sent at once, and
* no command will be split across USB packets. If timeout
* is non-zero, write in band command will return after
* waiting unsuccessfully for the URB status to clear for
* timeout ticks. Returns 0 if successful, or a negative
* error returned by digi_write.
*/
static int digi_write_inb_command(struct usb_serial_port *port,
unsigned char *buf, int count, unsigned long timeout)
{
int ret = 0;
int len;
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned char *data = port->write_urb->transfer_buffer;
unsigned long flags = 0;
dbg("digi_write_inb_command: TOP: port=%d, count=%d",
priv->dp_port_num, count);
if (timeout)
timeout += jiffies;
else
timeout = ULONG_MAX;
spin_lock_irqsave(&priv->dp_port_lock, flags);
while (count > 0 && ret == 0) {
while (priv->dp_write_urb_in_use &&
time_before(jiffies, timeout)) {
cond_wait_interruptible_timeout_irqrestore(
&port->write_wait, DIGI_RETRY_TIMEOUT,
&priv->dp_port_lock, flags);
if (signal_pending(current))
return -EINTR;
spin_lock_irqsave(&priv->dp_port_lock, flags);
}
/* len must be a multiple of 4 and small enough to */
/* guarantee the write will send buffered data first, */
/* so commands are in order with data and not split */
len = min(count, port->bulk_out_size-2-priv->dp_out_buf_len);
if (len > 4)
len &= ~3;
/* write any buffered data first */
if (priv->dp_out_buf_len > 0) {
data[0] = DIGI_CMD_SEND_DATA;
data[1] = priv->dp_out_buf_len;
memcpy(data + 2, priv->dp_out_buf,
priv->dp_out_buf_len);
memcpy(data + 2 + priv->dp_out_buf_len, buf, len);
port->write_urb->transfer_buffer_length
= priv->dp_out_buf_len + 2 + len;
} else {
memcpy(data, buf, len);
port->write_urb->transfer_buffer_length = len;
}
ret = usb_submit_urb(port->write_urb, GFP_ATOMIC);
if (ret == 0) {
priv->dp_write_urb_in_use = 1;
priv->dp_out_buf_len = 0;
count -= len;
buf += len;
}
}
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
if (ret)
dev_err(&port->dev,
"%s: usb_submit_urb failed, ret=%d, port=%d\n",
__func__, ret, priv->dp_port_num);
return ret;
}
/*
* Digi Set Modem Signals
*
* Sets or clears DTR and RTS on the port, according to the
* modem_signals argument. Use TIOCM_DTR and TIOCM_RTS flags
* for the modem_signals argument. Returns 0 if successful,
* -EINTR if interrupted while sleeping, or a non-zero error
* returned by usb_submit_urb.
*/
static int digi_set_modem_signals(struct usb_serial_port *port,
unsigned int modem_signals, int interruptible)
{
int ret;
struct digi_port *port_priv = usb_get_serial_port_data(port);
struct usb_serial_port *oob_port = (struct usb_serial_port *) ((struct digi_serial *)(usb_get_serial_data(port->serial)))->ds_oob_port;
struct digi_port *oob_priv = usb_get_serial_port_data(oob_port);
unsigned char *data = oob_port->write_urb->transfer_buffer;
unsigned long flags = 0;
dbg("digi_set_modem_signals: TOP: port=%d, modem_signals=0x%x",
port_priv->dp_port_num, modem_signals);
spin_lock_irqsave(&oob_priv->dp_port_lock, flags);
spin_lock(&port_priv->dp_port_lock);
while (oob_priv->dp_write_urb_in_use) {
spin_unlock(&port_priv->dp_port_lock);
cond_wait_interruptible_timeout_irqrestore(
&oob_port->write_wait, DIGI_RETRY_TIMEOUT,
&oob_priv->dp_port_lock, flags);
if (interruptible && signal_pending(current))
return -EINTR;
spin_lock_irqsave(&oob_priv->dp_port_lock, flags);
spin_lock(&port_priv->dp_port_lock);
}
data[0] = DIGI_CMD_SET_DTR_SIGNAL;
data[1] = port_priv->dp_port_num;
data[2] = (modem_signals & TIOCM_DTR) ?
DIGI_DTR_ACTIVE : DIGI_DTR_INACTIVE;
data[3] = 0;
data[4] = DIGI_CMD_SET_RTS_SIGNAL;
data[5] = port_priv->dp_port_num;
data[6] = (modem_signals & TIOCM_RTS) ?
DIGI_RTS_ACTIVE : DIGI_RTS_INACTIVE;
data[7] = 0;
oob_port->write_urb->transfer_buffer_length = 8;
ret = usb_submit_urb(oob_port->write_urb, GFP_ATOMIC);
if (ret == 0) {
oob_priv->dp_write_urb_in_use = 1;
port_priv->dp_modem_signals =
(port_priv->dp_modem_signals&~(TIOCM_DTR|TIOCM_RTS))
| (modem_signals&(TIOCM_DTR|TIOCM_RTS));
}
spin_unlock(&port_priv->dp_port_lock);
spin_unlock_irqrestore(&oob_priv->dp_port_lock, flags);
if (ret)
dev_err(&port->dev, "%s: usb_submit_urb failed, ret=%d\n",
__func__, ret);
return ret;
}
/*
* Digi Transmit Idle
*
* Digi transmit idle waits, up to timeout ticks, for the transmitter
* to go idle. It returns 0 if successful or a negative error.
*
* There are race conditions here if more than one process is calling
* digi_transmit_idle on the same port at the same time. However, this
* is only called from close, and only one process can be in close on a
* port at a time, so its ok.
*/
static int digi_transmit_idle(struct usb_serial_port *port,
unsigned long timeout)
{
int ret;
unsigned char buf[2];
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned long flags = 0;
spin_lock_irqsave(&priv->dp_port_lock, flags);
priv->dp_transmit_idle = 0;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
buf[0] = DIGI_CMD_TRANSMIT_IDLE;
buf[1] = 0;
timeout += jiffies;
ret = digi_write_inb_command(port, buf, 2, timeout - jiffies);
if (ret != 0)
return ret;
spin_lock_irqsave(&priv->dp_port_lock, flags);
while (time_before(jiffies, timeout) && !priv->dp_transmit_idle) {
cond_wait_interruptible_timeout_irqrestore(
&priv->dp_transmit_idle_wait, DIGI_RETRY_TIMEOUT,
&priv->dp_port_lock, flags);
if (signal_pending(current))
return -EINTR;
spin_lock_irqsave(&priv->dp_port_lock, flags);
}
priv->dp_transmit_idle = 0;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
return 0;
}
static void digi_rx_throttle(struct tty_struct *tty)
{
unsigned long flags;
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
dbg("digi_rx_throttle: TOP: port=%d", priv->dp_port_num);
/* stop receiving characters by not resubmitting the read urb */
spin_lock_irqsave(&priv->dp_port_lock, flags);
priv->dp_throttled = 1;
priv->dp_throttle_restart = 0;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
}
static void digi_rx_unthrottle(struct tty_struct *tty)
{
int ret = 0;
unsigned long flags;
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
dbg("digi_rx_unthrottle: TOP: port=%d", priv->dp_port_num);
spin_lock_irqsave(&priv->dp_port_lock, flags);
/* restart read chain */
if (priv->dp_throttle_restart)
ret = usb_submit_urb(port->read_urb, GFP_ATOMIC);
/* turn throttle off */
priv->dp_throttled = 0;
priv->dp_throttle_restart = 0;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
if (ret)
dev_err(&port->dev,
"%s: usb_submit_urb failed, ret=%d, port=%d\n",
__func__, ret, priv->dp_port_num);
}
static void digi_set_termios(struct tty_struct *tty,
struct usb_serial_port *port, struct ktermios *old_termios)
{
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned int iflag = tty->termios->c_iflag;
unsigned int cflag = tty->termios->c_cflag;
unsigned int old_iflag = old_termios->c_iflag;
unsigned int old_cflag = old_termios->c_cflag;
unsigned char buf[32];
unsigned int modem_signals;
int arg, ret;
int i = 0;
speed_t baud;
dbg("digi_set_termios: TOP: port=%d, iflag=0x%x, old_iflag=0x%x, cflag=0x%x, old_cflag=0x%x", priv->dp_port_num, iflag, old_iflag, cflag, old_cflag);
/* set baud rate */
baud = tty_get_baud_rate(tty);
if (baud != tty_termios_baud_rate(old_termios)) {
arg = -1;
/* reassert DTR and (maybe) RTS on transition from B0 */
if ((old_cflag&CBAUD) == B0) {
/* don't set RTS if using hardware flow control */
/* and throttling input */
modem_signals = TIOCM_DTR;
if (!(tty->termios->c_cflag & CRTSCTS) ||
!test_bit(TTY_THROTTLED, &tty->flags))
modem_signals |= TIOCM_RTS;
digi_set_modem_signals(port, modem_signals, 1);
}
switch (baud) {
/* drop DTR and RTS on transition to B0 */
case 0: digi_set_modem_signals(port, 0, 1); break;
case 50: arg = DIGI_BAUD_50; break;
case 75: arg = DIGI_BAUD_75; break;
case 110: arg = DIGI_BAUD_110; break;
case 150: arg = DIGI_BAUD_150; break;
case 200: arg = DIGI_BAUD_200; break;
case 300: arg = DIGI_BAUD_300; break;
case 600: arg = DIGI_BAUD_600; break;
case 1200: arg = DIGI_BAUD_1200; break;
case 1800: arg = DIGI_BAUD_1800; break;
case 2400: arg = DIGI_BAUD_2400; break;
case 4800: arg = DIGI_BAUD_4800; break;
case 9600: arg = DIGI_BAUD_9600; break;
case 19200: arg = DIGI_BAUD_19200; break;
case 38400: arg = DIGI_BAUD_38400; break;
case 57600: arg = DIGI_BAUD_57600; break;
case 115200: arg = DIGI_BAUD_115200; break;
case 230400: arg = DIGI_BAUD_230400; break;
case 460800: arg = DIGI_BAUD_460800; break;
default:
arg = DIGI_BAUD_9600;
baud = 9600;
break;
}
if (arg != -1) {
buf[i++] = DIGI_CMD_SET_BAUD_RATE;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
}
/* set parity */
tty->termios->c_cflag &= ~CMSPAR;
if ((cflag&(PARENB|PARODD)) != (old_cflag&(PARENB|PARODD))) {
if (cflag&PARENB) {
if (cflag&PARODD)
arg = DIGI_PARITY_ODD;
else
arg = DIGI_PARITY_EVEN;
} else {
arg = DIGI_PARITY_NONE;
}
buf[i++] = DIGI_CMD_SET_PARITY;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
/* set word size */
if ((cflag&CSIZE) != (old_cflag&CSIZE)) {
arg = -1;
switch (cflag&CSIZE) {
case CS5: arg = DIGI_WORD_SIZE_5; break;
case CS6: arg = DIGI_WORD_SIZE_6; break;
case CS7: arg = DIGI_WORD_SIZE_7; break;
case CS8: arg = DIGI_WORD_SIZE_8; break;
default:
dbg("digi_set_termios: can't handle word size %d",
(cflag&CSIZE));
break;
}
if (arg != -1) {
buf[i++] = DIGI_CMD_SET_WORD_SIZE;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
}
/* set stop bits */
if ((cflag&CSTOPB) != (old_cflag&CSTOPB)) {
if ((cflag&CSTOPB))
arg = DIGI_STOP_BITS_2;
else
arg = DIGI_STOP_BITS_1;
buf[i++] = DIGI_CMD_SET_STOP_BITS;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
/* set input flow control */
if ((iflag&IXOFF) != (old_iflag&IXOFF)
|| (cflag&CRTSCTS) != (old_cflag&CRTSCTS)) {
arg = 0;
if (iflag&IXOFF)
arg |= DIGI_INPUT_FLOW_CONTROL_XON_XOFF;
else
arg &= ~DIGI_INPUT_FLOW_CONTROL_XON_XOFF;
if (cflag&CRTSCTS) {
arg |= DIGI_INPUT_FLOW_CONTROL_RTS;
/* On USB-4 it is necessary to assert RTS prior */
/* to selecting RTS input flow control. */
buf[i++] = DIGI_CMD_SET_RTS_SIGNAL;
buf[i++] = priv->dp_port_num;
buf[i++] = DIGI_RTS_ACTIVE;
buf[i++] = 0;
} else {
arg &= ~DIGI_INPUT_FLOW_CONTROL_RTS;
}
buf[i++] = DIGI_CMD_SET_INPUT_FLOW_CONTROL;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
/* set output flow control */
if ((iflag & IXON) != (old_iflag & IXON)
|| (cflag & CRTSCTS) != (old_cflag & CRTSCTS)) {
arg = 0;
if (iflag & IXON)
arg |= DIGI_OUTPUT_FLOW_CONTROL_XON_XOFF;
else
arg &= ~DIGI_OUTPUT_FLOW_CONTROL_XON_XOFF;
if (cflag & CRTSCTS) {
arg |= DIGI_OUTPUT_FLOW_CONTROL_CTS;
} else {
arg &= ~DIGI_OUTPUT_FLOW_CONTROL_CTS;
tty->hw_stopped = 0;
}
buf[i++] = DIGI_CMD_SET_OUTPUT_FLOW_CONTROL;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
/* set receive enable/disable */
if ((cflag & CREAD) != (old_cflag & CREAD)) {
if (cflag & CREAD)
arg = DIGI_ENABLE;
else
arg = DIGI_DISABLE;
buf[i++] = DIGI_CMD_RECEIVE_ENABLE;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
ret = digi_write_oob_command(port, buf, i, 1);
if (ret != 0)
dbg("digi_set_termios: write oob failed, ret=%d", ret);
tty_encode_baud_rate(tty, baud, baud);
}
static void digi_break_ctl(struct tty_struct *tty, int break_state)
{
struct usb_serial_port *port = tty->driver_data;
unsigned char buf[4];
buf[0] = DIGI_CMD_BREAK_CONTROL;
buf[1] = 2; /* length */
buf[2] = break_state ? 1 : 0;
buf[3] = 0; /* pad */
digi_write_inb_command(port, buf, 4, 0);
}
static int digi_tiocmget(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned int val;
unsigned long flags;
dbg("%s: TOP: port=%d", __func__, priv->dp_port_num);
spin_lock_irqsave(&priv->dp_port_lock, flags);
val = priv->dp_modem_signals;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
return val;
}
static int digi_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned int val;
unsigned long flags;
dbg("%s: TOP: port=%d", __func__, priv->dp_port_num);
spin_lock_irqsave(&priv->dp_port_lock, flags);
val = (priv->dp_modem_signals & ~clear) | set;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
return digi_set_modem_signals(port, val, 1);
}
static int digi_write(struct tty_struct *tty, struct usb_serial_port *port,
const unsigned char *buf, int count)
{
int ret, data_len, new_len;
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned char *data = port->write_urb->transfer_buffer;
unsigned long flags = 0;
dbg("digi_write: TOP: port=%d, count=%d, in_interrupt=%ld",
priv->dp_port_num, count, in_interrupt());
/* copy user data (which can sleep) before getting spin lock */
count = min(count, port->bulk_out_size-2);
count = min(64, count);
/* be sure only one write proceeds at a time */
/* there are races on the port private buffer */
spin_lock_irqsave(&priv->dp_port_lock, flags);
/* wait for urb status clear to submit another urb */
if (priv->dp_write_urb_in_use) {
/* buffer data if count is 1 (probably put_char) if possible */
if (count == 1 && priv->dp_out_buf_len < DIGI_OUT_BUF_SIZE) {
priv->dp_out_buf[priv->dp_out_buf_len++] = *buf;
new_len = 1;
} else {
new_len = 0;
}
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
return new_len;
}
/* allow space for any buffered data and for new data, up to */
/* transfer buffer size - 2 (for command and length bytes) */
new_len = min(count, port->bulk_out_size-2-priv->dp_out_buf_len);
data_len = new_len + priv->dp_out_buf_len;
if (data_len == 0) {
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
return 0;
}
port->write_urb->transfer_buffer_length = data_len+2;
*data++ = DIGI_CMD_SEND_DATA;
*data++ = data_len;
/* copy in buffered data first */
memcpy(data, priv->dp_out_buf, priv->dp_out_buf_len);
data += priv->dp_out_buf_len;
/* copy in new data */
memcpy(data, buf, new_len);
ret = usb_submit_urb(port->write_urb, GFP_ATOMIC);
if (ret == 0) {
priv->dp_write_urb_in_use = 1;
ret = new_len;
priv->dp_out_buf_len = 0;
}
/* return length of new data written, or error */
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
if (ret < 0)
dev_err_console(port,
"%s: usb_submit_urb failed, ret=%d, port=%d\n",
__func__, ret, priv->dp_port_num);
dbg("digi_write: returning %d", ret);
return ret;
}
static void digi_write_bulk_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct usb_serial *serial;
struct digi_port *priv;
struct digi_serial *serial_priv;
int ret = 0;
int status = urb->status;
dbg("digi_write_bulk_callback: TOP, status=%d", status);
/* port and serial sanity check */
if (port == NULL || (priv = usb_get_serial_port_data(port)) == NULL) {
pr_err("%s: port or port->private is NULL, status=%d\n",
__func__, status);
return;
}
serial = port->serial;
if (serial == NULL || (serial_priv = usb_get_serial_data(serial)) == NULL) {
dev_err(&port->dev,
"%s: serial or serial->private is NULL, status=%d\n",
__func__, status);
return;
}
/* handle oob callback */
if (priv->dp_port_num == serial_priv->ds_oob_port_num) {
dbg("digi_write_bulk_callback: oob callback");
spin_lock(&priv->dp_port_lock);
priv->dp_write_urb_in_use = 0;
wake_up_interruptible(&port->write_wait);
spin_unlock(&priv->dp_port_lock);
return;
}
/* try to send any buffered data on this port */
spin_lock(&priv->dp_port_lock);
priv->dp_write_urb_in_use = 0;
if (priv->dp_out_buf_len > 0) {
*((unsigned char *)(port->write_urb->transfer_buffer))
= (unsigned char)DIGI_CMD_SEND_DATA;
*((unsigned char *)(port->write_urb->transfer_buffer) + 1)
= (unsigned char)priv->dp_out_buf_len;
port->write_urb->transfer_buffer_length =
priv->dp_out_buf_len + 2;
memcpy(port->write_urb->transfer_buffer + 2, priv->dp_out_buf,
priv->dp_out_buf_len);
ret = usb_submit_urb(port->write_urb, GFP_ATOMIC);
if (ret == 0) {
priv->dp_write_urb_in_use = 1;
priv->dp_out_buf_len = 0;
}
}
/* wake up processes sleeping on writes immediately */
digi_wakeup_write(port);
/* also queue up a wakeup at scheduler time, in case we */
/* lost the race in write_chan(). */
schedule_work(&priv->dp_wakeup_work);
spin_unlock(&priv->dp_port_lock);
if (ret && ret != -EPERM)
dev_err_console(port,
"%s: usb_submit_urb failed, ret=%d, port=%d\n",
__func__, ret, priv->dp_port_num);
}
static int digi_write_room(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
int room;
unsigned long flags = 0;
spin_lock_irqsave(&priv->dp_port_lock, flags);
if (priv->dp_write_urb_in_use)
room = 0;
else
room = port->bulk_out_size - 2 - priv->dp_out_buf_len;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
dbg("digi_write_room: port=%d, room=%d", priv->dp_port_num, room);
return room;
}
static int digi_chars_in_buffer(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
if (priv->dp_write_urb_in_use) {
dbg("digi_chars_in_buffer: port=%d, chars=%d",
priv->dp_port_num, port->bulk_out_size - 2);
/* return(port->bulk_out_size - 2); */
return 256;
} else {
dbg("digi_chars_in_buffer: port=%d, chars=%d",
priv->dp_port_num, priv->dp_out_buf_len);
return priv->dp_out_buf_len;
}
}
static void digi_dtr_rts(struct usb_serial_port *port, int on)
{
/* Adjust DTR and RTS */
digi_set_modem_signals(port, on * (TIOCM_DTR|TIOCM_RTS), 1);
}
static int digi_open(struct tty_struct *tty, struct usb_serial_port *port)
{
int ret;
unsigned char buf[32];
struct digi_port *priv = usb_get_serial_port_data(port);
struct ktermios not_termios;
dbg("digi_open: TOP: port=%d", priv->dp_port_num);
/* be sure the device is started up */
if (digi_startup_device(port->serial) != 0)
return -ENXIO;
/* read modem signals automatically whenever they change */
buf[0] = DIGI_CMD_READ_INPUT_SIGNALS;
buf[1] = priv->dp_port_num;
buf[2] = DIGI_ENABLE;
buf[3] = 0;
/* flush fifos */
buf[4] = DIGI_CMD_IFLUSH_FIFO;
buf[5] = priv->dp_port_num;
buf[6] = DIGI_FLUSH_TX | DIGI_FLUSH_RX;
buf[7] = 0;
ret = digi_write_oob_command(port, buf, 8, 1);
if (ret != 0)
dbg("digi_open: write oob failed, ret=%d", ret);
/* set termios settings */
if (tty) {
not_termios.c_cflag = ~tty->termios->c_cflag;
not_termios.c_iflag = ~tty->termios->c_iflag;
digi_set_termios(tty, port, ¬_termios);
}
return 0;
}
static void digi_close(struct usb_serial_port *port)
{
DEFINE_WAIT(wait);
int ret;
unsigned char buf[32];
struct digi_port *priv = usb_get_serial_port_data(port);
dbg("digi_close: TOP: port=%d", priv->dp_port_num);
mutex_lock(&port->serial->disc_mutex);
/* if disconnected, just clear flags */
if (port->serial->disconnected)
goto exit;
if (port->serial->dev) {
/* FIXME: Transmit idle belongs in the wait_unti_sent path */
digi_transmit_idle(port, DIGI_CLOSE_TIMEOUT);
/* disable input flow control */
buf[0] = DIGI_CMD_SET_INPUT_FLOW_CONTROL;
buf[1] = priv->dp_port_num;
buf[2] = DIGI_DISABLE;
buf[3] = 0;
/* disable output flow control */
buf[4] = DIGI_CMD_SET_OUTPUT_FLOW_CONTROL;
buf[5] = priv->dp_port_num;
buf[6] = DIGI_DISABLE;
buf[7] = 0;
/* disable reading modem signals automatically */
buf[8] = DIGI_CMD_READ_INPUT_SIGNALS;
buf[9] = priv->dp_port_num;
buf[10] = DIGI_DISABLE;
buf[11] = 0;
/* disable receive */
buf[12] = DIGI_CMD_RECEIVE_ENABLE;
buf[13] = priv->dp_port_num;
buf[14] = DIGI_DISABLE;
buf[15] = 0;
/* flush fifos */
buf[16] = DIGI_CMD_IFLUSH_FIFO;
buf[17] = priv->dp_port_num;
buf[18] = DIGI_FLUSH_TX | DIGI_FLUSH_RX;
buf[19] = 0;
ret = digi_write_oob_command(port, buf, 20, 0);
if (ret != 0)
dbg("digi_close: write oob failed, ret=%d", ret);
/* wait for final commands on oob port to complete */
prepare_to_wait(&priv->dp_flush_wait, &wait,
TASK_INTERRUPTIBLE);
schedule_timeout(DIGI_CLOSE_TIMEOUT);
finish_wait(&priv->dp_flush_wait, &wait);
/* shutdown any outstanding bulk writes */
usb_kill_urb(port->write_urb);
}
exit:
spin_lock_irq(&priv->dp_port_lock);
priv->dp_write_urb_in_use = 0;
wake_up_interruptible(&priv->dp_close_wait);
spin_unlock_irq(&priv->dp_port_lock);
mutex_unlock(&port->serial->disc_mutex);
dbg("digi_close: done");
}
/*
* Digi Startup Device
*
* Starts reads on all ports. Must be called AFTER startup, with
* urbs initialized. Returns 0 if successful, non-zero error otherwise.
*/
static int digi_startup_device(struct usb_serial *serial)
{
int i, ret = 0;
struct digi_serial *serial_priv = usb_get_serial_data(serial);
struct usb_serial_port *port;
/* be sure this happens exactly once */
spin_lock(&serial_priv->ds_serial_lock);
if (serial_priv->ds_device_started) {
spin_unlock(&serial_priv->ds_serial_lock);
return 0;
}
serial_priv->ds_device_started = 1;
spin_unlock(&serial_priv->ds_serial_lock);
/* start reading from each bulk in endpoint for the device */
/* set USB_DISABLE_SPD flag for write bulk urbs */
for (i = 0; i < serial->type->num_ports + 1; i++) {
port = serial->port[i];
ret = usb_submit_urb(port->read_urb, GFP_KERNEL);
if (ret != 0) {
dev_err(&port->dev,
"%s: usb_submit_urb failed, ret=%d, port=%d\n",
__func__, ret, i);
break;
}
}
return ret;
}
static int digi_startup(struct usb_serial *serial)
{
int i;
struct digi_port *priv;
struct digi_serial *serial_priv;
dbg("digi_startup: TOP");
/* allocate the private data structures for all ports */
/* number of regular ports + 1 for the out-of-band port */
for (i = 0; i < serial->type->num_ports + 1; i++) {
/* allocate port private structure */
priv = kmalloc(sizeof(struct digi_port), GFP_KERNEL);
if (priv == NULL) {
while (--i >= 0)
kfree(usb_get_serial_port_data(serial->port[i]));
return 1; /* error */
}
/* initialize port private structure */
spin_lock_init(&priv->dp_port_lock);
priv->dp_port_num = i;
priv->dp_out_buf_len = 0;
priv->dp_write_urb_in_use = 0;
priv->dp_modem_signals = 0;
init_waitqueue_head(&priv->dp_modem_change_wait);
priv->dp_transmit_idle = 0;
init_waitqueue_head(&priv->dp_transmit_idle_wait);
priv->dp_throttled = 0;
priv->dp_throttle_restart = 0;
init_waitqueue_head(&priv->dp_flush_wait);
init_waitqueue_head(&priv->dp_close_wait);
INIT_WORK(&priv->dp_wakeup_work, digi_wakeup_write_lock);
priv->dp_port = serial->port[i];
/* initialize write wait queue for this port */
init_waitqueue_head(&serial->port[i]->write_wait);
usb_set_serial_port_data(serial->port[i], priv);
}
/* allocate serial private structure */
serial_priv = kmalloc(sizeof(struct digi_serial), GFP_KERNEL);
if (serial_priv == NULL) {
for (i = 0; i < serial->type->num_ports + 1; i++)
kfree(usb_get_serial_port_data(serial->port[i]));
return 1; /* error */
}
/* initialize serial private structure */
spin_lock_init(&serial_priv->ds_serial_lock);
serial_priv->ds_oob_port_num = serial->type->num_ports;
serial_priv->ds_oob_port = serial->port[serial_priv->ds_oob_port_num];
serial_priv->ds_device_started = 0;
usb_set_serial_data(serial, serial_priv);
return 0;
}
static void digi_disconnect(struct usb_serial *serial)
{
int i;
dbg("digi_disconnect: TOP, in_interrupt()=%ld", in_interrupt());
/* stop reads and writes on all ports */
for (i = 0; i < serial->type->num_ports + 1; i++) {
usb_kill_urb(serial->port[i]->read_urb);
usb_kill_urb(serial->port[i]->write_urb);
}
}
static void digi_release(struct usb_serial *serial)
{
int i;
dbg("digi_release: TOP, in_interrupt()=%ld", in_interrupt());
/* free the private data structures for all ports */
/* number of regular ports + 1 for the out-of-band port */
for (i = 0; i < serial->type->num_ports + 1; i++)
kfree(usb_get_serial_port_data(serial->port[i]));
kfree(usb_get_serial_data(serial));
}
static void digi_read_bulk_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct digi_port *priv;
struct digi_serial *serial_priv;
int ret;
int status = urb->status;
dbg("digi_read_bulk_callback: TOP");
/* port sanity check, do not resubmit if port is not valid */
if (port == NULL)
return;
priv = usb_get_serial_port_data(port);
if (priv == NULL) {
dev_err(&port->dev, "%s: port->private is NULL, status=%d\n",
__func__, status);
return;
}
if (port->serial == NULL ||
(serial_priv = usb_get_serial_data(port->serial)) == NULL) {
dev_err(&port->dev, "%s: serial is bad or serial->private "
"is NULL, status=%d\n", __func__, status);
return;
}
/* do not resubmit urb if it has any status error */
if (status) {
dev_err(&port->dev,
"%s: nonzero read bulk status: status=%d, port=%d\n",
__func__, status, priv->dp_port_num);
return;
}
/* handle oob or inb callback, do not resubmit if error */
if (priv->dp_port_num == serial_priv->ds_oob_port_num) {
if (digi_read_oob_callback(urb) != 0)
return;
} else {
if (digi_read_inb_callback(urb) != 0)
return;
}
/* continue read */
ret = usb_submit_urb(urb, GFP_ATOMIC);
if (ret != 0 && ret != -EPERM) {
dev_err(&port->dev,
"%s: failed resubmitting urb, ret=%d, port=%d\n",
__func__, ret, priv->dp_port_num);
}
}
/*
* Digi Read INB Callback
*
* Digi Read INB Callback handles reads on the in band ports, sending
* the data on to the tty subsystem. When called we know port and
* port->private are not NULL and port->serial has been validated.
* It returns 0 if successful, 1 if successful but the port is
* throttled, and -1 if the sanity checks failed.
*/
static int digi_read_inb_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct tty_struct *tty;
struct digi_port *priv = usb_get_serial_port_data(port);
int opcode = ((unsigned char *)urb->transfer_buffer)[0];
int len = ((unsigned char *)urb->transfer_buffer)[1];
int port_status = ((unsigned char *)urb->transfer_buffer)[2];
unsigned char *data = ((unsigned char *)urb->transfer_buffer) + 3;
int flag, throttled;
int status = urb->status;
/* do not process callbacks on closed ports */
/* but do continue the read chain */
if (urb->status == -ENOENT)
return 0;
/* short/multiple packet check */
if (urb->actual_length != len + 2) {
dev_err(&port->dev, "%s: INCOMPLETE OR MULTIPLE PACKET, "
"status=%d, port=%d, opcode=%d, len=%d, "
"actual_length=%d, status=%d\n", __func__, status,
priv->dp_port_num, opcode, len, urb->actual_length,
port_status);
return -1;
}
tty = tty_port_tty_get(&port->port);
spin_lock(&priv->dp_port_lock);
/* check for throttle; if set, do not resubmit read urb */
/* indicate the read chain needs to be restarted on unthrottle */
throttled = priv->dp_throttled;
if (throttled)
priv->dp_throttle_restart = 1;
/* receive data */
if (tty && opcode == DIGI_CMD_RECEIVE_DATA) {
/* get flag from port_status */
flag = 0;
/* overrun is special, not associated with a char */
if (port_status & DIGI_OVERRUN_ERROR)
tty_insert_flip_char(tty, 0, TTY_OVERRUN);
/* break takes precedence over parity, */
/* which takes precedence over framing errors */
if (port_status & DIGI_BREAK_ERROR)
flag = TTY_BREAK;
else if (port_status & DIGI_PARITY_ERROR)
flag = TTY_PARITY;
else if (port_status & DIGI_FRAMING_ERROR)
flag = TTY_FRAME;
/* data length is len-1 (one byte of len is port_status) */
--len;
if (len > 0) {
tty_insert_flip_string_fixed_flag(tty, data, flag,
len);
tty_flip_buffer_push(tty);
}
}
spin_unlock(&priv->dp_port_lock);
tty_kref_put(tty);
if (opcode == DIGI_CMD_RECEIVE_DISABLE)
dbg("%s: got RECEIVE_DISABLE", __func__);
else if (opcode != DIGI_CMD_RECEIVE_DATA)
dbg("%s: unknown opcode: %d", __func__, opcode);
return throttled ? 1 : 0;
}
/*
* Digi Read OOB Callback
*
* Digi Read OOB Callback handles reads on the out of band port.
* When called we know port and port->private are not NULL and
* the port->serial is valid. It returns 0 if successful, and
* -1 if the sanity checks failed.
*/
static int digi_read_oob_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct usb_serial *serial = port->serial;
struct tty_struct *tty;
struct digi_port *priv = usb_get_serial_port_data(port);
int opcode, line, status, val;
int i;
unsigned int rts;
dbg("digi_read_oob_callback: port=%d, len=%d",
priv->dp_port_num, urb->actual_length);
/* handle each oob command */
for (i = 0; i < urb->actual_length - 3;) {
opcode = ((unsigned char *)urb->transfer_buffer)[i++];
line = ((unsigned char *)urb->transfer_buffer)[i++];
status = ((unsigned char *)urb->transfer_buffer)[i++];
val = ((unsigned char *)urb->transfer_buffer)[i++];
dbg("digi_read_oob_callback: opcode=%d, line=%d, status=%d, val=%d",
opcode, line, status, val);
if (status != 0 || line >= serial->type->num_ports)
continue;
port = serial->port[line];
priv = usb_get_serial_port_data(port);
if (priv == NULL)
return -1;
tty = tty_port_tty_get(&port->port);
rts = 0;
if (tty)
rts = tty->termios->c_cflag & CRTSCTS;
if (tty && opcode == DIGI_CMD_READ_INPUT_SIGNALS) {
spin_lock(&priv->dp_port_lock);
/* convert from digi flags to termiox flags */
if (val & DIGI_READ_INPUT_SIGNALS_CTS) {
priv->dp_modem_signals |= TIOCM_CTS;
/* port must be open to use tty struct */
if (rts) {
tty->hw_stopped = 0;
digi_wakeup_write(port);
}
} else {
priv->dp_modem_signals &= ~TIOCM_CTS;
/* port must be open to use tty struct */
if (rts)
tty->hw_stopped = 1;
}
if (val & DIGI_READ_INPUT_SIGNALS_DSR)
priv->dp_modem_signals |= TIOCM_DSR;
else
priv->dp_modem_signals &= ~TIOCM_DSR;
if (val & DIGI_READ_INPUT_SIGNALS_RI)
priv->dp_modem_signals |= TIOCM_RI;
else
priv->dp_modem_signals &= ~TIOCM_RI;
if (val & DIGI_READ_INPUT_SIGNALS_DCD)
priv->dp_modem_signals |= TIOCM_CD;
else
priv->dp_modem_signals &= ~TIOCM_CD;
wake_up_interruptible(&priv->dp_modem_change_wait);
spin_unlock(&priv->dp_port_lock);
} else if (opcode == DIGI_CMD_TRANSMIT_IDLE) {
spin_lock(&priv->dp_port_lock);
priv->dp_transmit_idle = 1;
wake_up_interruptible(&priv->dp_transmit_idle_wait);
spin_unlock(&priv->dp_port_lock);
} else if (opcode == DIGI_CMD_IFLUSH_FIFO) {
wake_up_interruptible(&priv->dp_flush_wait);
}
tty_kref_put(tty);
}
return 0;
}
module_usb_serial_driver(digi_driver, serial_drivers);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug enabled or not");
| gpl-2.0 |
BanBxda/Sense_4.3 | drivers/usb/serial/digi_acceleport.c | 4728 | 45694 | /*
* Digi AccelePort USB-4 and USB-2 Serial Converters
*
* Copyright 2000 by Digi International
*
* 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.
*
* Shamelessly based on Brian Warner's keyspan_pda.c and Greg Kroah-Hartman's
* usb-serial driver.
*
* Peter Berger (pberger@brimson.com)
* Al Borchers (borchers@steinerpoint.com)
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/workqueue.h>
#include <linux/uaccess.h>
#include <linux/usb.h>
#include <linux/wait.h>
#include <linux/usb/serial.h>
/* Defines */
/*
* Version Information
*/
#define DRIVER_VERSION "v1.80.1.2"
#define DRIVER_AUTHOR "Peter Berger <pberger@brimson.com>, Al Borchers <borchers@steinerpoint.com>"
#define DRIVER_DESC "Digi AccelePort USB-2/USB-4 Serial Converter driver"
/* port output buffer length -- must be <= transfer buffer length - 2 */
/* so we can be sure to send the full buffer in one urb */
#define DIGI_OUT_BUF_SIZE 8
/* port input buffer length -- must be >= transfer buffer length - 3 */
/* so we can be sure to hold at least one full buffer from one urb */
#define DIGI_IN_BUF_SIZE 64
/* retry timeout while sleeping */
#define DIGI_RETRY_TIMEOUT (HZ/10)
/* timeout while waiting for tty output to drain in close */
/* this delay is used twice in close, so the total delay could */
/* be twice this value */
#define DIGI_CLOSE_TIMEOUT (5*HZ)
/* AccelePort USB Defines */
/* ids */
#define DIGI_VENDOR_ID 0x05c5
#define DIGI_2_ID 0x0002 /* USB-2 */
#define DIGI_4_ID 0x0004 /* USB-4 */
/* commands
* "INB": can be used on the in-band endpoint
* "OOB": can be used on the out-of-band endpoint
*/
#define DIGI_CMD_SET_BAUD_RATE 0 /* INB, OOB */
#define DIGI_CMD_SET_WORD_SIZE 1 /* INB, OOB */
#define DIGI_CMD_SET_PARITY 2 /* INB, OOB */
#define DIGI_CMD_SET_STOP_BITS 3 /* INB, OOB */
#define DIGI_CMD_SET_INPUT_FLOW_CONTROL 4 /* INB, OOB */
#define DIGI_CMD_SET_OUTPUT_FLOW_CONTROL 5 /* INB, OOB */
#define DIGI_CMD_SET_DTR_SIGNAL 6 /* INB, OOB */
#define DIGI_CMD_SET_RTS_SIGNAL 7 /* INB, OOB */
#define DIGI_CMD_READ_INPUT_SIGNALS 8 /* OOB */
#define DIGI_CMD_IFLUSH_FIFO 9 /* OOB */
#define DIGI_CMD_RECEIVE_ENABLE 10 /* INB, OOB */
#define DIGI_CMD_BREAK_CONTROL 11 /* INB, OOB */
#define DIGI_CMD_LOCAL_LOOPBACK 12 /* INB, OOB */
#define DIGI_CMD_TRANSMIT_IDLE 13 /* INB, OOB */
#define DIGI_CMD_READ_UART_REGISTER 14 /* OOB */
#define DIGI_CMD_WRITE_UART_REGISTER 15 /* INB, OOB */
#define DIGI_CMD_AND_UART_REGISTER 16 /* INB, OOB */
#define DIGI_CMD_OR_UART_REGISTER 17 /* INB, OOB */
#define DIGI_CMD_SEND_DATA 18 /* INB */
#define DIGI_CMD_RECEIVE_DATA 19 /* INB */
#define DIGI_CMD_RECEIVE_DISABLE 20 /* INB */
#define DIGI_CMD_GET_PORT_TYPE 21 /* OOB */
/* baud rates */
#define DIGI_BAUD_50 0
#define DIGI_BAUD_75 1
#define DIGI_BAUD_110 2
#define DIGI_BAUD_150 3
#define DIGI_BAUD_200 4
#define DIGI_BAUD_300 5
#define DIGI_BAUD_600 6
#define DIGI_BAUD_1200 7
#define DIGI_BAUD_1800 8
#define DIGI_BAUD_2400 9
#define DIGI_BAUD_4800 10
#define DIGI_BAUD_7200 11
#define DIGI_BAUD_9600 12
#define DIGI_BAUD_14400 13
#define DIGI_BAUD_19200 14
#define DIGI_BAUD_28800 15
#define DIGI_BAUD_38400 16
#define DIGI_BAUD_57600 17
#define DIGI_BAUD_76800 18
#define DIGI_BAUD_115200 19
#define DIGI_BAUD_153600 20
#define DIGI_BAUD_230400 21
#define DIGI_BAUD_460800 22
/* arguments */
#define DIGI_WORD_SIZE_5 0
#define DIGI_WORD_SIZE_6 1
#define DIGI_WORD_SIZE_7 2
#define DIGI_WORD_SIZE_8 3
#define DIGI_PARITY_NONE 0
#define DIGI_PARITY_ODD 1
#define DIGI_PARITY_EVEN 2
#define DIGI_PARITY_MARK 3
#define DIGI_PARITY_SPACE 4
#define DIGI_STOP_BITS_1 0
#define DIGI_STOP_BITS_2 1
#define DIGI_INPUT_FLOW_CONTROL_XON_XOFF 1
#define DIGI_INPUT_FLOW_CONTROL_RTS 2
#define DIGI_INPUT_FLOW_CONTROL_DTR 4
#define DIGI_OUTPUT_FLOW_CONTROL_XON_XOFF 1
#define DIGI_OUTPUT_FLOW_CONTROL_CTS 2
#define DIGI_OUTPUT_FLOW_CONTROL_DSR 4
#define DIGI_DTR_INACTIVE 0
#define DIGI_DTR_ACTIVE 1
#define DIGI_DTR_INPUT_FLOW_CONTROL 2
#define DIGI_RTS_INACTIVE 0
#define DIGI_RTS_ACTIVE 1
#define DIGI_RTS_INPUT_FLOW_CONTROL 2
#define DIGI_RTS_TOGGLE 3
#define DIGI_FLUSH_TX 1
#define DIGI_FLUSH_RX 2
#define DIGI_RESUME_TX 4 /* clears xoff condition */
#define DIGI_TRANSMIT_NOT_IDLE 0
#define DIGI_TRANSMIT_IDLE 1
#define DIGI_DISABLE 0
#define DIGI_ENABLE 1
#define DIGI_DEASSERT 0
#define DIGI_ASSERT 1
/* in band status codes */
#define DIGI_OVERRUN_ERROR 4
#define DIGI_PARITY_ERROR 8
#define DIGI_FRAMING_ERROR 16
#define DIGI_BREAK_ERROR 32
/* out of band status */
#define DIGI_NO_ERROR 0
#define DIGI_BAD_FIRST_PARAMETER 1
#define DIGI_BAD_SECOND_PARAMETER 2
#define DIGI_INVALID_LINE 3
#define DIGI_INVALID_OPCODE 4
/* input signals */
#define DIGI_READ_INPUT_SIGNALS_SLOT 1
#define DIGI_READ_INPUT_SIGNALS_ERR 2
#define DIGI_READ_INPUT_SIGNALS_BUSY 4
#define DIGI_READ_INPUT_SIGNALS_PE 8
#define DIGI_READ_INPUT_SIGNALS_CTS 16
#define DIGI_READ_INPUT_SIGNALS_DSR 32
#define DIGI_READ_INPUT_SIGNALS_RI 64
#define DIGI_READ_INPUT_SIGNALS_DCD 128
/* Structures */
struct digi_serial {
spinlock_t ds_serial_lock;
struct usb_serial_port *ds_oob_port; /* out-of-band port */
int ds_oob_port_num; /* index of out-of-band port */
int ds_device_started;
};
struct digi_port {
spinlock_t dp_port_lock;
int dp_port_num;
int dp_out_buf_len;
unsigned char dp_out_buf[DIGI_OUT_BUF_SIZE];
int dp_write_urb_in_use;
unsigned int dp_modem_signals;
wait_queue_head_t dp_modem_change_wait;
int dp_transmit_idle;
wait_queue_head_t dp_transmit_idle_wait;
int dp_throttled;
int dp_throttle_restart;
wait_queue_head_t dp_flush_wait;
wait_queue_head_t dp_close_wait; /* wait queue for close */
struct work_struct dp_wakeup_work;
struct usb_serial_port *dp_port;
};
/* Local Function Declarations */
static void digi_wakeup_write(struct usb_serial_port *port);
static void digi_wakeup_write_lock(struct work_struct *work);
static int digi_write_oob_command(struct usb_serial_port *port,
unsigned char *buf, int count, int interruptible);
static int digi_write_inb_command(struct usb_serial_port *port,
unsigned char *buf, int count, unsigned long timeout);
static int digi_set_modem_signals(struct usb_serial_port *port,
unsigned int modem_signals, int interruptible);
static int digi_transmit_idle(struct usb_serial_port *port,
unsigned long timeout);
static void digi_rx_throttle(struct tty_struct *tty);
static void digi_rx_unthrottle(struct tty_struct *tty);
static void digi_set_termios(struct tty_struct *tty,
struct usb_serial_port *port, struct ktermios *old_termios);
static void digi_break_ctl(struct tty_struct *tty, int break_state);
static int digi_tiocmget(struct tty_struct *tty);
static int digi_tiocmset(struct tty_struct *tty, unsigned int set,
unsigned int clear);
static int digi_write(struct tty_struct *tty, struct usb_serial_port *port,
const unsigned char *buf, int count);
static void digi_write_bulk_callback(struct urb *urb);
static int digi_write_room(struct tty_struct *tty);
static int digi_chars_in_buffer(struct tty_struct *tty);
static int digi_open(struct tty_struct *tty, struct usb_serial_port *port);
static void digi_close(struct usb_serial_port *port);
static void digi_dtr_rts(struct usb_serial_port *port, int on);
static int digi_startup_device(struct usb_serial *serial);
static int digi_startup(struct usb_serial *serial);
static void digi_disconnect(struct usb_serial *serial);
static void digi_release(struct usb_serial *serial);
static void digi_read_bulk_callback(struct urb *urb);
static int digi_read_inb_callback(struct urb *urb);
static int digi_read_oob_callback(struct urb *urb);
/* Statics */
static bool debug;
static const struct usb_device_id id_table_combined[] = {
{ USB_DEVICE(DIGI_VENDOR_ID, DIGI_2_ID) },
{ USB_DEVICE(DIGI_VENDOR_ID, DIGI_4_ID) },
{ } /* Terminating entry */
};
static const struct usb_device_id id_table_2[] = {
{ USB_DEVICE(DIGI_VENDOR_ID, DIGI_2_ID) },
{ } /* Terminating entry */
};
static const struct usb_device_id id_table_4[] = {
{ USB_DEVICE(DIGI_VENDOR_ID, DIGI_4_ID) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, id_table_combined);
static struct usb_driver digi_driver = {
.name = "digi_acceleport",
.probe = usb_serial_probe,
.disconnect = usb_serial_disconnect,
.id_table = id_table_combined,
};
/* device info needed for the Digi serial converter */
static struct usb_serial_driver digi_acceleport_2_device = {
.driver = {
.owner = THIS_MODULE,
.name = "digi_2",
},
.description = "Digi 2 port USB adapter",
.id_table = id_table_2,
.num_ports = 3,
.open = digi_open,
.close = digi_close,
.dtr_rts = digi_dtr_rts,
.write = digi_write,
.write_room = digi_write_room,
.write_bulk_callback = digi_write_bulk_callback,
.read_bulk_callback = digi_read_bulk_callback,
.chars_in_buffer = digi_chars_in_buffer,
.throttle = digi_rx_throttle,
.unthrottle = digi_rx_unthrottle,
.set_termios = digi_set_termios,
.break_ctl = digi_break_ctl,
.tiocmget = digi_tiocmget,
.tiocmset = digi_tiocmset,
.attach = digi_startup,
.disconnect = digi_disconnect,
.release = digi_release,
};
static struct usb_serial_driver digi_acceleport_4_device = {
.driver = {
.owner = THIS_MODULE,
.name = "digi_4",
},
.description = "Digi 4 port USB adapter",
.id_table = id_table_4,
.num_ports = 4,
.open = digi_open,
.close = digi_close,
.write = digi_write,
.write_room = digi_write_room,
.write_bulk_callback = digi_write_bulk_callback,
.read_bulk_callback = digi_read_bulk_callback,
.chars_in_buffer = digi_chars_in_buffer,
.throttle = digi_rx_throttle,
.unthrottle = digi_rx_unthrottle,
.set_termios = digi_set_termios,
.break_ctl = digi_break_ctl,
.tiocmget = digi_tiocmget,
.tiocmset = digi_tiocmset,
.attach = digi_startup,
.disconnect = digi_disconnect,
.release = digi_release,
};
static struct usb_serial_driver * const serial_drivers[] = {
&digi_acceleport_2_device, &digi_acceleport_4_device, NULL
};
/* Functions */
/*
* Cond Wait Interruptible Timeout Irqrestore
*
* Do spin_unlock_irqrestore and interruptible_sleep_on_timeout
* so that wake ups are not lost if they occur between the unlock
* and the sleep. In other words, spin_unlock_irqrestore and
* interruptible_sleep_on_timeout are "atomic" with respect to
* wake ups. This is used to implement condition variables.
*
* interruptible_sleep_on_timeout is deprecated and has been replaced
* with the equivalent code.
*/
static long cond_wait_interruptible_timeout_irqrestore(
wait_queue_head_t *q, long timeout,
spinlock_t *lock, unsigned long flags)
__releases(lock)
{
DEFINE_WAIT(wait);
prepare_to_wait(q, &wait, TASK_INTERRUPTIBLE);
spin_unlock_irqrestore(lock, flags);
timeout = schedule_timeout(timeout);
finish_wait(q, &wait);
return timeout;
}
/*
* Digi Wakeup Write
*
* Wake up port, line discipline, and tty processes sleeping
* on writes.
*/
static void digi_wakeup_write_lock(struct work_struct *work)
{
struct digi_port *priv =
container_of(work, struct digi_port, dp_wakeup_work);
struct usb_serial_port *port = priv->dp_port;
unsigned long flags;
spin_lock_irqsave(&priv->dp_port_lock, flags);
digi_wakeup_write(port);
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
}
static void digi_wakeup_write(struct usb_serial_port *port)
{
struct tty_struct *tty = tty_port_tty_get(&port->port);
if (tty) {
tty_wakeup(tty);
tty_kref_put(tty);
}
}
/*
* Digi Write OOB Command
*
* Write commands on the out of band port. Commands are 4
* bytes each, multiple commands can be sent at once, and
* no command will be split across USB packets. Returns 0
* if successful, -EINTR if interrupted while sleeping and
* the interruptible flag is true, or a negative error
* returned by usb_submit_urb.
*/
static int digi_write_oob_command(struct usb_serial_port *port,
unsigned char *buf, int count, int interruptible)
{
int ret = 0;
int len;
struct usb_serial_port *oob_port = (struct usb_serial_port *)((struct digi_serial *)(usb_get_serial_data(port->serial)))->ds_oob_port;
struct digi_port *oob_priv = usb_get_serial_port_data(oob_port);
unsigned long flags = 0;
dbg("digi_write_oob_command: TOP: port=%d, count=%d", oob_priv->dp_port_num, count);
spin_lock_irqsave(&oob_priv->dp_port_lock, flags);
while (count > 0) {
while (oob_priv->dp_write_urb_in_use) {
cond_wait_interruptible_timeout_irqrestore(
&oob_port->write_wait, DIGI_RETRY_TIMEOUT,
&oob_priv->dp_port_lock, flags);
if (interruptible && signal_pending(current))
return -EINTR;
spin_lock_irqsave(&oob_priv->dp_port_lock, flags);
}
/* len must be a multiple of 4, so commands are not split */
len = min(count, oob_port->bulk_out_size);
if (len > 4)
len &= ~3;
memcpy(oob_port->write_urb->transfer_buffer, buf, len);
oob_port->write_urb->transfer_buffer_length = len;
ret = usb_submit_urb(oob_port->write_urb, GFP_ATOMIC);
if (ret == 0) {
oob_priv->dp_write_urb_in_use = 1;
count -= len;
buf += len;
}
}
spin_unlock_irqrestore(&oob_priv->dp_port_lock, flags);
if (ret)
dev_err(&port->dev, "%s: usb_submit_urb failed, ret=%d\n",
__func__, ret);
return ret;
}
/*
* Digi Write In Band Command
*
* Write commands on the given port. Commands are 4
* bytes each, multiple commands can be sent at once, and
* no command will be split across USB packets. If timeout
* is non-zero, write in band command will return after
* waiting unsuccessfully for the URB status to clear for
* timeout ticks. Returns 0 if successful, or a negative
* error returned by digi_write.
*/
static int digi_write_inb_command(struct usb_serial_port *port,
unsigned char *buf, int count, unsigned long timeout)
{
int ret = 0;
int len;
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned char *data = port->write_urb->transfer_buffer;
unsigned long flags = 0;
dbg("digi_write_inb_command: TOP: port=%d, count=%d",
priv->dp_port_num, count);
if (timeout)
timeout += jiffies;
else
timeout = ULONG_MAX;
spin_lock_irqsave(&priv->dp_port_lock, flags);
while (count > 0 && ret == 0) {
while (priv->dp_write_urb_in_use &&
time_before(jiffies, timeout)) {
cond_wait_interruptible_timeout_irqrestore(
&port->write_wait, DIGI_RETRY_TIMEOUT,
&priv->dp_port_lock, flags);
if (signal_pending(current))
return -EINTR;
spin_lock_irqsave(&priv->dp_port_lock, flags);
}
/* len must be a multiple of 4 and small enough to */
/* guarantee the write will send buffered data first, */
/* so commands are in order with data and not split */
len = min(count, port->bulk_out_size-2-priv->dp_out_buf_len);
if (len > 4)
len &= ~3;
/* write any buffered data first */
if (priv->dp_out_buf_len > 0) {
data[0] = DIGI_CMD_SEND_DATA;
data[1] = priv->dp_out_buf_len;
memcpy(data + 2, priv->dp_out_buf,
priv->dp_out_buf_len);
memcpy(data + 2 + priv->dp_out_buf_len, buf, len);
port->write_urb->transfer_buffer_length
= priv->dp_out_buf_len + 2 + len;
} else {
memcpy(data, buf, len);
port->write_urb->transfer_buffer_length = len;
}
ret = usb_submit_urb(port->write_urb, GFP_ATOMIC);
if (ret == 0) {
priv->dp_write_urb_in_use = 1;
priv->dp_out_buf_len = 0;
count -= len;
buf += len;
}
}
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
if (ret)
dev_err(&port->dev,
"%s: usb_submit_urb failed, ret=%d, port=%d\n",
__func__, ret, priv->dp_port_num);
return ret;
}
/*
* Digi Set Modem Signals
*
* Sets or clears DTR and RTS on the port, according to the
* modem_signals argument. Use TIOCM_DTR and TIOCM_RTS flags
* for the modem_signals argument. Returns 0 if successful,
* -EINTR if interrupted while sleeping, or a non-zero error
* returned by usb_submit_urb.
*/
static int digi_set_modem_signals(struct usb_serial_port *port,
unsigned int modem_signals, int interruptible)
{
int ret;
struct digi_port *port_priv = usb_get_serial_port_data(port);
struct usb_serial_port *oob_port = (struct usb_serial_port *) ((struct digi_serial *)(usb_get_serial_data(port->serial)))->ds_oob_port;
struct digi_port *oob_priv = usb_get_serial_port_data(oob_port);
unsigned char *data = oob_port->write_urb->transfer_buffer;
unsigned long flags = 0;
dbg("digi_set_modem_signals: TOP: port=%d, modem_signals=0x%x",
port_priv->dp_port_num, modem_signals);
spin_lock_irqsave(&oob_priv->dp_port_lock, flags);
spin_lock(&port_priv->dp_port_lock);
while (oob_priv->dp_write_urb_in_use) {
spin_unlock(&port_priv->dp_port_lock);
cond_wait_interruptible_timeout_irqrestore(
&oob_port->write_wait, DIGI_RETRY_TIMEOUT,
&oob_priv->dp_port_lock, flags);
if (interruptible && signal_pending(current))
return -EINTR;
spin_lock_irqsave(&oob_priv->dp_port_lock, flags);
spin_lock(&port_priv->dp_port_lock);
}
data[0] = DIGI_CMD_SET_DTR_SIGNAL;
data[1] = port_priv->dp_port_num;
data[2] = (modem_signals & TIOCM_DTR) ?
DIGI_DTR_ACTIVE : DIGI_DTR_INACTIVE;
data[3] = 0;
data[4] = DIGI_CMD_SET_RTS_SIGNAL;
data[5] = port_priv->dp_port_num;
data[6] = (modem_signals & TIOCM_RTS) ?
DIGI_RTS_ACTIVE : DIGI_RTS_INACTIVE;
data[7] = 0;
oob_port->write_urb->transfer_buffer_length = 8;
ret = usb_submit_urb(oob_port->write_urb, GFP_ATOMIC);
if (ret == 0) {
oob_priv->dp_write_urb_in_use = 1;
port_priv->dp_modem_signals =
(port_priv->dp_modem_signals&~(TIOCM_DTR|TIOCM_RTS))
| (modem_signals&(TIOCM_DTR|TIOCM_RTS));
}
spin_unlock(&port_priv->dp_port_lock);
spin_unlock_irqrestore(&oob_priv->dp_port_lock, flags);
if (ret)
dev_err(&port->dev, "%s: usb_submit_urb failed, ret=%d\n",
__func__, ret);
return ret;
}
/*
* Digi Transmit Idle
*
* Digi transmit idle waits, up to timeout ticks, for the transmitter
* to go idle. It returns 0 if successful or a negative error.
*
* There are race conditions here if more than one process is calling
* digi_transmit_idle on the same port at the same time. However, this
* is only called from close, and only one process can be in close on a
* port at a time, so its ok.
*/
static int digi_transmit_idle(struct usb_serial_port *port,
unsigned long timeout)
{
int ret;
unsigned char buf[2];
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned long flags = 0;
spin_lock_irqsave(&priv->dp_port_lock, flags);
priv->dp_transmit_idle = 0;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
buf[0] = DIGI_CMD_TRANSMIT_IDLE;
buf[1] = 0;
timeout += jiffies;
ret = digi_write_inb_command(port, buf, 2, timeout - jiffies);
if (ret != 0)
return ret;
spin_lock_irqsave(&priv->dp_port_lock, flags);
while (time_before(jiffies, timeout) && !priv->dp_transmit_idle) {
cond_wait_interruptible_timeout_irqrestore(
&priv->dp_transmit_idle_wait, DIGI_RETRY_TIMEOUT,
&priv->dp_port_lock, flags);
if (signal_pending(current))
return -EINTR;
spin_lock_irqsave(&priv->dp_port_lock, flags);
}
priv->dp_transmit_idle = 0;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
return 0;
}
static void digi_rx_throttle(struct tty_struct *tty)
{
unsigned long flags;
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
dbg("digi_rx_throttle: TOP: port=%d", priv->dp_port_num);
/* stop receiving characters by not resubmitting the read urb */
spin_lock_irqsave(&priv->dp_port_lock, flags);
priv->dp_throttled = 1;
priv->dp_throttle_restart = 0;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
}
static void digi_rx_unthrottle(struct tty_struct *tty)
{
int ret = 0;
unsigned long flags;
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
dbg("digi_rx_unthrottle: TOP: port=%d", priv->dp_port_num);
spin_lock_irqsave(&priv->dp_port_lock, flags);
/* restart read chain */
if (priv->dp_throttle_restart)
ret = usb_submit_urb(port->read_urb, GFP_ATOMIC);
/* turn throttle off */
priv->dp_throttled = 0;
priv->dp_throttle_restart = 0;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
if (ret)
dev_err(&port->dev,
"%s: usb_submit_urb failed, ret=%d, port=%d\n",
__func__, ret, priv->dp_port_num);
}
static void digi_set_termios(struct tty_struct *tty,
struct usb_serial_port *port, struct ktermios *old_termios)
{
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned int iflag = tty->termios->c_iflag;
unsigned int cflag = tty->termios->c_cflag;
unsigned int old_iflag = old_termios->c_iflag;
unsigned int old_cflag = old_termios->c_cflag;
unsigned char buf[32];
unsigned int modem_signals;
int arg, ret;
int i = 0;
speed_t baud;
dbg("digi_set_termios: TOP: port=%d, iflag=0x%x, old_iflag=0x%x, cflag=0x%x, old_cflag=0x%x", priv->dp_port_num, iflag, old_iflag, cflag, old_cflag);
/* set baud rate */
baud = tty_get_baud_rate(tty);
if (baud != tty_termios_baud_rate(old_termios)) {
arg = -1;
/* reassert DTR and (maybe) RTS on transition from B0 */
if ((old_cflag&CBAUD) == B0) {
/* don't set RTS if using hardware flow control */
/* and throttling input */
modem_signals = TIOCM_DTR;
if (!(tty->termios->c_cflag & CRTSCTS) ||
!test_bit(TTY_THROTTLED, &tty->flags))
modem_signals |= TIOCM_RTS;
digi_set_modem_signals(port, modem_signals, 1);
}
switch (baud) {
/* drop DTR and RTS on transition to B0 */
case 0: digi_set_modem_signals(port, 0, 1); break;
case 50: arg = DIGI_BAUD_50; break;
case 75: arg = DIGI_BAUD_75; break;
case 110: arg = DIGI_BAUD_110; break;
case 150: arg = DIGI_BAUD_150; break;
case 200: arg = DIGI_BAUD_200; break;
case 300: arg = DIGI_BAUD_300; break;
case 600: arg = DIGI_BAUD_600; break;
case 1200: arg = DIGI_BAUD_1200; break;
case 1800: arg = DIGI_BAUD_1800; break;
case 2400: arg = DIGI_BAUD_2400; break;
case 4800: arg = DIGI_BAUD_4800; break;
case 9600: arg = DIGI_BAUD_9600; break;
case 19200: arg = DIGI_BAUD_19200; break;
case 38400: arg = DIGI_BAUD_38400; break;
case 57600: arg = DIGI_BAUD_57600; break;
case 115200: arg = DIGI_BAUD_115200; break;
case 230400: arg = DIGI_BAUD_230400; break;
case 460800: arg = DIGI_BAUD_460800; break;
default:
arg = DIGI_BAUD_9600;
baud = 9600;
break;
}
if (arg != -1) {
buf[i++] = DIGI_CMD_SET_BAUD_RATE;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
}
/* set parity */
tty->termios->c_cflag &= ~CMSPAR;
if ((cflag&(PARENB|PARODD)) != (old_cflag&(PARENB|PARODD))) {
if (cflag&PARENB) {
if (cflag&PARODD)
arg = DIGI_PARITY_ODD;
else
arg = DIGI_PARITY_EVEN;
} else {
arg = DIGI_PARITY_NONE;
}
buf[i++] = DIGI_CMD_SET_PARITY;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
/* set word size */
if ((cflag&CSIZE) != (old_cflag&CSIZE)) {
arg = -1;
switch (cflag&CSIZE) {
case CS5: arg = DIGI_WORD_SIZE_5; break;
case CS6: arg = DIGI_WORD_SIZE_6; break;
case CS7: arg = DIGI_WORD_SIZE_7; break;
case CS8: arg = DIGI_WORD_SIZE_8; break;
default:
dbg("digi_set_termios: can't handle word size %d",
(cflag&CSIZE));
break;
}
if (arg != -1) {
buf[i++] = DIGI_CMD_SET_WORD_SIZE;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
}
/* set stop bits */
if ((cflag&CSTOPB) != (old_cflag&CSTOPB)) {
if ((cflag&CSTOPB))
arg = DIGI_STOP_BITS_2;
else
arg = DIGI_STOP_BITS_1;
buf[i++] = DIGI_CMD_SET_STOP_BITS;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
/* set input flow control */
if ((iflag&IXOFF) != (old_iflag&IXOFF)
|| (cflag&CRTSCTS) != (old_cflag&CRTSCTS)) {
arg = 0;
if (iflag&IXOFF)
arg |= DIGI_INPUT_FLOW_CONTROL_XON_XOFF;
else
arg &= ~DIGI_INPUT_FLOW_CONTROL_XON_XOFF;
if (cflag&CRTSCTS) {
arg |= DIGI_INPUT_FLOW_CONTROL_RTS;
/* On USB-4 it is necessary to assert RTS prior */
/* to selecting RTS input flow control. */
buf[i++] = DIGI_CMD_SET_RTS_SIGNAL;
buf[i++] = priv->dp_port_num;
buf[i++] = DIGI_RTS_ACTIVE;
buf[i++] = 0;
} else {
arg &= ~DIGI_INPUT_FLOW_CONTROL_RTS;
}
buf[i++] = DIGI_CMD_SET_INPUT_FLOW_CONTROL;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
/* set output flow control */
if ((iflag & IXON) != (old_iflag & IXON)
|| (cflag & CRTSCTS) != (old_cflag & CRTSCTS)) {
arg = 0;
if (iflag & IXON)
arg |= DIGI_OUTPUT_FLOW_CONTROL_XON_XOFF;
else
arg &= ~DIGI_OUTPUT_FLOW_CONTROL_XON_XOFF;
if (cflag & CRTSCTS) {
arg |= DIGI_OUTPUT_FLOW_CONTROL_CTS;
} else {
arg &= ~DIGI_OUTPUT_FLOW_CONTROL_CTS;
tty->hw_stopped = 0;
}
buf[i++] = DIGI_CMD_SET_OUTPUT_FLOW_CONTROL;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
/* set receive enable/disable */
if ((cflag & CREAD) != (old_cflag & CREAD)) {
if (cflag & CREAD)
arg = DIGI_ENABLE;
else
arg = DIGI_DISABLE;
buf[i++] = DIGI_CMD_RECEIVE_ENABLE;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
ret = digi_write_oob_command(port, buf, i, 1);
if (ret != 0)
dbg("digi_set_termios: write oob failed, ret=%d", ret);
tty_encode_baud_rate(tty, baud, baud);
}
static void digi_break_ctl(struct tty_struct *tty, int break_state)
{
struct usb_serial_port *port = tty->driver_data;
unsigned char buf[4];
buf[0] = DIGI_CMD_BREAK_CONTROL;
buf[1] = 2; /* length */
buf[2] = break_state ? 1 : 0;
buf[3] = 0; /* pad */
digi_write_inb_command(port, buf, 4, 0);
}
static int digi_tiocmget(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned int val;
unsigned long flags;
dbg("%s: TOP: port=%d", __func__, priv->dp_port_num);
spin_lock_irqsave(&priv->dp_port_lock, flags);
val = priv->dp_modem_signals;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
return val;
}
static int digi_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned int val;
unsigned long flags;
dbg("%s: TOP: port=%d", __func__, priv->dp_port_num);
spin_lock_irqsave(&priv->dp_port_lock, flags);
val = (priv->dp_modem_signals & ~clear) | set;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
return digi_set_modem_signals(port, val, 1);
}
static int digi_write(struct tty_struct *tty, struct usb_serial_port *port,
const unsigned char *buf, int count)
{
int ret, data_len, new_len;
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned char *data = port->write_urb->transfer_buffer;
unsigned long flags = 0;
dbg("digi_write: TOP: port=%d, count=%d, in_interrupt=%ld",
priv->dp_port_num, count, in_interrupt());
/* copy user data (which can sleep) before getting spin lock */
count = min(count, port->bulk_out_size-2);
count = min(64, count);
/* be sure only one write proceeds at a time */
/* there are races on the port private buffer */
spin_lock_irqsave(&priv->dp_port_lock, flags);
/* wait for urb status clear to submit another urb */
if (priv->dp_write_urb_in_use) {
/* buffer data if count is 1 (probably put_char) if possible */
if (count == 1 && priv->dp_out_buf_len < DIGI_OUT_BUF_SIZE) {
priv->dp_out_buf[priv->dp_out_buf_len++] = *buf;
new_len = 1;
} else {
new_len = 0;
}
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
return new_len;
}
/* allow space for any buffered data and for new data, up to */
/* transfer buffer size - 2 (for command and length bytes) */
new_len = min(count, port->bulk_out_size-2-priv->dp_out_buf_len);
data_len = new_len + priv->dp_out_buf_len;
if (data_len == 0) {
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
return 0;
}
port->write_urb->transfer_buffer_length = data_len+2;
*data++ = DIGI_CMD_SEND_DATA;
*data++ = data_len;
/* copy in buffered data first */
memcpy(data, priv->dp_out_buf, priv->dp_out_buf_len);
data += priv->dp_out_buf_len;
/* copy in new data */
memcpy(data, buf, new_len);
ret = usb_submit_urb(port->write_urb, GFP_ATOMIC);
if (ret == 0) {
priv->dp_write_urb_in_use = 1;
ret = new_len;
priv->dp_out_buf_len = 0;
}
/* return length of new data written, or error */
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
if (ret < 0)
dev_err_console(port,
"%s: usb_submit_urb failed, ret=%d, port=%d\n",
__func__, ret, priv->dp_port_num);
dbg("digi_write: returning %d", ret);
return ret;
}
static void digi_write_bulk_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct usb_serial *serial;
struct digi_port *priv;
struct digi_serial *serial_priv;
int ret = 0;
int status = urb->status;
dbg("digi_write_bulk_callback: TOP, status=%d", status);
/* port and serial sanity check */
if (port == NULL || (priv = usb_get_serial_port_data(port)) == NULL) {
pr_err("%s: port or port->private is NULL, status=%d\n",
__func__, status);
return;
}
serial = port->serial;
if (serial == NULL || (serial_priv = usb_get_serial_data(serial)) == NULL) {
dev_err(&port->dev,
"%s: serial or serial->private is NULL, status=%d\n",
__func__, status);
return;
}
/* handle oob callback */
if (priv->dp_port_num == serial_priv->ds_oob_port_num) {
dbg("digi_write_bulk_callback: oob callback");
spin_lock(&priv->dp_port_lock);
priv->dp_write_urb_in_use = 0;
wake_up_interruptible(&port->write_wait);
spin_unlock(&priv->dp_port_lock);
return;
}
/* try to send any buffered data on this port */
spin_lock(&priv->dp_port_lock);
priv->dp_write_urb_in_use = 0;
if (priv->dp_out_buf_len > 0) {
*((unsigned char *)(port->write_urb->transfer_buffer))
= (unsigned char)DIGI_CMD_SEND_DATA;
*((unsigned char *)(port->write_urb->transfer_buffer) + 1)
= (unsigned char)priv->dp_out_buf_len;
port->write_urb->transfer_buffer_length =
priv->dp_out_buf_len + 2;
memcpy(port->write_urb->transfer_buffer + 2, priv->dp_out_buf,
priv->dp_out_buf_len);
ret = usb_submit_urb(port->write_urb, GFP_ATOMIC);
if (ret == 0) {
priv->dp_write_urb_in_use = 1;
priv->dp_out_buf_len = 0;
}
}
/* wake up processes sleeping on writes immediately */
digi_wakeup_write(port);
/* also queue up a wakeup at scheduler time, in case we */
/* lost the race in write_chan(). */
schedule_work(&priv->dp_wakeup_work);
spin_unlock(&priv->dp_port_lock);
if (ret && ret != -EPERM)
dev_err_console(port,
"%s: usb_submit_urb failed, ret=%d, port=%d\n",
__func__, ret, priv->dp_port_num);
}
static int digi_write_room(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
int room;
unsigned long flags = 0;
spin_lock_irqsave(&priv->dp_port_lock, flags);
if (priv->dp_write_urb_in_use)
room = 0;
else
room = port->bulk_out_size - 2 - priv->dp_out_buf_len;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
dbg("digi_write_room: port=%d, room=%d", priv->dp_port_num, room);
return room;
}
static int digi_chars_in_buffer(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
if (priv->dp_write_urb_in_use) {
dbg("digi_chars_in_buffer: port=%d, chars=%d",
priv->dp_port_num, port->bulk_out_size - 2);
/* return(port->bulk_out_size - 2); */
return 256;
} else {
dbg("digi_chars_in_buffer: port=%d, chars=%d",
priv->dp_port_num, priv->dp_out_buf_len);
return priv->dp_out_buf_len;
}
}
static void digi_dtr_rts(struct usb_serial_port *port, int on)
{
/* Adjust DTR and RTS */
digi_set_modem_signals(port, on * (TIOCM_DTR|TIOCM_RTS), 1);
}
static int digi_open(struct tty_struct *tty, struct usb_serial_port *port)
{
int ret;
unsigned char buf[32];
struct digi_port *priv = usb_get_serial_port_data(port);
struct ktermios not_termios;
dbg("digi_open: TOP: port=%d", priv->dp_port_num);
/* be sure the device is started up */
if (digi_startup_device(port->serial) != 0)
return -ENXIO;
/* read modem signals automatically whenever they change */
buf[0] = DIGI_CMD_READ_INPUT_SIGNALS;
buf[1] = priv->dp_port_num;
buf[2] = DIGI_ENABLE;
buf[3] = 0;
/* flush fifos */
buf[4] = DIGI_CMD_IFLUSH_FIFO;
buf[5] = priv->dp_port_num;
buf[6] = DIGI_FLUSH_TX | DIGI_FLUSH_RX;
buf[7] = 0;
ret = digi_write_oob_command(port, buf, 8, 1);
if (ret != 0)
dbg("digi_open: write oob failed, ret=%d", ret);
/* set termios settings */
if (tty) {
not_termios.c_cflag = ~tty->termios->c_cflag;
not_termios.c_iflag = ~tty->termios->c_iflag;
digi_set_termios(tty, port, ¬_termios);
}
return 0;
}
static void digi_close(struct usb_serial_port *port)
{
DEFINE_WAIT(wait);
int ret;
unsigned char buf[32];
struct digi_port *priv = usb_get_serial_port_data(port);
dbg("digi_close: TOP: port=%d", priv->dp_port_num);
mutex_lock(&port->serial->disc_mutex);
/* if disconnected, just clear flags */
if (port->serial->disconnected)
goto exit;
if (port->serial->dev) {
/* FIXME: Transmit idle belongs in the wait_unti_sent path */
digi_transmit_idle(port, DIGI_CLOSE_TIMEOUT);
/* disable input flow control */
buf[0] = DIGI_CMD_SET_INPUT_FLOW_CONTROL;
buf[1] = priv->dp_port_num;
buf[2] = DIGI_DISABLE;
buf[3] = 0;
/* disable output flow control */
buf[4] = DIGI_CMD_SET_OUTPUT_FLOW_CONTROL;
buf[5] = priv->dp_port_num;
buf[6] = DIGI_DISABLE;
buf[7] = 0;
/* disable reading modem signals automatically */
buf[8] = DIGI_CMD_READ_INPUT_SIGNALS;
buf[9] = priv->dp_port_num;
buf[10] = DIGI_DISABLE;
buf[11] = 0;
/* disable receive */
buf[12] = DIGI_CMD_RECEIVE_ENABLE;
buf[13] = priv->dp_port_num;
buf[14] = DIGI_DISABLE;
buf[15] = 0;
/* flush fifos */
buf[16] = DIGI_CMD_IFLUSH_FIFO;
buf[17] = priv->dp_port_num;
buf[18] = DIGI_FLUSH_TX | DIGI_FLUSH_RX;
buf[19] = 0;
ret = digi_write_oob_command(port, buf, 20, 0);
if (ret != 0)
dbg("digi_close: write oob failed, ret=%d", ret);
/* wait for final commands on oob port to complete */
prepare_to_wait(&priv->dp_flush_wait, &wait,
TASK_INTERRUPTIBLE);
schedule_timeout(DIGI_CLOSE_TIMEOUT);
finish_wait(&priv->dp_flush_wait, &wait);
/* shutdown any outstanding bulk writes */
usb_kill_urb(port->write_urb);
}
exit:
spin_lock_irq(&priv->dp_port_lock);
priv->dp_write_urb_in_use = 0;
wake_up_interruptible(&priv->dp_close_wait);
spin_unlock_irq(&priv->dp_port_lock);
mutex_unlock(&port->serial->disc_mutex);
dbg("digi_close: done");
}
/*
* Digi Startup Device
*
* Starts reads on all ports. Must be called AFTER startup, with
* urbs initialized. Returns 0 if successful, non-zero error otherwise.
*/
static int digi_startup_device(struct usb_serial *serial)
{
int i, ret = 0;
struct digi_serial *serial_priv = usb_get_serial_data(serial);
struct usb_serial_port *port;
/* be sure this happens exactly once */
spin_lock(&serial_priv->ds_serial_lock);
if (serial_priv->ds_device_started) {
spin_unlock(&serial_priv->ds_serial_lock);
return 0;
}
serial_priv->ds_device_started = 1;
spin_unlock(&serial_priv->ds_serial_lock);
/* start reading from each bulk in endpoint for the device */
/* set USB_DISABLE_SPD flag for write bulk urbs */
for (i = 0; i < serial->type->num_ports + 1; i++) {
port = serial->port[i];
ret = usb_submit_urb(port->read_urb, GFP_KERNEL);
if (ret != 0) {
dev_err(&port->dev,
"%s: usb_submit_urb failed, ret=%d, port=%d\n",
__func__, ret, i);
break;
}
}
return ret;
}
static int digi_startup(struct usb_serial *serial)
{
int i;
struct digi_port *priv;
struct digi_serial *serial_priv;
dbg("digi_startup: TOP");
/* allocate the private data structures for all ports */
/* number of regular ports + 1 for the out-of-band port */
for (i = 0; i < serial->type->num_ports + 1; i++) {
/* allocate port private structure */
priv = kmalloc(sizeof(struct digi_port), GFP_KERNEL);
if (priv == NULL) {
while (--i >= 0)
kfree(usb_get_serial_port_data(serial->port[i]));
return 1; /* error */
}
/* initialize port private structure */
spin_lock_init(&priv->dp_port_lock);
priv->dp_port_num = i;
priv->dp_out_buf_len = 0;
priv->dp_write_urb_in_use = 0;
priv->dp_modem_signals = 0;
init_waitqueue_head(&priv->dp_modem_change_wait);
priv->dp_transmit_idle = 0;
init_waitqueue_head(&priv->dp_transmit_idle_wait);
priv->dp_throttled = 0;
priv->dp_throttle_restart = 0;
init_waitqueue_head(&priv->dp_flush_wait);
init_waitqueue_head(&priv->dp_close_wait);
INIT_WORK(&priv->dp_wakeup_work, digi_wakeup_write_lock);
priv->dp_port = serial->port[i];
/* initialize write wait queue for this port */
init_waitqueue_head(&serial->port[i]->write_wait);
usb_set_serial_port_data(serial->port[i], priv);
}
/* allocate serial private structure */
serial_priv = kmalloc(sizeof(struct digi_serial), GFP_KERNEL);
if (serial_priv == NULL) {
for (i = 0; i < serial->type->num_ports + 1; i++)
kfree(usb_get_serial_port_data(serial->port[i]));
return 1; /* error */
}
/* initialize serial private structure */
spin_lock_init(&serial_priv->ds_serial_lock);
serial_priv->ds_oob_port_num = serial->type->num_ports;
serial_priv->ds_oob_port = serial->port[serial_priv->ds_oob_port_num];
serial_priv->ds_device_started = 0;
usb_set_serial_data(serial, serial_priv);
return 0;
}
static void digi_disconnect(struct usb_serial *serial)
{
int i;
dbg("digi_disconnect: TOP, in_interrupt()=%ld", in_interrupt());
/* stop reads and writes on all ports */
for (i = 0; i < serial->type->num_ports + 1; i++) {
usb_kill_urb(serial->port[i]->read_urb);
usb_kill_urb(serial->port[i]->write_urb);
}
}
static void digi_release(struct usb_serial *serial)
{
int i;
dbg("digi_release: TOP, in_interrupt()=%ld", in_interrupt());
/* free the private data structures for all ports */
/* number of regular ports + 1 for the out-of-band port */
for (i = 0; i < serial->type->num_ports + 1; i++)
kfree(usb_get_serial_port_data(serial->port[i]));
kfree(usb_get_serial_data(serial));
}
static void digi_read_bulk_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct digi_port *priv;
struct digi_serial *serial_priv;
int ret;
int status = urb->status;
dbg("digi_read_bulk_callback: TOP");
/* port sanity check, do not resubmit if port is not valid */
if (port == NULL)
return;
priv = usb_get_serial_port_data(port);
if (priv == NULL) {
dev_err(&port->dev, "%s: port->private is NULL, status=%d\n",
__func__, status);
return;
}
if (port->serial == NULL ||
(serial_priv = usb_get_serial_data(port->serial)) == NULL) {
dev_err(&port->dev, "%s: serial is bad or serial->private "
"is NULL, status=%d\n", __func__, status);
return;
}
/* do not resubmit urb if it has any status error */
if (status) {
dev_err(&port->dev,
"%s: nonzero read bulk status: status=%d, port=%d\n",
__func__, status, priv->dp_port_num);
return;
}
/* handle oob or inb callback, do not resubmit if error */
if (priv->dp_port_num == serial_priv->ds_oob_port_num) {
if (digi_read_oob_callback(urb) != 0)
return;
} else {
if (digi_read_inb_callback(urb) != 0)
return;
}
/* continue read */
ret = usb_submit_urb(urb, GFP_ATOMIC);
if (ret != 0 && ret != -EPERM) {
dev_err(&port->dev,
"%s: failed resubmitting urb, ret=%d, port=%d\n",
__func__, ret, priv->dp_port_num);
}
}
/*
* Digi Read INB Callback
*
* Digi Read INB Callback handles reads on the in band ports, sending
* the data on to the tty subsystem. When called we know port and
* port->private are not NULL and port->serial has been validated.
* It returns 0 if successful, 1 if successful but the port is
* throttled, and -1 if the sanity checks failed.
*/
static int digi_read_inb_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct tty_struct *tty;
struct digi_port *priv = usb_get_serial_port_data(port);
int opcode = ((unsigned char *)urb->transfer_buffer)[0];
int len = ((unsigned char *)urb->transfer_buffer)[1];
int port_status = ((unsigned char *)urb->transfer_buffer)[2];
unsigned char *data = ((unsigned char *)urb->transfer_buffer) + 3;
int flag, throttled;
int status = urb->status;
/* do not process callbacks on closed ports */
/* but do continue the read chain */
if (urb->status == -ENOENT)
return 0;
/* short/multiple packet check */
if (urb->actual_length != len + 2) {
dev_err(&port->dev, "%s: INCOMPLETE OR MULTIPLE PACKET, "
"status=%d, port=%d, opcode=%d, len=%d, "
"actual_length=%d, status=%d\n", __func__, status,
priv->dp_port_num, opcode, len, urb->actual_length,
port_status);
return -1;
}
tty = tty_port_tty_get(&port->port);
spin_lock(&priv->dp_port_lock);
/* check for throttle; if set, do not resubmit read urb */
/* indicate the read chain needs to be restarted on unthrottle */
throttled = priv->dp_throttled;
if (throttled)
priv->dp_throttle_restart = 1;
/* receive data */
if (tty && opcode == DIGI_CMD_RECEIVE_DATA) {
/* get flag from port_status */
flag = 0;
/* overrun is special, not associated with a char */
if (port_status & DIGI_OVERRUN_ERROR)
tty_insert_flip_char(tty, 0, TTY_OVERRUN);
/* break takes precedence over parity, */
/* which takes precedence over framing errors */
if (port_status & DIGI_BREAK_ERROR)
flag = TTY_BREAK;
else if (port_status & DIGI_PARITY_ERROR)
flag = TTY_PARITY;
else if (port_status & DIGI_FRAMING_ERROR)
flag = TTY_FRAME;
/* data length is len-1 (one byte of len is port_status) */
--len;
if (len > 0) {
tty_insert_flip_string_fixed_flag(tty, data, flag,
len);
tty_flip_buffer_push(tty);
}
}
spin_unlock(&priv->dp_port_lock);
tty_kref_put(tty);
if (opcode == DIGI_CMD_RECEIVE_DISABLE)
dbg("%s: got RECEIVE_DISABLE", __func__);
else if (opcode != DIGI_CMD_RECEIVE_DATA)
dbg("%s: unknown opcode: %d", __func__, opcode);
return throttled ? 1 : 0;
}
/*
* Digi Read OOB Callback
*
* Digi Read OOB Callback handles reads on the out of band port.
* When called we know port and port->private are not NULL and
* the port->serial is valid. It returns 0 if successful, and
* -1 if the sanity checks failed.
*/
static int digi_read_oob_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct usb_serial *serial = port->serial;
struct tty_struct *tty;
struct digi_port *priv = usb_get_serial_port_data(port);
int opcode, line, status, val;
int i;
unsigned int rts;
dbg("digi_read_oob_callback: port=%d, len=%d",
priv->dp_port_num, urb->actual_length);
/* handle each oob command */
for (i = 0; i < urb->actual_length - 3;) {
opcode = ((unsigned char *)urb->transfer_buffer)[i++];
line = ((unsigned char *)urb->transfer_buffer)[i++];
status = ((unsigned char *)urb->transfer_buffer)[i++];
val = ((unsigned char *)urb->transfer_buffer)[i++];
dbg("digi_read_oob_callback: opcode=%d, line=%d, status=%d, val=%d",
opcode, line, status, val);
if (status != 0 || line >= serial->type->num_ports)
continue;
port = serial->port[line];
priv = usb_get_serial_port_data(port);
if (priv == NULL)
return -1;
tty = tty_port_tty_get(&port->port);
rts = 0;
if (tty)
rts = tty->termios->c_cflag & CRTSCTS;
if (tty && opcode == DIGI_CMD_READ_INPUT_SIGNALS) {
spin_lock(&priv->dp_port_lock);
/* convert from digi flags to termiox flags */
if (val & DIGI_READ_INPUT_SIGNALS_CTS) {
priv->dp_modem_signals |= TIOCM_CTS;
/* port must be open to use tty struct */
if (rts) {
tty->hw_stopped = 0;
digi_wakeup_write(port);
}
} else {
priv->dp_modem_signals &= ~TIOCM_CTS;
/* port must be open to use tty struct */
if (rts)
tty->hw_stopped = 1;
}
if (val & DIGI_READ_INPUT_SIGNALS_DSR)
priv->dp_modem_signals |= TIOCM_DSR;
else
priv->dp_modem_signals &= ~TIOCM_DSR;
if (val & DIGI_READ_INPUT_SIGNALS_RI)
priv->dp_modem_signals |= TIOCM_RI;
else
priv->dp_modem_signals &= ~TIOCM_RI;
if (val & DIGI_READ_INPUT_SIGNALS_DCD)
priv->dp_modem_signals |= TIOCM_CD;
else
priv->dp_modem_signals &= ~TIOCM_CD;
wake_up_interruptible(&priv->dp_modem_change_wait);
spin_unlock(&priv->dp_port_lock);
} else if (opcode == DIGI_CMD_TRANSMIT_IDLE) {
spin_lock(&priv->dp_port_lock);
priv->dp_transmit_idle = 1;
wake_up_interruptible(&priv->dp_transmit_idle_wait);
spin_unlock(&priv->dp_port_lock);
} else if (opcode == DIGI_CMD_IFLUSH_FIFO) {
wake_up_interruptible(&priv->dp_flush_wait);
}
tty_kref_put(tty);
}
return 0;
}
module_usb_serial_driver(digi_driver, serial_drivers);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug enabled or not");
| gpl-2.0 |
Sohamlad7/kernel | arch/sh/boards/board-apsh4ad0a.c | 4728 | 3405 | /*
* ALPHAPROJECT AP-SH4AD-0A Support.
*
* Copyright (C) 2010 ALPHAPROJECT Co.,Ltd.
* Copyright (C) 2010 Matt Fleming
* Copyright (C) 2010 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/regulator/fixed.h>
#include <linux/regulator/machine.h>
#include <linux/smsc911x.h>
#include <linux/irq.h>
#include <linux/clk.h>
#include <asm/machvec.h>
#include <asm/sizes.h>
/* Dummy supplies, where voltage doesn't matter */
static struct regulator_consumer_supply dummy_supplies[] = {
REGULATOR_SUPPLY("vddvario", "smsc911x"),
REGULATOR_SUPPLY("vdd33a", "smsc911x"),
};
static struct resource smsc911x_resources[] = {
[0] = {
.name = "smsc911x-memory",
.start = 0xA4000000,
.end = 0xA4000000 + SZ_256 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.name = "smsc911x-irq",
.start = evt2irq(0x200),
.end = evt2irq(0x200),
.flags = IORESOURCE_IRQ,
},
};
static struct smsc911x_platform_config smsc911x_config = {
.irq_polarity = SMSC911X_IRQ_POLARITY_ACTIVE_LOW,
.irq_type = SMSC911X_IRQ_TYPE_OPEN_DRAIN,
.flags = SMSC911X_USE_16BIT,
.phy_interface = PHY_INTERFACE_MODE_MII,
};
static struct platform_device smsc911x_device = {
.name = "smsc911x",
.id = -1,
.num_resources = ARRAY_SIZE(smsc911x_resources),
.resource = smsc911x_resources,
.dev = {
.platform_data = &smsc911x_config,
},
};
static struct platform_device *apsh4ad0a_devices[] __initdata = {
&smsc911x_device,
};
static int __init apsh4ad0a_devices_setup(void)
{
regulator_register_fixed(0, dummy_supplies, ARRAY_SIZE(dummy_supplies));
return platform_add_devices(apsh4ad0a_devices,
ARRAY_SIZE(apsh4ad0a_devices));
}
device_initcall(apsh4ad0a_devices_setup);
static int apsh4ad0a_mode_pins(void)
{
int value = 0;
/* These are the factory default settings of SW1 and SW2.
* If you change these dip switches then you will need to
* adjust the values below as well.
*/
value |= MODE_PIN0; /* Clock Mode 3 */
value |= MODE_PIN1;
value &= ~MODE_PIN2;
value &= ~MODE_PIN3;
value &= ~MODE_PIN4; /* 16-bit Area0 bus width */
value |= MODE_PIN5;
value |= MODE_PIN6;
value |= MODE_PIN7; /* Normal mode */
value |= MODE_PIN8; /* Little Endian */
value |= MODE_PIN9; /* Crystal resonator */
value &= ~MODE_PIN10; /* 29-bit address mode */
value &= ~MODE_PIN11; /* PCI-E Root port */
value &= ~MODE_PIN12; /* 4 lane + 1 lane */
value |= MODE_PIN13; /* AUD Enable */
value &= ~MODE_PIN14; /* Normal Operation */
return value;
}
static int apsh4ad0a_clk_init(void)
{
struct clk *clk;
int ret;
clk = clk_get(NULL, "extal");
if (IS_ERR(clk))
return PTR_ERR(clk);
ret = clk_set_rate(clk, 33333000);
clk_put(clk);
return ret;
}
/* Initialize the board */
static void __init apsh4ad0a_setup(char **cmdline_p)
{
pr_info("Alpha Project AP-SH4AD-0A support:\n");
}
static void __init apsh4ad0a_init_irq(void)
{
plat_irq_setup_pins(IRQ_MODE_IRQ3210);
}
/*
* The Machine Vector
*/
static struct sh_machine_vector mv_apsh4ad0a __initmv = {
.mv_name = "AP-SH4AD-0A",
.mv_setup = apsh4ad0a_setup,
.mv_mode_pins = apsh4ad0a_mode_pins,
.mv_clk_init = apsh4ad0a_clk_init,
.mv_init_irq = apsh4ad0a_init_irq,
};
| gpl-2.0 |
HighwindONE/android_kernel_lge_msm8226 | drivers/usb/serial/digi_acceleport.c | 4728 | 45694 | /*
* Digi AccelePort USB-4 and USB-2 Serial Converters
*
* Copyright 2000 by Digi International
*
* 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.
*
* Shamelessly based on Brian Warner's keyspan_pda.c and Greg Kroah-Hartman's
* usb-serial driver.
*
* Peter Berger (pberger@brimson.com)
* Al Borchers (borchers@steinerpoint.com)
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/workqueue.h>
#include <linux/uaccess.h>
#include <linux/usb.h>
#include <linux/wait.h>
#include <linux/usb/serial.h>
/* Defines */
/*
* Version Information
*/
#define DRIVER_VERSION "v1.80.1.2"
#define DRIVER_AUTHOR "Peter Berger <pberger@brimson.com>, Al Borchers <borchers@steinerpoint.com>"
#define DRIVER_DESC "Digi AccelePort USB-2/USB-4 Serial Converter driver"
/* port output buffer length -- must be <= transfer buffer length - 2 */
/* so we can be sure to send the full buffer in one urb */
#define DIGI_OUT_BUF_SIZE 8
/* port input buffer length -- must be >= transfer buffer length - 3 */
/* so we can be sure to hold at least one full buffer from one urb */
#define DIGI_IN_BUF_SIZE 64
/* retry timeout while sleeping */
#define DIGI_RETRY_TIMEOUT (HZ/10)
/* timeout while waiting for tty output to drain in close */
/* this delay is used twice in close, so the total delay could */
/* be twice this value */
#define DIGI_CLOSE_TIMEOUT (5*HZ)
/* AccelePort USB Defines */
/* ids */
#define DIGI_VENDOR_ID 0x05c5
#define DIGI_2_ID 0x0002 /* USB-2 */
#define DIGI_4_ID 0x0004 /* USB-4 */
/* commands
* "INB": can be used on the in-band endpoint
* "OOB": can be used on the out-of-band endpoint
*/
#define DIGI_CMD_SET_BAUD_RATE 0 /* INB, OOB */
#define DIGI_CMD_SET_WORD_SIZE 1 /* INB, OOB */
#define DIGI_CMD_SET_PARITY 2 /* INB, OOB */
#define DIGI_CMD_SET_STOP_BITS 3 /* INB, OOB */
#define DIGI_CMD_SET_INPUT_FLOW_CONTROL 4 /* INB, OOB */
#define DIGI_CMD_SET_OUTPUT_FLOW_CONTROL 5 /* INB, OOB */
#define DIGI_CMD_SET_DTR_SIGNAL 6 /* INB, OOB */
#define DIGI_CMD_SET_RTS_SIGNAL 7 /* INB, OOB */
#define DIGI_CMD_READ_INPUT_SIGNALS 8 /* OOB */
#define DIGI_CMD_IFLUSH_FIFO 9 /* OOB */
#define DIGI_CMD_RECEIVE_ENABLE 10 /* INB, OOB */
#define DIGI_CMD_BREAK_CONTROL 11 /* INB, OOB */
#define DIGI_CMD_LOCAL_LOOPBACK 12 /* INB, OOB */
#define DIGI_CMD_TRANSMIT_IDLE 13 /* INB, OOB */
#define DIGI_CMD_READ_UART_REGISTER 14 /* OOB */
#define DIGI_CMD_WRITE_UART_REGISTER 15 /* INB, OOB */
#define DIGI_CMD_AND_UART_REGISTER 16 /* INB, OOB */
#define DIGI_CMD_OR_UART_REGISTER 17 /* INB, OOB */
#define DIGI_CMD_SEND_DATA 18 /* INB */
#define DIGI_CMD_RECEIVE_DATA 19 /* INB */
#define DIGI_CMD_RECEIVE_DISABLE 20 /* INB */
#define DIGI_CMD_GET_PORT_TYPE 21 /* OOB */
/* baud rates */
#define DIGI_BAUD_50 0
#define DIGI_BAUD_75 1
#define DIGI_BAUD_110 2
#define DIGI_BAUD_150 3
#define DIGI_BAUD_200 4
#define DIGI_BAUD_300 5
#define DIGI_BAUD_600 6
#define DIGI_BAUD_1200 7
#define DIGI_BAUD_1800 8
#define DIGI_BAUD_2400 9
#define DIGI_BAUD_4800 10
#define DIGI_BAUD_7200 11
#define DIGI_BAUD_9600 12
#define DIGI_BAUD_14400 13
#define DIGI_BAUD_19200 14
#define DIGI_BAUD_28800 15
#define DIGI_BAUD_38400 16
#define DIGI_BAUD_57600 17
#define DIGI_BAUD_76800 18
#define DIGI_BAUD_115200 19
#define DIGI_BAUD_153600 20
#define DIGI_BAUD_230400 21
#define DIGI_BAUD_460800 22
/* arguments */
#define DIGI_WORD_SIZE_5 0
#define DIGI_WORD_SIZE_6 1
#define DIGI_WORD_SIZE_7 2
#define DIGI_WORD_SIZE_8 3
#define DIGI_PARITY_NONE 0
#define DIGI_PARITY_ODD 1
#define DIGI_PARITY_EVEN 2
#define DIGI_PARITY_MARK 3
#define DIGI_PARITY_SPACE 4
#define DIGI_STOP_BITS_1 0
#define DIGI_STOP_BITS_2 1
#define DIGI_INPUT_FLOW_CONTROL_XON_XOFF 1
#define DIGI_INPUT_FLOW_CONTROL_RTS 2
#define DIGI_INPUT_FLOW_CONTROL_DTR 4
#define DIGI_OUTPUT_FLOW_CONTROL_XON_XOFF 1
#define DIGI_OUTPUT_FLOW_CONTROL_CTS 2
#define DIGI_OUTPUT_FLOW_CONTROL_DSR 4
#define DIGI_DTR_INACTIVE 0
#define DIGI_DTR_ACTIVE 1
#define DIGI_DTR_INPUT_FLOW_CONTROL 2
#define DIGI_RTS_INACTIVE 0
#define DIGI_RTS_ACTIVE 1
#define DIGI_RTS_INPUT_FLOW_CONTROL 2
#define DIGI_RTS_TOGGLE 3
#define DIGI_FLUSH_TX 1
#define DIGI_FLUSH_RX 2
#define DIGI_RESUME_TX 4 /* clears xoff condition */
#define DIGI_TRANSMIT_NOT_IDLE 0
#define DIGI_TRANSMIT_IDLE 1
#define DIGI_DISABLE 0
#define DIGI_ENABLE 1
#define DIGI_DEASSERT 0
#define DIGI_ASSERT 1
/* in band status codes */
#define DIGI_OVERRUN_ERROR 4
#define DIGI_PARITY_ERROR 8
#define DIGI_FRAMING_ERROR 16
#define DIGI_BREAK_ERROR 32
/* out of band status */
#define DIGI_NO_ERROR 0
#define DIGI_BAD_FIRST_PARAMETER 1
#define DIGI_BAD_SECOND_PARAMETER 2
#define DIGI_INVALID_LINE 3
#define DIGI_INVALID_OPCODE 4
/* input signals */
#define DIGI_READ_INPUT_SIGNALS_SLOT 1
#define DIGI_READ_INPUT_SIGNALS_ERR 2
#define DIGI_READ_INPUT_SIGNALS_BUSY 4
#define DIGI_READ_INPUT_SIGNALS_PE 8
#define DIGI_READ_INPUT_SIGNALS_CTS 16
#define DIGI_READ_INPUT_SIGNALS_DSR 32
#define DIGI_READ_INPUT_SIGNALS_RI 64
#define DIGI_READ_INPUT_SIGNALS_DCD 128
/* Structures */
struct digi_serial {
spinlock_t ds_serial_lock;
struct usb_serial_port *ds_oob_port; /* out-of-band port */
int ds_oob_port_num; /* index of out-of-band port */
int ds_device_started;
};
struct digi_port {
spinlock_t dp_port_lock;
int dp_port_num;
int dp_out_buf_len;
unsigned char dp_out_buf[DIGI_OUT_BUF_SIZE];
int dp_write_urb_in_use;
unsigned int dp_modem_signals;
wait_queue_head_t dp_modem_change_wait;
int dp_transmit_idle;
wait_queue_head_t dp_transmit_idle_wait;
int dp_throttled;
int dp_throttle_restart;
wait_queue_head_t dp_flush_wait;
wait_queue_head_t dp_close_wait; /* wait queue for close */
struct work_struct dp_wakeup_work;
struct usb_serial_port *dp_port;
};
/* Local Function Declarations */
static void digi_wakeup_write(struct usb_serial_port *port);
static void digi_wakeup_write_lock(struct work_struct *work);
static int digi_write_oob_command(struct usb_serial_port *port,
unsigned char *buf, int count, int interruptible);
static int digi_write_inb_command(struct usb_serial_port *port,
unsigned char *buf, int count, unsigned long timeout);
static int digi_set_modem_signals(struct usb_serial_port *port,
unsigned int modem_signals, int interruptible);
static int digi_transmit_idle(struct usb_serial_port *port,
unsigned long timeout);
static void digi_rx_throttle(struct tty_struct *tty);
static void digi_rx_unthrottle(struct tty_struct *tty);
static void digi_set_termios(struct tty_struct *tty,
struct usb_serial_port *port, struct ktermios *old_termios);
static void digi_break_ctl(struct tty_struct *tty, int break_state);
static int digi_tiocmget(struct tty_struct *tty);
static int digi_tiocmset(struct tty_struct *tty, unsigned int set,
unsigned int clear);
static int digi_write(struct tty_struct *tty, struct usb_serial_port *port,
const unsigned char *buf, int count);
static void digi_write_bulk_callback(struct urb *urb);
static int digi_write_room(struct tty_struct *tty);
static int digi_chars_in_buffer(struct tty_struct *tty);
static int digi_open(struct tty_struct *tty, struct usb_serial_port *port);
static void digi_close(struct usb_serial_port *port);
static void digi_dtr_rts(struct usb_serial_port *port, int on);
static int digi_startup_device(struct usb_serial *serial);
static int digi_startup(struct usb_serial *serial);
static void digi_disconnect(struct usb_serial *serial);
static void digi_release(struct usb_serial *serial);
static void digi_read_bulk_callback(struct urb *urb);
static int digi_read_inb_callback(struct urb *urb);
static int digi_read_oob_callback(struct urb *urb);
/* Statics */
static bool debug;
static const struct usb_device_id id_table_combined[] = {
{ USB_DEVICE(DIGI_VENDOR_ID, DIGI_2_ID) },
{ USB_DEVICE(DIGI_VENDOR_ID, DIGI_4_ID) },
{ } /* Terminating entry */
};
static const struct usb_device_id id_table_2[] = {
{ USB_DEVICE(DIGI_VENDOR_ID, DIGI_2_ID) },
{ } /* Terminating entry */
};
static const struct usb_device_id id_table_4[] = {
{ USB_DEVICE(DIGI_VENDOR_ID, DIGI_4_ID) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, id_table_combined);
static struct usb_driver digi_driver = {
.name = "digi_acceleport",
.probe = usb_serial_probe,
.disconnect = usb_serial_disconnect,
.id_table = id_table_combined,
};
/* device info needed for the Digi serial converter */
static struct usb_serial_driver digi_acceleport_2_device = {
.driver = {
.owner = THIS_MODULE,
.name = "digi_2",
},
.description = "Digi 2 port USB adapter",
.id_table = id_table_2,
.num_ports = 3,
.open = digi_open,
.close = digi_close,
.dtr_rts = digi_dtr_rts,
.write = digi_write,
.write_room = digi_write_room,
.write_bulk_callback = digi_write_bulk_callback,
.read_bulk_callback = digi_read_bulk_callback,
.chars_in_buffer = digi_chars_in_buffer,
.throttle = digi_rx_throttle,
.unthrottle = digi_rx_unthrottle,
.set_termios = digi_set_termios,
.break_ctl = digi_break_ctl,
.tiocmget = digi_tiocmget,
.tiocmset = digi_tiocmset,
.attach = digi_startup,
.disconnect = digi_disconnect,
.release = digi_release,
};
static struct usb_serial_driver digi_acceleport_4_device = {
.driver = {
.owner = THIS_MODULE,
.name = "digi_4",
},
.description = "Digi 4 port USB adapter",
.id_table = id_table_4,
.num_ports = 4,
.open = digi_open,
.close = digi_close,
.write = digi_write,
.write_room = digi_write_room,
.write_bulk_callback = digi_write_bulk_callback,
.read_bulk_callback = digi_read_bulk_callback,
.chars_in_buffer = digi_chars_in_buffer,
.throttle = digi_rx_throttle,
.unthrottle = digi_rx_unthrottle,
.set_termios = digi_set_termios,
.break_ctl = digi_break_ctl,
.tiocmget = digi_tiocmget,
.tiocmset = digi_tiocmset,
.attach = digi_startup,
.disconnect = digi_disconnect,
.release = digi_release,
};
static struct usb_serial_driver * const serial_drivers[] = {
&digi_acceleport_2_device, &digi_acceleport_4_device, NULL
};
/* Functions */
/*
* Cond Wait Interruptible Timeout Irqrestore
*
* Do spin_unlock_irqrestore and interruptible_sleep_on_timeout
* so that wake ups are not lost if they occur between the unlock
* and the sleep. In other words, spin_unlock_irqrestore and
* interruptible_sleep_on_timeout are "atomic" with respect to
* wake ups. This is used to implement condition variables.
*
* interruptible_sleep_on_timeout is deprecated and has been replaced
* with the equivalent code.
*/
static long cond_wait_interruptible_timeout_irqrestore(
wait_queue_head_t *q, long timeout,
spinlock_t *lock, unsigned long flags)
__releases(lock)
{
DEFINE_WAIT(wait);
prepare_to_wait(q, &wait, TASK_INTERRUPTIBLE);
spin_unlock_irqrestore(lock, flags);
timeout = schedule_timeout(timeout);
finish_wait(q, &wait);
return timeout;
}
/*
* Digi Wakeup Write
*
* Wake up port, line discipline, and tty processes sleeping
* on writes.
*/
static void digi_wakeup_write_lock(struct work_struct *work)
{
struct digi_port *priv =
container_of(work, struct digi_port, dp_wakeup_work);
struct usb_serial_port *port = priv->dp_port;
unsigned long flags;
spin_lock_irqsave(&priv->dp_port_lock, flags);
digi_wakeup_write(port);
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
}
static void digi_wakeup_write(struct usb_serial_port *port)
{
struct tty_struct *tty = tty_port_tty_get(&port->port);
if (tty) {
tty_wakeup(tty);
tty_kref_put(tty);
}
}
/*
* Digi Write OOB Command
*
* Write commands on the out of band port. Commands are 4
* bytes each, multiple commands can be sent at once, and
* no command will be split across USB packets. Returns 0
* if successful, -EINTR if interrupted while sleeping and
* the interruptible flag is true, or a negative error
* returned by usb_submit_urb.
*/
static int digi_write_oob_command(struct usb_serial_port *port,
unsigned char *buf, int count, int interruptible)
{
int ret = 0;
int len;
struct usb_serial_port *oob_port = (struct usb_serial_port *)((struct digi_serial *)(usb_get_serial_data(port->serial)))->ds_oob_port;
struct digi_port *oob_priv = usb_get_serial_port_data(oob_port);
unsigned long flags = 0;
dbg("digi_write_oob_command: TOP: port=%d, count=%d", oob_priv->dp_port_num, count);
spin_lock_irqsave(&oob_priv->dp_port_lock, flags);
while (count > 0) {
while (oob_priv->dp_write_urb_in_use) {
cond_wait_interruptible_timeout_irqrestore(
&oob_port->write_wait, DIGI_RETRY_TIMEOUT,
&oob_priv->dp_port_lock, flags);
if (interruptible && signal_pending(current))
return -EINTR;
spin_lock_irqsave(&oob_priv->dp_port_lock, flags);
}
/* len must be a multiple of 4, so commands are not split */
len = min(count, oob_port->bulk_out_size);
if (len > 4)
len &= ~3;
memcpy(oob_port->write_urb->transfer_buffer, buf, len);
oob_port->write_urb->transfer_buffer_length = len;
ret = usb_submit_urb(oob_port->write_urb, GFP_ATOMIC);
if (ret == 0) {
oob_priv->dp_write_urb_in_use = 1;
count -= len;
buf += len;
}
}
spin_unlock_irqrestore(&oob_priv->dp_port_lock, flags);
if (ret)
dev_err(&port->dev, "%s: usb_submit_urb failed, ret=%d\n",
__func__, ret);
return ret;
}
/*
* Digi Write In Band Command
*
* Write commands on the given port. Commands are 4
* bytes each, multiple commands can be sent at once, and
* no command will be split across USB packets. If timeout
* is non-zero, write in band command will return after
* waiting unsuccessfully for the URB status to clear for
* timeout ticks. Returns 0 if successful, or a negative
* error returned by digi_write.
*/
static int digi_write_inb_command(struct usb_serial_port *port,
unsigned char *buf, int count, unsigned long timeout)
{
int ret = 0;
int len;
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned char *data = port->write_urb->transfer_buffer;
unsigned long flags = 0;
dbg("digi_write_inb_command: TOP: port=%d, count=%d",
priv->dp_port_num, count);
if (timeout)
timeout += jiffies;
else
timeout = ULONG_MAX;
spin_lock_irqsave(&priv->dp_port_lock, flags);
while (count > 0 && ret == 0) {
while (priv->dp_write_urb_in_use &&
time_before(jiffies, timeout)) {
cond_wait_interruptible_timeout_irqrestore(
&port->write_wait, DIGI_RETRY_TIMEOUT,
&priv->dp_port_lock, flags);
if (signal_pending(current))
return -EINTR;
spin_lock_irqsave(&priv->dp_port_lock, flags);
}
/* len must be a multiple of 4 and small enough to */
/* guarantee the write will send buffered data first, */
/* so commands are in order with data and not split */
len = min(count, port->bulk_out_size-2-priv->dp_out_buf_len);
if (len > 4)
len &= ~3;
/* write any buffered data first */
if (priv->dp_out_buf_len > 0) {
data[0] = DIGI_CMD_SEND_DATA;
data[1] = priv->dp_out_buf_len;
memcpy(data + 2, priv->dp_out_buf,
priv->dp_out_buf_len);
memcpy(data + 2 + priv->dp_out_buf_len, buf, len);
port->write_urb->transfer_buffer_length
= priv->dp_out_buf_len + 2 + len;
} else {
memcpy(data, buf, len);
port->write_urb->transfer_buffer_length = len;
}
ret = usb_submit_urb(port->write_urb, GFP_ATOMIC);
if (ret == 0) {
priv->dp_write_urb_in_use = 1;
priv->dp_out_buf_len = 0;
count -= len;
buf += len;
}
}
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
if (ret)
dev_err(&port->dev,
"%s: usb_submit_urb failed, ret=%d, port=%d\n",
__func__, ret, priv->dp_port_num);
return ret;
}
/*
* Digi Set Modem Signals
*
* Sets or clears DTR and RTS on the port, according to the
* modem_signals argument. Use TIOCM_DTR and TIOCM_RTS flags
* for the modem_signals argument. Returns 0 if successful,
* -EINTR if interrupted while sleeping, or a non-zero error
* returned by usb_submit_urb.
*/
static int digi_set_modem_signals(struct usb_serial_port *port,
unsigned int modem_signals, int interruptible)
{
int ret;
struct digi_port *port_priv = usb_get_serial_port_data(port);
struct usb_serial_port *oob_port = (struct usb_serial_port *) ((struct digi_serial *)(usb_get_serial_data(port->serial)))->ds_oob_port;
struct digi_port *oob_priv = usb_get_serial_port_data(oob_port);
unsigned char *data = oob_port->write_urb->transfer_buffer;
unsigned long flags = 0;
dbg("digi_set_modem_signals: TOP: port=%d, modem_signals=0x%x",
port_priv->dp_port_num, modem_signals);
spin_lock_irqsave(&oob_priv->dp_port_lock, flags);
spin_lock(&port_priv->dp_port_lock);
while (oob_priv->dp_write_urb_in_use) {
spin_unlock(&port_priv->dp_port_lock);
cond_wait_interruptible_timeout_irqrestore(
&oob_port->write_wait, DIGI_RETRY_TIMEOUT,
&oob_priv->dp_port_lock, flags);
if (interruptible && signal_pending(current))
return -EINTR;
spin_lock_irqsave(&oob_priv->dp_port_lock, flags);
spin_lock(&port_priv->dp_port_lock);
}
data[0] = DIGI_CMD_SET_DTR_SIGNAL;
data[1] = port_priv->dp_port_num;
data[2] = (modem_signals & TIOCM_DTR) ?
DIGI_DTR_ACTIVE : DIGI_DTR_INACTIVE;
data[3] = 0;
data[4] = DIGI_CMD_SET_RTS_SIGNAL;
data[5] = port_priv->dp_port_num;
data[6] = (modem_signals & TIOCM_RTS) ?
DIGI_RTS_ACTIVE : DIGI_RTS_INACTIVE;
data[7] = 0;
oob_port->write_urb->transfer_buffer_length = 8;
ret = usb_submit_urb(oob_port->write_urb, GFP_ATOMIC);
if (ret == 0) {
oob_priv->dp_write_urb_in_use = 1;
port_priv->dp_modem_signals =
(port_priv->dp_modem_signals&~(TIOCM_DTR|TIOCM_RTS))
| (modem_signals&(TIOCM_DTR|TIOCM_RTS));
}
spin_unlock(&port_priv->dp_port_lock);
spin_unlock_irqrestore(&oob_priv->dp_port_lock, flags);
if (ret)
dev_err(&port->dev, "%s: usb_submit_urb failed, ret=%d\n",
__func__, ret);
return ret;
}
/*
* Digi Transmit Idle
*
* Digi transmit idle waits, up to timeout ticks, for the transmitter
* to go idle. It returns 0 if successful or a negative error.
*
* There are race conditions here if more than one process is calling
* digi_transmit_idle on the same port at the same time. However, this
* is only called from close, and only one process can be in close on a
* port at a time, so its ok.
*/
static int digi_transmit_idle(struct usb_serial_port *port,
unsigned long timeout)
{
int ret;
unsigned char buf[2];
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned long flags = 0;
spin_lock_irqsave(&priv->dp_port_lock, flags);
priv->dp_transmit_idle = 0;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
buf[0] = DIGI_CMD_TRANSMIT_IDLE;
buf[1] = 0;
timeout += jiffies;
ret = digi_write_inb_command(port, buf, 2, timeout - jiffies);
if (ret != 0)
return ret;
spin_lock_irqsave(&priv->dp_port_lock, flags);
while (time_before(jiffies, timeout) && !priv->dp_transmit_idle) {
cond_wait_interruptible_timeout_irqrestore(
&priv->dp_transmit_idle_wait, DIGI_RETRY_TIMEOUT,
&priv->dp_port_lock, flags);
if (signal_pending(current))
return -EINTR;
spin_lock_irqsave(&priv->dp_port_lock, flags);
}
priv->dp_transmit_idle = 0;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
return 0;
}
static void digi_rx_throttle(struct tty_struct *tty)
{
unsigned long flags;
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
dbg("digi_rx_throttle: TOP: port=%d", priv->dp_port_num);
/* stop receiving characters by not resubmitting the read urb */
spin_lock_irqsave(&priv->dp_port_lock, flags);
priv->dp_throttled = 1;
priv->dp_throttle_restart = 0;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
}
static void digi_rx_unthrottle(struct tty_struct *tty)
{
int ret = 0;
unsigned long flags;
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
dbg("digi_rx_unthrottle: TOP: port=%d", priv->dp_port_num);
spin_lock_irqsave(&priv->dp_port_lock, flags);
/* restart read chain */
if (priv->dp_throttle_restart)
ret = usb_submit_urb(port->read_urb, GFP_ATOMIC);
/* turn throttle off */
priv->dp_throttled = 0;
priv->dp_throttle_restart = 0;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
if (ret)
dev_err(&port->dev,
"%s: usb_submit_urb failed, ret=%d, port=%d\n",
__func__, ret, priv->dp_port_num);
}
static void digi_set_termios(struct tty_struct *tty,
struct usb_serial_port *port, struct ktermios *old_termios)
{
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned int iflag = tty->termios->c_iflag;
unsigned int cflag = tty->termios->c_cflag;
unsigned int old_iflag = old_termios->c_iflag;
unsigned int old_cflag = old_termios->c_cflag;
unsigned char buf[32];
unsigned int modem_signals;
int arg, ret;
int i = 0;
speed_t baud;
dbg("digi_set_termios: TOP: port=%d, iflag=0x%x, old_iflag=0x%x, cflag=0x%x, old_cflag=0x%x", priv->dp_port_num, iflag, old_iflag, cflag, old_cflag);
/* set baud rate */
baud = tty_get_baud_rate(tty);
if (baud != tty_termios_baud_rate(old_termios)) {
arg = -1;
/* reassert DTR and (maybe) RTS on transition from B0 */
if ((old_cflag&CBAUD) == B0) {
/* don't set RTS if using hardware flow control */
/* and throttling input */
modem_signals = TIOCM_DTR;
if (!(tty->termios->c_cflag & CRTSCTS) ||
!test_bit(TTY_THROTTLED, &tty->flags))
modem_signals |= TIOCM_RTS;
digi_set_modem_signals(port, modem_signals, 1);
}
switch (baud) {
/* drop DTR and RTS on transition to B0 */
case 0: digi_set_modem_signals(port, 0, 1); break;
case 50: arg = DIGI_BAUD_50; break;
case 75: arg = DIGI_BAUD_75; break;
case 110: arg = DIGI_BAUD_110; break;
case 150: arg = DIGI_BAUD_150; break;
case 200: arg = DIGI_BAUD_200; break;
case 300: arg = DIGI_BAUD_300; break;
case 600: arg = DIGI_BAUD_600; break;
case 1200: arg = DIGI_BAUD_1200; break;
case 1800: arg = DIGI_BAUD_1800; break;
case 2400: arg = DIGI_BAUD_2400; break;
case 4800: arg = DIGI_BAUD_4800; break;
case 9600: arg = DIGI_BAUD_9600; break;
case 19200: arg = DIGI_BAUD_19200; break;
case 38400: arg = DIGI_BAUD_38400; break;
case 57600: arg = DIGI_BAUD_57600; break;
case 115200: arg = DIGI_BAUD_115200; break;
case 230400: arg = DIGI_BAUD_230400; break;
case 460800: arg = DIGI_BAUD_460800; break;
default:
arg = DIGI_BAUD_9600;
baud = 9600;
break;
}
if (arg != -1) {
buf[i++] = DIGI_CMD_SET_BAUD_RATE;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
}
/* set parity */
tty->termios->c_cflag &= ~CMSPAR;
if ((cflag&(PARENB|PARODD)) != (old_cflag&(PARENB|PARODD))) {
if (cflag&PARENB) {
if (cflag&PARODD)
arg = DIGI_PARITY_ODD;
else
arg = DIGI_PARITY_EVEN;
} else {
arg = DIGI_PARITY_NONE;
}
buf[i++] = DIGI_CMD_SET_PARITY;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
/* set word size */
if ((cflag&CSIZE) != (old_cflag&CSIZE)) {
arg = -1;
switch (cflag&CSIZE) {
case CS5: arg = DIGI_WORD_SIZE_5; break;
case CS6: arg = DIGI_WORD_SIZE_6; break;
case CS7: arg = DIGI_WORD_SIZE_7; break;
case CS8: arg = DIGI_WORD_SIZE_8; break;
default:
dbg("digi_set_termios: can't handle word size %d",
(cflag&CSIZE));
break;
}
if (arg != -1) {
buf[i++] = DIGI_CMD_SET_WORD_SIZE;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
}
/* set stop bits */
if ((cflag&CSTOPB) != (old_cflag&CSTOPB)) {
if ((cflag&CSTOPB))
arg = DIGI_STOP_BITS_2;
else
arg = DIGI_STOP_BITS_1;
buf[i++] = DIGI_CMD_SET_STOP_BITS;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
/* set input flow control */
if ((iflag&IXOFF) != (old_iflag&IXOFF)
|| (cflag&CRTSCTS) != (old_cflag&CRTSCTS)) {
arg = 0;
if (iflag&IXOFF)
arg |= DIGI_INPUT_FLOW_CONTROL_XON_XOFF;
else
arg &= ~DIGI_INPUT_FLOW_CONTROL_XON_XOFF;
if (cflag&CRTSCTS) {
arg |= DIGI_INPUT_FLOW_CONTROL_RTS;
/* On USB-4 it is necessary to assert RTS prior */
/* to selecting RTS input flow control. */
buf[i++] = DIGI_CMD_SET_RTS_SIGNAL;
buf[i++] = priv->dp_port_num;
buf[i++] = DIGI_RTS_ACTIVE;
buf[i++] = 0;
} else {
arg &= ~DIGI_INPUT_FLOW_CONTROL_RTS;
}
buf[i++] = DIGI_CMD_SET_INPUT_FLOW_CONTROL;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
/* set output flow control */
if ((iflag & IXON) != (old_iflag & IXON)
|| (cflag & CRTSCTS) != (old_cflag & CRTSCTS)) {
arg = 0;
if (iflag & IXON)
arg |= DIGI_OUTPUT_FLOW_CONTROL_XON_XOFF;
else
arg &= ~DIGI_OUTPUT_FLOW_CONTROL_XON_XOFF;
if (cflag & CRTSCTS) {
arg |= DIGI_OUTPUT_FLOW_CONTROL_CTS;
} else {
arg &= ~DIGI_OUTPUT_FLOW_CONTROL_CTS;
tty->hw_stopped = 0;
}
buf[i++] = DIGI_CMD_SET_OUTPUT_FLOW_CONTROL;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
/* set receive enable/disable */
if ((cflag & CREAD) != (old_cflag & CREAD)) {
if (cflag & CREAD)
arg = DIGI_ENABLE;
else
arg = DIGI_DISABLE;
buf[i++] = DIGI_CMD_RECEIVE_ENABLE;
buf[i++] = priv->dp_port_num;
buf[i++] = arg;
buf[i++] = 0;
}
ret = digi_write_oob_command(port, buf, i, 1);
if (ret != 0)
dbg("digi_set_termios: write oob failed, ret=%d", ret);
tty_encode_baud_rate(tty, baud, baud);
}
static void digi_break_ctl(struct tty_struct *tty, int break_state)
{
struct usb_serial_port *port = tty->driver_data;
unsigned char buf[4];
buf[0] = DIGI_CMD_BREAK_CONTROL;
buf[1] = 2; /* length */
buf[2] = break_state ? 1 : 0;
buf[3] = 0; /* pad */
digi_write_inb_command(port, buf, 4, 0);
}
static int digi_tiocmget(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned int val;
unsigned long flags;
dbg("%s: TOP: port=%d", __func__, priv->dp_port_num);
spin_lock_irqsave(&priv->dp_port_lock, flags);
val = priv->dp_modem_signals;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
return val;
}
static int digi_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned int val;
unsigned long flags;
dbg("%s: TOP: port=%d", __func__, priv->dp_port_num);
spin_lock_irqsave(&priv->dp_port_lock, flags);
val = (priv->dp_modem_signals & ~clear) | set;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
return digi_set_modem_signals(port, val, 1);
}
static int digi_write(struct tty_struct *tty, struct usb_serial_port *port,
const unsigned char *buf, int count)
{
int ret, data_len, new_len;
struct digi_port *priv = usb_get_serial_port_data(port);
unsigned char *data = port->write_urb->transfer_buffer;
unsigned long flags = 0;
dbg("digi_write: TOP: port=%d, count=%d, in_interrupt=%ld",
priv->dp_port_num, count, in_interrupt());
/* copy user data (which can sleep) before getting spin lock */
count = min(count, port->bulk_out_size-2);
count = min(64, count);
/* be sure only one write proceeds at a time */
/* there are races on the port private buffer */
spin_lock_irqsave(&priv->dp_port_lock, flags);
/* wait for urb status clear to submit another urb */
if (priv->dp_write_urb_in_use) {
/* buffer data if count is 1 (probably put_char) if possible */
if (count == 1 && priv->dp_out_buf_len < DIGI_OUT_BUF_SIZE) {
priv->dp_out_buf[priv->dp_out_buf_len++] = *buf;
new_len = 1;
} else {
new_len = 0;
}
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
return new_len;
}
/* allow space for any buffered data and for new data, up to */
/* transfer buffer size - 2 (for command and length bytes) */
new_len = min(count, port->bulk_out_size-2-priv->dp_out_buf_len);
data_len = new_len + priv->dp_out_buf_len;
if (data_len == 0) {
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
return 0;
}
port->write_urb->transfer_buffer_length = data_len+2;
*data++ = DIGI_CMD_SEND_DATA;
*data++ = data_len;
/* copy in buffered data first */
memcpy(data, priv->dp_out_buf, priv->dp_out_buf_len);
data += priv->dp_out_buf_len;
/* copy in new data */
memcpy(data, buf, new_len);
ret = usb_submit_urb(port->write_urb, GFP_ATOMIC);
if (ret == 0) {
priv->dp_write_urb_in_use = 1;
ret = new_len;
priv->dp_out_buf_len = 0;
}
/* return length of new data written, or error */
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
if (ret < 0)
dev_err_console(port,
"%s: usb_submit_urb failed, ret=%d, port=%d\n",
__func__, ret, priv->dp_port_num);
dbg("digi_write: returning %d", ret);
return ret;
}
static void digi_write_bulk_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct usb_serial *serial;
struct digi_port *priv;
struct digi_serial *serial_priv;
int ret = 0;
int status = urb->status;
dbg("digi_write_bulk_callback: TOP, status=%d", status);
/* port and serial sanity check */
if (port == NULL || (priv = usb_get_serial_port_data(port)) == NULL) {
pr_err("%s: port or port->private is NULL, status=%d\n",
__func__, status);
return;
}
serial = port->serial;
if (serial == NULL || (serial_priv = usb_get_serial_data(serial)) == NULL) {
dev_err(&port->dev,
"%s: serial or serial->private is NULL, status=%d\n",
__func__, status);
return;
}
/* handle oob callback */
if (priv->dp_port_num == serial_priv->ds_oob_port_num) {
dbg("digi_write_bulk_callback: oob callback");
spin_lock(&priv->dp_port_lock);
priv->dp_write_urb_in_use = 0;
wake_up_interruptible(&port->write_wait);
spin_unlock(&priv->dp_port_lock);
return;
}
/* try to send any buffered data on this port */
spin_lock(&priv->dp_port_lock);
priv->dp_write_urb_in_use = 0;
if (priv->dp_out_buf_len > 0) {
*((unsigned char *)(port->write_urb->transfer_buffer))
= (unsigned char)DIGI_CMD_SEND_DATA;
*((unsigned char *)(port->write_urb->transfer_buffer) + 1)
= (unsigned char)priv->dp_out_buf_len;
port->write_urb->transfer_buffer_length =
priv->dp_out_buf_len + 2;
memcpy(port->write_urb->transfer_buffer + 2, priv->dp_out_buf,
priv->dp_out_buf_len);
ret = usb_submit_urb(port->write_urb, GFP_ATOMIC);
if (ret == 0) {
priv->dp_write_urb_in_use = 1;
priv->dp_out_buf_len = 0;
}
}
/* wake up processes sleeping on writes immediately */
digi_wakeup_write(port);
/* also queue up a wakeup at scheduler time, in case we */
/* lost the race in write_chan(). */
schedule_work(&priv->dp_wakeup_work);
spin_unlock(&priv->dp_port_lock);
if (ret && ret != -EPERM)
dev_err_console(port,
"%s: usb_submit_urb failed, ret=%d, port=%d\n",
__func__, ret, priv->dp_port_num);
}
static int digi_write_room(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
int room;
unsigned long flags = 0;
spin_lock_irqsave(&priv->dp_port_lock, flags);
if (priv->dp_write_urb_in_use)
room = 0;
else
room = port->bulk_out_size - 2 - priv->dp_out_buf_len;
spin_unlock_irqrestore(&priv->dp_port_lock, flags);
dbg("digi_write_room: port=%d, room=%d", priv->dp_port_num, room);
return room;
}
static int digi_chars_in_buffer(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct digi_port *priv = usb_get_serial_port_data(port);
if (priv->dp_write_urb_in_use) {
dbg("digi_chars_in_buffer: port=%d, chars=%d",
priv->dp_port_num, port->bulk_out_size - 2);
/* return(port->bulk_out_size - 2); */
return 256;
} else {
dbg("digi_chars_in_buffer: port=%d, chars=%d",
priv->dp_port_num, priv->dp_out_buf_len);
return priv->dp_out_buf_len;
}
}
static void digi_dtr_rts(struct usb_serial_port *port, int on)
{
/* Adjust DTR and RTS */
digi_set_modem_signals(port, on * (TIOCM_DTR|TIOCM_RTS), 1);
}
static int digi_open(struct tty_struct *tty, struct usb_serial_port *port)
{
int ret;
unsigned char buf[32];
struct digi_port *priv = usb_get_serial_port_data(port);
struct ktermios not_termios;
dbg("digi_open: TOP: port=%d", priv->dp_port_num);
/* be sure the device is started up */
if (digi_startup_device(port->serial) != 0)
return -ENXIO;
/* read modem signals automatically whenever they change */
buf[0] = DIGI_CMD_READ_INPUT_SIGNALS;
buf[1] = priv->dp_port_num;
buf[2] = DIGI_ENABLE;
buf[3] = 0;
/* flush fifos */
buf[4] = DIGI_CMD_IFLUSH_FIFO;
buf[5] = priv->dp_port_num;
buf[6] = DIGI_FLUSH_TX | DIGI_FLUSH_RX;
buf[7] = 0;
ret = digi_write_oob_command(port, buf, 8, 1);
if (ret != 0)
dbg("digi_open: write oob failed, ret=%d", ret);
/* set termios settings */
if (tty) {
not_termios.c_cflag = ~tty->termios->c_cflag;
not_termios.c_iflag = ~tty->termios->c_iflag;
digi_set_termios(tty, port, ¬_termios);
}
return 0;
}
static void digi_close(struct usb_serial_port *port)
{
DEFINE_WAIT(wait);
int ret;
unsigned char buf[32];
struct digi_port *priv = usb_get_serial_port_data(port);
dbg("digi_close: TOP: port=%d", priv->dp_port_num);
mutex_lock(&port->serial->disc_mutex);
/* if disconnected, just clear flags */
if (port->serial->disconnected)
goto exit;
if (port->serial->dev) {
/* FIXME: Transmit idle belongs in the wait_unti_sent path */
digi_transmit_idle(port, DIGI_CLOSE_TIMEOUT);
/* disable input flow control */
buf[0] = DIGI_CMD_SET_INPUT_FLOW_CONTROL;
buf[1] = priv->dp_port_num;
buf[2] = DIGI_DISABLE;
buf[3] = 0;
/* disable output flow control */
buf[4] = DIGI_CMD_SET_OUTPUT_FLOW_CONTROL;
buf[5] = priv->dp_port_num;
buf[6] = DIGI_DISABLE;
buf[7] = 0;
/* disable reading modem signals automatically */
buf[8] = DIGI_CMD_READ_INPUT_SIGNALS;
buf[9] = priv->dp_port_num;
buf[10] = DIGI_DISABLE;
buf[11] = 0;
/* disable receive */
buf[12] = DIGI_CMD_RECEIVE_ENABLE;
buf[13] = priv->dp_port_num;
buf[14] = DIGI_DISABLE;
buf[15] = 0;
/* flush fifos */
buf[16] = DIGI_CMD_IFLUSH_FIFO;
buf[17] = priv->dp_port_num;
buf[18] = DIGI_FLUSH_TX | DIGI_FLUSH_RX;
buf[19] = 0;
ret = digi_write_oob_command(port, buf, 20, 0);
if (ret != 0)
dbg("digi_close: write oob failed, ret=%d", ret);
/* wait for final commands on oob port to complete */
prepare_to_wait(&priv->dp_flush_wait, &wait,
TASK_INTERRUPTIBLE);
schedule_timeout(DIGI_CLOSE_TIMEOUT);
finish_wait(&priv->dp_flush_wait, &wait);
/* shutdown any outstanding bulk writes */
usb_kill_urb(port->write_urb);
}
exit:
spin_lock_irq(&priv->dp_port_lock);
priv->dp_write_urb_in_use = 0;
wake_up_interruptible(&priv->dp_close_wait);
spin_unlock_irq(&priv->dp_port_lock);
mutex_unlock(&port->serial->disc_mutex);
dbg("digi_close: done");
}
/*
* Digi Startup Device
*
* Starts reads on all ports. Must be called AFTER startup, with
* urbs initialized. Returns 0 if successful, non-zero error otherwise.
*/
static int digi_startup_device(struct usb_serial *serial)
{
int i, ret = 0;
struct digi_serial *serial_priv = usb_get_serial_data(serial);
struct usb_serial_port *port;
/* be sure this happens exactly once */
spin_lock(&serial_priv->ds_serial_lock);
if (serial_priv->ds_device_started) {
spin_unlock(&serial_priv->ds_serial_lock);
return 0;
}
serial_priv->ds_device_started = 1;
spin_unlock(&serial_priv->ds_serial_lock);
/* start reading from each bulk in endpoint for the device */
/* set USB_DISABLE_SPD flag for write bulk urbs */
for (i = 0; i < serial->type->num_ports + 1; i++) {
port = serial->port[i];
ret = usb_submit_urb(port->read_urb, GFP_KERNEL);
if (ret != 0) {
dev_err(&port->dev,
"%s: usb_submit_urb failed, ret=%d, port=%d\n",
__func__, ret, i);
break;
}
}
return ret;
}
static int digi_startup(struct usb_serial *serial)
{
int i;
struct digi_port *priv;
struct digi_serial *serial_priv;
dbg("digi_startup: TOP");
/* allocate the private data structures for all ports */
/* number of regular ports + 1 for the out-of-band port */
for (i = 0; i < serial->type->num_ports + 1; i++) {
/* allocate port private structure */
priv = kmalloc(sizeof(struct digi_port), GFP_KERNEL);
if (priv == NULL) {
while (--i >= 0)
kfree(usb_get_serial_port_data(serial->port[i]));
return 1; /* error */
}
/* initialize port private structure */
spin_lock_init(&priv->dp_port_lock);
priv->dp_port_num = i;
priv->dp_out_buf_len = 0;
priv->dp_write_urb_in_use = 0;
priv->dp_modem_signals = 0;
init_waitqueue_head(&priv->dp_modem_change_wait);
priv->dp_transmit_idle = 0;
init_waitqueue_head(&priv->dp_transmit_idle_wait);
priv->dp_throttled = 0;
priv->dp_throttle_restart = 0;
init_waitqueue_head(&priv->dp_flush_wait);
init_waitqueue_head(&priv->dp_close_wait);
INIT_WORK(&priv->dp_wakeup_work, digi_wakeup_write_lock);
priv->dp_port = serial->port[i];
/* initialize write wait queue for this port */
init_waitqueue_head(&serial->port[i]->write_wait);
usb_set_serial_port_data(serial->port[i], priv);
}
/* allocate serial private structure */
serial_priv = kmalloc(sizeof(struct digi_serial), GFP_KERNEL);
if (serial_priv == NULL) {
for (i = 0; i < serial->type->num_ports + 1; i++)
kfree(usb_get_serial_port_data(serial->port[i]));
return 1; /* error */
}
/* initialize serial private structure */
spin_lock_init(&serial_priv->ds_serial_lock);
serial_priv->ds_oob_port_num = serial->type->num_ports;
serial_priv->ds_oob_port = serial->port[serial_priv->ds_oob_port_num];
serial_priv->ds_device_started = 0;
usb_set_serial_data(serial, serial_priv);
return 0;
}
static void digi_disconnect(struct usb_serial *serial)
{
int i;
dbg("digi_disconnect: TOP, in_interrupt()=%ld", in_interrupt());
/* stop reads and writes on all ports */
for (i = 0; i < serial->type->num_ports + 1; i++) {
usb_kill_urb(serial->port[i]->read_urb);
usb_kill_urb(serial->port[i]->write_urb);
}
}
static void digi_release(struct usb_serial *serial)
{
int i;
dbg("digi_release: TOP, in_interrupt()=%ld", in_interrupt());
/* free the private data structures for all ports */
/* number of regular ports + 1 for the out-of-band port */
for (i = 0; i < serial->type->num_ports + 1; i++)
kfree(usb_get_serial_port_data(serial->port[i]));
kfree(usb_get_serial_data(serial));
}
static void digi_read_bulk_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct digi_port *priv;
struct digi_serial *serial_priv;
int ret;
int status = urb->status;
dbg("digi_read_bulk_callback: TOP");
/* port sanity check, do not resubmit if port is not valid */
if (port == NULL)
return;
priv = usb_get_serial_port_data(port);
if (priv == NULL) {
dev_err(&port->dev, "%s: port->private is NULL, status=%d\n",
__func__, status);
return;
}
if (port->serial == NULL ||
(serial_priv = usb_get_serial_data(port->serial)) == NULL) {
dev_err(&port->dev, "%s: serial is bad or serial->private "
"is NULL, status=%d\n", __func__, status);
return;
}
/* do not resubmit urb if it has any status error */
if (status) {
dev_err(&port->dev,
"%s: nonzero read bulk status: status=%d, port=%d\n",
__func__, status, priv->dp_port_num);
return;
}
/* handle oob or inb callback, do not resubmit if error */
if (priv->dp_port_num == serial_priv->ds_oob_port_num) {
if (digi_read_oob_callback(urb) != 0)
return;
} else {
if (digi_read_inb_callback(urb) != 0)
return;
}
/* continue read */
ret = usb_submit_urb(urb, GFP_ATOMIC);
if (ret != 0 && ret != -EPERM) {
dev_err(&port->dev,
"%s: failed resubmitting urb, ret=%d, port=%d\n",
__func__, ret, priv->dp_port_num);
}
}
/*
* Digi Read INB Callback
*
* Digi Read INB Callback handles reads on the in band ports, sending
* the data on to the tty subsystem. When called we know port and
* port->private are not NULL and port->serial has been validated.
* It returns 0 if successful, 1 if successful but the port is
* throttled, and -1 if the sanity checks failed.
*/
static int digi_read_inb_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct tty_struct *tty;
struct digi_port *priv = usb_get_serial_port_data(port);
int opcode = ((unsigned char *)urb->transfer_buffer)[0];
int len = ((unsigned char *)urb->transfer_buffer)[1];
int port_status = ((unsigned char *)urb->transfer_buffer)[2];
unsigned char *data = ((unsigned char *)urb->transfer_buffer) + 3;
int flag, throttled;
int status = urb->status;
/* do not process callbacks on closed ports */
/* but do continue the read chain */
if (urb->status == -ENOENT)
return 0;
/* short/multiple packet check */
if (urb->actual_length != len + 2) {
dev_err(&port->dev, "%s: INCOMPLETE OR MULTIPLE PACKET, "
"status=%d, port=%d, opcode=%d, len=%d, "
"actual_length=%d, status=%d\n", __func__, status,
priv->dp_port_num, opcode, len, urb->actual_length,
port_status);
return -1;
}
tty = tty_port_tty_get(&port->port);
spin_lock(&priv->dp_port_lock);
/* check for throttle; if set, do not resubmit read urb */
/* indicate the read chain needs to be restarted on unthrottle */
throttled = priv->dp_throttled;
if (throttled)
priv->dp_throttle_restart = 1;
/* receive data */
if (tty && opcode == DIGI_CMD_RECEIVE_DATA) {
/* get flag from port_status */
flag = 0;
/* overrun is special, not associated with a char */
if (port_status & DIGI_OVERRUN_ERROR)
tty_insert_flip_char(tty, 0, TTY_OVERRUN);
/* break takes precedence over parity, */
/* which takes precedence over framing errors */
if (port_status & DIGI_BREAK_ERROR)
flag = TTY_BREAK;
else if (port_status & DIGI_PARITY_ERROR)
flag = TTY_PARITY;
else if (port_status & DIGI_FRAMING_ERROR)
flag = TTY_FRAME;
/* data length is len-1 (one byte of len is port_status) */
--len;
if (len > 0) {
tty_insert_flip_string_fixed_flag(tty, data, flag,
len);
tty_flip_buffer_push(tty);
}
}
spin_unlock(&priv->dp_port_lock);
tty_kref_put(tty);
if (opcode == DIGI_CMD_RECEIVE_DISABLE)
dbg("%s: got RECEIVE_DISABLE", __func__);
else if (opcode != DIGI_CMD_RECEIVE_DATA)
dbg("%s: unknown opcode: %d", __func__, opcode);
return throttled ? 1 : 0;
}
/*
* Digi Read OOB Callback
*
* Digi Read OOB Callback handles reads on the out of band port.
* When called we know port and port->private are not NULL and
* the port->serial is valid. It returns 0 if successful, and
* -1 if the sanity checks failed.
*/
static int digi_read_oob_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct usb_serial *serial = port->serial;
struct tty_struct *tty;
struct digi_port *priv = usb_get_serial_port_data(port);
int opcode, line, status, val;
int i;
unsigned int rts;
dbg("digi_read_oob_callback: port=%d, len=%d",
priv->dp_port_num, urb->actual_length);
/* handle each oob command */
for (i = 0; i < urb->actual_length - 3;) {
opcode = ((unsigned char *)urb->transfer_buffer)[i++];
line = ((unsigned char *)urb->transfer_buffer)[i++];
status = ((unsigned char *)urb->transfer_buffer)[i++];
val = ((unsigned char *)urb->transfer_buffer)[i++];
dbg("digi_read_oob_callback: opcode=%d, line=%d, status=%d, val=%d",
opcode, line, status, val);
if (status != 0 || line >= serial->type->num_ports)
continue;
port = serial->port[line];
priv = usb_get_serial_port_data(port);
if (priv == NULL)
return -1;
tty = tty_port_tty_get(&port->port);
rts = 0;
if (tty)
rts = tty->termios->c_cflag & CRTSCTS;
if (tty && opcode == DIGI_CMD_READ_INPUT_SIGNALS) {
spin_lock(&priv->dp_port_lock);
/* convert from digi flags to termiox flags */
if (val & DIGI_READ_INPUT_SIGNALS_CTS) {
priv->dp_modem_signals |= TIOCM_CTS;
/* port must be open to use tty struct */
if (rts) {
tty->hw_stopped = 0;
digi_wakeup_write(port);
}
} else {
priv->dp_modem_signals &= ~TIOCM_CTS;
/* port must be open to use tty struct */
if (rts)
tty->hw_stopped = 1;
}
if (val & DIGI_READ_INPUT_SIGNALS_DSR)
priv->dp_modem_signals |= TIOCM_DSR;
else
priv->dp_modem_signals &= ~TIOCM_DSR;
if (val & DIGI_READ_INPUT_SIGNALS_RI)
priv->dp_modem_signals |= TIOCM_RI;
else
priv->dp_modem_signals &= ~TIOCM_RI;
if (val & DIGI_READ_INPUT_SIGNALS_DCD)
priv->dp_modem_signals |= TIOCM_CD;
else
priv->dp_modem_signals &= ~TIOCM_CD;
wake_up_interruptible(&priv->dp_modem_change_wait);
spin_unlock(&priv->dp_port_lock);
} else if (opcode == DIGI_CMD_TRANSMIT_IDLE) {
spin_lock(&priv->dp_port_lock);
priv->dp_transmit_idle = 1;
wake_up_interruptible(&priv->dp_transmit_idle_wait);
spin_unlock(&priv->dp_port_lock);
} else if (opcode == DIGI_CMD_IFLUSH_FIFO) {
wake_up_interruptible(&priv->dp_flush_wait);
}
tty_kref_put(tty);
}
return 0;
}
module_usb_serial_driver(digi_driver, serial_drivers);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug enabled or not");
| gpl-2.0 |
hiikezoe/android_kernel_kyocera_201k | drivers/platform/x86/intel_oaktrail.c | 4984 | 9833 | /*
* intel_oaktrail.c - Intel OakTrail Platform support.
*
* Copyright (C) 2010-2011 Intel Corporation
* Author: Yin Kangkai (kangkai.yin@intel.com)
*
* based on Compal driver, Copyright (C) 2008 Cezary Jackiewicz
* <cezary.jackiewicz (at) gmail.com>, based on MSI driver
* Copyright (C) 2006 Lennart Poettering <mzxreary (at) 0pointer (dot) 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., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
* This driver does below things:
* 1. registers itself in the Linux backlight control in
* /sys/class/backlight/intel_oaktrail/
*
* 2. registers in the rfkill subsystem here: /sys/class/rfkill/rfkillX/
* for these components: wifi, bluetooth, wwan (3g), gps
*
* This driver might work on other products based on Oaktrail. If you
* want to try it you can pass force=1 as argument to the module which
* will force it to load even when the DMI data doesn't identify the
* product as compatible.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/acpi.h>
#include <linux/fb.h>
#include <linux/mutex.h>
#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/backlight.h>
#include <linux/platform_device.h>
#include <linux/dmi.h>
#include <linux/rfkill.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#define DRIVER_NAME "intel_oaktrail"
#define DRIVER_VERSION "0.4ac1"
/*
* This is the devices status address in EC space, and the control bits
* definition:
*
* (1 << 0): Camera enable/disable, RW.
* (1 << 1): Bluetooth enable/disable, RW.
* (1 << 2): GPS enable/disable, RW.
* (1 << 3): WiFi enable/disable, RW.
* (1 << 4): WWAN (3G) enable/disalbe, RW.
* (1 << 5): Touchscreen enable/disable, Read Only.
*/
#define OT_EC_DEVICE_STATE_ADDRESS 0xD6
#define OT_EC_CAMERA_MASK (1 << 0)
#define OT_EC_BT_MASK (1 << 1)
#define OT_EC_GPS_MASK (1 << 2)
#define OT_EC_WIFI_MASK (1 << 3)
#define OT_EC_WWAN_MASK (1 << 4)
#define OT_EC_TS_MASK (1 << 5)
/*
* This is the address in EC space and commands used to control LCD backlight:
*
* Two steps needed to change the LCD backlight:
* 1. write the backlight percentage into OT_EC_BL_BRIGHTNESS_ADDRESS;
* 2. write OT_EC_BL_CONTROL_ON_DATA into OT_EC_BL_CONTROL_ADDRESS.
*
* To read the LCD back light, just read out the value from
* OT_EC_BL_BRIGHTNESS_ADDRESS.
*
* LCD backlight brightness range: 0 - 100 (OT_EC_BL_BRIGHTNESS_MAX)
*/
#define OT_EC_BL_BRIGHTNESS_ADDRESS 0x44
#define OT_EC_BL_BRIGHTNESS_MAX 100
#define OT_EC_BL_CONTROL_ADDRESS 0x3A
#define OT_EC_BL_CONTROL_ON_DATA 0x1A
static bool force;
module_param(force, bool, 0);
MODULE_PARM_DESC(force, "Force driver load, ignore DMI data");
static struct platform_device *oaktrail_device;
static struct backlight_device *oaktrail_bl_device;
static struct rfkill *bt_rfkill;
static struct rfkill *gps_rfkill;
static struct rfkill *wifi_rfkill;
static struct rfkill *wwan_rfkill;
/* rfkill */
static int oaktrail_rfkill_set(void *data, bool blocked)
{
u8 value;
u8 result;
unsigned long radio = (unsigned long) data;
ec_read(OT_EC_DEVICE_STATE_ADDRESS, &result);
if (!blocked)
value = (u8) (result | radio);
else
value = (u8) (result & ~radio);
ec_write(OT_EC_DEVICE_STATE_ADDRESS, value);
return 0;
}
static const struct rfkill_ops oaktrail_rfkill_ops = {
.set_block = oaktrail_rfkill_set,
};
static struct rfkill *oaktrail_rfkill_new(char *name, enum rfkill_type type,
unsigned long mask)
{
struct rfkill *rfkill_dev;
u8 value;
int err;
rfkill_dev = rfkill_alloc(name, &oaktrail_device->dev, type,
&oaktrail_rfkill_ops, (void *)mask);
if (!rfkill_dev)
return ERR_PTR(-ENOMEM);
ec_read(OT_EC_DEVICE_STATE_ADDRESS, &value);
rfkill_init_sw_state(rfkill_dev, (value & mask) != 1);
err = rfkill_register(rfkill_dev);
if (err) {
rfkill_destroy(rfkill_dev);
return ERR_PTR(err);
}
return rfkill_dev;
}
static inline void __oaktrail_rfkill_cleanup(struct rfkill *rf)
{
if (rf) {
rfkill_unregister(rf);
rfkill_destroy(rf);
}
}
static void oaktrail_rfkill_cleanup(void)
{
__oaktrail_rfkill_cleanup(wifi_rfkill);
__oaktrail_rfkill_cleanup(bt_rfkill);
__oaktrail_rfkill_cleanup(gps_rfkill);
__oaktrail_rfkill_cleanup(wwan_rfkill);
}
static int oaktrail_rfkill_init(void)
{
int ret;
wifi_rfkill = oaktrail_rfkill_new("oaktrail-wifi",
RFKILL_TYPE_WLAN,
OT_EC_WIFI_MASK);
if (IS_ERR(wifi_rfkill)) {
ret = PTR_ERR(wifi_rfkill);
wifi_rfkill = NULL;
goto cleanup;
}
bt_rfkill = oaktrail_rfkill_new("oaktrail-bluetooth",
RFKILL_TYPE_BLUETOOTH,
OT_EC_BT_MASK);
if (IS_ERR(bt_rfkill)) {
ret = PTR_ERR(bt_rfkill);
bt_rfkill = NULL;
goto cleanup;
}
gps_rfkill = oaktrail_rfkill_new("oaktrail-gps",
RFKILL_TYPE_GPS,
OT_EC_GPS_MASK);
if (IS_ERR(gps_rfkill)) {
ret = PTR_ERR(gps_rfkill);
gps_rfkill = NULL;
goto cleanup;
}
wwan_rfkill = oaktrail_rfkill_new("oaktrail-wwan",
RFKILL_TYPE_WWAN,
OT_EC_WWAN_MASK);
if (IS_ERR(wwan_rfkill)) {
ret = PTR_ERR(wwan_rfkill);
wwan_rfkill = NULL;
goto cleanup;
}
return 0;
cleanup:
oaktrail_rfkill_cleanup();
return ret;
}
/* backlight */
static int get_backlight_brightness(struct backlight_device *b)
{
u8 value;
ec_read(OT_EC_BL_BRIGHTNESS_ADDRESS, &value);
return value;
}
static int set_backlight_brightness(struct backlight_device *b)
{
u8 percent = (u8) b->props.brightness;
if (percent < 0 || percent > OT_EC_BL_BRIGHTNESS_MAX)
return -EINVAL;
ec_write(OT_EC_BL_BRIGHTNESS_ADDRESS, percent);
ec_write(OT_EC_BL_CONTROL_ADDRESS, OT_EC_BL_CONTROL_ON_DATA);
return 0;
}
static const struct backlight_ops oaktrail_bl_ops = {
.get_brightness = get_backlight_brightness,
.update_status = set_backlight_brightness,
};
static int oaktrail_backlight_init(void)
{
struct backlight_device *bd;
struct backlight_properties props;
memset(&props, 0, sizeof(struct backlight_properties));
props.type = BACKLIGHT_PLATFORM;
props.max_brightness = OT_EC_BL_BRIGHTNESS_MAX;
bd = backlight_device_register(DRIVER_NAME,
&oaktrail_device->dev, NULL,
&oaktrail_bl_ops,
&props);
if (IS_ERR(bd)) {
oaktrail_bl_device = NULL;
pr_warning("Unable to register backlight device\n");
return PTR_ERR(bd);
}
oaktrail_bl_device = bd;
bd->props.brightness = get_backlight_brightness(bd);
bd->props.power = FB_BLANK_UNBLANK;
backlight_update_status(bd);
return 0;
}
static void oaktrail_backlight_exit(void)
{
if (oaktrail_bl_device)
backlight_device_unregister(oaktrail_bl_device);
}
static int __devinit oaktrail_probe(struct platform_device *pdev)
{
return 0;
}
static int __devexit oaktrail_remove(struct platform_device *pdev)
{
return 0;
}
static struct platform_driver oaktrail_driver = {
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
},
.probe = oaktrail_probe,
.remove = __devexit_p(oaktrail_remove)
};
static int dmi_check_cb(const struct dmi_system_id *id)
{
pr_info("Identified model '%s'\n", id->ident);
return 0;
}
static struct dmi_system_id __initdata oaktrail_dmi_table[] = {
{
.ident = "OakTrail platform",
.matches = {
DMI_MATCH(DMI_PRODUCT_NAME, "OakTrail platform"),
},
.callback = dmi_check_cb
},
{ }
};
MODULE_DEVICE_TABLE(dmi, oaktrail_dmi_table);
static int __init oaktrail_init(void)
{
int ret;
if (acpi_disabled) {
pr_err("ACPI needs to be enabled for this driver to work!\n");
return -ENODEV;
}
if (!force && !dmi_check_system(oaktrail_dmi_table)) {
pr_err("Platform not recognized (You could try the module's force-parameter)");
return -ENODEV;
}
ret = platform_driver_register(&oaktrail_driver);
if (ret) {
pr_warning("Unable to register platform driver\n");
goto err_driver_reg;
}
oaktrail_device = platform_device_alloc(DRIVER_NAME, -1);
if (!oaktrail_device) {
pr_warning("Unable to allocate platform device\n");
ret = -ENOMEM;
goto err_device_alloc;
}
ret = platform_device_add(oaktrail_device);
if (ret) {
pr_warning("Unable to add platform device\n");
goto err_device_add;
}
if (!acpi_video_backlight_support()) {
ret = oaktrail_backlight_init();
if (ret)
goto err_backlight;
} else
pr_info("Backlight controlled by ACPI video driver\n");
ret = oaktrail_rfkill_init();
if (ret) {
pr_warning("Setup rfkill failed\n");
goto err_rfkill;
}
pr_info("Driver "DRIVER_VERSION" successfully loaded\n");
return 0;
err_rfkill:
oaktrail_backlight_exit();
err_backlight:
platform_device_del(oaktrail_device);
err_device_add:
platform_device_put(oaktrail_device);
err_device_alloc:
platform_driver_unregister(&oaktrail_driver);
err_driver_reg:
return ret;
}
static void __exit oaktrail_cleanup(void)
{
oaktrail_backlight_exit();
oaktrail_rfkill_cleanup();
platform_device_unregister(oaktrail_device);
platform_driver_unregister(&oaktrail_driver);
pr_info("Driver unloaded\n");
}
module_init(oaktrail_init);
module_exit(oaktrail_cleanup);
MODULE_AUTHOR("Yin Kangkai (kangkai.yin@intel.com)");
MODULE_DESCRIPTION("Intel Oaktrail Platform ACPI Extras");
MODULE_VERSION(DRIVER_VERSION);
MODULE_LICENSE("GPL");
| gpl-2.0 |
nbr11/android_kernel_lge_hammerhead | drivers/staging/crystalhd/crystalhd_cmds.c | 4984 | 26871 | /***************************************************************************
* Copyright (c) 2005-2009, Broadcom Corporation.
*
* Name: crystalhd_cmds . c
*
* Description:
* BCM70010 Linux driver user command interfaces.
*
* HISTORY:
*
**********************************************************************
* This file is part of the crystalhd device driver.
*
* This driver 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 driver 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 driver. If not, see <http://www.gnu.org/licenses/>.
**********************************************************************/
#include "crystalhd.h"
static struct crystalhd_user *bc_cproc_get_uid(struct crystalhd_cmd *ctx)
{
struct crystalhd_user *user = NULL;
int i;
for (i = 0; i < BC_LINK_MAX_OPENS; i++) {
if (!ctx->user[i].in_use) {
user = &ctx->user[i];
break;
}
}
return user;
}
static int bc_cproc_get_user_count(struct crystalhd_cmd *ctx)
{
int i, count = 0;
for (i = 0; i < BC_LINK_MAX_OPENS; i++) {
if (ctx->user[i].in_use)
count++;
}
return count;
}
static void bc_cproc_mark_pwr_state(struct crystalhd_cmd *ctx)
{
int i;
for (i = 0; i < BC_LINK_MAX_OPENS; i++) {
if (!ctx->user[i].in_use)
continue;
if (ctx->user[i].mode == DTS_DIAG_MODE ||
ctx->user[i].mode == DTS_PLAYBACK_MODE) {
ctx->pwr_state_change = 1;
break;
}
}
}
static enum BC_STATUS bc_cproc_notify_mode(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
int rc = 0, i = 0;
if (!ctx || !idata) {
BCMLOG_ERR("Invalid Arg!!\n");
return BC_STS_INV_ARG;
}
if (ctx->user[idata->u_id].mode != DTS_MODE_INV) {
BCMLOG_ERR("Close the handle first..\n");
return BC_STS_ERR_USAGE;
}
if (idata->udata.u.NotifyMode.Mode == DTS_MONITOR_MODE) {
ctx->user[idata->u_id].mode = idata->udata.u.NotifyMode.Mode;
return BC_STS_SUCCESS;
}
if (ctx->state != BC_LINK_INVALID) {
BCMLOG_ERR("Link invalid state %d\n", ctx->state);
return BC_STS_ERR_USAGE;
}
/* Check for duplicate playback sessions..*/
for (i = 0; i < BC_LINK_MAX_OPENS; i++) {
if (ctx->user[i].mode == DTS_DIAG_MODE ||
ctx->user[i].mode == DTS_PLAYBACK_MODE) {
BCMLOG_ERR("multiple playback sessions are not "
"supported..\n");
return BC_STS_ERR_USAGE;
}
}
ctx->cin_wait_exit = 0;
ctx->user[idata->u_id].mode = idata->udata.u.NotifyMode.Mode;
/* Setup mmap pool for uaddr sgl mapping..*/
rc = crystalhd_create_dio_pool(ctx->adp, BC_LINK_MAX_SGLS);
if (rc)
return BC_STS_ERROR;
/* Setup Hardware DMA rings */
return crystalhd_hw_setup_dma_rings(&ctx->hw_ctx);
}
static enum BC_STATUS bc_cproc_get_version(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
if (!ctx || !idata) {
BCMLOG_ERR("Invalid Arg!!\n");
return BC_STS_INV_ARG;
}
idata->udata.u.VerInfo.DriverMajor = crystalhd_kmod_major;
idata->udata.u.VerInfo.DriverMinor = crystalhd_kmod_minor;
idata->udata.u.VerInfo.DriverRevision = crystalhd_kmod_rev;
return BC_STS_SUCCESS;
}
static enum BC_STATUS bc_cproc_get_hwtype(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
if (!ctx || !idata) {
BCMLOG_ERR("Invalid Arg!!\n");
return BC_STS_INV_ARG;
}
crystalhd_pci_cfg_rd(ctx->adp, 0, 2,
(uint32_t *)&idata->udata.u.hwType.PciVenId);
crystalhd_pci_cfg_rd(ctx->adp, 2, 2,
(uint32_t *)&idata->udata.u.hwType.PciDevId);
crystalhd_pci_cfg_rd(ctx->adp, 8, 1,
(uint32_t *)&idata->udata.u.hwType.HwRev);
return BC_STS_SUCCESS;
}
static enum BC_STATUS bc_cproc_reg_rd(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
if (!ctx || !idata)
return BC_STS_INV_ARG;
idata->udata.u.regAcc.Value = bc_dec_reg_rd(ctx->adp,
idata->udata.u.regAcc.Offset);
return BC_STS_SUCCESS;
}
static enum BC_STATUS bc_cproc_reg_wr(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
if (!ctx || !idata)
return BC_STS_INV_ARG;
bc_dec_reg_wr(ctx->adp, idata->udata.u.regAcc.Offset,
idata->udata.u.regAcc.Value);
return BC_STS_SUCCESS;
}
static enum BC_STATUS bc_cproc_link_reg_rd(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
if (!ctx || !idata)
return BC_STS_INV_ARG;
idata->udata.u.regAcc.Value = crystalhd_reg_rd(ctx->adp,
idata->udata.u.regAcc.Offset);
return BC_STS_SUCCESS;
}
static enum BC_STATUS bc_cproc_link_reg_wr(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
if (!ctx || !idata)
return BC_STS_INV_ARG;
crystalhd_reg_wr(ctx->adp, idata->udata.u.regAcc.Offset,
idata->udata.u.regAcc.Value);
return BC_STS_SUCCESS;
}
static enum BC_STATUS bc_cproc_mem_rd(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
enum BC_STATUS sts = BC_STS_SUCCESS;
if (!ctx || !idata || !idata->add_cdata)
return BC_STS_INV_ARG;
if (idata->udata.u.devMem.NumDwords > (idata->add_cdata_sz / 4)) {
BCMLOG_ERR("insufficient buffer\n");
return BC_STS_INV_ARG;
}
sts = crystalhd_mem_rd(ctx->adp, idata->udata.u.devMem.StartOff,
idata->udata.u.devMem.NumDwords,
(uint32_t *)idata->add_cdata);
return sts;
}
static enum BC_STATUS bc_cproc_mem_wr(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
enum BC_STATUS sts = BC_STS_SUCCESS;
if (!ctx || !idata || !idata->add_cdata)
return BC_STS_INV_ARG;
if (idata->udata.u.devMem.NumDwords > (idata->add_cdata_sz / 4)) {
BCMLOG_ERR("insufficient buffer\n");
return BC_STS_INV_ARG;
}
sts = crystalhd_mem_wr(ctx->adp, idata->udata.u.devMem.StartOff,
idata->udata.u.devMem.NumDwords,
(uint32_t *)idata->add_cdata);
return sts;
}
static enum BC_STATUS bc_cproc_cfg_rd(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
uint32_t ix, cnt, off, len;
enum BC_STATUS sts = BC_STS_SUCCESS;
uint32_t *temp;
if (!ctx || !idata)
return BC_STS_INV_ARG;
temp = (uint32_t *) idata->udata.u.pciCfg.pci_cfg_space;
off = idata->udata.u.pciCfg.Offset;
len = idata->udata.u.pciCfg.Size;
if (len <= 4)
return crystalhd_pci_cfg_rd(ctx->adp, off, len, temp);
/* Truncate to dword alignment..*/
len = 4;
cnt = idata->udata.u.pciCfg.Size / len;
for (ix = 0; ix < cnt; ix++) {
sts = crystalhd_pci_cfg_rd(ctx->adp, off, len, &temp[ix]);
if (sts != BC_STS_SUCCESS) {
BCMLOG_ERR("config read : %d\n", sts);
return sts;
}
off += len;
}
return sts;
}
static enum BC_STATUS bc_cproc_cfg_wr(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
uint32_t ix, cnt, off, len;
enum BC_STATUS sts = BC_STS_SUCCESS;
uint32_t *temp;
if (!ctx || !idata)
return BC_STS_INV_ARG;
temp = (uint32_t *) idata->udata.u.pciCfg.pci_cfg_space;
off = idata->udata.u.pciCfg.Offset;
len = idata->udata.u.pciCfg.Size;
if (len <= 4)
return crystalhd_pci_cfg_wr(ctx->adp, off, len, temp[0]);
/* Truncate to dword alignment..*/
len = 4;
cnt = idata->udata.u.pciCfg.Size / len;
for (ix = 0; ix < cnt; ix++) {
sts = crystalhd_pci_cfg_wr(ctx->adp, off, len, temp[ix]);
if (sts != BC_STS_SUCCESS) {
BCMLOG_ERR("config write : %d\n", sts);
return sts;
}
off += len;
}
return sts;
}
static enum BC_STATUS bc_cproc_download_fw(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
enum BC_STATUS sts = BC_STS_SUCCESS;
if (!ctx || !idata || !idata->add_cdata || !idata->add_cdata_sz) {
BCMLOG_ERR("Invalid Arg!!\n");
return BC_STS_INV_ARG;
}
if (ctx->state != BC_LINK_INVALID) {
BCMLOG_ERR("Link invalid state %d\n", ctx->state);
return BC_STS_ERR_USAGE;
}
sts = crystalhd_download_fw(ctx->adp, (uint8_t *)idata->add_cdata,
idata->add_cdata_sz);
if (sts != BC_STS_SUCCESS) {
BCMLOG_ERR("Firmware Download Failure!! - %d\n", sts);
} else
ctx->state |= BC_LINK_INIT;
return sts;
}
/*
* We use the FW_CMD interface to sync up playback state with application
* and firmware. This function will perform the required pre and post
* processing of the Firmware commands.
*
* Pause -
* Disable capture after decoder pause.
* Resume -
* First enable capture and issue decoder resume command.
* Flush -
* Abort pending input transfers and issue decoder flush command.
*
*/
static enum BC_STATUS bc_cproc_do_fw_cmd(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
enum BC_STATUS sts;
uint32_t *cmd;
if (!(ctx->state & BC_LINK_INIT)) {
BCMLOG_ERR("Link invalid state %d\n", ctx->state);
return BC_STS_ERR_USAGE;
}
cmd = idata->udata.u.fwCmd.cmd;
/* Pre-Process */
if (cmd[0] == eCMD_C011_DEC_CHAN_PAUSE) {
if (!cmd[3]) {
ctx->state &= ~BC_LINK_PAUSED;
crystalhd_hw_unpause(&ctx->hw_ctx);
}
} else if (cmd[0] == eCMD_C011_DEC_CHAN_FLUSH) {
BCMLOG(BCMLOG_INFO, "Flush issued\n");
if (cmd[3])
ctx->cin_wait_exit = 1;
}
sts = crystalhd_do_fw_cmd(&ctx->hw_ctx, &idata->udata.u.fwCmd);
if (sts != BC_STS_SUCCESS) {
BCMLOG(BCMLOG_INFO, "fw cmd %x failed\n", cmd[0]);
return sts;
}
/* Post-Process */
if (cmd[0] == eCMD_C011_DEC_CHAN_PAUSE) {
if (cmd[3]) {
ctx->state |= BC_LINK_PAUSED;
crystalhd_hw_pause(&ctx->hw_ctx);
}
}
return sts;
}
static void bc_proc_in_completion(struct crystalhd_dio_req *dio_hnd,
wait_queue_head_t *event, enum BC_STATUS sts)
{
if (!dio_hnd || !event) {
BCMLOG_ERR("Invalid Arg!!\n");
return;
}
if (sts == BC_STS_IO_USER_ABORT)
return;
dio_hnd->uinfo.comp_sts = sts;
dio_hnd->uinfo.ev_sts = 1;
crystalhd_set_event(event);
}
static enum BC_STATUS bc_cproc_codein_sleep(struct crystalhd_cmd *ctx)
{
wait_queue_head_t sleep_ev;
int rc = 0;
if (ctx->state & BC_LINK_SUSPEND)
return BC_STS_IO_USER_ABORT;
if (ctx->cin_wait_exit) {
ctx->cin_wait_exit = 0;
return BC_STS_CMD_CANCELLED;
}
crystalhd_create_event(&sleep_ev);
crystalhd_wait_on_event(&sleep_ev, 0, 100, rc, 0);
if (rc == -EINTR)
return BC_STS_IO_USER_ABORT;
return BC_STS_SUCCESS;
}
static enum BC_STATUS bc_cproc_hw_txdma(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata,
struct crystalhd_dio_req *dio)
{
uint32_t tx_listid = 0;
enum BC_STATUS sts = BC_STS_SUCCESS;
wait_queue_head_t event;
int rc = 0;
if (!ctx || !idata || !dio) {
BCMLOG_ERR("Invalid Arg!!\n");
return BC_STS_INV_ARG;
}
crystalhd_create_event(&event);
ctx->tx_list_id = 0;
/* msleep_interruptible(2000); */
sts = crystalhd_hw_post_tx(&ctx->hw_ctx, dio, bc_proc_in_completion,
&event, &tx_listid,
idata->udata.u.ProcInput.Encrypted);
while (sts == BC_STS_BUSY) {
sts = bc_cproc_codein_sleep(ctx);
if (sts != BC_STS_SUCCESS)
break;
sts = crystalhd_hw_post_tx(&ctx->hw_ctx, dio,
bc_proc_in_completion,
&event, &tx_listid,
idata->udata.u.ProcInput.Encrypted);
}
if (sts != BC_STS_SUCCESS) {
BCMLOG(BCMLOG_DBG, "_hw_txdma returning sts:%d\n", sts);
return sts;
}
if (ctx->cin_wait_exit)
ctx->cin_wait_exit = 0;
ctx->tx_list_id = tx_listid;
/* _post() succeeded.. wait for the completion. */
crystalhd_wait_on_event(&event, (dio->uinfo.ev_sts), 3000, rc, 0);
ctx->tx_list_id = 0;
if (!rc) {
return dio->uinfo.comp_sts;
} else if (rc == -EBUSY) {
BCMLOG(BCMLOG_DBG, "_tx_post() T/O\n");
sts = BC_STS_TIMEOUT;
} else if (rc == -EINTR) {
BCMLOG(BCMLOG_DBG, "Tx Wait Signal int.\n");
sts = BC_STS_IO_USER_ABORT;
} else {
sts = BC_STS_IO_ERROR;
}
/* We are cancelling the IO from the same context as the _post().
* so no need to wait on the event again.. the return itself
* ensures the release of our resources.
*/
crystalhd_hw_cancel_tx(&ctx->hw_ctx, tx_listid);
return sts;
}
/* Helper function to check on user buffers */
static enum BC_STATUS bc_cproc_check_inbuffs(bool pin, void *ubuff, uint32_t ub_sz,
uint32_t uv_off, bool en_422)
{
if (!ubuff || !ub_sz) {
BCMLOG_ERR("%s->Invalid Arg %p %x\n",
((pin) ? "TX" : "RX"), ubuff, ub_sz);
return BC_STS_INV_ARG;
}
/* Check for alignment */
if (((uintptr_t)ubuff) & 0x03) {
BCMLOG_ERR("%s-->Un-aligned address not implemented yet.. %p\n",
((pin) ? "TX" : "RX"), ubuff);
return BC_STS_NOT_IMPL;
}
if (pin)
return BC_STS_SUCCESS;
if (!en_422 && !uv_off) {
BCMLOG_ERR("Need UV offset for 420 mode.\n");
return BC_STS_INV_ARG;
}
if (en_422 && uv_off) {
BCMLOG_ERR("UV offset in 422 mode ??\n");
return BC_STS_INV_ARG;
}
return BC_STS_SUCCESS;
}
static enum BC_STATUS bc_cproc_proc_input(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
void *ubuff;
uint32_t ub_sz;
struct crystalhd_dio_req *dio_hnd = NULL;
enum BC_STATUS sts = BC_STS_SUCCESS;
if (!ctx || !idata) {
BCMLOG_ERR("Invalid Arg!!\n");
return BC_STS_INV_ARG;
}
ubuff = idata->udata.u.ProcInput.pDmaBuff;
ub_sz = idata->udata.u.ProcInput.BuffSz;
sts = bc_cproc_check_inbuffs(1, ubuff, ub_sz, 0, 0);
if (sts != BC_STS_SUCCESS)
return sts;
sts = crystalhd_map_dio(ctx->adp, ubuff, ub_sz, 0, 0, 1, &dio_hnd);
if (sts != BC_STS_SUCCESS) {
BCMLOG_ERR("dio map - %d\n", sts);
return sts;
}
if (!dio_hnd)
return BC_STS_ERROR;
sts = bc_cproc_hw_txdma(ctx, idata, dio_hnd);
crystalhd_unmap_dio(ctx->adp, dio_hnd);
return sts;
}
static enum BC_STATUS bc_cproc_add_cap_buff(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
void *ubuff;
uint32_t ub_sz, uv_off;
bool en_422;
struct crystalhd_dio_req *dio_hnd = NULL;
enum BC_STATUS sts = BC_STS_SUCCESS;
if (!ctx || !idata) {
BCMLOG_ERR("Invalid Arg!!\n");
return BC_STS_INV_ARG;
}
ubuff = idata->udata.u.RxBuffs.YuvBuff;
ub_sz = idata->udata.u.RxBuffs.YuvBuffSz;
uv_off = idata->udata.u.RxBuffs.UVbuffOffset;
en_422 = idata->udata.u.RxBuffs.b422Mode;
sts = bc_cproc_check_inbuffs(0, ubuff, ub_sz, uv_off, en_422);
if (sts != BC_STS_SUCCESS)
return sts;
sts = crystalhd_map_dio(ctx->adp, ubuff, ub_sz, uv_off,
en_422, 0, &dio_hnd);
if (sts != BC_STS_SUCCESS) {
BCMLOG_ERR("dio map - %d\n", sts);
return sts;
}
if (!dio_hnd)
return BC_STS_ERROR;
sts = crystalhd_hw_add_cap_buffer(&ctx->hw_ctx, dio_hnd, (ctx->state == BC_LINK_READY));
if ((sts != BC_STS_SUCCESS) && (sts != BC_STS_BUSY)) {
crystalhd_unmap_dio(ctx->adp, dio_hnd);
return sts;
}
return BC_STS_SUCCESS;
}
static enum BC_STATUS bc_cproc_fmt_change(struct crystalhd_cmd *ctx,
struct crystalhd_dio_req *dio)
{
enum BC_STATUS sts = BC_STS_SUCCESS;
sts = crystalhd_hw_add_cap_buffer(&ctx->hw_ctx, dio, 0);
if (sts != BC_STS_SUCCESS)
return sts;
ctx->state |= BC_LINK_FMT_CHG;
if (ctx->state == BC_LINK_READY)
sts = crystalhd_hw_start_capture(&ctx->hw_ctx);
return sts;
}
static enum BC_STATUS bc_cproc_fetch_frame(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
struct crystalhd_dio_req *dio = NULL;
enum BC_STATUS sts = BC_STS_SUCCESS;
struct BC_DEC_OUT_BUFF *frame;
if (!ctx || !idata) {
BCMLOG_ERR("Invalid Arg!!\n");
return BC_STS_INV_ARG;
}
if (!(ctx->state & BC_LINK_CAP_EN)) {
BCMLOG(BCMLOG_DBG, "Capture not enabled..%x\n", ctx->state);
return BC_STS_ERR_USAGE;
}
frame = &idata->udata.u.DecOutData;
sts = crystalhd_hw_get_cap_buffer(&ctx->hw_ctx, &frame->PibInfo, &dio);
if (sts != BC_STS_SUCCESS)
return (ctx->state & BC_LINK_SUSPEND) ? BC_STS_IO_USER_ABORT : sts;
frame->Flags = dio->uinfo.comp_flags;
if (frame->Flags & COMP_FLAG_FMT_CHANGE)
return bc_cproc_fmt_change(ctx, dio);
frame->OutPutBuffs.YuvBuff = dio->uinfo.xfr_buff;
frame->OutPutBuffs.YuvBuffSz = dio->uinfo.xfr_len;
frame->OutPutBuffs.UVbuffOffset = dio->uinfo.uv_offset;
frame->OutPutBuffs.b422Mode = dio->uinfo.b422mode;
frame->OutPutBuffs.YBuffDoneSz = dio->uinfo.y_done_sz;
frame->OutPutBuffs.UVBuffDoneSz = dio->uinfo.uv_done_sz;
crystalhd_unmap_dio(ctx->adp, dio);
return BC_STS_SUCCESS;
}
static enum BC_STATUS bc_cproc_start_capture(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
ctx->state |= BC_LINK_CAP_EN;
if (ctx->state == BC_LINK_READY)
return crystalhd_hw_start_capture(&ctx->hw_ctx);
return BC_STS_SUCCESS;
}
static enum BC_STATUS bc_cproc_flush_cap_buffs(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
struct crystalhd_dio_req *dio = NULL;
enum BC_STATUS sts = BC_STS_SUCCESS;
struct BC_DEC_OUT_BUFF *frame;
uint32_t count;
if (!ctx || !idata) {
BCMLOG_ERR("Invalid Arg!!\n");
return BC_STS_INV_ARG;
}
if (!(ctx->state & BC_LINK_CAP_EN))
return BC_STS_ERR_USAGE;
/* We should ack flush even when we are in paused/suspend state */
if (!(ctx->state & BC_LINK_READY))
return crystalhd_hw_stop_capture(&ctx->hw_ctx);
ctx->state &= ~(BC_LINK_CAP_EN|BC_LINK_FMT_CHG);
frame = &idata->udata.u.DecOutData;
for (count = 0; count < BC_RX_LIST_CNT; count++) {
sts = crystalhd_hw_get_cap_buffer(&ctx->hw_ctx, &frame->PibInfo, &dio);
if (sts != BC_STS_SUCCESS)
break;
crystalhd_unmap_dio(ctx->adp, dio);
}
return crystalhd_hw_stop_capture(&ctx->hw_ctx);
}
static enum BC_STATUS bc_cproc_get_stats(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
struct BC_DTS_STATS *stats;
struct crystalhd_hw_stats hw_stats;
if (!ctx || !idata) {
BCMLOG_ERR("Invalid Arg!!\n");
return BC_STS_INV_ARG;
}
crystalhd_hw_stats(&ctx->hw_ctx, &hw_stats);
stats = &idata->udata.u.drvStat;
stats->drvRLL = hw_stats.rdyq_count;
stats->drvFLL = hw_stats.freeq_count;
stats->DrvTotalFrmDropped = hw_stats.rx_errors;
stats->DrvTotalHWErrs = hw_stats.rx_errors + hw_stats.tx_errors;
stats->intCount = hw_stats.num_interrupts;
stats->DrvIgnIntrCnt = hw_stats.num_interrupts -
hw_stats.dev_interrupts;
stats->TxFifoBsyCnt = hw_stats.cin_busy;
stats->pauseCount = hw_stats.pause_cnt;
if (ctx->pwr_state_change)
stats->pwr_state_change = 1;
if (ctx->state & BC_LINK_PAUSED)
stats->DrvPauseTime = 1;
return BC_STS_SUCCESS;
}
static enum BC_STATUS bc_cproc_reset_stats(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
crystalhd_hw_stats(&ctx->hw_ctx, NULL);
return BC_STS_SUCCESS;
}
static enum BC_STATUS bc_cproc_chg_clk(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
struct BC_CLOCK *clock;
uint32_t oldClk;
enum BC_STATUS sts = BC_STS_SUCCESS;
if (!ctx || !idata) {
BCMLOG_ERR("Invalid Arg!!\n");
return BC_STS_INV_ARG;
}
clock = &idata->udata.u.clockValue;
oldClk = ctx->hw_ctx.core_clock_mhz;
ctx->hw_ctx.core_clock_mhz = clock->clk;
if (ctx->state & BC_LINK_READY) {
sts = crystalhd_hw_set_core_clock(&ctx->hw_ctx);
if (sts == BC_STS_CLK_NOCHG)
ctx->hw_ctx.core_clock_mhz = oldClk;
}
clock->clk = ctx->hw_ctx.core_clock_mhz;
return sts;
}
/*=============== Cmd Proc Table.. ======================================*/
static const struct crystalhd_cmd_tbl g_crystalhd_cproc_tbl[] = {
{ BCM_IOC_GET_VERSION, bc_cproc_get_version, 0},
{ BCM_IOC_GET_HWTYPE, bc_cproc_get_hwtype, 0},
{ BCM_IOC_REG_RD, bc_cproc_reg_rd, 0},
{ BCM_IOC_REG_WR, bc_cproc_reg_wr, 0},
{ BCM_IOC_FPGA_RD, bc_cproc_link_reg_rd, 0},
{ BCM_IOC_FPGA_WR, bc_cproc_link_reg_wr, 0},
{ BCM_IOC_MEM_RD, bc_cproc_mem_rd, 0},
{ BCM_IOC_MEM_WR, bc_cproc_mem_wr, 0},
{ BCM_IOC_RD_PCI_CFG, bc_cproc_cfg_rd, 0},
{ BCM_IOC_WR_PCI_CFG, bc_cproc_cfg_wr, 1},
{ BCM_IOC_FW_DOWNLOAD, bc_cproc_download_fw, 1},
{ BCM_IOC_FW_CMD, bc_cproc_do_fw_cmd, 1},
{ BCM_IOC_PROC_INPUT, bc_cproc_proc_input, 1},
{ BCM_IOC_ADD_RXBUFFS, bc_cproc_add_cap_buff, 1},
{ BCM_IOC_FETCH_RXBUFF, bc_cproc_fetch_frame, 1},
{ BCM_IOC_START_RX_CAP, bc_cproc_start_capture, 1},
{ BCM_IOC_FLUSH_RX_CAP, bc_cproc_flush_cap_buffs, 1},
{ BCM_IOC_GET_DRV_STAT, bc_cproc_get_stats, 0},
{ BCM_IOC_RST_DRV_STAT, bc_cproc_reset_stats, 0},
{ BCM_IOC_NOTIFY_MODE, bc_cproc_notify_mode, 0},
{ BCM_IOC_CHG_CLK, bc_cproc_chg_clk, 0},
{ BCM_IOC_END, NULL},
};
/*=============== Cmd Proc Functions.. ===================================*/
/**
* crystalhd_suspend - Power management suspend request.
* @ctx: Command layer context.
* @idata: Iodata - required for internal use.
*
* Return:
* status
*
* 1. Set the state to Suspend.
* 2. Flush the Rx Buffers it will unmap all the buffers and
* stop the RxDMA engine.
* 3. Cancel The TX Io and Stop Dma Engine.
* 4. Put the DDR in to deep sleep.
* 5. Stop the hardware putting it in to Reset State.
*
* Current gstreamer frame work does not provide any power management
* related notification to user mode decoder plug-in. As a work-around
* we pass on the power mangement notification to our plug-in by completing
* all outstanding requests with BC_STS_IO_USER_ABORT return code.
*/
enum BC_STATUS crystalhd_suspend(struct crystalhd_cmd *ctx,
struct crystalhd_ioctl_data *idata)
{
enum BC_STATUS sts = BC_STS_SUCCESS;
if (!ctx || !idata) {
BCMLOG_ERR("Invalid Parameters\n");
return BC_STS_ERROR;
}
if (ctx->state & BC_LINK_SUSPEND)
return BC_STS_SUCCESS;
if (ctx->state == BC_LINK_INVALID) {
BCMLOG(BCMLOG_DBG, "Nothing To Do Suspend Success\n");
return BC_STS_SUCCESS;
}
ctx->state |= BC_LINK_SUSPEND;
bc_cproc_mark_pwr_state(ctx);
if (ctx->state & BC_LINK_CAP_EN) {
sts = bc_cproc_flush_cap_buffs(ctx, idata);
if (sts != BC_STS_SUCCESS)
return sts;
}
if (ctx->tx_list_id) {
sts = crystalhd_hw_cancel_tx(&ctx->hw_ctx, ctx->tx_list_id);
if (sts != BC_STS_SUCCESS)
return sts;
}
sts = crystalhd_hw_suspend(&ctx->hw_ctx);
if (sts != BC_STS_SUCCESS)
return sts;
BCMLOG(BCMLOG_DBG, "BCM70012 suspend success\n");
return BC_STS_SUCCESS;
}
/**
* crystalhd_resume - Resume frame capture.
* @ctx: Command layer contextx.
*
* Return:
* status
*
*
* Resume frame capture.
*
* PM_Resume can't resume the playback state back to pre-suspend state
* because we don't keep video clip related information within driver.
* To get back to the pre-suspend state App will re-open the device and
* start a new playback session from the pre-suspend clip position.
*
*/
enum BC_STATUS crystalhd_resume(struct crystalhd_cmd *ctx)
{
BCMLOG(BCMLOG_DBG, "crystalhd_resume Success %x\n", ctx->state);
bc_cproc_mark_pwr_state(ctx);
return BC_STS_SUCCESS;
}
/**
* crystalhd_user_open - Create application handle.
* @ctx: Command layer contextx.
* @user_ctx: User ID context.
*
* Return:
* status
*
* Creates an application specific UID and allocates
* application specific resources. HW layer initialization
* is done for the first open request.
*/
enum BC_STATUS crystalhd_user_open(struct crystalhd_cmd *ctx,
struct crystalhd_user **user_ctx)
{
struct crystalhd_user *uc;
if (!ctx || !user_ctx) {
BCMLOG_ERR("Invalid arg..\n");
return BC_STS_INV_ARG;
}
uc = bc_cproc_get_uid(ctx);
if (!uc) {
BCMLOG(BCMLOG_INFO, "No free user context...\n");
return BC_STS_BUSY;
}
BCMLOG(BCMLOG_INFO, "Opening new user[%x] handle\n", uc->uid);
crystalhd_hw_open(&ctx->hw_ctx, ctx->adp);
uc->in_use = 1;
*user_ctx = uc;
return BC_STS_SUCCESS;
}
/**
* crystalhd_user_close - Close application handle.
* @ctx: Command layer contextx.
* @uc: User ID context.
*
* Return:
* status
*
* Closer application handle and release app specific
* resources.
*/
enum BC_STATUS crystalhd_user_close(struct crystalhd_cmd *ctx, struct crystalhd_user *uc)
{
uint32_t mode = uc->mode;
ctx->user[uc->uid].mode = DTS_MODE_INV;
ctx->user[uc->uid].in_use = 0;
ctx->cin_wait_exit = 1;
ctx->pwr_state_change = 0;
BCMLOG(BCMLOG_INFO, "Closing user[%x] handle\n", uc->uid);
if ((mode == DTS_DIAG_MODE) || (mode == DTS_PLAYBACK_MODE)) {
crystalhd_hw_free_dma_rings(&ctx->hw_ctx);
crystalhd_destroy_dio_pool(ctx->adp);
} else if (bc_cproc_get_user_count(ctx)) {
return BC_STS_SUCCESS;
}
crystalhd_hw_close(&ctx->hw_ctx);
ctx->state = BC_LINK_INVALID;
return BC_STS_SUCCESS;
}
/**
* crystalhd_setup_cmd_context - Setup Command layer resources.
* @ctx: Command layer contextx.
* @adp: Adapter context
*
* Return:
* status
*
* Called at the time of driver load.
*/
enum BC_STATUS __devinit crystalhd_setup_cmd_context(struct crystalhd_cmd *ctx,
struct crystalhd_adp *adp)
{
int i = 0;
if (!ctx || !adp) {
BCMLOG_ERR("Invalid arg!!\n");
return BC_STS_INV_ARG;
}
if (ctx->adp)
BCMLOG(BCMLOG_DBG, "Resetting Cmd context delete missing..\n");
ctx->adp = adp;
for (i = 0; i < BC_LINK_MAX_OPENS; i++) {
ctx->user[i].uid = i;
ctx->user[i].in_use = 0;
ctx->user[i].mode = DTS_MODE_INV;
}
/*Open and Close the Hardware to put it in to sleep state*/
crystalhd_hw_open(&ctx->hw_ctx, ctx->adp);
crystalhd_hw_close(&ctx->hw_ctx);
return BC_STS_SUCCESS;
}
/**
* crystalhd_delete_cmd_context - Release Command layer resources.
* @ctx: Command layer contextx.
*
* Return:
* status
*
* Called at the time of driver un-load.
*/
enum BC_STATUS __devexit crystalhd_delete_cmd_context(struct crystalhd_cmd *ctx)
{
BCMLOG(BCMLOG_DBG, "Deleting Command context..\n");
ctx->adp = NULL;
return BC_STS_SUCCESS;
}
/**
* crystalhd_get_cmd_proc - Cproc table lookup.
* @ctx: Command layer contextx.
* @cmd: IOCTL command code.
* @uc: User ID context.
*
* Return:
* command proc function pointer
*
* This function checks the process context, application's
* mode of operation and returns the function pointer
* from the cproc table.
*/
crystalhd_cmd_proc crystalhd_get_cmd_proc(struct crystalhd_cmd *ctx, uint32_t cmd,
struct crystalhd_user *uc)
{
crystalhd_cmd_proc cproc = NULL;
unsigned int i, tbl_sz;
if (!ctx) {
BCMLOG_ERR("Invalid arg.. Cmd[%d]\n", cmd);
return NULL;
}
if ((cmd != BCM_IOC_GET_DRV_STAT) && (ctx->state & BC_LINK_SUSPEND)) {
BCMLOG_ERR("Invalid State [suspend Set].. Cmd[%d]\n", cmd);
return NULL;
}
tbl_sz = sizeof(g_crystalhd_cproc_tbl) / sizeof(struct crystalhd_cmd_tbl);
for (i = 0; i < tbl_sz; i++) {
if (g_crystalhd_cproc_tbl[i].cmd_id == cmd) {
if ((uc->mode == DTS_MONITOR_MODE) &&
(g_crystalhd_cproc_tbl[i].block_mon)) {
BCMLOG(BCMLOG_INFO, "Blocking cmd %d\n", cmd);
break;
}
cproc = g_crystalhd_cproc_tbl[i].cmd_proc;
break;
}
}
return cproc;
}
/**
* crystalhd_cmd_interrupt - ISR entry point
* @ctx: Command layer contextx.
*
* Return:
* TRUE: If interrupt from bcm70012 device.
*
*
* ISR entry point from OS layer.
*/
bool crystalhd_cmd_interrupt(struct crystalhd_cmd *ctx)
{
if (!ctx) {
BCMLOG_ERR("Invalid arg..\n");
return 0;
}
return crystalhd_hw_interrupt(ctx->adp, &ctx->hw_ctx);
}
| gpl-2.0 |
cybojenix/android_kernel_nvidia_kalamata | drivers/scsi/ps3rom.c | 5240 | 11539 | /*
* PS3 BD/DVD/CD-ROM Storage Driver
*
* Copyright (C) 2007 Sony Computer Entertainment Inc.
* Copyright 2007 Sony Corp.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published
* by the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <linux/cdrom.h>
#include <linux/highmem.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_dbg.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_eh.h>
#include <asm/lv1call.h>
#include <asm/ps3stor.h>
#define DEVICE_NAME "ps3rom"
#define BOUNCE_SIZE (64*1024)
#define PS3ROM_MAX_SECTORS (BOUNCE_SIZE >> 9)
struct ps3rom_private {
struct ps3_storage_device *dev;
struct scsi_cmnd *curr_cmd;
};
#define LV1_STORAGE_SEND_ATAPI_COMMAND (1)
struct lv1_atapi_cmnd_block {
u8 pkt[32]; /* packet command block */
u32 pktlen; /* should be 12 for ATAPI 8020 */
u32 blocks;
u32 block_size;
u32 proto; /* transfer mode */
u32 in_out; /* transfer direction */
u64 buffer; /* parameter except command block */
u32 arglen; /* length above */
};
enum lv1_atapi_proto {
NON_DATA_PROTO = 0,
PIO_DATA_IN_PROTO = 1,
PIO_DATA_OUT_PROTO = 2,
DMA_PROTO = 3
};
enum lv1_atapi_in_out {
DIR_WRITE = 0, /* memory -> device */
DIR_READ = 1 /* device -> memory */
};
static int ps3rom_slave_configure(struct scsi_device *scsi_dev)
{
struct ps3rom_private *priv = shost_priv(scsi_dev->host);
struct ps3_storage_device *dev = priv->dev;
dev_dbg(&dev->sbd.core, "%s:%u: id %u, lun %u, channel %u\n", __func__,
__LINE__, scsi_dev->id, scsi_dev->lun, scsi_dev->channel);
/*
* ATAPI SFF8020 devices use MODE_SENSE_10,
* so we can prohibit MODE_SENSE_6
*/
scsi_dev->use_10_for_ms = 1;
/* we don't support {READ,WRITE}_6 */
scsi_dev->use_10_for_rw = 1;
return 0;
}
static int ps3rom_atapi_request(struct ps3_storage_device *dev,
struct scsi_cmnd *cmd)
{
struct lv1_atapi_cmnd_block atapi_cmnd;
unsigned char opcode = cmd->cmnd[0];
int res;
u64 lpar;
dev_dbg(&dev->sbd.core, "%s:%u: send ATAPI command 0x%02x\n", __func__,
__LINE__, opcode);
memset(&atapi_cmnd, 0, sizeof(struct lv1_atapi_cmnd_block));
memcpy(&atapi_cmnd.pkt, cmd->cmnd, 12);
atapi_cmnd.pktlen = 12;
atapi_cmnd.block_size = 1; /* transfer size is block_size * blocks */
atapi_cmnd.blocks = atapi_cmnd.arglen = scsi_bufflen(cmd);
atapi_cmnd.buffer = dev->bounce_lpar;
switch (cmd->sc_data_direction) {
case DMA_FROM_DEVICE:
if (scsi_bufflen(cmd) >= CD_FRAMESIZE)
atapi_cmnd.proto = DMA_PROTO;
else
atapi_cmnd.proto = PIO_DATA_IN_PROTO;
atapi_cmnd.in_out = DIR_READ;
break;
case DMA_TO_DEVICE:
if (scsi_bufflen(cmd) >= CD_FRAMESIZE)
atapi_cmnd.proto = DMA_PROTO;
else
atapi_cmnd.proto = PIO_DATA_OUT_PROTO;
atapi_cmnd.in_out = DIR_WRITE;
scsi_sg_copy_to_buffer(cmd, dev->bounce_buf, dev->bounce_size);
break;
default:
atapi_cmnd.proto = NON_DATA_PROTO;
break;
}
lpar = ps3_mm_phys_to_lpar(__pa(&atapi_cmnd));
res = lv1_storage_send_device_command(dev->sbd.dev_id,
LV1_STORAGE_SEND_ATAPI_COMMAND,
lpar, sizeof(atapi_cmnd),
atapi_cmnd.buffer,
atapi_cmnd.arglen, &dev->tag);
if (res == LV1_DENIED_BY_POLICY) {
dev_dbg(&dev->sbd.core,
"%s:%u: ATAPI command 0x%02x denied by policy\n",
__func__, __LINE__, opcode);
return DID_ERROR << 16;
}
if (res) {
dev_err(&dev->sbd.core,
"%s:%u: ATAPI command 0x%02x failed %d\n", __func__,
__LINE__, opcode, res);
return DID_ERROR << 16;
}
return 0;
}
static inline unsigned int srb10_lba(const struct scsi_cmnd *cmd)
{
return cmd->cmnd[2] << 24 | cmd->cmnd[3] << 16 | cmd->cmnd[4] << 8 |
cmd->cmnd[5];
}
static inline unsigned int srb10_len(const struct scsi_cmnd *cmd)
{
return cmd->cmnd[7] << 8 | cmd->cmnd[8];
}
static int ps3rom_read_request(struct ps3_storage_device *dev,
struct scsi_cmnd *cmd, u32 start_sector,
u32 sectors)
{
int res;
dev_dbg(&dev->sbd.core, "%s:%u: read %u sectors starting at %u\n",
__func__, __LINE__, sectors, start_sector);
res = lv1_storage_read(dev->sbd.dev_id,
dev->regions[dev->region_idx].id, start_sector,
sectors, 0, dev->bounce_lpar, &dev->tag);
if (res) {
dev_err(&dev->sbd.core, "%s:%u: read failed %d\n", __func__,
__LINE__, res);
return DID_ERROR << 16;
}
return 0;
}
static int ps3rom_write_request(struct ps3_storage_device *dev,
struct scsi_cmnd *cmd, u32 start_sector,
u32 sectors)
{
int res;
dev_dbg(&dev->sbd.core, "%s:%u: write %u sectors starting at %u\n",
__func__, __LINE__, sectors, start_sector);
scsi_sg_copy_to_buffer(cmd, dev->bounce_buf, dev->bounce_size);
res = lv1_storage_write(dev->sbd.dev_id,
dev->regions[dev->region_idx].id, start_sector,
sectors, 0, dev->bounce_lpar, &dev->tag);
if (res) {
dev_err(&dev->sbd.core, "%s:%u: write failed %d\n", __func__,
__LINE__, res);
return DID_ERROR << 16;
}
return 0;
}
static int ps3rom_queuecommand_lck(struct scsi_cmnd *cmd,
void (*done)(struct scsi_cmnd *))
{
struct ps3rom_private *priv = shost_priv(cmd->device->host);
struct ps3_storage_device *dev = priv->dev;
unsigned char opcode;
int res;
#ifdef DEBUG
scsi_print_command(cmd);
#endif
priv->curr_cmd = cmd;
cmd->scsi_done = done;
opcode = cmd->cmnd[0];
/*
* While we can submit READ/WRITE SCSI commands as ATAPI commands,
* it's recommended for various reasons (performance, error handling,
* ...) to use lv1_storage_{read,write}() instead
*/
switch (opcode) {
case READ_10:
res = ps3rom_read_request(dev, cmd, srb10_lba(cmd),
srb10_len(cmd));
break;
case WRITE_10:
res = ps3rom_write_request(dev, cmd, srb10_lba(cmd),
srb10_len(cmd));
break;
default:
res = ps3rom_atapi_request(dev, cmd);
break;
}
if (res) {
memset(cmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
cmd->result = res;
cmd->sense_buffer[0] = 0x70;
cmd->sense_buffer[2] = ILLEGAL_REQUEST;
priv->curr_cmd = NULL;
cmd->scsi_done(cmd);
}
return 0;
}
static DEF_SCSI_QCMD(ps3rom_queuecommand)
static int decode_lv1_status(u64 status, unsigned char *sense_key,
unsigned char *asc, unsigned char *ascq)
{
if (((status >> 24) & 0xff) != SAM_STAT_CHECK_CONDITION)
return -1;
*sense_key = (status >> 16) & 0xff;
*asc = (status >> 8) & 0xff;
*ascq = status & 0xff;
return 0;
}
static irqreturn_t ps3rom_interrupt(int irq, void *data)
{
struct ps3_storage_device *dev = data;
struct Scsi_Host *host;
struct ps3rom_private *priv;
struct scsi_cmnd *cmd;
int res;
u64 tag, status;
unsigned char sense_key, asc, ascq;
res = lv1_storage_get_async_status(dev->sbd.dev_id, &tag, &status);
/*
* status = -1 may mean that ATAPI transport completed OK, but
* ATAPI command itself resulted CHECK CONDITION
* so, upper layer should issue REQUEST_SENSE to check the sense data
*/
if (tag != dev->tag)
dev_err(&dev->sbd.core,
"%s:%u: tag mismatch, got %llx, expected %llx\n",
__func__, __LINE__, tag, dev->tag);
if (res) {
dev_err(&dev->sbd.core, "%s:%u: res=%d status=0x%llx\n",
__func__, __LINE__, res, status);
return IRQ_HANDLED;
}
host = ps3_system_bus_get_drvdata(&dev->sbd);
priv = shost_priv(host);
cmd = priv->curr_cmd;
if (!status) {
/* OK, completed */
if (cmd->sc_data_direction == DMA_FROM_DEVICE) {
int len;
len = scsi_sg_copy_from_buffer(cmd,
dev->bounce_buf,
dev->bounce_size);
scsi_set_resid(cmd, scsi_bufflen(cmd) - len);
}
cmd->result = DID_OK << 16;
goto done;
}
if (cmd->cmnd[0] == REQUEST_SENSE) {
/* SCSI spec says request sense should never get error */
dev_err(&dev->sbd.core, "%s:%u: end error without autosense\n",
__func__, __LINE__);
cmd->result = DID_ERROR << 16 | SAM_STAT_CHECK_CONDITION;
goto done;
}
if (decode_lv1_status(status, &sense_key, &asc, &ascq)) {
cmd->result = DID_ERROR << 16;
goto done;
}
scsi_build_sense_buffer(0, cmd->sense_buffer, sense_key, asc, ascq);
cmd->result = SAM_STAT_CHECK_CONDITION;
done:
priv->curr_cmd = NULL;
cmd->scsi_done(cmd);
return IRQ_HANDLED;
}
static struct scsi_host_template ps3rom_host_template = {
.name = DEVICE_NAME,
.slave_configure = ps3rom_slave_configure,
.queuecommand = ps3rom_queuecommand,
.can_queue = 1,
.this_id = 7,
.sg_tablesize = SG_ALL,
.cmd_per_lun = 1,
.emulated = 1, /* only sg driver uses this */
.max_sectors = PS3ROM_MAX_SECTORS,
.use_clustering = ENABLE_CLUSTERING,
.module = THIS_MODULE,
};
static int __devinit ps3rom_probe(struct ps3_system_bus_device *_dev)
{
struct ps3_storage_device *dev = to_ps3_storage_device(&_dev->core);
int error;
struct Scsi_Host *host;
struct ps3rom_private *priv;
if (dev->blk_size != CD_FRAMESIZE) {
dev_err(&dev->sbd.core,
"%s:%u: cannot handle block size %llu\n", __func__,
__LINE__, dev->blk_size);
return -EINVAL;
}
dev->bounce_size = BOUNCE_SIZE;
dev->bounce_buf = kmalloc(BOUNCE_SIZE, GFP_DMA);
if (!dev->bounce_buf)
return -ENOMEM;
error = ps3stor_setup(dev, ps3rom_interrupt);
if (error)
goto fail_free_bounce;
host = scsi_host_alloc(&ps3rom_host_template,
sizeof(struct ps3rom_private));
if (!host) {
dev_err(&dev->sbd.core, "%s:%u: scsi_host_alloc failed\n",
__func__, __LINE__);
goto fail_teardown;
}
priv = shost_priv(host);
ps3_system_bus_set_drvdata(&dev->sbd, host);
priv->dev = dev;
/* One device/LUN per SCSI bus */
host->max_id = 1;
host->max_lun = 1;
error = scsi_add_host(host, &dev->sbd.core);
if (error) {
dev_err(&dev->sbd.core, "%s:%u: scsi_host_alloc failed %d\n",
__func__, __LINE__, error);
error = -ENODEV;
goto fail_host_put;
}
scsi_scan_host(host);
return 0;
fail_host_put:
scsi_host_put(host);
ps3_system_bus_set_drvdata(&dev->sbd, NULL);
fail_teardown:
ps3stor_teardown(dev);
fail_free_bounce:
kfree(dev->bounce_buf);
return error;
}
static int ps3rom_remove(struct ps3_system_bus_device *_dev)
{
struct ps3_storage_device *dev = to_ps3_storage_device(&_dev->core);
struct Scsi_Host *host = ps3_system_bus_get_drvdata(&dev->sbd);
scsi_remove_host(host);
ps3stor_teardown(dev);
scsi_host_put(host);
ps3_system_bus_set_drvdata(&dev->sbd, NULL);
kfree(dev->bounce_buf);
return 0;
}
static struct ps3_system_bus_driver ps3rom = {
.match_id = PS3_MATCH_ID_STOR_ROM,
.core.name = DEVICE_NAME,
.core.owner = THIS_MODULE,
.probe = ps3rom_probe,
.remove = ps3rom_remove
};
static int __init ps3rom_init(void)
{
return ps3_system_bus_driver_register(&ps3rom);
}
static void __exit ps3rom_exit(void)
{
ps3_system_bus_driver_unregister(&ps3rom);
}
module_init(ps3rom_init);
module_exit(ps3rom_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("PS3 BD/DVD/CD-ROM Storage Driver");
MODULE_AUTHOR("Sony Corporation");
MODULE_ALIAS(PS3_MODULE_ALIAS_STOR_ROM);
| gpl-2.0 |
niker/elitekernel_oxp_kk | drivers/net/enic/vnic_cq.c | 9592 | 2830 | /*
* Copyright 2008-2010 Cisco Systems, Inc. All rights reserved.
* Copyright 2007 Nuova Systems, Inc. All rights reserved.
*
* This program is free software; you may redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/pci.h>
#include "vnic_dev.h"
#include "vnic_cq.h"
void vnic_cq_free(struct vnic_cq *cq)
{
vnic_dev_free_desc_ring(cq->vdev, &cq->ring);
cq->ctrl = NULL;
}
int vnic_cq_alloc(struct vnic_dev *vdev, struct vnic_cq *cq, unsigned int index,
unsigned int desc_count, unsigned int desc_size)
{
int err;
cq->index = index;
cq->vdev = vdev;
cq->ctrl = vnic_dev_get_res(vdev, RES_TYPE_CQ, index);
if (!cq->ctrl) {
pr_err("Failed to hook CQ[%d] resource\n", index);
return -EINVAL;
}
err = vnic_dev_alloc_desc_ring(vdev, &cq->ring, desc_count, desc_size);
if (err)
return err;
return 0;
}
void vnic_cq_init(struct vnic_cq *cq, unsigned int flow_control_enable,
unsigned int color_enable, unsigned int cq_head, unsigned int cq_tail,
unsigned int cq_tail_color, unsigned int interrupt_enable,
unsigned int cq_entry_enable, unsigned int cq_message_enable,
unsigned int interrupt_offset, u64 cq_message_addr)
{
u64 paddr;
paddr = (u64)cq->ring.base_addr | VNIC_PADDR_TARGET;
writeq(paddr, &cq->ctrl->ring_base);
iowrite32(cq->ring.desc_count, &cq->ctrl->ring_size);
iowrite32(flow_control_enable, &cq->ctrl->flow_control_enable);
iowrite32(color_enable, &cq->ctrl->color_enable);
iowrite32(cq_head, &cq->ctrl->cq_head);
iowrite32(cq_tail, &cq->ctrl->cq_tail);
iowrite32(cq_tail_color, &cq->ctrl->cq_tail_color);
iowrite32(interrupt_enable, &cq->ctrl->interrupt_enable);
iowrite32(cq_entry_enable, &cq->ctrl->cq_entry_enable);
iowrite32(cq_message_enable, &cq->ctrl->cq_message_enable);
iowrite32(interrupt_offset, &cq->ctrl->interrupt_offset);
writeq(cq_message_addr, &cq->ctrl->cq_message_addr);
cq->interrupt_offset = interrupt_offset;
}
void vnic_cq_clean(struct vnic_cq *cq)
{
cq->to_clean = 0;
cq->last_color = 0;
iowrite32(0, &cq->ctrl->cq_head);
iowrite32(0, &cq->ctrl->cq_tail);
iowrite32(1, &cq->ctrl->cq_tail_color);
vnic_dev_clear_desc_ring(&cq->ring);
}
| gpl-2.0 |
Jackeagle/kernel_caf | drivers/input/mouse/pc110pad.c | 13176 | 4680 | /*
* Copyright (c) 2000-2001 Vojtech Pavlik
*
* Based on the work of:
* Alan Cox Robin O'Leary
*/
/*
* IBM PC110 touchpad driver for Linux
*/
/*
* 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
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@ucw.cz>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/input.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <asm/io.h>
#include <asm/irq.h>
MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>");
MODULE_DESCRIPTION("IBM PC110 touchpad driver");
MODULE_LICENSE("GPL");
#define PC110PAD_OFF 0x30
#define PC110PAD_ON 0x38
static int pc110pad_irq = 10;
static int pc110pad_io = 0x15e0;
static struct input_dev *pc110pad_dev;
static int pc110pad_data[3];
static int pc110pad_count;
static irqreturn_t pc110pad_interrupt(int irq, void *ptr)
{
int value = inb_p(pc110pad_io);
int handshake = inb_p(pc110pad_io + 2);
outb(handshake | 1, pc110pad_io + 2);
udelay(2);
outb(handshake & ~1, pc110pad_io + 2);
udelay(2);
inb_p(0x64);
pc110pad_data[pc110pad_count++] = value;
if (pc110pad_count < 3)
return IRQ_HANDLED;
input_report_key(pc110pad_dev, BTN_TOUCH,
pc110pad_data[0] & 0x01);
input_report_abs(pc110pad_dev, ABS_X,
pc110pad_data[1] | ((pc110pad_data[0] << 3) & 0x80) | ((pc110pad_data[0] << 1) & 0x100));
input_report_abs(pc110pad_dev, ABS_Y,
pc110pad_data[2] | ((pc110pad_data[0] << 4) & 0x80));
input_sync(pc110pad_dev);
pc110pad_count = 0;
return IRQ_HANDLED;
}
static void pc110pad_close(struct input_dev *dev)
{
outb(PC110PAD_OFF, pc110pad_io + 2);
}
static int pc110pad_open(struct input_dev *dev)
{
pc110pad_interrupt(0, NULL);
pc110pad_interrupt(0, NULL);
pc110pad_interrupt(0, NULL);
outb(PC110PAD_ON, pc110pad_io + 2);
pc110pad_count = 0;
return 0;
}
/*
* We try to avoid enabling the hardware if it's not
* there, but we don't know how to test. But we do know
* that the PC110 is not a PCI system. So if we find any
* PCI devices in the machine, we don't have a PC110.
*/
static int __init pc110pad_init(void)
{
int err;
if (!no_pci_devices())
return -ENODEV;
if (!request_region(pc110pad_io, 4, "pc110pad")) {
printk(KERN_ERR "pc110pad: I/O area %#x-%#x in use.\n",
pc110pad_io, pc110pad_io + 4);
return -EBUSY;
}
outb(PC110PAD_OFF, pc110pad_io + 2);
if (request_irq(pc110pad_irq, pc110pad_interrupt, 0, "pc110pad", NULL)) {
printk(KERN_ERR "pc110pad: Unable to get irq %d.\n", pc110pad_irq);
err = -EBUSY;
goto err_release_region;
}
pc110pad_dev = input_allocate_device();
if (!pc110pad_dev) {
printk(KERN_ERR "pc110pad: Not enough memory.\n");
err = -ENOMEM;
goto err_free_irq;
}
pc110pad_dev->name = "IBM PC110 TouchPad";
pc110pad_dev->phys = "isa15e0/input0";
pc110pad_dev->id.bustype = BUS_ISA;
pc110pad_dev->id.vendor = 0x0003;
pc110pad_dev->id.product = 0x0001;
pc110pad_dev->id.version = 0x0100;
pc110pad_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
pc110pad_dev->absbit[0] = BIT_MASK(ABS_X) | BIT_MASK(ABS_Y);
pc110pad_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH);
input_abs_set_max(pc110pad_dev, ABS_X, 0x1ff);
input_abs_set_max(pc110pad_dev, ABS_Y, 0x0ff);
pc110pad_dev->open = pc110pad_open;
pc110pad_dev->close = pc110pad_close;
err = input_register_device(pc110pad_dev);
if (err)
goto err_free_dev;
return 0;
err_free_dev:
input_free_device(pc110pad_dev);
err_free_irq:
free_irq(pc110pad_irq, NULL);
err_release_region:
release_region(pc110pad_io, 4);
return err;
}
static void __exit pc110pad_exit(void)
{
outb(PC110PAD_OFF, pc110pad_io + 2);
free_irq(pc110pad_irq, NULL);
input_unregister_device(pc110pad_dev);
release_region(pc110pad_io, 4);
}
module_init(pc110pad_init);
module_exit(pc110pad_exit);
| gpl-2.0 |
DerArtem/android-tegra-2.6.36-hc-dev | arch/sparc/kernel/perf_event.c | 121 | 35015 | /* Performance event support for sparc64.
*
* Copyright (C) 2009, 2010 David S. Miller <davem@davemloft.net>
*
* This code is based almost entirely upon the x86 perf event
* code, which is:
*
* Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
* Copyright (C) 2008-2009 Red Hat, Inc., Ingo Molnar
* Copyright (C) 2009 Jaswinder Singh Rajput
* Copyright (C) 2009 Advanced Micro Devices, Inc., Robert Richter
* Copyright (C) 2008-2009 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
*/
#include <linux/perf_event.h>
#include <linux/kprobes.h>
#include <linux/ftrace.h>
#include <linux/kernel.h>
#include <linux/kdebug.h>
#include <linux/mutex.h>
#include <asm/stacktrace.h>
#include <asm/cpudata.h>
#include <asm/uaccess.h>
#include <asm/atomic.h>
#include <asm/nmi.h>
#include <asm/pcr.h>
#include "kstack.h"
/* Sparc64 chips have two performance counters, 32-bits each, with
* overflow interrupts generated on transition from 0xffffffff to 0.
* The counters are accessed in one go using a 64-bit register.
*
* Both counters are controlled using a single control register. The
* only way to stop all sampling is to clear all of the context (user,
* supervisor, hypervisor) sampling enable bits. But these bits apply
* to both counters, thus the two counters can't be enabled/disabled
* individually.
*
* The control register has two event fields, one for each of the two
* counters. It's thus nearly impossible to have one counter going
* while keeping the other one stopped. Therefore it is possible to
* get overflow interrupts for counters not currently "in use" and
* that condition must be checked in the overflow interrupt handler.
*
* So we use a hack, in that we program inactive counters with the
* "sw_count0" and "sw_count1" events. These count how many times
* the instruction "sethi %hi(0xfc000), %g0" is executed. It's an
* unusual way to encode a NOP and therefore will not trigger in
* normal code.
*/
#define MAX_HWEVENTS 2
#define MAX_PERIOD ((1UL << 32) - 1)
#define PIC_UPPER_INDEX 0
#define PIC_LOWER_INDEX 1
#define PIC_NO_INDEX -1
struct cpu_hw_events {
/* Number of events currently scheduled onto this cpu.
* This tells how many entries in the arrays below
* are valid.
*/
int n_events;
/* Number of new events added since the last hw_perf_disable().
* This works because the perf event layer always adds new
* events inside of a perf_{disable,enable}() sequence.
*/
int n_added;
/* Array of events current scheduled on this cpu. */
struct perf_event *event[MAX_HWEVENTS];
/* Array of encoded longs, specifying the %pcr register
* encoding and the mask of PIC counters this even can
* be scheduled on. See perf_event_encode() et al.
*/
unsigned long events[MAX_HWEVENTS];
/* The current counter index assigned to an event. When the
* event hasn't been programmed into the cpu yet, this will
* hold PIC_NO_INDEX. The event->hw.idx value tells us where
* we ought to schedule the event.
*/
int current_idx[MAX_HWEVENTS];
/* Software copy of %pcr register on this cpu. */
u64 pcr;
/* Enabled/disable state. */
int enabled;
unsigned int group_flag;
};
DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events) = { .enabled = 1, };
/* An event map describes the characteristics of a performance
* counter event. In particular it gives the encoding as well as
* a mask telling which counters the event can be measured on.
*/
struct perf_event_map {
u16 encoding;
u8 pic_mask;
#define PIC_NONE 0x00
#define PIC_UPPER 0x01
#define PIC_LOWER 0x02
};
/* Encode a perf_event_map entry into a long. */
static unsigned long perf_event_encode(const struct perf_event_map *pmap)
{
return ((unsigned long) pmap->encoding << 16) | pmap->pic_mask;
}
static u8 perf_event_get_msk(unsigned long val)
{
return val & 0xff;
}
static u64 perf_event_get_enc(unsigned long val)
{
return val >> 16;
}
#define C(x) PERF_COUNT_HW_CACHE_##x
#define CACHE_OP_UNSUPPORTED 0xfffe
#define CACHE_OP_NONSENSE 0xffff
typedef struct perf_event_map cache_map_t
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX];
struct sparc_pmu {
const struct perf_event_map *(*event_map)(int);
const cache_map_t *cache_map;
int max_events;
int upper_shift;
int lower_shift;
int event_mask;
int hv_bit;
int irq_bit;
int upper_nop;
int lower_nop;
};
static const struct perf_event_map ultra3_perfmon_event_map[] = {
[PERF_COUNT_HW_CPU_CYCLES] = { 0x0000, PIC_UPPER | PIC_LOWER },
[PERF_COUNT_HW_INSTRUCTIONS] = { 0x0001, PIC_UPPER | PIC_LOWER },
[PERF_COUNT_HW_CACHE_REFERENCES] = { 0x0009, PIC_LOWER },
[PERF_COUNT_HW_CACHE_MISSES] = { 0x0009, PIC_UPPER },
};
static const struct perf_event_map *ultra3_event_map(int event_id)
{
return &ultra3_perfmon_event_map[event_id];
}
static const cache_map_t ultra3_cache_map = {
[C(L1D)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x09, PIC_LOWER, },
[C(RESULT_MISS)] = { 0x09, PIC_UPPER, },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x0a, PIC_LOWER },
[C(RESULT_MISS)] = { 0x0a, PIC_UPPER },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
},
[C(L1I)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x09, PIC_LOWER, },
[C(RESULT_MISS)] = { 0x09, PIC_UPPER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_NONSENSE },
[ C(RESULT_MISS) ] = { CACHE_OP_NONSENSE },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(LL)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x0c, PIC_LOWER, },
[C(RESULT_MISS)] = { 0x0c, PIC_UPPER, },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x0c, PIC_LOWER },
[C(RESULT_MISS)] = { 0x0c, PIC_UPPER },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
},
[C(DTLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x12, PIC_UPPER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(ITLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x11, PIC_UPPER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(BPU)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
};
static const struct sparc_pmu ultra3_pmu = {
.event_map = ultra3_event_map,
.cache_map = &ultra3_cache_map,
.max_events = ARRAY_SIZE(ultra3_perfmon_event_map),
.upper_shift = 11,
.lower_shift = 4,
.event_mask = 0x3f,
.upper_nop = 0x1c,
.lower_nop = 0x14,
};
/* Niagara1 is very limited. The upper PIC is hard-locked to count
* only instructions, so it is free running which creates all kinds of
* problems. Some hardware designs make one wonder if the creator
* even looked at how this stuff gets used by software.
*/
static const struct perf_event_map niagara1_perfmon_event_map[] = {
[PERF_COUNT_HW_CPU_CYCLES] = { 0x00, PIC_UPPER },
[PERF_COUNT_HW_INSTRUCTIONS] = { 0x00, PIC_UPPER },
[PERF_COUNT_HW_CACHE_REFERENCES] = { 0, PIC_NONE },
[PERF_COUNT_HW_CACHE_MISSES] = { 0x03, PIC_LOWER },
};
static const struct perf_event_map *niagara1_event_map(int event_id)
{
return &niagara1_perfmon_event_map[event_id];
}
static const cache_map_t niagara1_cache_map = {
[C(L1D)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x03, PIC_LOWER, },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x03, PIC_LOWER, },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
},
[C(L1I)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x00, PIC_UPPER },
[C(RESULT_MISS)] = { 0x02, PIC_LOWER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_NONSENSE },
[ C(RESULT_MISS) ] = { CACHE_OP_NONSENSE },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(LL)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x07, PIC_LOWER, },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x07, PIC_LOWER, },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
},
[C(DTLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x05, PIC_LOWER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(ITLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x04, PIC_LOWER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(BPU)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
};
static const struct sparc_pmu niagara1_pmu = {
.event_map = niagara1_event_map,
.cache_map = &niagara1_cache_map,
.max_events = ARRAY_SIZE(niagara1_perfmon_event_map),
.upper_shift = 0,
.lower_shift = 4,
.event_mask = 0x7,
.upper_nop = 0x0,
.lower_nop = 0x0,
};
static const struct perf_event_map niagara2_perfmon_event_map[] = {
[PERF_COUNT_HW_CPU_CYCLES] = { 0x02ff, PIC_UPPER | PIC_LOWER },
[PERF_COUNT_HW_INSTRUCTIONS] = { 0x02ff, PIC_UPPER | PIC_LOWER },
[PERF_COUNT_HW_CACHE_REFERENCES] = { 0x0208, PIC_UPPER | PIC_LOWER },
[PERF_COUNT_HW_CACHE_MISSES] = { 0x0302, PIC_UPPER | PIC_LOWER },
[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = { 0x0201, PIC_UPPER | PIC_LOWER },
[PERF_COUNT_HW_BRANCH_MISSES] = { 0x0202, PIC_UPPER | PIC_LOWER },
};
static const struct perf_event_map *niagara2_event_map(int event_id)
{
return &niagara2_perfmon_event_map[event_id];
}
static const cache_map_t niagara2_cache_map = {
[C(L1D)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x0208, PIC_UPPER | PIC_LOWER, },
[C(RESULT_MISS)] = { 0x0302, PIC_UPPER | PIC_LOWER, },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x0210, PIC_UPPER | PIC_LOWER, },
[C(RESULT_MISS)] = { 0x0302, PIC_UPPER | PIC_LOWER, },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
},
[C(L1I)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x02ff, PIC_UPPER | PIC_LOWER, },
[C(RESULT_MISS)] = { 0x0301, PIC_UPPER | PIC_LOWER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_NONSENSE },
[ C(RESULT_MISS) ] = { CACHE_OP_NONSENSE },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(LL)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x0208, PIC_UPPER | PIC_LOWER, },
[C(RESULT_MISS)] = { 0x0330, PIC_UPPER | PIC_LOWER, },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x0210, PIC_UPPER | PIC_LOWER, },
[C(RESULT_MISS)] = { 0x0320, PIC_UPPER | PIC_LOWER, },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
},
[C(DTLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x0b08, PIC_UPPER | PIC_LOWER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(ITLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0xb04, PIC_UPPER | PIC_LOWER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(BPU)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
};
static const struct sparc_pmu niagara2_pmu = {
.event_map = niagara2_event_map,
.cache_map = &niagara2_cache_map,
.max_events = ARRAY_SIZE(niagara2_perfmon_event_map),
.upper_shift = 19,
.lower_shift = 6,
.event_mask = 0xfff,
.hv_bit = 0x8,
.irq_bit = 0x30,
.upper_nop = 0x220,
.lower_nop = 0x220,
};
static const struct sparc_pmu *sparc_pmu __read_mostly;
static u64 event_encoding(u64 event_id, int idx)
{
if (idx == PIC_UPPER_INDEX)
event_id <<= sparc_pmu->upper_shift;
else
event_id <<= sparc_pmu->lower_shift;
return event_id;
}
static u64 mask_for_index(int idx)
{
return event_encoding(sparc_pmu->event_mask, idx);
}
static u64 nop_for_index(int idx)
{
return event_encoding(idx == PIC_UPPER_INDEX ?
sparc_pmu->upper_nop :
sparc_pmu->lower_nop, idx);
}
static inline void sparc_pmu_enable_event(struct cpu_hw_events *cpuc, struct hw_perf_event *hwc, int idx)
{
u64 val, mask = mask_for_index(idx);
val = cpuc->pcr;
val &= ~mask;
val |= hwc->config;
cpuc->pcr = val;
pcr_ops->write(cpuc->pcr);
}
static inline void sparc_pmu_disable_event(struct cpu_hw_events *cpuc, struct hw_perf_event *hwc, int idx)
{
u64 mask = mask_for_index(idx);
u64 nop = nop_for_index(idx);
u64 val;
val = cpuc->pcr;
val &= ~mask;
val |= nop;
cpuc->pcr = val;
pcr_ops->write(cpuc->pcr);
}
static u32 read_pmc(int idx)
{
u64 val;
read_pic(val);
if (idx == PIC_UPPER_INDEX)
val >>= 32;
return val & 0xffffffff;
}
static void write_pmc(int idx, u64 val)
{
u64 shift, mask, pic;
shift = 0;
if (idx == PIC_UPPER_INDEX)
shift = 32;
mask = ((u64) 0xffffffff) << shift;
val <<= shift;
read_pic(pic);
pic &= ~mask;
pic |= val;
write_pic(pic);
}
static u64 sparc_perf_event_update(struct perf_event *event,
struct hw_perf_event *hwc, int idx)
{
int shift = 64 - 32;
u64 prev_raw_count, new_raw_count;
s64 delta;
again:
prev_raw_count = local64_read(&hwc->prev_count);
new_raw_count = read_pmc(idx);
if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
new_raw_count) != prev_raw_count)
goto again;
delta = (new_raw_count << shift) - (prev_raw_count << shift);
delta >>= shift;
local64_add(delta, &event->count);
local64_sub(delta, &hwc->period_left);
return new_raw_count;
}
static int sparc_perf_event_set_period(struct perf_event *event,
struct hw_perf_event *hwc, int idx)
{
s64 left = local64_read(&hwc->period_left);
s64 period = hwc->sample_period;
int ret = 0;
if (unlikely(left <= -period)) {
left = period;
local64_set(&hwc->period_left, left);
hwc->last_period = period;
ret = 1;
}
if (unlikely(left <= 0)) {
left += period;
local64_set(&hwc->period_left, left);
hwc->last_period = period;
ret = 1;
}
if (left > MAX_PERIOD)
left = MAX_PERIOD;
local64_set(&hwc->prev_count, (u64)-left);
write_pmc(idx, (u64)(-left) & 0xffffffff);
perf_event_update_userpage(event);
return ret;
}
/* If performance event entries have been added, move existing
* events around (if necessary) and then assign new entries to
* counters.
*/
static u64 maybe_change_configuration(struct cpu_hw_events *cpuc, u64 pcr)
{
int i;
if (!cpuc->n_added)
goto out;
/* Read in the counters which are moving. */
for (i = 0; i < cpuc->n_events; i++) {
struct perf_event *cp = cpuc->event[i];
if (cpuc->current_idx[i] != PIC_NO_INDEX &&
cpuc->current_idx[i] != cp->hw.idx) {
sparc_perf_event_update(cp, &cp->hw,
cpuc->current_idx[i]);
cpuc->current_idx[i] = PIC_NO_INDEX;
}
}
/* Assign to counters all unassigned events. */
for (i = 0; i < cpuc->n_events; i++) {
struct perf_event *cp = cpuc->event[i];
struct hw_perf_event *hwc = &cp->hw;
int idx = hwc->idx;
u64 enc;
if (cpuc->current_idx[i] != PIC_NO_INDEX)
continue;
sparc_perf_event_set_period(cp, hwc, idx);
cpuc->current_idx[i] = idx;
enc = perf_event_get_enc(cpuc->events[i]);
pcr &= ~mask_for_index(idx);
pcr |= event_encoding(enc, idx);
}
out:
return pcr;
}
void hw_perf_enable(void)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
u64 pcr;
if (cpuc->enabled)
return;
cpuc->enabled = 1;
barrier();
pcr = cpuc->pcr;
if (!cpuc->n_events) {
pcr = 0;
} else {
pcr = maybe_change_configuration(cpuc, pcr);
/* We require that all of the events have the same
* configuration, so just fetch the settings from the
* first entry.
*/
cpuc->pcr = pcr | cpuc->event[0]->hw.config_base;
}
pcr_ops->write(cpuc->pcr);
}
void hw_perf_disable(void)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
u64 val;
if (!cpuc->enabled)
return;
cpuc->enabled = 0;
cpuc->n_added = 0;
val = cpuc->pcr;
val &= ~(PCR_UTRACE | PCR_STRACE |
sparc_pmu->hv_bit | sparc_pmu->irq_bit);
cpuc->pcr = val;
pcr_ops->write(cpuc->pcr);
}
static void sparc_pmu_disable(struct perf_event *event)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct hw_perf_event *hwc = &event->hw;
unsigned long flags;
int i;
local_irq_save(flags);
perf_disable();
for (i = 0; i < cpuc->n_events; i++) {
if (event == cpuc->event[i]) {
int idx = cpuc->current_idx[i];
/* Shift remaining entries down into
* the existing slot.
*/
while (++i < cpuc->n_events) {
cpuc->event[i - 1] = cpuc->event[i];
cpuc->events[i - 1] = cpuc->events[i];
cpuc->current_idx[i - 1] =
cpuc->current_idx[i];
}
/* Absorb the final count and turn off the
* event.
*/
sparc_pmu_disable_event(cpuc, hwc, idx);
barrier();
sparc_perf_event_update(event, hwc, idx);
perf_event_update_userpage(event);
cpuc->n_events--;
break;
}
}
perf_enable();
local_irq_restore(flags);
}
static int active_event_index(struct cpu_hw_events *cpuc,
struct perf_event *event)
{
int i;
for (i = 0; i < cpuc->n_events; i++) {
if (cpuc->event[i] == event)
break;
}
BUG_ON(i == cpuc->n_events);
return cpuc->current_idx[i];
}
static void sparc_pmu_read(struct perf_event *event)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
int idx = active_event_index(cpuc, event);
struct hw_perf_event *hwc = &event->hw;
sparc_perf_event_update(event, hwc, idx);
}
static void sparc_pmu_unthrottle(struct perf_event *event)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
int idx = active_event_index(cpuc, event);
struct hw_perf_event *hwc = &event->hw;
sparc_pmu_enable_event(cpuc, hwc, idx);
}
static atomic_t active_events = ATOMIC_INIT(0);
static DEFINE_MUTEX(pmc_grab_mutex);
static void perf_stop_nmi_watchdog(void *unused)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
stop_nmi_watchdog(NULL);
cpuc->pcr = pcr_ops->read();
}
void perf_event_grab_pmc(void)
{
if (atomic_inc_not_zero(&active_events))
return;
mutex_lock(&pmc_grab_mutex);
if (atomic_read(&active_events) == 0) {
if (atomic_read(&nmi_active) > 0) {
on_each_cpu(perf_stop_nmi_watchdog, NULL, 1);
BUG_ON(atomic_read(&nmi_active) != 0);
}
atomic_inc(&active_events);
}
mutex_unlock(&pmc_grab_mutex);
}
void perf_event_release_pmc(void)
{
if (atomic_dec_and_mutex_lock(&active_events, &pmc_grab_mutex)) {
if (atomic_read(&nmi_active) == 0)
on_each_cpu(start_nmi_watchdog, NULL, 1);
mutex_unlock(&pmc_grab_mutex);
}
}
static const struct perf_event_map *sparc_map_cache_event(u64 config)
{
unsigned int cache_type, cache_op, cache_result;
const struct perf_event_map *pmap;
if (!sparc_pmu->cache_map)
return ERR_PTR(-ENOENT);
cache_type = (config >> 0) & 0xff;
if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
return ERR_PTR(-EINVAL);
cache_op = (config >> 8) & 0xff;
if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
return ERR_PTR(-EINVAL);
cache_result = (config >> 16) & 0xff;
if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
return ERR_PTR(-EINVAL);
pmap = &((*sparc_pmu->cache_map)[cache_type][cache_op][cache_result]);
if (pmap->encoding == CACHE_OP_UNSUPPORTED)
return ERR_PTR(-ENOENT);
if (pmap->encoding == CACHE_OP_NONSENSE)
return ERR_PTR(-EINVAL);
return pmap;
}
static void hw_perf_event_destroy(struct perf_event *event)
{
perf_event_release_pmc();
}
/* Make sure all events can be scheduled into the hardware at
* the same time. This is simplified by the fact that we only
* need to support 2 simultaneous HW events.
*
* As a side effect, the evts[]->hw.idx values will be assigned
* on success. These are pending indexes. When the events are
* actually programmed into the chip, these values will propagate
* to the per-cpu cpuc->current_idx[] slots, see the code in
* maybe_change_configuration() for details.
*/
static int sparc_check_constraints(struct perf_event **evts,
unsigned long *events, int n_ev)
{
u8 msk0 = 0, msk1 = 0;
int idx0 = 0;
/* This case is possible when we are invoked from
* hw_perf_group_sched_in().
*/
if (!n_ev)
return 0;
if (n_ev > perf_max_events)
return -1;
msk0 = perf_event_get_msk(events[0]);
if (n_ev == 1) {
if (msk0 & PIC_LOWER)
idx0 = 1;
goto success;
}
BUG_ON(n_ev != 2);
msk1 = perf_event_get_msk(events[1]);
/* If both events can go on any counter, OK. */
if (msk0 == (PIC_UPPER | PIC_LOWER) &&
msk1 == (PIC_UPPER | PIC_LOWER))
goto success;
/* If one event is limited to a specific counter,
* and the other can go on both, OK.
*/
if ((msk0 == PIC_UPPER || msk0 == PIC_LOWER) &&
msk1 == (PIC_UPPER | PIC_LOWER)) {
if (msk0 & PIC_LOWER)
idx0 = 1;
goto success;
}
if ((msk1 == PIC_UPPER || msk1 == PIC_LOWER) &&
msk0 == (PIC_UPPER | PIC_LOWER)) {
if (msk1 & PIC_UPPER)
idx0 = 1;
goto success;
}
/* If the events are fixed to different counters, OK. */
if ((msk0 == PIC_UPPER && msk1 == PIC_LOWER) ||
(msk0 == PIC_LOWER && msk1 == PIC_UPPER)) {
if (msk0 & PIC_LOWER)
idx0 = 1;
goto success;
}
/* Otherwise, there is a conflict. */
return -1;
success:
evts[0]->hw.idx = idx0;
if (n_ev == 2)
evts[1]->hw.idx = idx0 ^ 1;
return 0;
}
static int check_excludes(struct perf_event **evts, int n_prev, int n_new)
{
int eu = 0, ek = 0, eh = 0;
struct perf_event *event;
int i, n, first;
n = n_prev + n_new;
if (n <= 1)
return 0;
first = 1;
for (i = 0; i < n; i++) {
event = evts[i];
if (first) {
eu = event->attr.exclude_user;
ek = event->attr.exclude_kernel;
eh = event->attr.exclude_hv;
first = 0;
} else if (event->attr.exclude_user != eu ||
event->attr.exclude_kernel != ek ||
event->attr.exclude_hv != eh) {
return -EAGAIN;
}
}
return 0;
}
static int collect_events(struct perf_event *group, int max_count,
struct perf_event *evts[], unsigned long *events,
int *current_idx)
{
struct perf_event *event;
int n = 0;
if (!is_software_event(group)) {
if (n >= max_count)
return -1;
evts[n] = group;
events[n] = group->hw.event_base;
current_idx[n++] = PIC_NO_INDEX;
}
list_for_each_entry(event, &group->sibling_list, group_entry) {
if (!is_software_event(event) &&
event->state != PERF_EVENT_STATE_OFF) {
if (n >= max_count)
return -1;
evts[n] = event;
events[n] = event->hw.event_base;
current_idx[n++] = PIC_NO_INDEX;
}
}
return n;
}
static int sparc_pmu_enable(struct perf_event *event)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
int n0, ret = -EAGAIN;
unsigned long flags;
local_irq_save(flags);
perf_disable();
n0 = cpuc->n_events;
if (n0 >= perf_max_events)
goto out;
cpuc->event[n0] = event;
cpuc->events[n0] = event->hw.event_base;
cpuc->current_idx[n0] = PIC_NO_INDEX;
/*
* If group events scheduling transaction was started,
* skip the schedulability test here, it will be peformed
* at commit time(->commit_txn) as a whole
*/
if (cpuc->group_flag & PERF_EVENT_TXN)
goto nocheck;
if (check_excludes(cpuc->event, n0, 1))
goto out;
if (sparc_check_constraints(cpuc->event, cpuc->events, n0 + 1))
goto out;
nocheck:
cpuc->n_events++;
cpuc->n_added++;
ret = 0;
out:
perf_enable();
local_irq_restore(flags);
return ret;
}
static int __hw_perf_event_init(struct perf_event *event)
{
struct perf_event_attr *attr = &event->attr;
struct perf_event *evts[MAX_HWEVENTS];
struct hw_perf_event *hwc = &event->hw;
unsigned long events[MAX_HWEVENTS];
int current_idx_dmy[MAX_HWEVENTS];
const struct perf_event_map *pmap;
int n;
if (atomic_read(&nmi_active) < 0)
return -ENODEV;
pmap = NULL;
if (attr->type == PERF_TYPE_HARDWARE) {
if (attr->config >= sparc_pmu->max_events)
return -EINVAL;
pmap = sparc_pmu->event_map(attr->config);
} else if (attr->type == PERF_TYPE_HW_CACHE) {
pmap = sparc_map_cache_event(attr->config);
if (IS_ERR(pmap))
return PTR_ERR(pmap);
} else if (attr->type != PERF_TYPE_RAW)
return -EOPNOTSUPP;
if (pmap) {
hwc->event_base = perf_event_encode(pmap);
} else {
/* User gives us "(encoding << 16) | pic_mask" for
* PERF_TYPE_RAW events.
*/
hwc->event_base = attr->config;
}
/* We save the enable bits in the config_base. */
hwc->config_base = sparc_pmu->irq_bit;
if (!attr->exclude_user)
hwc->config_base |= PCR_UTRACE;
if (!attr->exclude_kernel)
hwc->config_base |= PCR_STRACE;
if (!attr->exclude_hv)
hwc->config_base |= sparc_pmu->hv_bit;
n = 0;
if (event->group_leader != event) {
n = collect_events(event->group_leader,
perf_max_events - 1,
evts, events, current_idx_dmy);
if (n < 0)
return -EINVAL;
}
events[n] = hwc->event_base;
evts[n] = event;
if (check_excludes(evts, n, 1))
return -EINVAL;
if (sparc_check_constraints(evts, events, n + 1))
return -EINVAL;
hwc->idx = PIC_NO_INDEX;
/* Try to do all error checking before this point, as unwinding
* state after grabbing the PMC is difficult.
*/
perf_event_grab_pmc();
event->destroy = hw_perf_event_destroy;
if (!hwc->sample_period) {
hwc->sample_period = MAX_PERIOD;
hwc->last_period = hwc->sample_period;
local64_set(&hwc->period_left, hwc->sample_period);
}
return 0;
}
/*
* Start group events scheduling transaction
* Set the flag to make pmu::enable() not perform the
* schedulability test, it will be performed at commit time
*/
static void sparc_pmu_start_txn(const struct pmu *pmu)
{
struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events);
cpuhw->group_flag |= PERF_EVENT_TXN;
}
/*
* Stop group events scheduling transaction
* Clear the flag and pmu::enable() will perform the
* schedulability test.
*/
static void sparc_pmu_cancel_txn(const struct pmu *pmu)
{
struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events);
cpuhw->group_flag &= ~PERF_EVENT_TXN;
}
/*
* Commit group events scheduling transaction
* Perform the group schedulability test as a whole
* Return 0 if success
*/
static int sparc_pmu_commit_txn(const struct pmu *pmu)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
int n;
if (!sparc_pmu)
return -EINVAL;
cpuc = &__get_cpu_var(cpu_hw_events);
n = cpuc->n_events;
if (check_excludes(cpuc->event, 0, n))
return -EINVAL;
if (sparc_check_constraints(cpuc->event, cpuc->events, n))
return -EAGAIN;
cpuc->group_flag &= ~PERF_EVENT_TXN;
return 0;
}
static const struct pmu pmu = {
.enable = sparc_pmu_enable,
.disable = sparc_pmu_disable,
.read = sparc_pmu_read,
.unthrottle = sparc_pmu_unthrottle,
.start_txn = sparc_pmu_start_txn,
.cancel_txn = sparc_pmu_cancel_txn,
.commit_txn = sparc_pmu_commit_txn,
};
const struct pmu *hw_perf_event_init(struct perf_event *event)
{
int err = __hw_perf_event_init(event);
if (err)
return ERR_PTR(err);
return &pmu;
}
void perf_event_print_debug(void)
{
unsigned long flags;
u64 pcr, pic;
int cpu;
if (!sparc_pmu)
return;
local_irq_save(flags);
cpu = smp_processor_id();
pcr = pcr_ops->read();
read_pic(pic);
pr_info("\n");
pr_info("CPU#%d: PCR[%016llx] PIC[%016llx]\n",
cpu, pcr, pic);
local_irq_restore(flags);
}
static int __kprobes perf_event_nmi_handler(struct notifier_block *self,
unsigned long cmd, void *__args)
{
struct die_args *args = __args;
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
struct pt_regs *regs;
int i;
if (!atomic_read(&active_events))
return NOTIFY_DONE;
switch (cmd) {
case DIE_NMI:
break;
default:
return NOTIFY_DONE;
}
regs = args->regs;
perf_sample_data_init(&data, 0);
cpuc = &__get_cpu_var(cpu_hw_events);
/* If the PMU has the TOE IRQ enable bits, we need to do a
* dummy write to the %pcr to clear the overflow bits and thus
* the interrupt.
*
* Do this before we peek at the counters to determine
* overflow so we don't lose any events.
*/
if (sparc_pmu->irq_bit)
pcr_ops->write(cpuc->pcr);
for (i = 0; i < cpuc->n_events; i++) {
struct perf_event *event = cpuc->event[i];
int idx = cpuc->current_idx[i];
struct hw_perf_event *hwc;
u64 val;
hwc = &event->hw;
val = sparc_perf_event_update(event, hwc, idx);
if (val & (1ULL << 31))
continue;
data.period = event->hw.last_period;
if (!sparc_perf_event_set_period(event, hwc, idx))
continue;
if (perf_event_overflow(event, 1, &data, regs))
sparc_pmu_disable_event(cpuc, hwc, idx);
}
return NOTIFY_STOP;
}
static __read_mostly struct notifier_block perf_event_nmi_notifier = {
.notifier_call = perf_event_nmi_handler,
};
static bool __init supported_pmu(void)
{
if (!strcmp(sparc_pmu_type, "ultra3") ||
!strcmp(sparc_pmu_type, "ultra3+") ||
!strcmp(sparc_pmu_type, "ultra3i") ||
!strcmp(sparc_pmu_type, "ultra4+")) {
sparc_pmu = &ultra3_pmu;
return true;
}
if (!strcmp(sparc_pmu_type, "niagara")) {
sparc_pmu = &niagara1_pmu;
return true;
}
if (!strcmp(sparc_pmu_type, "niagara2")) {
sparc_pmu = &niagara2_pmu;
return true;
}
return false;
}
void __init init_hw_perf_events(void)
{
pr_info("Performance events: ");
if (!supported_pmu()) {
pr_cont("No support for PMU type '%s'\n", sparc_pmu_type);
return;
}
pr_cont("Supported PMU type is '%s'\n", sparc_pmu_type);
/* All sparc64 PMUs currently have 2 events. */
perf_max_events = 2;
register_die_notifier(&perf_event_nmi_notifier);
}
static inline void callchain_store(struct perf_callchain_entry *entry, u64 ip)
{
if (entry->nr < PERF_MAX_STACK_DEPTH)
entry->ip[entry->nr++] = ip;
}
static void perf_callchain_kernel(struct pt_regs *regs,
struct perf_callchain_entry *entry)
{
unsigned long ksp, fp;
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
int graph = 0;
#endif
callchain_store(entry, PERF_CONTEXT_KERNEL);
callchain_store(entry, regs->tpc);
ksp = regs->u_regs[UREG_I6];
fp = ksp + STACK_BIAS;
do {
struct sparc_stackf *sf;
struct pt_regs *regs;
unsigned long pc;
if (!kstack_valid(current_thread_info(), fp))
break;
sf = (struct sparc_stackf *) fp;
regs = (struct pt_regs *) (sf + 1);
if (kstack_is_trap_frame(current_thread_info(), regs)) {
if (user_mode(regs))
break;
pc = regs->tpc;
fp = regs->u_regs[UREG_I6] + STACK_BIAS;
} else {
pc = sf->callers_pc;
fp = (unsigned long)sf->fp + STACK_BIAS;
}
callchain_store(entry, pc);
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
if ((pc + 8UL) == (unsigned long) &return_to_handler) {
int index = current->curr_ret_stack;
if (current->ret_stack && index >= graph) {
pc = current->ret_stack[index - graph].ret;
callchain_store(entry, pc);
graph++;
}
}
#endif
} while (entry->nr < PERF_MAX_STACK_DEPTH);
}
static void perf_callchain_user_64(struct pt_regs *regs,
struct perf_callchain_entry *entry)
{
unsigned long ufp;
callchain_store(entry, PERF_CONTEXT_USER);
callchain_store(entry, regs->tpc);
ufp = regs->u_regs[UREG_I6] + STACK_BIAS;
do {
struct sparc_stackf *usf, sf;
unsigned long pc;
usf = (struct sparc_stackf *) ufp;
if (__copy_from_user_inatomic(&sf, usf, sizeof(sf)))
break;
pc = sf.callers_pc;
ufp = (unsigned long)sf.fp + STACK_BIAS;
callchain_store(entry, pc);
} while (entry->nr < PERF_MAX_STACK_DEPTH);
}
static void perf_callchain_user_32(struct pt_regs *regs,
struct perf_callchain_entry *entry)
{
unsigned long ufp;
callchain_store(entry, PERF_CONTEXT_USER);
callchain_store(entry, regs->tpc);
ufp = regs->u_regs[UREG_I6] & 0xffffffffUL;
do {
struct sparc_stackf32 *usf, sf;
unsigned long pc;
usf = (struct sparc_stackf32 *) ufp;
if (__copy_from_user_inatomic(&sf, usf, sizeof(sf)))
break;
pc = sf.callers_pc;
ufp = (unsigned long)sf.fp;
callchain_store(entry, pc);
} while (entry->nr < PERF_MAX_STACK_DEPTH);
}
/* Like powerpc we can't get PMU interrupts within the PMU handler,
* so no need for separate NMI and IRQ chains as on x86.
*/
static DEFINE_PER_CPU(struct perf_callchain_entry, callchain);
struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
{
struct perf_callchain_entry *entry = &__get_cpu_var(callchain);
entry->nr = 0;
if (!user_mode(regs)) {
stack_trace_flush();
perf_callchain_kernel(regs, entry);
if (current->mm)
regs = task_pt_regs(current);
else
regs = NULL;
}
if (regs) {
flushw_user();
if (test_thread_flag(TIF_32BIT))
perf_callchain_user_32(regs, entry);
else
perf_callchain_user_64(regs, entry);
}
return entry;
}
| gpl-2.0 |
sid1607/linux-3.14.65-src | drivers/i2c/busses/i2c-ismt.c | 121 | 28405 | /*
* This file is provided under a dual BSD/GPLv2 license. When using or
* redistributing this file, you may do so under either license.
*
* Copyright(c) 2012 Intel Corporation. All rights reserved.
*
* GPL LICENSE SUMMARY
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
* The full GNU General Public License is included in this distribution
* in the file called LICENSE.GPL.
*
* BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Supports the SMBus Message Transport (SMT) in the Intel Atom Processor
* S12xx Product Family.
*
* Features supported by this driver:
* Hardware PEC yes
* Block buffer yes
* Block process call transaction no
* Slave mode no
*/
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/stddef.h>
#include <linux/completion.h>
#include <linux/dma-mapping.h>
#include <linux/i2c.h>
#include <linux/acpi.h>
#include <linux/interrupt.h>
#include <asm-generic/io-64-nonatomic-lo-hi.h>
/* PCI Address Constants */
#define SMBBAR 0
/* PCI DIDs for the Intel SMBus Message Transport (SMT) Devices */
#define PCI_DEVICE_ID_INTEL_S1200_SMT0 0x0c59
#define PCI_DEVICE_ID_INTEL_S1200_SMT1 0x0c5a
#define PCI_DEVICE_ID_INTEL_AVOTON_SMT 0x1f15
#define ISMT_DESC_ENTRIES 32 /* number of descriptor entries */
#define ISMT_MAX_RETRIES 3 /* number of SMBus retries to attempt */
/* Hardware Descriptor Constants - Control Field */
#define ISMT_DESC_CWRL 0x01 /* Command/Write Length */
#define ISMT_DESC_BLK 0X04 /* Perform Block Transaction */
#define ISMT_DESC_FAIR 0x08 /* Set fairness flag upon successful arbit. */
#define ISMT_DESC_PEC 0x10 /* Packet Error Code */
#define ISMT_DESC_I2C 0x20 /* I2C Enable */
#define ISMT_DESC_INT 0x40 /* Interrupt */
#define ISMT_DESC_SOE 0x80 /* Stop On Error */
/* Hardware Descriptor Constants - Status Field */
#define ISMT_DESC_SCS 0x01 /* Success */
#define ISMT_DESC_DLTO 0x04 /* Data Low Time Out */
#define ISMT_DESC_NAK 0x08 /* NAK Received */
#define ISMT_DESC_CRC 0x10 /* CRC Error */
#define ISMT_DESC_CLTO 0x20 /* Clock Low Time Out */
#define ISMT_DESC_COL 0x40 /* Collisions */
#define ISMT_DESC_LPR 0x80 /* Large Packet Received */
/* Macros */
#define ISMT_DESC_ADDR_RW(addr, rw) (((addr) << 1) | (rw))
/* iSMT General Register address offsets (SMBBAR + <addr>) */
#define ISMT_GR_GCTRL 0x000 /* General Control */
#define ISMT_GR_SMTICL 0x008 /* SMT Interrupt Cause Location */
#define ISMT_GR_ERRINTMSK 0x010 /* Error Interrupt Mask */
#define ISMT_GR_ERRAERMSK 0x014 /* Error AER Mask */
#define ISMT_GR_ERRSTS 0x018 /* Error Status */
#define ISMT_GR_ERRINFO 0x01c /* Error Information */
/* iSMT Master Registers */
#define ISMT_MSTR_MDBA 0x100 /* Master Descriptor Base Address */
#define ISMT_MSTR_MCTRL 0x108 /* Master Control */
#define ISMT_MSTR_MSTS 0x10c /* Master Status */
#define ISMT_MSTR_MDS 0x110 /* Master Descriptor Size */
#define ISMT_MSTR_RPOLICY 0x114 /* Retry Policy */
/* iSMT Miscellaneous Registers */
#define ISMT_SPGT 0x300 /* SMBus PHY Global Timing */
/* General Control Register (GCTRL) bit definitions */
#define ISMT_GCTRL_TRST 0x04 /* Target Reset */
#define ISMT_GCTRL_KILL 0x08 /* Kill */
#define ISMT_GCTRL_SRST 0x40 /* Soft Reset */
/* Master Control Register (MCTRL) bit definitions */
#define ISMT_MCTRL_SS 0x01 /* Start/Stop */
#define ISMT_MCTRL_MEIE 0x10 /* Master Error Interrupt Enable */
#define ISMT_MCTRL_FMHP 0x00ff0000 /* Firmware Master Head Ptr (FMHP) */
/* Master Status Register (MSTS) bit definitions */
#define ISMT_MSTS_HMTP 0xff0000 /* HW Master Tail Pointer (HMTP) */
#define ISMT_MSTS_MIS 0x20 /* Master Interrupt Status (MIS) */
#define ISMT_MSTS_MEIS 0x10 /* Master Error Int Status (MEIS) */
#define ISMT_MSTS_IP 0x01 /* In Progress */
/* Master Descriptor Size (MDS) bit definitions */
#define ISMT_MDS_MASK 0xff /* Master Descriptor Size mask (MDS) */
/* SMBus PHY Global Timing Register (SPGT) bit definitions */
#define ISMT_SPGT_SPD_MASK 0xc0000000 /* SMBus Speed mask */
#define ISMT_SPGT_SPD_80K 0x00 /* 80 kHz */
#define ISMT_SPGT_SPD_100K (0x1 << 30) /* 100 kHz */
#define ISMT_SPGT_SPD_400K (0x2 << 30) /* 400 kHz */
#define ISMT_SPGT_SPD_1M (0x3 << 30) /* 1 MHz */
/* MSI Control Register (MSICTL) bit definitions */
#define ISMT_MSICTL_MSIE 0x01 /* MSI Enable */
/* iSMT Hardware Descriptor */
struct ismt_desc {
u8 tgtaddr_rw; /* target address & r/w bit */
u8 wr_len_cmd; /* write length in bytes or a command */
u8 rd_len; /* read length */
u8 control; /* control bits */
u8 status; /* status bits */
u8 retry; /* collision retry and retry count */
u8 rxbytes; /* received bytes */
u8 txbytes; /* transmitted bytes */
u32 dptr_low; /* lower 32 bit of the data pointer */
u32 dptr_high; /* upper 32 bit of the data pointer */
} __packed;
struct ismt_priv {
struct i2c_adapter adapter;
void *smba; /* PCI BAR */
struct pci_dev *pci_dev;
struct ismt_desc *hw; /* descriptor virt base addr */
dma_addr_t io_rng_dma; /* descriptor HW base addr */
u8 head; /* ring buffer head pointer */
struct completion cmp; /* interrupt completion */
u8 dma_buffer[I2C_SMBUS_BLOCK_MAX + 1]; /* temp R/W data buffer */
bool using_msi; /* type of interrupt flag */
};
/**
* ismt_ids - PCI device IDs supported by this driver
*/
static DEFINE_PCI_DEVICE_TABLE(ismt_ids) = {
{ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_S1200_SMT0) },
{ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_S1200_SMT1) },
{ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_AVOTON_SMT) },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, ismt_ids);
/* Bus speed control bits for slow debuggers - refer to the docs for usage */
static unsigned int bus_speed;
module_param(bus_speed, uint, S_IRUGO);
MODULE_PARM_DESC(bus_speed, "Bus Speed in kHz (0 = BIOS default)");
/**
* __ismt_desc_dump() - dump the contents of a specific descriptor
*/
static void __ismt_desc_dump(struct device *dev, const struct ismt_desc *desc)
{
dev_dbg(dev, "Descriptor struct: %p\n", desc);
dev_dbg(dev, "\ttgtaddr_rw=0x%02X\n", desc->tgtaddr_rw);
dev_dbg(dev, "\twr_len_cmd=0x%02X\n", desc->wr_len_cmd);
dev_dbg(dev, "\trd_len= 0x%02X\n", desc->rd_len);
dev_dbg(dev, "\tcontrol= 0x%02X\n", desc->control);
dev_dbg(dev, "\tstatus= 0x%02X\n", desc->status);
dev_dbg(dev, "\tretry= 0x%02X\n", desc->retry);
dev_dbg(dev, "\trxbytes= 0x%02X\n", desc->rxbytes);
dev_dbg(dev, "\ttxbytes= 0x%02X\n", desc->txbytes);
dev_dbg(dev, "\tdptr_low= 0x%08X\n", desc->dptr_low);
dev_dbg(dev, "\tdptr_high= 0x%08X\n", desc->dptr_high);
}
/**
* ismt_desc_dump() - dump the contents of a descriptor for debug purposes
* @priv: iSMT private data
*/
static void ismt_desc_dump(struct ismt_priv *priv)
{
struct device *dev = &priv->pci_dev->dev;
struct ismt_desc *desc = &priv->hw[priv->head];
dev_dbg(dev, "Dump of the descriptor struct: 0x%X\n", priv->head);
__ismt_desc_dump(dev, desc);
}
/**
* ismt_gen_reg_dump() - dump the iSMT General Registers
* @priv: iSMT private data
*/
static void ismt_gen_reg_dump(struct ismt_priv *priv)
{
struct device *dev = &priv->pci_dev->dev;
dev_dbg(dev, "Dump of the iSMT General Registers\n");
dev_dbg(dev, " GCTRL.... : (0x%p)=0x%X\n",
priv->smba + ISMT_GR_GCTRL,
readl(priv->smba + ISMT_GR_GCTRL));
dev_dbg(dev, " SMTICL... : (0x%p)=0x%016llX\n",
priv->smba + ISMT_GR_SMTICL,
(long long unsigned int)readq(priv->smba + ISMT_GR_SMTICL));
dev_dbg(dev, " ERRINTMSK : (0x%p)=0x%X\n",
priv->smba + ISMT_GR_ERRINTMSK,
readl(priv->smba + ISMT_GR_ERRINTMSK));
dev_dbg(dev, " ERRAERMSK : (0x%p)=0x%X\n",
priv->smba + ISMT_GR_ERRAERMSK,
readl(priv->smba + ISMT_GR_ERRAERMSK));
dev_dbg(dev, " ERRSTS... : (0x%p)=0x%X\n",
priv->smba + ISMT_GR_ERRSTS,
readl(priv->smba + ISMT_GR_ERRSTS));
dev_dbg(dev, " ERRINFO.. : (0x%p)=0x%X\n",
priv->smba + ISMT_GR_ERRINFO,
readl(priv->smba + ISMT_GR_ERRINFO));
}
/**
* ismt_mstr_reg_dump() - dump the iSMT Master Registers
* @priv: iSMT private data
*/
static void ismt_mstr_reg_dump(struct ismt_priv *priv)
{
struct device *dev = &priv->pci_dev->dev;
dev_dbg(dev, "Dump of the iSMT Master Registers\n");
dev_dbg(dev, " MDBA..... : (0x%p)=0x%016llX\n",
priv->smba + ISMT_MSTR_MDBA,
(long long unsigned int)readq(priv->smba + ISMT_MSTR_MDBA));
dev_dbg(dev, " MCTRL.... : (0x%p)=0x%X\n",
priv->smba + ISMT_MSTR_MCTRL,
readl(priv->smba + ISMT_MSTR_MCTRL));
dev_dbg(dev, " MSTS..... : (0x%p)=0x%X\n",
priv->smba + ISMT_MSTR_MSTS,
readl(priv->smba + ISMT_MSTR_MSTS));
dev_dbg(dev, " MDS...... : (0x%p)=0x%X\n",
priv->smba + ISMT_MSTR_MDS,
readl(priv->smba + ISMT_MSTR_MDS));
dev_dbg(dev, " RPOLICY.. : (0x%p)=0x%X\n",
priv->smba + ISMT_MSTR_RPOLICY,
readl(priv->smba + ISMT_MSTR_RPOLICY));
dev_dbg(dev, " SPGT..... : (0x%p)=0x%X\n",
priv->smba + ISMT_SPGT,
readl(priv->smba + ISMT_SPGT));
}
/**
* ismt_submit_desc() - add a descriptor to the ring
* @priv: iSMT private data
*/
static void ismt_submit_desc(struct ismt_priv *priv)
{
uint fmhp;
uint val;
ismt_desc_dump(priv);
ismt_gen_reg_dump(priv);
ismt_mstr_reg_dump(priv);
/* Set the FMHP (Firmware Master Head Pointer)*/
fmhp = ((priv->head + 1) % ISMT_DESC_ENTRIES) << 16;
val = readl(priv->smba + ISMT_MSTR_MCTRL);
writel((val & ~ISMT_MCTRL_FMHP) | fmhp,
priv->smba + ISMT_MSTR_MCTRL);
/* Set the start bit */
val = readl(priv->smba + ISMT_MSTR_MCTRL);
writel(val | ISMT_MCTRL_SS,
priv->smba + ISMT_MSTR_MCTRL);
}
/**
* ismt_process_desc() - handle the completion of the descriptor
* @desc: the iSMT hardware descriptor
* @data: data buffer from the upper layer
* @priv: ismt_priv struct holding our dma buffer
* @size: SMBus transaction type
* @read_write: flag to indicate if this is a read or write
*/
static int ismt_process_desc(const struct ismt_desc *desc,
union i2c_smbus_data *data,
struct ismt_priv *priv, int size,
char read_write)
{
u8 *dma_buffer = priv->dma_buffer;
dev_dbg(&priv->pci_dev->dev, "Processing completed descriptor\n");
__ismt_desc_dump(&priv->pci_dev->dev, desc);
if (desc->status & ISMT_DESC_SCS) {
if (read_write == I2C_SMBUS_WRITE &&
size != I2C_SMBUS_PROC_CALL)
return 0;
switch (size) {
case I2C_SMBUS_BYTE:
case I2C_SMBUS_BYTE_DATA:
data->byte = dma_buffer[0];
break;
case I2C_SMBUS_WORD_DATA:
case I2C_SMBUS_PROC_CALL:
data->word = dma_buffer[0] | (dma_buffer[1] << 8);
break;
case I2C_SMBUS_BLOCK_DATA:
case I2C_SMBUS_I2C_BLOCK_DATA:
memcpy(&data->block[1], dma_buffer, desc->rxbytes);
data->block[0] = desc->rxbytes;
break;
}
return 0;
}
if (likely(desc->status & ISMT_DESC_NAK))
return -ENXIO;
if (desc->status & ISMT_DESC_CRC)
return -EBADMSG;
if (desc->status & ISMT_DESC_COL)
return -EAGAIN;
if (desc->status & ISMT_DESC_LPR)
return -EPROTO;
if (desc->status & (ISMT_DESC_DLTO | ISMT_DESC_CLTO))
return -ETIMEDOUT;
return -EIO;
}
/**
* ismt_access() - process an SMBus command
* @adap: the i2c host adapter
* @addr: address of the i2c/SMBus target
* @flags: command options
* @read_write: read from or write to device
* @command: the i2c/SMBus command to issue
* @size: SMBus transaction type
* @data: read/write data buffer
*/
static int ismt_access(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write, u8 command,
int size, union i2c_smbus_data *data)
{
int ret;
dma_addr_t dma_addr = 0; /* address of the data buffer */
u8 dma_size = 0;
enum dma_data_direction dma_direction = 0;
struct ismt_desc *desc;
struct ismt_priv *priv = i2c_get_adapdata(adap);
struct device *dev = &priv->pci_dev->dev;
desc = &priv->hw[priv->head];
/* Initialize the DMA buffer */
memset(priv->dma_buffer, 0, sizeof(priv->dma_buffer));
/* Initialize the descriptor */
memset(desc, 0, sizeof(struct ismt_desc));
desc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, read_write);
/* Initialize common control bits */
if (likely(priv->using_msi))
desc->control = ISMT_DESC_INT | ISMT_DESC_FAIR;
else
desc->control = ISMT_DESC_FAIR;
if ((flags & I2C_CLIENT_PEC) && (size != I2C_SMBUS_QUICK)
&& (size != I2C_SMBUS_I2C_BLOCK_DATA))
desc->control |= ISMT_DESC_PEC;
switch (size) {
case I2C_SMBUS_QUICK:
dev_dbg(dev, "I2C_SMBUS_QUICK\n");
break;
case I2C_SMBUS_BYTE:
if (read_write == I2C_SMBUS_WRITE) {
/*
* Send Byte
* The command field contains the write data
*/
dev_dbg(dev, "I2C_SMBUS_BYTE: WRITE\n");
desc->control |= ISMT_DESC_CWRL;
desc->wr_len_cmd = command;
} else {
/* Receive Byte */
dev_dbg(dev, "I2C_SMBUS_BYTE: READ\n");
dma_size = 1;
dma_direction = DMA_FROM_DEVICE;
desc->rd_len = 1;
}
break;
case I2C_SMBUS_BYTE_DATA:
if (read_write == I2C_SMBUS_WRITE) {
/*
* Write Byte
* Command plus 1 data byte
*/
dev_dbg(dev, "I2C_SMBUS_BYTE_DATA: WRITE\n");
desc->wr_len_cmd = 2;
dma_size = 2;
dma_direction = DMA_TO_DEVICE;
priv->dma_buffer[0] = command;
priv->dma_buffer[1] = data->byte;
} else {
/* Read Byte */
dev_dbg(dev, "I2C_SMBUS_BYTE_DATA: READ\n");
desc->control |= ISMT_DESC_CWRL;
desc->wr_len_cmd = command;
desc->rd_len = 1;
dma_size = 1;
dma_direction = DMA_FROM_DEVICE;
}
break;
case I2C_SMBUS_WORD_DATA:
if (read_write == I2C_SMBUS_WRITE) {
/* Write Word */
dev_dbg(dev, "I2C_SMBUS_WORD_DATA: WRITE\n");
desc->wr_len_cmd = 3;
dma_size = 3;
dma_direction = DMA_TO_DEVICE;
priv->dma_buffer[0] = command;
priv->dma_buffer[1] = data->word & 0xff;
priv->dma_buffer[2] = data->word >> 8;
} else {
/* Read Word */
dev_dbg(dev, "I2C_SMBUS_WORD_DATA: READ\n");
desc->wr_len_cmd = command;
desc->control |= ISMT_DESC_CWRL;
desc->rd_len = 2;
dma_size = 2;
dma_direction = DMA_FROM_DEVICE;
}
break;
case I2C_SMBUS_PROC_CALL:
dev_dbg(dev, "I2C_SMBUS_PROC_CALL\n");
desc->wr_len_cmd = 3;
desc->rd_len = 2;
dma_size = 3;
dma_direction = DMA_BIDIRECTIONAL;
priv->dma_buffer[0] = command;
priv->dma_buffer[1] = data->word & 0xff;
priv->dma_buffer[2] = data->word >> 8;
break;
case I2C_SMBUS_BLOCK_DATA:
if (read_write == I2C_SMBUS_WRITE) {
/* Block Write */
dev_dbg(dev, "I2C_SMBUS_BLOCK_DATA: WRITE\n");
dma_size = data->block[0] + 1;
dma_direction = DMA_TO_DEVICE;
desc->wr_len_cmd = dma_size;
desc->control |= ISMT_DESC_BLK;
priv->dma_buffer[0] = command;
memcpy(&priv->dma_buffer[1], &data->block[1], dma_size - 1);
} else {
/* Block Read */
dev_dbg(dev, "I2C_SMBUS_BLOCK_DATA: READ\n");
dma_size = I2C_SMBUS_BLOCK_MAX;
dma_direction = DMA_FROM_DEVICE;
desc->rd_len = dma_size;
desc->wr_len_cmd = command;
desc->control |= (ISMT_DESC_BLK | ISMT_DESC_CWRL);
}
break;
case I2C_SMBUS_I2C_BLOCK_DATA:
/* Make sure the length is valid */
if (data->block[0] < 1)
data->block[0] = 1;
if (data->block[0] > I2C_SMBUS_BLOCK_MAX)
data->block[0] = I2C_SMBUS_BLOCK_MAX;
if (read_write == I2C_SMBUS_WRITE) {
/* i2c Block Write */
dev_dbg(dev, "I2C_SMBUS_I2C_BLOCK_DATA: WRITE\n");
dma_size = data->block[0] + 1;
dma_direction = DMA_TO_DEVICE;
desc->wr_len_cmd = dma_size;
desc->control |= ISMT_DESC_I2C;
priv->dma_buffer[0] = command;
memcpy(&priv->dma_buffer[1], &data->block[1], dma_size - 1);
} else {
/* i2c Block Read */
dev_dbg(dev, "I2C_SMBUS_I2C_BLOCK_DATA: READ\n");
dma_size = data->block[0];
dma_direction = DMA_FROM_DEVICE;
desc->rd_len = dma_size;
desc->wr_len_cmd = command;
desc->control |= (ISMT_DESC_I2C | ISMT_DESC_CWRL);
/*
* Per the "Table 15-15. I2C Commands",
* in the External Design Specification (EDS),
* (Document Number: 508084, Revision: 2.0),
* the _rw bit must be 0
*/
desc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, 0);
}
break;
default:
dev_err(dev, "Unsupported transaction %d\n",
size);
return -EOPNOTSUPP;
}
/* map the data buffer */
if (dma_size != 0) {
dev_dbg(dev, " dev=%p\n", dev);
dev_dbg(dev, " data=%p\n", data);
dev_dbg(dev, " dma_buffer=%p\n", priv->dma_buffer);
dev_dbg(dev, " dma_size=%d\n", dma_size);
dev_dbg(dev, " dma_direction=%d\n", dma_direction);
dma_addr = dma_map_single(dev,
priv->dma_buffer,
dma_size,
dma_direction);
if (dma_mapping_error(dev, dma_addr)) {
dev_err(dev, "Error in mapping dma buffer %p\n",
priv->dma_buffer);
return -EIO;
}
dev_dbg(dev, " dma_addr = 0x%016llX\n",
(unsigned long long)dma_addr);
desc->dptr_low = lower_32_bits(dma_addr);
desc->dptr_high = upper_32_bits(dma_addr);
}
reinit_completion(&priv->cmp);
/* Add the descriptor */
ismt_submit_desc(priv);
/* Now we wait for interrupt completion, 1s */
ret = wait_for_completion_timeout(&priv->cmp, HZ*1);
/* unmap the data buffer */
if (dma_size != 0)
dma_unmap_single(&adap->dev, dma_addr, dma_size, dma_direction);
if (unlikely(!ret)) {
dev_err(dev, "completion wait timed out\n");
ret = -ETIMEDOUT;
goto out;
}
/* do any post processing of the descriptor here */
ret = ismt_process_desc(desc, data, priv, size, read_write);
out:
/* Update the ring pointer */
priv->head++;
priv->head %= ISMT_DESC_ENTRIES;
return ret;
}
/**
* ismt_func() - report which i2c commands are supported by this adapter
* @adap: the i2c host adapter
*/
static u32 ismt_func(struct i2c_adapter *adap)
{
return I2C_FUNC_SMBUS_QUICK |
I2C_FUNC_SMBUS_BYTE |
I2C_FUNC_SMBUS_BYTE_DATA |
I2C_FUNC_SMBUS_WORD_DATA |
I2C_FUNC_SMBUS_PROC_CALL |
I2C_FUNC_SMBUS_BLOCK_DATA |
I2C_FUNC_SMBUS_I2C_BLOCK |
I2C_FUNC_SMBUS_PEC;
}
/**
* smbus_algorithm - the adapter algorithm and supported functionality
* @smbus_xfer: the adapter algorithm
* @functionality: functionality supported by the adapter
*/
static const struct i2c_algorithm smbus_algorithm = {
.smbus_xfer = ismt_access,
.functionality = ismt_func,
};
/**
* ismt_handle_isr() - interrupt handler bottom half
* @priv: iSMT private data
*/
static irqreturn_t ismt_handle_isr(struct ismt_priv *priv)
{
complete(&priv->cmp);
return IRQ_HANDLED;
}
/**
* ismt_do_interrupt() - IRQ interrupt handler
* @vec: interrupt vector
* @data: iSMT private data
*/
static irqreturn_t ismt_do_interrupt(int vec, void *data)
{
u32 val;
struct ismt_priv *priv = data;
/*
* check to see it's our interrupt, return IRQ_NONE if not ours
* since we are sharing interrupt
*/
val = readl(priv->smba + ISMT_MSTR_MSTS);
if (!(val & (ISMT_MSTS_MIS | ISMT_MSTS_MEIS)))
return IRQ_NONE;
else
writel(val | ISMT_MSTS_MIS | ISMT_MSTS_MEIS,
priv->smba + ISMT_MSTR_MSTS);
return ismt_handle_isr(priv);
}
/**
* ismt_do_msi_interrupt() - MSI interrupt handler
* @vec: interrupt vector
* @data: iSMT private data
*/
static irqreturn_t ismt_do_msi_interrupt(int vec, void *data)
{
return ismt_handle_isr(data);
}
/**
* ismt_hw_init() - initialize the iSMT hardware
* @priv: iSMT private data
*/
static void ismt_hw_init(struct ismt_priv *priv)
{
u32 val;
struct device *dev = &priv->pci_dev->dev;
/* initialize the Master Descriptor Base Address (MDBA) */
writeq(priv->io_rng_dma, priv->smba + ISMT_MSTR_MDBA);
/* initialize the Master Control Register (MCTRL) */
writel(ISMT_MCTRL_MEIE, priv->smba + ISMT_MSTR_MCTRL);
/* initialize the Master Status Register (MSTS) */
writel(0, priv->smba + ISMT_MSTR_MSTS);
/* initialize the Master Descriptor Size (MDS) */
val = readl(priv->smba + ISMT_MSTR_MDS);
writel((val & ~ISMT_MDS_MASK) | (ISMT_DESC_ENTRIES - 1),
priv->smba + ISMT_MSTR_MDS);
/*
* Set the SMBus speed (could use this for slow HW debuggers)
*/
val = readl(priv->smba + ISMT_SPGT);
switch (bus_speed) {
case 0:
break;
case 80:
dev_dbg(dev, "Setting SMBus clock to 80 kHz\n");
writel(((val & ~ISMT_SPGT_SPD_MASK) | ISMT_SPGT_SPD_80K),
priv->smba + ISMT_SPGT);
break;
case 100:
dev_dbg(dev, "Setting SMBus clock to 100 kHz\n");
writel(((val & ~ISMT_SPGT_SPD_MASK) | ISMT_SPGT_SPD_100K),
priv->smba + ISMT_SPGT);
break;
case 400:
dev_dbg(dev, "Setting SMBus clock to 400 kHz\n");
writel(((val & ~ISMT_SPGT_SPD_MASK) | ISMT_SPGT_SPD_400K),
priv->smba + ISMT_SPGT);
break;
case 1000:
dev_dbg(dev, "Setting SMBus clock to 1000 kHz\n");
writel(((val & ~ISMT_SPGT_SPD_MASK) | ISMT_SPGT_SPD_1M),
priv->smba + ISMT_SPGT);
break;
default:
dev_warn(dev, "Invalid SMBus clock speed, only 0, 80, 100, 400, and 1000 are valid\n");
break;
}
val = readl(priv->smba + ISMT_SPGT);
switch (val & ISMT_SPGT_SPD_MASK) {
case ISMT_SPGT_SPD_80K:
bus_speed = 80;
break;
case ISMT_SPGT_SPD_100K:
bus_speed = 100;
break;
case ISMT_SPGT_SPD_400K:
bus_speed = 400;
break;
case ISMT_SPGT_SPD_1M:
bus_speed = 1000;
break;
}
dev_dbg(dev, "SMBus clock is running at %d kHz\n", bus_speed);
}
/**
* ismt_dev_init() - initialize the iSMT data structures
* @priv: iSMT private data
*/
static int ismt_dev_init(struct ismt_priv *priv)
{
/* allocate memory for the descriptor */
priv->hw = dmam_alloc_coherent(&priv->pci_dev->dev,
(ISMT_DESC_ENTRIES
* sizeof(struct ismt_desc)),
&priv->io_rng_dma,
GFP_KERNEL);
if (!priv->hw)
return -ENOMEM;
memset(priv->hw, 0, (ISMT_DESC_ENTRIES * sizeof(struct ismt_desc)));
priv->head = 0;
init_completion(&priv->cmp);
return 0;
}
/**
* ismt_int_init() - initialize interrupts
* @priv: iSMT private data
*/
static int ismt_int_init(struct ismt_priv *priv)
{
int err;
/* Try using MSI interrupts */
err = pci_enable_msi(priv->pci_dev);
if (err) {
dev_warn(&priv->pci_dev->dev,
"Unable to use MSI interrupts, falling back to legacy\n");
goto intx;
}
err = devm_request_irq(&priv->pci_dev->dev,
priv->pci_dev->irq,
ismt_do_msi_interrupt,
0,
"ismt-msi",
priv);
if (err) {
pci_disable_msi(priv->pci_dev);
goto intx;
}
priv->using_msi = true;
goto done;
/* Try using legacy interrupts */
intx:
err = devm_request_irq(&priv->pci_dev->dev,
priv->pci_dev->irq,
ismt_do_interrupt,
IRQF_SHARED,
"ismt-intx",
priv);
if (err) {
dev_err(&priv->pci_dev->dev, "no usable interrupts\n");
return -ENODEV;
}
priv->using_msi = false;
done:
return 0;
}
static struct pci_driver ismt_driver;
/**
* ismt_probe() - probe for iSMT devices
* @pdev: PCI-Express device
* @id: PCI-Express device ID
*/
static int
ismt_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
int err;
struct ismt_priv *priv;
unsigned long start, len;
priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
pci_set_drvdata(pdev, priv);
i2c_set_adapdata(&priv->adapter, priv);
priv->adapter.owner = THIS_MODULE;
priv->adapter.class = I2C_CLASS_HWMON;
priv->adapter.algo = &smbus_algorithm;
/* set up the sysfs linkage to our parent device */
priv->adapter.dev.parent = &pdev->dev;
/* number of retries on lost arbitration */
priv->adapter.retries = ISMT_MAX_RETRIES;
priv->pci_dev = pdev;
err = pcim_enable_device(pdev);
if (err) {
dev_err(&pdev->dev, "Failed to enable SMBus PCI device (%d)\n",
err);
return err;
}
/* enable bus mastering */
pci_set_master(pdev);
/* Determine the address of the SMBus area */
start = pci_resource_start(pdev, SMBBAR);
len = pci_resource_len(pdev, SMBBAR);
if (!start || !len) {
dev_err(&pdev->dev,
"SMBus base address uninitialized, upgrade BIOS\n");
return -ENODEV;
}
snprintf(priv->adapter.name, sizeof(priv->adapter.name),
"SMBus iSMT adapter at %lx", start);
dev_dbg(&priv->pci_dev->dev, " start=0x%lX\n", start);
dev_dbg(&priv->pci_dev->dev, " len=0x%lX\n", len);
err = acpi_check_resource_conflict(&pdev->resource[SMBBAR]);
if (err) {
dev_err(&pdev->dev, "ACPI resource conflict!\n");
return err;
}
err = pci_request_region(pdev, SMBBAR, ismt_driver.name);
if (err) {
dev_err(&pdev->dev,
"Failed to request SMBus region 0x%lx-0x%lx\n",
start, start + len);
return err;
}
priv->smba = pcim_iomap(pdev, SMBBAR, len);
if (!priv->smba) {
dev_err(&pdev->dev, "Unable to ioremap SMBus BAR\n");
err = -ENODEV;
goto fail;
}
if ((pci_set_dma_mask(pdev, DMA_BIT_MASK(64)) != 0) ||
(pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64)) != 0)) {
if ((pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0) ||
(pci_set_consistent_dma_mask(pdev,
DMA_BIT_MASK(32)) != 0)) {
dev_err(&pdev->dev, "pci_set_dma_mask fail %p\n",
pdev);
err = -ENODEV;
goto fail;
}
}
err = ismt_dev_init(priv);
if (err)
goto fail;
ismt_hw_init(priv);
err = ismt_int_init(priv);
if (err)
goto fail;
err = i2c_add_adapter(&priv->adapter);
if (err) {
dev_err(&pdev->dev, "Failed to add SMBus iSMT adapter\n");
err = -ENODEV;
goto fail;
}
return 0;
fail:
pci_release_region(pdev, SMBBAR);
return err;
}
/**
* ismt_remove() - release driver resources
* @pdev: PCI-Express device
*/
static void ismt_remove(struct pci_dev *pdev)
{
struct ismt_priv *priv = pci_get_drvdata(pdev);
i2c_del_adapter(&priv->adapter);
pci_release_region(pdev, SMBBAR);
}
/**
* ismt_suspend() - place the device in suspend
* @pdev: PCI-Express device
* @mesg: PM message
*/
#ifdef CONFIG_PM
static int ismt_suspend(struct pci_dev *pdev, pm_message_t mesg)
{
pci_save_state(pdev);
pci_set_power_state(pdev, pci_choose_state(pdev, mesg));
return 0;
}
/**
* ismt_resume() - PCI resume code
* @pdev: PCI-Express device
*/
static int ismt_resume(struct pci_dev *pdev)
{
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
return pci_enable_device(pdev);
}
#else
#define ismt_suspend NULL
#define ismt_resume NULL
#endif
static struct pci_driver ismt_driver = {
.name = "ismt_smbus",
.id_table = ismt_ids,
.probe = ismt_probe,
.remove = ismt_remove,
.suspend = ismt_suspend,
.resume = ismt_resume,
};
module_pci_driver(ismt_driver);
MODULE_LICENSE("Dual BSD/GPL");
MODULE_AUTHOR("Bill E. Brown <bill.e.brown@intel.com>");
MODULE_DESCRIPTION("Intel SMBus Message Transport (iSMT) driver");
| gpl-2.0 |
OrdinaryMagician/dolphin | Externals/wxWidgets3/src/generic/choicbkg.cpp | 121 | 7638 | ///////////////////////////////////////////////////////////////////////////////
// Name: src/generic/choicbkg.cpp
// Purpose: generic implementation of wxChoicebook
// Author: Vadim Zeitlin
// Modified by: Wlodzimierz ABX Skiba from generic/listbkg.cpp
// Created: 15.09.04
// Copyright: (c) Vadim Zeitlin, Wlodzimierz Skiba
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_CHOICEBOOK
#include "wx/choicebk.h"
#ifndef WX_PRECOMP
#include "wx/settings.h"
#include "wx/choice.h"
#include "wx/sizer.h"
#endif
#include "wx/imaglist.h"
// ----------------------------------------------------------------------------
// various wxWidgets macros
// ----------------------------------------------------------------------------
// check that the page index is valid
#define IS_VALID_PAGE(nPage) ((nPage) < GetPageCount())
// ----------------------------------------------------------------------------
// event table
// ----------------------------------------------------------------------------
IMPLEMENT_DYNAMIC_CLASS(wxChoicebook, wxBookCtrlBase)
wxDEFINE_EVENT( wxEVT_CHOICEBOOK_PAGE_CHANGING, wxBookCtrlEvent );
wxDEFINE_EVENT( wxEVT_CHOICEBOOK_PAGE_CHANGED, wxBookCtrlEvent );
BEGIN_EVENT_TABLE(wxChoicebook, wxBookCtrlBase)
EVT_CHOICE(wxID_ANY, wxChoicebook::OnChoiceSelected)
END_EVENT_TABLE()
// ============================================================================
// wxChoicebook implementation
// ============================================================================
// ----------------------------------------------------------------------------
// wxChoicebook creation
// ----------------------------------------------------------------------------
bool
wxChoicebook::Create(wxWindow *parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name)
{
if ( (style & wxBK_ALIGN_MASK) == wxBK_DEFAULT )
{
style |= wxBK_TOP;
}
// no border for this control, it doesn't look nice together with
// wxChoice border
style &= ~wxBORDER_MASK;
style |= wxBORDER_NONE;
if ( !wxControl::Create(parent, id, pos, size, style,
wxDefaultValidator, name) )
return false;
m_bookctrl = new wxChoice
(
this,
wxID_ANY,
wxDefaultPosition,
wxDefaultSize
);
wxSizer* mainSizer = new wxBoxSizer(IsVertical() ? wxVERTICAL : wxHORIZONTAL);
if (style & wxBK_RIGHT || style & wxBK_BOTTOM)
mainSizer->Add(0, 0, 1, wxEXPAND, 0);
m_controlSizer = new wxBoxSizer(IsVertical() ? wxHORIZONTAL : wxVERTICAL);
m_controlSizer->Add(m_bookctrl, 1, (IsVertical() ? wxALIGN_CENTRE_VERTICAL : wxALIGN_CENTRE) |wxGROW, 0);
mainSizer->Add(m_controlSizer, 0, (IsVertical() ? (int) wxGROW : (int) wxALIGN_CENTRE_VERTICAL)|wxALL, m_controlMargin);
SetSizer(mainSizer);
return true;
}
// ----------------------------------------------------------------------------
// accessing the pages
// ----------------------------------------------------------------------------
bool wxChoicebook::SetPageText(size_t n, const wxString& strText)
{
GetChoiceCtrl()->SetString(n, strText);
return true;
}
wxString wxChoicebook::GetPageText(size_t n) const
{
return GetChoiceCtrl()->GetString(n);
}
int wxChoicebook::GetPageImage(size_t WXUNUSED(n)) const
{
return wxNOT_FOUND;
}
bool wxChoicebook::SetPageImage(size_t WXUNUSED(n), int WXUNUSED(imageId))
{
// fail silently, the code may be written to use one of several book
// classes and call SetPageImage() unconditionally, it's better to just
// ignore it (which is the best we can do short of rewriting this class to
// use wxBitmapComboBox anyhow) than complain loudly about a rather
// harmless problem
return false;
}
// ----------------------------------------------------------------------------
// miscellaneous other stuff
// ----------------------------------------------------------------------------
void wxChoicebook::DoSetWindowVariant(wxWindowVariant variant)
{
wxBookCtrlBase::DoSetWindowVariant(variant);
if (m_bookctrl)
m_bookctrl->SetWindowVariant(variant);
}
void wxChoicebook::SetImageList(wxImageList *imageList)
{
// TODO: can be implemented in form of static bitmap near choice control
wxBookCtrlBase::SetImageList(imageList);
}
// ----------------------------------------------------------------------------
// selection
// ----------------------------------------------------------------------------
wxBookCtrlEvent* wxChoicebook::CreatePageChangingEvent() const
{
return new wxBookCtrlEvent(wxEVT_CHOICEBOOK_PAGE_CHANGING, m_windowId);
}
void wxChoicebook::MakeChangedEvent(wxBookCtrlEvent &event)
{
event.SetEventType(wxEVT_CHOICEBOOK_PAGE_CHANGED);
}
// ----------------------------------------------------------------------------
// adding/removing the pages
// ----------------------------------------------------------------------------
bool
wxChoicebook::InsertPage(size_t n,
wxWindow *page,
const wxString& text,
bool bSelect,
int imageId)
{
if ( !wxBookCtrlBase::InsertPage(n, page, text, bSelect, imageId) )
return false;
GetChoiceCtrl()->Insert(text, n);
// if the inserted page is before the selected one, we must update the
// index of the selected page
if ( int(n) <= m_selection )
{
// one extra page added
m_selection++;
GetChoiceCtrl()->Select(m_selection);
}
if ( !DoSetSelectionAfterInsertion(n, bSelect) )
page->Hide();
return true;
}
wxWindow *wxChoicebook::DoRemovePage(size_t page)
{
wxWindow *win = wxBookCtrlBase::DoRemovePage(page);
if ( win )
{
GetChoiceCtrl()->Delete(page);
DoSetSelectionAfterRemoval(page);
}
return win;
}
bool wxChoicebook::DeleteAllPages()
{
GetChoiceCtrl()->Clear();
return wxBookCtrlBase::DeleteAllPages();
}
// ----------------------------------------------------------------------------
// wxChoicebook events
// ----------------------------------------------------------------------------
void wxChoicebook::OnChoiceSelected(wxCommandEvent& eventChoice)
{
if ( eventChoice.GetEventObject() != m_bookctrl )
{
eventChoice.Skip();
return;
}
const int selNew = eventChoice.GetSelection();
if ( selNew == m_selection )
{
// this event can only come from our own Select(m_selection) below
// which we call when the page change is vetoed, so we should simply
// ignore it
return;
}
SetSelection(selNew);
// change wasn't allowed, return to previous state
if (m_selection != selNew)
GetChoiceCtrl()->Select(m_selection);
}
#endif // wxUSE_CHOICEBOOK
| gpl-2.0 |
drowningchild/sgh-i997GB | fs/ocfs2/cluster/nodemanager.c | 889 | 25218 | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* Copyright (C) 2004, 2005 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*/
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/configfs.h>
#include "tcp.h"
#include "nodemanager.h"
#include "heartbeat.h"
#include "masklog.h"
#include "sys.h"
#include "ver.h"
/* for now we operate under the assertion that there can be only one
* cluster active at a time. Changing this will require trickling
* cluster references throughout where nodes are looked up */
struct o2nm_cluster *o2nm_single_cluster = NULL;
char *o2nm_fence_method_desc[O2NM_FENCE_METHODS] = {
"reset", /* O2NM_FENCE_RESET */
"panic", /* O2NM_FENCE_PANIC */
};
struct o2nm_node *o2nm_get_node_by_num(u8 node_num)
{
struct o2nm_node *node = NULL;
if (node_num >= O2NM_MAX_NODES || o2nm_single_cluster == NULL)
goto out;
read_lock(&o2nm_single_cluster->cl_nodes_lock);
node = o2nm_single_cluster->cl_nodes[node_num];
if (node)
config_item_get(&node->nd_item);
read_unlock(&o2nm_single_cluster->cl_nodes_lock);
out:
return node;
}
EXPORT_SYMBOL_GPL(o2nm_get_node_by_num);
int o2nm_configured_node_map(unsigned long *map, unsigned bytes)
{
struct o2nm_cluster *cluster = o2nm_single_cluster;
BUG_ON(bytes < (sizeof(cluster->cl_nodes_bitmap)));
if (cluster == NULL)
return -EINVAL;
read_lock(&cluster->cl_nodes_lock);
memcpy(map, cluster->cl_nodes_bitmap, sizeof(cluster->cl_nodes_bitmap));
read_unlock(&cluster->cl_nodes_lock);
return 0;
}
EXPORT_SYMBOL_GPL(o2nm_configured_node_map);
static struct o2nm_node *o2nm_node_ip_tree_lookup(struct o2nm_cluster *cluster,
__be32 ip_needle,
struct rb_node ***ret_p,
struct rb_node **ret_parent)
{
struct rb_node **p = &cluster->cl_node_ip_tree.rb_node;
struct rb_node *parent = NULL;
struct o2nm_node *node, *ret = NULL;
while (*p) {
int cmp;
parent = *p;
node = rb_entry(parent, struct o2nm_node, nd_ip_node);
cmp = memcmp(&ip_needle, &node->nd_ipv4_address,
sizeof(ip_needle));
if (cmp < 0)
p = &(*p)->rb_left;
else if (cmp > 0)
p = &(*p)->rb_right;
else {
ret = node;
break;
}
}
if (ret_p != NULL)
*ret_p = p;
if (ret_parent != NULL)
*ret_parent = parent;
return ret;
}
struct o2nm_node *o2nm_get_node_by_ip(__be32 addr)
{
struct o2nm_node *node = NULL;
struct o2nm_cluster *cluster = o2nm_single_cluster;
if (cluster == NULL)
goto out;
read_lock(&cluster->cl_nodes_lock);
node = o2nm_node_ip_tree_lookup(cluster, addr, NULL, NULL);
if (node)
config_item_get(&node->nd_item);
read_unlock(&cluster->cl_nodes_lock);
out:
return node;
}
EXPORT_SYMBOL_GPL(o2nm_get_node_by_ip);
void o2nm_node_put(struct o2nm_node *node)
{
config_item_put(&node->nd_item);
}
EXPORT_SYMBOL_GPL(o2nm_node_put);
void o2nm_node_get(struct o2nm_node *node)
{
config_item_get(&node->nd_item);
}
EXPORT_SYMBOL_GPL(o2nm_node_get);
u8 o2nm_this_node(void)
{
u8 node_num = O2NM_MAX_NODES;
if (o2nm_single_cluster && o2nm_single_cluster->cl_has_local)
node_num = o2nm_single_cluster->cl_local_node;
return node_num;
}
EXPORT_SYMBOL_GPL(o2nm_this_node);
/* node configfs bits */
static struct o2nm_cluster *to_o2nm_cluster(struct config_item *item)
{
return item ?
container_of(to_config_group(item), struct o2nm_cluster,
cl_group)
: NULL;
}
static struct o2nm_node *to_o2nm_node(struct config_item *item)
{
return item ? container_of(item, struct o2nm_node, nd_item) : NULL;
}
static void o2nm_node_release(struct config_item *item)
{
struct o2nm_node *node = to_o2nm_node(item);
kfree(node);
}
static ssize_t o2nm_node_num_read(struct o2nm_node *node, char *page)
{
return sprintf(page, "%d\n", node->nd_num);
}
static struct o2nm_cluster *to_o2nm_cluster_from_node(struct o2nm_node *node)
{
/* through the first node_set .parent
* mycluster/nodes/mynode == o2nm_cluster->o2nm_node_group->o2nm_node */
return to_o2nm_cluster(node->nd_item.ci_parent->ci_parent);
}
enum {
O2NM_NODE_ATTR_NUM = 0,
O2NM_NODE_ATTR_PORT,
O2NM_NODE_ATTR_ADDRESS,
O2NM_NODE_ATTR_LOCAL,
};
static ssize_t o2nm_node_num_write(struct o2nm_node *node, const char *page,
size_t count)
{
struct o2nm_cluster *cluster = to_o2nm_cluster_from_node(node);
unsigned long tmp;
char *p = (char *)page;
tmp = simple_strtoul(p, &p, 0);
if (!p || (*p && (*p != '\n')))
return -EINVAL;
if (tmp >= O2NM_MAX_NODES)
return -ERANGE;
/* once we're in the cl_nodes tree networking can look us up by
* node number and try to use our address and port attributes
* to connect to this node.. make sure that they've been set
* before writing the node attribute? */
if (!test_bit(O2NM_NODE_ATTR_ADDRESS, &node->nd_set_attributes) ||
!test_bit(O2NM_NODE_ATTR_PORT, &node->nd_set_attributes))
return -EINVAL; /* XXX */
write_lock(&cluster->cl_nodes_lock);
if (cluster->cl_nodes[tmp])
p = NULL;
else {
cluster->cl_nodes[tmp] = node;
node->nd_num = tmp;
set_bit(tmp, cluster->cl_nodes_bitmap);
}
write_unlock(&cluster->cl_nodes_lock);
if (p == NULL)
return -EEXIST;
return count;
}
static ssize_t o2nm_node_ipv4_port_read(struct o2nm_node *node, char *page)
{
return sprintf(page, "%u\n", ntohs(node->nd_ipv4_port));
}
static ssize_t o2nm_node_ipv4_port_write(struct o2nm_node *node,
const char *page, size_t count)
{
unsigned long tmp;
char *p = (char *)page;
tmp = simple_strtoul(p, &p, 0);
if (!p || (*p && (*p != '\n')))
return -EINVAL;
if (tmp == 0)
return -EINVAL;
if (tmp >= (u16)-1)
return -ERANGE;
node->nd_ipv4_port = htons(tmp);
return count;
}
static ssize_t o2nm_node_ipv4_address_read(struct o2nm_node *node, char *page)
{
return sprintf(page, "%pI4\n", &node->nd_ipv4_address);
}
static ssize_t o2nm_node_ipv4_address_write(struct o2nm_node *node,
const char *page,
size_t count)
{
struct o2nm_cluster *cluster = to_o2nm_cluster_from_node(node);
int ret, i;
struct rb_node **p, *parent;
unsigned int octets[4];
__be32 ipv4_addr = 0;
ret = sscanf(page, "%3u.%3u.%3u.%3u", &octets[3], &octets[2],
&octets[1], &octets[0]);
if (ret != 4)
return -EINVAL;
for (i = 0; i < ARRAY_SIZE(octets); i++) {
if (octets[i] > 255)
return -ERANGE;
be32_add_cpu(&ipv4_addr, octets[i] << (i * 8));
}
ret = 0;
write_lock(&cluster->cl_nodes_lock);
if (o2nm_node_ip_tree_lookup(cluster, ipv4_addr, &p, &parent))
ret = -EEXIST;
else {
rb_link_node(&node->nd_ip_node, parent, p);
rb_insert_color(&node->nd_ip_node, &cluster->cl_node_ip_tree);
}
write_unlock(&cluster->cl_nodes_lock);
if (ret)
return ret;
memcpy(&node->nd_ipv4_address, &ipv4_addr, sizeof(ipv4_addr));
return count;
}
static ssize_t o2nm_node_local_read(struct o2nm_node *node, char *page)
{
return sprintf(page, "%d\n", node->nd_local);
}
static ssize_t o2nm_node_local_write(struct o2nm_node *node, const char *page,
size_t count)
{
struct o2nm_cluster *cluster = to_o2nm_cluster_from_node(node);
unsigned long tmp;
char *p = (char *)page;
ssize_t ret;
tmp = simple_strtoul(p, &p, 0);
if (!p || (*p && (*p != '\n')))
return -EINVAL;
tmp = !!tmp; /* boolean of whether this node wants to be local */
/* setting local turns on networking rx for now so we require having
* set everything else first */
if (!test_bit(O2NM_NODE_ATTR_ADDRESS, &node->nd_set_attributes) ||
!test_bit(O2NM_NODE_ATTR_NUM, &node->nd_set_attributes) ||
!test_bit(O2NM_NODE_ATTR_PORT, &node->nd_set_attributes))
return -EINVAL; /* XXX */
/* the only failure case is trying to set a new local node
* when a different one is already set */
if (tmp && tmp == cluster->cl_has_local &&
cluster->cl_local_node != node->nd_num)
return -EBUSY;
/* bring up the rx thread if we're setting the new local node. */
if (tmp && !cluster->cl_has_local) {
ret = o2net_start_listening(node);
if (ret)
return ret;
}
if (!tmp && cluster->cl_has_local &&
cluster->cl_local_node == node->nd_num) {
o2net_stop_listening(node);
cluster->cl_local_node = O2NM_INVALID_NODE_NUM;
}
node->nd_local = tmp;
if (node->nd_local) {
cluster->cl_has_local = tmp;
cluster->cl_local_node = node->nd_num;
}
return count;
}
struct o2nm_node_attribute {
struct configfs_attribute attr;
ssize_t (*show)(struct o2nm_node *, char *);
ssize_t (*store)(struct o2nm_node *, const char *, size_t);
};
static struct o2nm_node_attribute o2nm_node_attr_num = {
.attr = { .ca_owner = THIS_MODULE,
.ca_name = "num",
.ca_mode = S_IRUGO | S_IWUSR },
.show = o2nm_node_num_read,
.store = o2nm_node_num_write,
};
static struct o2nm_node_attribute o2nm_node_attr_ipv4_port = {
.attr = { .ca_owner = THIS_MODULE,
.ca_name = "ipv4_port",
.ca_mode = S_IRUGO | S_IWUSR },
.show = o2nm_node_ipv4_port_read,
.store = o2nm_node_ipv4_port_write,
};
static struct o2nm_node_attribute o2nm_node_attr_ipv4_address = {
.attr = { .ca_owner = THIS_MODULE,
.ca_name = "ipv4_address",
.ca_mode = S_IRUGO | S_IWUSR },
.show = o2nm_node_ipv4_address_read,
.store = o2nm_node_ipv4_address_write,
};
static struct o2nm_node_attribute o2nm_node_attr_local = {
.attr = { .ca_owner = THIS_MODULE,
.ca_name = "local",
.ca_mode = S_IRUGO | S_IWUSR },
.show = o2nm_node_local_read,
.store = o2nm_node_local_write,
};
static struct configfs_attribute *o2nm_node_attrs[] = {
[O2NM_NODE_ATTR_NUM] = &o2nm_node_attr_num.attr,
[O2NM_NODE_ATTR_PORT] = &o2nm_node_attr_ipv4_port.attr,
[O2NM_NODE_ATTR_ADDRESS] = &o2nm_node_attr_ipv4_address.attr,
[O2NM_NODE_ATTR_LOCAL] = &o2nm_node_attr_local.attr,
NULL,
};
static int o2nm_attr_index(struct configfs_attribute *attr)
{
int i;
for (i = 0; i < ARRAY_SIZE(o2nm_node_attrs); i++) {
if (attr == o2nm_node_attrs[i])
return i;
}
BUG();
return 0;
}
static ssize_t o2nm_node_show(struct config_item *item,
struct configfs_attribute *attr,
char *page)
{
struct o2nm_node *node = to_o2nm_node(item);
struct o2nm_node_attribute *o2nm_node_attr =
container_of(attr, struct o2nm_node_attribute, attr);
ssize_t ret = 0;
if (o2nm_node_attr->show)
ret = o2nm_node_attr->show(node, page);
return ret;
}
static ssize_t o2nm_node_store(struct config_item *item,
struct configfs_attribute *attr,
const char *page, size_t count)
{
struct o2nm_node *node = to_o2nm_node(item);
struct o2nm_node_attribute *o2nm_node_attr =
container_of(attr, struct o2nm_node_attribute, attr);
ssize_t ret;
int attr_index = o2nm_attr_index(attr);
if (o2nm_node_attr->store == NULL) {
ret = -EINVAL;
goto out;
}
if (test_bit(attr_index, &node->nd_set_attributes))
return -EBUSY;
ret = o2nm_node_attr->store(node, page, count);
if (ret < count)
goto out;
set_bit(attr_index, &node->nd_set_attributes);
out:
return ret;
}
static struct configfs_item_operations o2nm_node_item_ops = {
.release = o2nm_node_release,
.show_attribute = o2nm_node_show,
.store_attribute = o2nm_node_store,
};
static struct config_item_type o2nm_node_type = {
.ct_item_ops = &o2nm_node_item_ops,
.ct_attrs = o2nm_node_attrs,
.ct_owner = THIS_MODULE,
};
/* node set */
struct o2nm_node_group {
struct config_group ns_group;
/* some stuff? */
};
#if 0
static struct o2nm_node_group *to_o2nm_node_group(struct config_group *group)
{
return group ?
container_of(group, struct o2nm_node_group, ns_group)
: NULL;
}
#endif
struct o2nm_cluster_attribute {
struct configfs_attribute attr;
ssize_t (*show)(struct o2nm_cluster *, char *);
ssize_t (*store)(struct o2nm_cluster *, const char *, size_t);
};
static ssize_t o2nm_cluster_attr_write(const char *page, ssize_t count,
unsigned int *val)
{
unsigned long tmp;
char *p = (char *)page;
tmp = simple_strtoul(p, &p, 0);
if (!p || (*p && (*p != '\n')))
return -EINVAL;
if (tmp == 0)
return -EINVAL;
if (tmp >= (u32)-1)
return -ERANGE;
*val = tmp;
return count;
}
static ssize_t o2nm_cluster_attr_idle_timeout_ms_read(
struct o2nm_cluster *cluster, char *page)
{
return sprintf(page, "%u\n", cluster->cl_idle_timeout_ms);
}
static ssize_t o2nm_cluster_attr_idle_timeout_ms_write(
struct o2nm_cluster *cluster, const char *page, size_t count)
{
ssize_t ret;
unsigned int val;
ret = o2nm_cluster_attr_write(page, count, &val);
if (ret > 0) {
if (cluster->cl_idle_timeout_ms != val
&& o2net_num_connected_peers()) {
mlog(ML_NOTICE,
"o2net: cannot change idle timeout after "
"the first peer has agreed to it."
" %d connected peers\n",
o2net_num_connected_peers());
ret = -EINVAL;
} else if (val <= cluster->cl_keepalive_delay_ms) {
mlog(ML_NOTICE, "o2net: idle timeout must be larger "
"than keepalive delay\n");
ret = -EINVAL;
} else {
cluster->cl_idle_timeout_ms = val;
}
}
return ret;
}
static ssize_t o2nm_cluster_attr_keepalive_delay_ms_read(
struct o2nm_cluster *cluster, char *page)
{
return sprintf(page, "%u\n", cluster->cl_keepalive_delay_ms);
}
static ssize_t o2nm_cluster_attr_keepalive_delay_ms_write(
struct o2nm_cluster *cluster, const char *page, size_t count)
{
ssize_t ret;
unsigned int val;
ret = o2nm_cluster_attr_write(page, count, &val);
if (ret > 0) {
if (cluster->cl_keepalive_delay_ms != val
&& o2net_num_connected_peers()) {
mlog(ML_NOTICE,
"o2net: cannot change keepalive delay after"
" the first peer has agreed to it."
" %d connected peers\n",
o2net_num_connected_peers());
ret = -EINVAL;
} else if (val >= cluster->cl_idle_timeout_ms) {
mlog(ML_NOTICE, "o2net: keepalive delay must be "
"smaller than idle timeout\n");
ret = -EINVAL;
} else {
cluster->cl_keepalive_delay_ms = val;
}
}
return ret;
}
static ssize_t o2nm_cluster_attr_reconnect_delay_ms_read(
struct o2nm_cluster *cluster, char *page)
{
return sprintf(page, "%u\n", cluster->cl_reconnect_delay_ms);
}
static ssize_t o2nm_cluster_attr_reconnect_delay_ms_write(
struct o2nm_cluster *cluster, const char *page, size_t count)
{
return o2nm_cluster_attr_write(page, count,
&cluster->cl_reconnect_delay_ms);
}
static ssize_t o2nm_cluster_attr_fence_method_read(
struct o2nm_cluster *cluster, char *page)
{
ssize_t ret = 0;
if (cluster)
ret = sprintf(page, "%s\n",
o2nm_fence_method_desc[cluster->cl_fence_method]);
return ret;
}
static ssize_t o2nm_cluster_attr_fence_method_write(
struct o2nm_cluster *cluster, const char *page, size_t count)
{
unsigned int i;
if (page[count - 1] != '\n')
goto bail;
for (i = 0; i < O2NM_FENCE_METHODS; ++i) {
if (count != strlen(o2nm_fence_method_desc[i]) + 1)
continue;
if (strncasecmp(page, o2nm_fence_method_desc[i], count - 1))
continue;
if (cluster->cl_fence_method != i) {
printk(KERN_INFO "ocfs2: Changing fence method to %s\n",
o2nm_fence_method_desc[i]);
cluster->cl_fence_method = i;
}
return count;
}
bail:
return -EINVAL;
}
static struct o2nm_cluster_attribute o2nm_cluster_attr_idle_timeout_ms = {
.attr = { .ca_owner = THIS_MODULE,
.ca_name = "idle_timeout_ms",
.ca_mode = S_IRUGO | S_IWUSR },
.show = o2nm_cluster_attr_idle_timeout_ms_read,
.store = o2nm_cluster_attr_idle_timeout_ms_write,
};
static struct o2nm_cluster_attribute o2nm_cluster_attr_keepalive_delay_ms = {
.attr = { .ca_owner = THIS_MODULE,
.ca_name = "keepalive_delay_ms",
.ca_mode = S_IRUGO | S_IWUSR },
.show = o2nm_cluster_attr_keepalive_delay_ms_read,
.store = o2nm_cluster_attr_keepalive_delay_ms_write,
};
static struct o2nm_cluster_attribute o2nm_cluster_attr_reconnect_delay_ms = {
.attr = { .ca_owner = THIS_MODULE,
.ca_name = "reconnect_delay_ms",
.ca_mode = S_IRUGO | S_IWUSR },
.show = o2nm_cluster_attr_reconnect_delay_ms_read,
.store = o2nm_cluster_attr_reconnect_delay_ms_write,
};
static struct o2nm_cluster_attribute o2nm_cluster_attr_fence_method = {
.attr = { .ca_owner = THIS_MODULE,
.ca_name = "fence_method",
.ca_mode = S_IRUGO | S_IWUSR },
.show = o2nm_cluster_attr_fence_method_read,
.store = o2nm_cluster_attr_fence_method_write,
};
static struct configfs_attribute *o2nm_cluster_attrs[] = {
&o2nm_cluster_attr_idle_timeout_ms.attr,
&o2nm_cluster_attr_keepalive_delay_ms.attr,
&o2nm_cluster_attr_reconnect_delay_ms.attr,
&o2nm_cluster_attr_fence_method.attr,
NULL,
};
static ssize_t o2nm_cluster_show(struct config_item *item,
struct configfs_attribute *attr,
char *page)
{
struct o2nm_cluster *cluster = to_o2nm_cluster(item);
struct o2nm_cluster_attribute *o2nm_cluster_attr =
container_of(attr, struct o2nm_cluster_attribute, attr);
ssize_t ret = 0;
if (o2nm_cluster_attr->show)
ret = o2nm_cluster_attr->show(cluster, page);
return ret;
}
static ssize_t o2nm_cluster_store(struct config_item *item,
struct configfs_attribute *attr,
const char *page, size_t count)
{
struct o2nm_cluster *cluster = to_o2nm_cluster(item);
struct o2nm_cluster_attribute *o2nm_cluster_attr =
container_of(attr, struct o2nm_cluster_attribute, attr);
ssize_t ret;
if (o2nm_cluster_attr->store == NULL) {
ret = -EINVAL;
goto out;
}
ret = o2nm_cluster_attr->store(cluster, page, count);
if (ret < count)
goto out;
out:
return ret;
}
static struct config_item *o2nm_node_group_make_item(struct config_group *group,
const char *name)
{
struct o2nm_node *node = NULL;
if (strlen(name) > O2NM_MAX_NAME_LEN)
return ERR_PTR(-ENAMETOOLONG);
node = kzalloc(sizeof(struct o2nm_node), GFP_KERNEL);
if (node == NULL)
return ERR_PTR(-ENOMEM);
strcpy(node->nd_name, name); /* use item.ci_namebuf instead? */
config_item_init_type_name(&node->nd_item, name, &o2nm_node_type);
spin_lock_init(&node->nd_lock);
return &node->nd_item;
}
static void o2nm_node_group_drop_item(struct config_group *group,
struct config_item *item)
{
struct o2nm_node *node = to_o2nm_node(item);
struct o2nm_cluster *cluster = to_o2nm_cluster(group->cg_item.ci_parent);
o2net_disconnect_node(node);
if (cluster->cl_has_local &&
(cluster->cl_local_node == node->nd_num)) {
cluster->cl_has_local = 0;
cluster->cl_local_node = O2NM_INVALID_NODE_NUM;
o2net_stop_listening(node);
}
/* XXX call into net to stop this node from trading messages */
write_lock(&cluster->cl_nodes_lock);
/* XXX sloppy */
if (node->nd_ipv4_address)
rb_erase(&node->nd_ip_node, &cluster->cl_node_ip_tree);
/* nd_num might be 0 if the node number hasn't been set.. */
if (cluster->cl_nodes[node->nd_num] == node) {
cluster->cl_nodes[node->nd_num] = NULL;
clear_bit(node->nd_num, cluster->cl_nodes_bitmap);
}
write_unlock(&cluster->cl_nodes_lock);
config_item_put(item);
}
static struct configfs_group_operations o2nm_node_group_group_ops = {
.make_item = o2nm_node_group_make_item,
.drop_item = o2nm_node_group_drop_item,
};
static struct config_item_type o2nm_node_group_type = {
.ct_group_ops = &o2nm_node_group_group_ops,
.ct_owner = THIS_MODULE,
};
/* cluster */
static void o2nm_cluster_release(struct config_item *item)
{
struct o2nm_cluster *cluster = to_o2nm_cluster(item);
kfree(cluster->cl_group.default_groups);
kfree(cluster);
}
static struct configfs_item_operations o2nm_cluster_item_ops = {
.release = o2nm_cluster_release,
.show_attribute = o2nm_cluster_show,
.store_attribute = o2nm_cluster_store,
};
static struct config_item_type o2nm_cluster_type = {
.ct_item_ops = &o2nm_cluster_item_ops,
.ct_attrs = o2nm_cluster_attrs,
.ct_owner = THIS_MODULE,
};
/* cluster set */
struct o2nm_cluster_group {
struct configfs_subsystem cs_subsys;
/* some stuff? */
};
#if 0
static struct o2nm_cluster_group *to_o2nm_cluster_group(struct config_group *group)
{
return group ?
container_of(to_configfs_subsystem(group), struct o2nm_cluster_group, cs_subsys)
: NULL;
}
#endif
static struct config_group *o2nm_cluster_group_make_group(struct config_group *group,
const char *name)
{
struct o2nm_cluster *cluster = NULL;
struct o2nm_node_group *ns = NULL;
struct config_group *o2hb_group = NULL, *ret = NULL;
void *defs = NULL;
/* this runs under the parent dir's i_mutex; there can be only
* one caller in here at a time */
if (o2nm_single_cluster)
return ERR_PTR(-ENOSPC);
cluster = kzalloc(sizeof(struct o2nm_cluster), GFP_KERNEL);
ns = kzalloc(sizeof(struct o2nm_node_group), GFP_KERNEL);
defs = kcalloc(3, sizeof(struct config_group *), GFP_KERNEL);
o2hb_group = o2hb_alloc_hb_set();
if (cluster == NULL || ns == NULL || o2hb_group == NULL || defs == NULL)
goto out;
config_group_init_type_name(&cluster->cl_group, name,
&o2nm_cluster_type);
config_group_init_type_name(&ns->ns_group, "node",
&o2nm_node_group_type);
cluster->cl_group.default_groups = defs;
cluster->cl_group.default_groups[0] = &ns->ns_group;
cluster->cl_group.default_groups[1] = o2hb_group;
cluster->cl_group.default_groups[2] = NULL;
rwlock_init(&cluster->cl_nodes_lock);
cluster->cl_node_ip_tree = RB_ROOT;
cluster->cl_reconnect_delay_ms = O2NET_RECONNECT_DELAY_MS_DEFAULT;
cluster->cl_idle_timeout_ms = O2NET_IDLE_TIMEOUT_MS_DEFAULT;
cluster->cl_keepalive_delay_ms = O2NET_KEEPALIVE_DELAY_MS_DEFAULT;
cluster->cl_fence_method = O2NM_FENCE_RESET;
ret = &cluster->cl_group;
o2nm_single_cluster = cluster;
out:
if (ret == NULL) {
kfree(cluster);
kfree(ns);
o2hb_free_hb_set(o2hb_group);
kfree(defs);
ret = ERR_PTR(-ENOMEM);
}
return ret;
}
static void o2nm_cluster_group_drop_item(struct config_group *group, struct config_item *item)
{
struct o2nm_cluster *cluster = to_o2nm_cluster(item);
int i;
struct config_item *killme;
BUG_ON(o2nm_single_cluster != cluster);
o2nm_single_cluster = NULL;
for (i = 0; cluster->cl_group.default_groups[i]; i++) {
killme = &cluster->cl_group.default_groups[i]->cg_item;
cluster->cl_group.default_groups[i] = NULL;
config_item_put(killme);
}
config_item_put(item);
}
static struct configfs_group_operations o2nm_cluster_group_group_ops = {
.make_group = o2nm_cluster_group_make_group,
.drop_item = o2nm_cluster_group_drop_item,
};
static struct config_item_type o2nm_cluster_group_type = {
.ct_group_ops = &o2nm_cluster_group_group_ops,
.ct_owner = THIS_MODULE,
};
static struct o2nm_cluster_group o2nm_cluster_group = {
.cs_subsys = {
.su_group = {
.cg_item = {
.ci_namebuf = "cluster",
.ci_type = &o2nm_cluster_group_type,
},
},
},
};
int o2nm_depend_item(struct config_item *item)
{
return configfs_depend_item(&o2nm_cluster_group.cs_subsys, item);
}
void o2nm_undepend_item(struct config_item *item)
{
configfs_undepend_item(&o2nm_cluster_group.cs_subsys, item);
}
int o2nm_depend_this_node(void)
{
int ret = 0;
struct o2nm_node *local_node;
local_node = o2nm_get_node_by_num(o2nm_this_node());
if (!local_node) {
ret = -EINVAL;
goto out;
}
ret = o2nm_depend_item(&local_node->nd_item);
o2nm_node_put(local_node);
out:
return ret;
}
void o2nm_undepend_this_node(void)
{
struct o2nm_node *local_node;
local_node = o2nm_get_node_by_num(o2nm_this_node());
BUG_ON(!local_node);
o2nm_undepend_item(&local_node->nd_item);
o2nm_node_put(local_node);
}
static void __exit exit_o2nm(void)
{
/* XXX sync with hb callbacks and shut down hb? */
o2net_unregister_hb_callbacks();
configfs_unregister_subsystem(&o2nm_cluster_group.cs_subsys);
o2cb_sys_shutdown();
o2net_exit();
o2hb_exit();
}
static int __init init_o2nm(void)
{
int ret = -1;
cluster_print_version();
ret = o2hb_init();
if (ret)
goto out;
ret = o2net_init();
if (ret)
goto out_o2hb;
ret = o2net_register_hb_callbacks();
if (ret)
goto out_o2net;
config_group_init(&o2nm_cluster_group.cs_subsys.su_group);
mutex_init(&o2nm_cluster_group.cs_subsys.su_mutex);
ret = configfs_register_subsystem(&o2nm_cluster_group.cs_subsys);
if (ret) {
printk(KERN_ERR "nodemanager: Registration returned %d\n", ret);
goto out_callbacks;
}
ret = o2cb_sys_init();
if (!ret)
goto out;
configfs_unregister_subsystem(&o2nm_cluster_group.cs_subsys);
out_callbacks:
o2net_unregister_hb_callbacks();
out_o2net:
o2net_exit();
out_o2hb:
o2hb_exit();
out:
return ret;
}
MODULE_AUTHOR("Oracle");
MODULE_LICENSE("GPL");
module_init(init_o2nm)
module_exit(exit_o2nm)
| gpl-2.0 |
Stane1983/amlogic-m1 | drivers/sbus/char/jsflash.c | 889 | 14352 | /*
* drivers/sbus/char/jsflash.c
*
* Copyright (C) 1991, 1992 Linus Torvalds (drivers/char/mem.c)
* Copyright (C) 1997 Eddie C. Dost (drivers/sbus/char/flash.c)
* Copyright (C) 1997-2000 Pavel Machek <pavel@ucw.cz> (drivers/block/nbd.c)
* Copyright (C) 1999-2000 Pete Zaitcev
*
* This driver is used to program OS into a Flash SIMM on
* Krups and Espresso platforms.
*
* TODO: do not allow erase/programming if file systems are mounted.
* TODO: Erase/program both banks of a 8MB SIMM.
*
* It is anticipated that programming an OS Flash will be a routine
* procedure. In the same time it is exeedingly dangerous because
* a user can program its OBP flash with OS image and effectively
* kill the machine.
*
* This driver uses an interface different from Eddie's flash.c
* as a silly safeguard.
*
* XXX The flash.c manipulates page caching characteristics in a certain
* dubious way; also it assumes that remap_pfn_range() can remap
* PCI bus locations, which may be false. ioremap() must be used
* instead. We should discuss this.
*/
#include <linux/module.h>
#include <linux/smp_lock.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/miscdevice.h>
#include <linux/fcntl.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/genhd.h>
#include <linux/blkdev.h>
#include <asm/uaccess.h>
#include <asm/pgtable.h>
#include <asm/io.h>
#include <asm/pcic.h>
#include <asm/oplib.h>
#include <asm/jsflash.h> /* ioctl arguments. <linux/> ?? */
#define JSFIDSZ (sizeof(struct jsflash_ident_arg))
#define JSFPRGSZ (sizeof(struct jsflash_program_arg))
/*
* Our device numbers have no business in system headers.
* The only thing a user knows is the device name /dev/jsflash.
*
* Block devices are laid out like this:
* minor+0 - Bootstrap, for 8MB SIMM 0x20400000[0x800000]
* minor+1 - Filesystem to mount, normally 0x20400400[0x7ffc00]
* minor+2 - Whole flash area for any case... 0x20000000[0x01000000]
* Total 3 minors per flash device.
*
* It is easier to have static size vectors, so we define
* a total minor range JSF_MAX, which must cover all minors.
*/
/* character device */
#define JSF_MINOR 178 /* 178 is registered with hpa */
/* block device */
#define JSF_MAX 3 /* 3 minors wasted total so far. */
#define JSF_NPART 3 /* 3 minors per flash device */
#define JSF_PART_BITS 2 /* 2 bits of minors to cover JSF_NPART */
#define JSF_PART_MASK 0x3 /* 2 bits mask */
/*
* Access functions.
* We could ioremap(), but it's easier this way.
*/
static unsigned int jsf_inl(unsigned long addr)
{
unsigned long retval;
__asm__ __volatile__("lda [%1] %2, %0\n\t" :
"=r" (retval) :
"r" (addr), "i" (ASI_M_BYPASS));
return retval;
}
static void jsf_outl(unsigned long addr, __u32 data)
{
__asm__ __volatile__("sta %0, [%1] %2\n\t" : :
"r" (data), "r" (addr), "i" (ASI_M_BYPASS) :
"memory");
}
/*
* soft carrier
*/
struct jsfd_part {
unsigned long dbase;
unsigned long dsize;
};
struct jsflash {
unsigned long base;
unsigned long size;
unsigned long busy; /* In use? */
struct jsflash_ident_arg id;
/* int mbase; */ /* Minor base, typically zero */
struct jsfd_part dv[JSF_NPART];
};
/*
* We do not map normal memory or obio as a safety precaution.
* But offsets are real, for ease of userland programming.
*/
#define JSF_BASE_TOP 0x30000000
#define JSF_BASE_ALL 0x20000000
#define JSF_BASE_JK 0x20400000
/*
*/
static struct gendisk *jsfd_disk[JSF_MAX];
/*
* Let's pretend we may have several of these...
*/
static struct jsflash jsf0;
/*
* Wait for AMD to finish its embedded algorithm.
* We use the Toggle bit DQ6 (0x40) because it does not
* depend on the data value as /DATA bit DQ7 does.
*
* XXX Do we need any timeout here? So far it never hanged, beware broken hw.
*/
static void jsf_wait(unsigned long p) {
unsigned int x1, x2;
for (;;) {
x1 = jsf_inl(p);
x2 = jsf_inl(p);
if ((x1 & 0x40404040) == (x2 & 0x40404040)) return;
}
}
/*
* Programming will only work if Flash is clean,
* we leave it to the programmer application.
*
* AMD must be programmed one byte at a time;
* thus, Simple Tech SIMM must be written 4 bytes at a time.
*
* Write waits for the chip to become ready after the write
* was finished. This is done so that application would read
* consistent data after the write is done.
*/
static void jsf_write4(unsigned long fa, u32 data) {
jsf_outl(fa, 0xAAAAAAAA); /* Unlock 1 Write 1 */
jsf_outl(fa, 0x55555555); /* Unlock 1 Write 2 */
jsf_outl(fa, 0xA0A0A0A0); /* Byte Program */
jsf_outl(fa, data);
jsf_wait(fa);
}
/*
*/
static void jsfd_read(char *buf, unsigned long p, size_t togo) {
union byte4 {
char s[4];
unsigned int n;
} b;
while (togo >= 4) {
togo -= 4;
b.n = jsf_inl(p);
memcpy(buf, b.s, 4);
p += 4;
buf += 4;
}
}
static void jsfd_do_request(struct request_queue *q)
{
struct request *req;
req = blk_fetch_request(q);
while (req) {
struct jsfd_part *jdp = req->rq_disk->private_data;
unsigned long offset = blk_rq_pos(req) << 9;
size_t len = blk_rq_cur_bytes(req);
int err = -EIO;
if ((offset + len) > jdp->dsize)
goto end;
if (rq_data_dir(req) != READ) {
printk(KERN_ERR "jsfd: write\n");
goto end;
}
if ((jdp->dbase & 0xff000000) != 0x20000000) {
printk(KERN_ERR "jsfd: bad base %x\n", (int)jdp->dbase);
goto end;
}
jsfd_read(req->buffer, jdp->dbase + offset, len);
err = 0;
end:
if (!__blk_end_request_cur(req, err))
req = blk_fetch_request(q);
}
}
/*
* The memory devices use the full 32/64 bits of the offset, and so we cannot
* check against negative addresses: they are ok. The return value is weird,
* though, in that case (0).
*
* also note that seeking relative to the "end of file" isn't supported:
* it has no meaning, so it returns -EINVAL.
*/
static loff_t jsf_lseek(struct file * file, loff_t offset, int orig)
{
loff_t ret;
lock_kernel();
switch (orig) {
case 0:
file->f_pos = offset;
ret = file->f_pos;
break;
case 1:
file->f_pos += offset;
ret = file->f_pos;
break;
default:
ret = -EINVAL;
}
unlock_kernel();
return ret;
}
/*
* OS SIMM Cannot be read in other size but a 32bits word.
*/
static ssize_t jsf_read(struct file * file, char __user * buf,
size_t togo, loff_t *ppos)
{
unsigned long p = *ppos;
char __user *tmp = buf;
union byte4 {
char s[4];
unsigned int n;
} b;
if (p < JSF_BASE_ALL || p >= JSF_BASE_TOP) {
return 0;
}
if ((p + togo) < p /* wrap */
|| (p + togo) >= JSF_BASE_TOP) {
togo = JSF_BASE_TOP - p;
}
if (p < JSF_BASE_ALL && togo != 0) {
#if 0 /* __bzero XXX */
size_t x = JSF_BASE_ALL - p;
if (x > togo) x = togo;
clear_user(tmp, x);
tmp += x;
p += x;
togo -= x;
#else
/*
* Implementation of clear_user() calls __bzero
* without regard to modversions,
* so we cannot build a module.
*/
return 0;
#endif
}
while (togo >= 4) {
togo -= 4;
b.n = jsf_inl(p);
if (copy_to_user(tmp, b.s, 4))
return -EFAULT;
tmp += 4;
p += 4;
}
/*
* XXX Small togo may remain if 1 byte is ordered.
* It would be nice if we did a word size read and unpacked it.
*/
*ppos = p;
return tmp-buf;
}
static ssize_t jsf_write(struct file * file, const char __user * buf,
size_t count, loff_t *ppos)
{
return -ENOSPC;
}
/*
*/
static int jsf_ioctl_erase(unsigned long arg)
{
unsigned long p;
/* p = jsf0.base; hits wrong bank */
p = 0x20400000;
jsf_outl(p, 0xAAAAAAAA); /* Unlock 1 Write 1 */
jsf_outl(p, 0x55555555); /* Unlock 1 Write 2 */
jsf_outl(p, 0x80808080); /* Erase setup */
jsf_outl(p, 0xAAAAAAAA); /* Unlock 2 Write 1 */
jsf_outl(p, 0x55555555); /* Unlock 2 Write 2 */
jsf_outl(p, 0x10101010); /* Chip erase */
#if 0
/*
* This code is ok, except that counter based timeout
* has no place in this world. Let's just drop timeouts...
*/
{
int i;
__u32 x;
for (i = 0; i < 1000000; i++) {
x = jsf_inl(p);
if ((x & 0x80808080) == 0x80808080) break;
}
if ((x & 0x80808080) != 0x80808080) {
printk("jsf0: erase timeout with 0x%08x\n", x);
} else {
printk("jsf0: erase done with 0x%08x\n", x);
}
}
#else
jsf_wait(p);
#endif
return 0;
}
/*
* Program a block of flash.
* Very simple because we can do it byte by byte anyway.
*/
static int jsf_ioctl_program(void __user *arg)
{
struct jsflash_program_arg abuf;
char __user *uptr;
unsigned long p;
unsigned int togo;
union {
unsigned int n;
char s[4];
} b;
if (copy_from_user(&abuf, arg, JSFPRGSZ))
return -EFAULT;
p = abuf.off;
togo = abuf.size;
if ((togo & 3) || (p & 3)) return -EINVAL;
uptr = (char __user *) (unsigned long) abuf.data;
while (togo != 0) {
togo -= 4;
if (copy_from_user(&b.s[0], uptr, 4))
return -EFAULT;
jsf_write4(p, b.n);
p += 4;
uptr += 4;
}
return 0;
}
static long jsf_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
{
lock_kernel();
int error = -ENOTTY;
void __user *argp = (void __user *)arg;
if (!capable(CAP_SYS_ADMIN)) {
unlock_kernel();
return -EPERM;
}
switch (cmd) {
case JSFLASH_IDENT:
if (copy_to_user(argp, &jsf0.id, JSFIDSZ)) {
unlock_kernel();
return -EFAULT;
}
break;
case JSFLASH_ERASE:
error = jsf_ioctl_erase(arg);
break;
case JSFLASH_PROGRAM:
error = jsf_ioctl_program(argp);
break;
}
unlock_kernel();
return error;
}
static int jsf_mmap(struct file * file, struct vm_area_struct * vma)
{
return -ENXIO;
}
static int jsf_open(struct inode * inode, struct file * filp)
{
lock_kernel();
if (jsf0.base == 0) {
unlock_kernel();
return -ENXIO;
}
if (test_and_set_bit(0, (void *)&jsf0.busy) != 0) {
unlock_kernel();
return -EBUSY;
}
unlock_kernel();
return 0; /* XXX What security? */
}
static int jsf_release(struct inode *inode, struct file *file)
{
jsf0.busy = 0;
return 0;
}
static const struct file_operations jsf_fops = {
.owner = THIS_MODULE,
.llseek = jsf_lseek,
.read = jsf_read,
.write = jsf_write,
.unlocked_ioctl = jsf_ioctl,
.mmap = jsf_mmap,
.open = jsf_open,
.release = jsf_release,
};
static struct miscdevice jsf_dev = { JSF_MINOR, "jsflash", &jsf_fops };
static const struct block_device_operations jsfd_fops = {
.owner = THIS_MODULE,
};
static int jsflash_init(void)
{
int rc;
struct jsflash *jsf;
int node;
char banner[128];
struct linux_prom_registers reg0;
node = prom_getchild(prom_root_node);
node = prom_searchsiblings(node, "flash-memory");
if (node != 0 && node != -1) {
if (prom_getproperty(node, "reg",
(char *)®0, sizeof(reg0)) == -1) {
printk("jsflash: no \"reg\" property\n");
return -ENXIO;
}
if (reg0.which_io != 0) {
printk("jsflash: bus number nonzero: 0x%x:%x\n",
reg0.which_io, reg0.phys_addr);
return -ENXIO;
}
/*
* Flash may be somewhere else, for instance on Ebus.
* So, don't do the following check for IIep flash space.
*/
#if 0
if ((reg0.phys_addr >> 24) != 0x20) {
printk("jsflash: suspicious address: 0x%x:%x\n",
reg0.which_io, reg0.phys_addr);
return -ENXIO;
}
#endif
if ((int)reg0.reg_size <= 0) {
printk("jsflash: bad size 0x%x\n", (int)reg0.reg_size);
return -ENXIO;
}
} else {
/* XXX Remove this code once PROLL ID12 got widespread */
printk("jsflash: no /flash-memory node, use PROLL >= 12\n");
prom_getproperty(prom_root_node, "banner-name", banner, 128);
if (strcmp (banner, "JavaStation-NC") != 0 &&
strcmp (banner, "JavaStation-E") != 0) {
return -ENXIO;
}
reg0.which_io = 0;
reg0.phys_addr = 0x20400000;
reg0.reg_size = 0x00800000;
}
/* Let us be really paranoid for modifications to probing code. */
/* extern enum sparc_cpu sparc_cpu_model; */ /* in <asm/system.h> */
if (sparc_cpu_model != sun4m) {
/* We must be on sun4m because we use MMU Bypass ASI. */
return -ENXIO;
}
if (jsf0.base == 0) {
jsf = &jsf0;
jsf->base = reg0.phys_addr;
jsf->size = reg0.reg_size;
/* XXX Redo the userland interface. */
jsf->id.off = JSF_BASE_ALL;
jsf->id.size = 0x01000000; /* 16M - all segments */
strcpy(jsf->id.name, "Krups_all");
jsf->dv[0].dbase = jsf->base;
jsf->dv[0].dsize = jsf->size;
jsf->dv[1].dbase = jsf->base + 1024;
jsf->dv[1].dsize = jsf->size - 1024;
jsf->dv[2].dbase = JSF_BASE_ALL;
jsf->dv[2].dsize = 0x01000000;
printk("Espresso Flash @0x%lx [%d MB]\n", jsf->base,
(int) (jsf->size / (1024*1024)));
}
if ((rc = misc_register(&jsf_dev)) != 0) {
printk(KERN_ERR "jsf: unable to get misc minor %d\n",
JSF_MINOR);
jsf0.base = 0;
return rc;
}
return 0;
}
static struct request_queue *jsf_queue;
static int jsfd_init(void)
{
static DEFINE_SPINLOCK(lock);
struct jsflash *jsf;
struct jsfd_part *jdp;
int err;
int i;
if (jsf0.base == 0)
return -ENXIO;
err = -ENOMEM;
for (i = 0; i < JSF_MAX; i++) {
struct gendisk *disk = alloc_disk(1);
if (!disk)
goto out;
jsfd_disk[i] = disk;
}
if (register_blkdev(JSFD_MAJOR, "jsfd")) {
err = -EIO;
goto out;
}
jsf_queue = blk_init_queue(jsfd_do_request, &lock);
if (!jsf_queue) {
err = -ENOMEM;
unregister_blkdev(JSFD_MAJOR, "jsfd");
goto out;
}
for (i = 0; i < JSF_MAX; i++) {
struct gendisk *disk = jsfd_disk[i];
if ((i & JSF_PART_MASK) >= JSF_NPART) continue;
jsf = &jsf0; /* actually, &jsfv[i >> JSF_PART_BITS] */
jdp = &jsf->dv[i&JSF_PART_MASK];
disk->major = JSFD_MAJOR;
disk->first_minor = i;
sprintf(disk->disk_name, "jsfd%d", i);
disk->fops = &jsfd_fops;
set_capacity(disk, jdp->dsize >> 9);
disk->private_data = jdp;
disk->queue = jsf_queue;
add_disk(disk);
set_disk_ro(disk, 1);
}
return 0;
out:
while (i--)
put_disk(jsfd_disk[i]);
return err;
}
MODULE_LICENSE("GPL");
static int __init jsflash_init_module(void) {
int rc;
if ((rc = jsflash_init()) == 0) {
jsfd_init();
return 0;
}
return rc;
}
static void __exit jsflash_cleanup_module(void)
{
int i;
for (i = 0; i < JSF_MAX; i++) {
if ((i & JSF_PART_MASK) >= JSF_NPART) continue;
del_gendisk(jsfd_disk[i]);
put_disk(jsfd_disk[i]);
}
if (jsf0.busy)
printk("jsf0: cleaning busy unit\n");
jsf0.base = 0;
jsf0.busy = 0;
misc_deregister(&jsf_dev);
unregister_blkdev(JSFD_MAJOR, "jsfd");
blk_cleanup_queue(jsf_queue);
}
module_init(jsflash_init_module);
module_exit(jsflash_cleanup_module);
| gpl-2.0 |
javelinanddart/kernel_zte_draconis | drivers/staging/prima/CORE/VOSS/src/vos_event.c | 1401 | 18443 | /*
* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by 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.
*/
/*
* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by 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.
*/
/*============================================================================
FILE: vos_event.c
OVERVIEW: This source file contains definitions for vOS event APIs
The five APIs mentioned in this file are used for
initializing, setting, resetting, destroying an event and
waiting on an occurance of an event among multiple events.
DEPENDENCIES:
Copyright (c) 2007 QUALCOMM Incorporated.
All Rights Reserved.
Qualcomm Confidential and Proprietary
============================================================================*/
/*============================================================================
EDIT HISTORY FOR MODULE
============================================================================*/
/*----------------------------------------------------------------------------
* Include Files
* -------------------------------------------------------------------------*/
#include "vos_event.h"
#include "vos_trace.h"
/*----------------------------------------------------------------------------
* Preprocessor Definitions and Constants
* -------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
* Type Declarations
* -------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
* Global Data Definitions
* -------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
* Static Variable Definitions
* -------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
Function Definitions and Documentation
* -------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------
\brief vos_event_init() - initializes a vOSS event
The vos_event_init() function initializes the specified event. Upon
successful initialization, the state of the event becomes initialized
and not signaled.
An event must be initialized before it may be used in any other event
functions.
Attempting to initialize an already initialized event results in
a failure.
\param lock - pointer to the opaque event object to initialize
\return VOS_STATUS_SUCCESS - event was successfully initialized and
is ready to be used.
VOS_STATUS_E_BUSY - The implementation has detected an attempt
to reinitialize the object referenced by event, a previously
initialized, but not yet destroyed, event.
VOS_STATUS_E_FAULT - event is an invalid pointer.
VOS_STATUS_E_FAILURE - event could not be created due to
unknown reasons
***VOS_STATUS_E_RESOURCES - System resources (other than memory)
are unavailable to initilize the event
***VOS_STATUS_E_NOMEM - insufficient memory exists to initialize
the event
\sa
( *** indicates return values do NOT exist yet )
-------------------------------------------------------------------------*/
VOS_STATUS vos_event_init ( vos_event_t* event )
{
// Check for null pointer
if ( NULL == event )
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"NULL event passed into %s", __func__);
VOS_ASSERT(0);
return VOS_STATUS_E_FAULT;
}
// check for 'already initialized' event
if ( LINUX_EVENT_COOKIE == event->cookie )
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"Initialized event passed into %s", __func__);
VOS_ASSERT(0);
return VOS_STATUS_E_BUSY;
}
// initialize new event
init_completion(&event->complete);
event->cookie = LINUX_EVENT_COOKIE;
return VOS_STATUS_SUCCESS;
}
/*--------------------------------------------------------------------------
\brief vos_event_set() - sets a vOSS event
The state of the specified event is set to 'signalled by calling
\a vos_event_set().
Any threads waiting on the event as a result of a vos_event_wait() will
be unblocked and available to be scheduled for execution when the event
is signaled by a call to \a vos_event_set().
\param event - the event to set to the signalled state
\return VOS_STATUS_SUCCESS - the event was successfully signalled.
VOS_STATUS_E_INVAL - The value specified by event does not refer
to an initialized event object.
VOS_STATUS_E_FAULT - event is an invalid pointer.
VOS_STATUS_E_FAILURE - event could not be signaled due to
unknown reasons
\sa
-------------------------------------------------------------------------*/
VOS_STATUS vos_event_set ( vos_event_t* event )
{
// Check for null pointer
if ( NULL == event )
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"NULL event passed into %s", __func__);
VOS_ASSERT(0);
return VOS_STATUS_E_FAULT;
}
// check if event refers to an initialized object
if ( LINUX_EVENT_COOKIE != event->cookie )
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"Uninitialized event passed into %s", __func__);
VOS_ASSERT(0);
return VOS_STATUS_E_INVAL;
}
complete(&event->complete);
return VOS_STATUS_SUCCESS;
}
/*--------------------------------------------------------------------------
\brief vos_event_reset() - resets a vOSS event - This function isn't required
for Linux. Therefore, it doesn't do much.
The state of the specified event is set to 'NOT signalled' by calling
\a vos_event_reset(). The state of the event remains NOT signalled until an
explicit call to vos_event_set().
This function sets the event to a NOT signalled state even if the event was
signalled multiple times before being signaled.
\param event - the event to set to the NOT signalled state
\return VOS_STATUS_SUCCESS - the event state was successfully change to
NOT signalled.
VOS_STATUS_E_INVAL - The value specified by event does not refer
to an initialized event object.
VOS_STATUS_E_FAULT - event is an invalid pointer.
VOS_STATUS_E_FAILURE - event could not be signaled due to
unknown reasons
\sa
-------------------------------------------------------------------------*/
VOS_STATUS vos_event_reset ( vos_event_t* event )
{
// check for null pointer
if ( NULL == event )
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"NULL event passed into %s", __func__);
VOS_ASSERT(0);
return VOS_STATUS_E_FAULT;
}
// check to make sure it is an 'already initialized' event
if ( LINUX_EVENT_COOKIE != event->cookie )
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"Uninitialized event passed into %s", __func__);
VOS_ASSERT(0);
return VOS_STATUS_E_INVAL;
}
// (re)initialize event
INIT_COMPLETION(event->complete);
return VOS_STATUS_SUCCESS;
}
/*----------------------------------------------------------------------------
\brief vos_wait_events() - Waits for the first event(s) to be set.
This API waits for any event in the input array of events to be
set. The caller is blocked waiting any event in the array to be
set or for the timeout to occur.
If multiple events in the array are set, only one event is identified
in the return from this call as satisfying the wait condition. The
caller is responsible for calling \a vos_wait_events() again to find
the other events that are set.
\param events - pointer to an array of events to wait on.
\param numEvents - Number of events in the events array to wait on.
\param timeout - Timeout value (in milliseconds). This function returns
if this interval elapses, regardless if any of the events have
been set. An input value of 0 for this timeout parameter means
to wait infinitely, meaning a timeout will never occur.
\param pEventIndex - This is a pointer to the location where the index of
the event in the event array that satisfied the wait because
the event was set.
\return VOS_STATUS_SUCCESS - the wait was satisifed by one of the events
in the event array being set. The index into the event arry
that satisfied the wait can be found at *pEventIndex.
VOS_STATUS_E_TIMEOUT - the timeout interval elapsed before any of
the events were set.
VOS_STATUS_E_INVAL - At least one of the values specified in the
event array refers to an uninitialized event object.
VOS_STATUS_E_ABORTED - The event due to which the wait was aborted
is identified by the index in *pEventIndex.
VOS_STATUS_E_EMPTY - the events array is empty. This condition
is detected by numEvents being 0 on input.
VOS_STATUS_E_FAULT - event or pEventIndex is an invalid pointer.
VOS_STATUS_E_FAILURE - default return value if it fails due to
unknown reasons
\sa
--------------------------------------------------------------------------*/
VOS_STATUS vos_wait_events ( vos_event_t* events,
v_U8_t numEvents, v_U32_t timeout,
v_U8_t *pEventIndex )
{
return vos_wait_single_event(events,timeout);
}
/*--------------------------------------------------------------------------
\brief vos_event_destroy() - Destroys a vOSS event - This function doesn't do
much in Linux. There is no need for the caller to explicitly destroy an event
after use.
The os_event_destroy() function shall destroy the event object
referenced by event. After a successful return from \a vos_event_destroy()
the event object becomes, in effect, uninitialized.
A destroyed event object can be reinitialized using vos_event_init();
the results of otherwise referencing the object after it has been destroyed
are undefined. Calls to vOSS event functions to manipulate the lock such
as vos_event_set() will fail if the event is destroyed. Therefore,
don't use the event after it has been destroyed until it has
been re-initialized.
\param event - the event object to be destroyed.
\return VOS_STATUS_SUCCESS - event was successfully destroyed.
VOS_STATUS_E_INVAL - The value specified by event is invalid.
VOS_STATUS_E_FAULT - event is an invalid pointer.
VOS_STATUS_E_FAILURE - event could not be signaled due to
unknown reasons
***VOS_STATUS_E_BUSY - The implementation has detected an attempt
to destroy the object referenced by event while it is still being
referenced (there are threads waiting on this event)
\sa
( *** indicates return values do NOT exist yet )
-------------------------------------------------------------------------*/
VOS_STATUS vos_event_destroy ( vos_event_t* event )
{
// check for null pointer
if ( NULL == event )
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"NULL event passed into %s", __func__);
VOS_ASSERT(0);
return VOS_STATUS_E_FAULT;
}
// check to make sure it is an 'already initialized' event
if ( LINUX_EVENT_COOKIE != event->cookie )
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"Uninitialized event passed into %s", __func__);
VOS_ASSERT(0);
return VOS_STATUS_E_INVAL;
}
// make sure nobody is waiting on the event
complete_all(&event->complete);
// destroy the event
memset(event, 0, sizeof(vos_event_t));
return VOS_STATUS_SUCCESS;
}
/*----------------------------------------------------------------------------
\brief vos_wait_single_event() - Waits for a single event to be set.
This API waits for the event to be set.
\param pEvent - pointer to an event to wait on.
\param timeout - Timeout value (in milliseconds). This function returns
if this interval elapses, regardless if any of the events have
been set. An input value of 0 for this timeout parameter means
to wait infinitely, meaning a timeout will never occur.
\return VOS_STATUS_SUCCESS - the wait was satisifed by the event being
set.
VOS_STATUS_E_TIMEOUT - the timeout interval elapsed before the
event was set.
VOS_STATUS_E_INVAL - The value specified by event is invalid.
VOS_STATUS_E_FAULT - pEvent is an invalid pointer.
\sa vos_wait_multiple_events()
--------------------------------------------------------------------------*/
VOS_STATUS vos_wait_single_event ( vos_event_t* event, v_U32_t timeout)
{
if (in_interrupt())
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"%s cannot be called from interrupt context!!!", __func__);
VOS_ASSERT(0);
return VOS_STATUS_E_FAULT;
}
// check for null pointer
if ( NULL == event )
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"NULL event passed into %s", __func__);
VOS_ASSERT(0);
return VOS_STATUS_E_FAULT;
}
// check if cookie is same as that of initialized event
if ( LINUX_EVENT_COOKIE != event->cookie )
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"Uninitialized event passed into %s", __func__);
VOS_ASSERT(0);
return VOS_STATUS_E_INVAL;
}
if (timeout)
{
long ret;
ret =
wait_for_completion_timeout(&event->complete,
msecs_to_jiffies(timeout));
if ( 0 >= ret )
{
return VOS_STATUS_E_TIMEOUT;
}
}
else
{
int ret;
ret = wait_for_completion_interruptible(&event->complete);
if ( 0 != ret )
{
// negative means interrupted
return VOS_STATUS_E_TIMEOUT;
}
}
return VOS_STATUS_SUCCESS;
}
/*----------------------------------------------------------------------------
\brief vos_wait_multiple_events() - Waits for event(s) to be set.
This is a duplicate of vos_wait_events() function. It ends up calling
vos_wait_events() with the params passed in.
This API waits for any event in the input array of events to be
set. The caller is blocked waiting any event in the array to be
set or for the timeout to occur.
If multiple events in the array are set, only one event is identified
in the return from this call as satisfying the wait condition. The
caller is responsible for calling \a vos_wait_events() again to find
the other events that are set.
\param pEventList - pointer to an array of event pointers
\param numEvents - Number of events
\param timeout - Timeout value (in milliseconds). This function returns
if this interval elapses, regardless if any of the events have
been set. An input value of 0 for this timeout parameter means
to wait infinitely, meaning a timeout will never occur.
\param pEventIndex - This is a pointer to the location where the index of
the event in the event array that satisfied the wait because
the event was set.
\return VOS_STATUS_SUCCESS - the wait was satisifed by one of the events
in the event array being set. The index into the event arry
that satisfied the wait can be found at *pEventIndex.
VOS_STATUS_E_TIMEOUT - the timeout interval elapsed before any of
the events were set.
VOS_STATUS_E_INVAL - At least one of the values specified in the
event array refers to an uninitialized event object. The invalid
event is identified by the index in *pEventIndex. Note that only
the first uninitialized event is detected when this error is
returned.
VOS_STATUS_E_EMPTY - the events array is empty. This condition
is detected by numEvents being 0 on input.
VOS_STATUS_E_FAULT - event or pEventIndex is an invalid pointer.
\sa vos_wait_single_events()
--------------------------------------------------------------------------*/
VOS_STATUS vos_wait_multiple_events( vos_event_t **events, v_U8_t numEvents,
v_U32_t timeout, v_U8_t *pEventIndex )
{
// NO LONGER SUPPORTED
return VOS_STATUS_E_FAILURE;
}
| gpl-2.0 |
dan82840/Netgear-RBR50 | git_home/linux.git/drivers/hid/hid-xinmo.c | 2169 | 1530 | /*
* HID driver for Xin-Mo devices, currently only the Dual Arcade controller.
* Fixes the negative axis event values (the devices sends -2) to match the
* logical axis minimum of the HID report descriptor (the report announces
* -1). It is needed because hid-input discards out of bounds values.
* (This module is based on "hid-saitek" and "hid-lg".)
*
* Copyright (c) 2013 Olivier Scherler
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*/
#include <linux/device.h>
#include <linux/hid.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include "hid-ids.h"
/*
* Fix negative events that are out of bounds.
*/
static int xinmo_event(struct hid_device *hdev, struct hid_field *field,
struct hid_usage *usage, __s32 value)
{
switch (usage->code) {
case ABS_X:
case ABS_Y:
case ABS_Z:
case ABS_RX:
if (value < -1) {
input_event(field->hidinput->input, usage->type,
usage->code, -1);
return 1;
}
break;
}
return 0;
}
static const struct hid_device_id xinmo_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_XIN_MO, USB_DEVICE_ID_XIN_MO_DUAL_ARCADE) },
{ }
};
MODULE_DEVICE_TABLE(hid, xinmo_devices);
static struct hid_driver xinmo_driver = {
.name = "xinmo",
.id_table = xinmo_devices,
.event = xinmo_event
};
module_hid_driver(xinmo_driver);
MODULE_LICENSE("GPL");
| gpl-2.0 |
trlsmax/rk3188_kernel_tinyastro | arch/sparc/mm/fault_32.c | 2169 | 14479 | /*
* fault.c: Page fault handlers for the Sparc.
*
* Copyright (C) 1995 David S. Miller (davem@caip.rutgers.edu)
* Copyright (C) 1996 Eddie C. Dost (ecd@skynet.be)
* Copyright (C) 1997 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
*/
#include <asm/head.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/sched.h>
#include <linux/ptrace.h>
#include <linux/mman.h>
#include <linux/threads.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/perf_event.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/kdebug.h>
#include <asm/system.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/memreg.h>
#include <asm/openprom.h>
#include <asm/oplib.h>
#include <asm/smp.h>
#include <asm/traps.h>
#include <asm/uaccess.h>
extern int prom_node_root;
int show_unhandled_signals = 1;
/* At boot time we determine these two values necessary for setting
* up the segment maps and page table entries (pte's).
*/
int num_segmaps, num_contexts;
int invalid_segment;
/* various Virtual Address Cache parameters we find at boot time... */
int vac_size, vac_linesize, vac_do_hw_vac_flushes;
int vac_entries_per_context, vac_entries_per_segment;
int vac_entries_per_page;
/* Return how much physical memory we have. */
unsigned long probe_memory(void)
{
unsigned long total = 0;
int i;
for (i = 0; sp_banks[i].num_bytes; i++)
total += sp_banks[i].num_bytes;
return total;
}
extern void sun4c_complete_all_stores(void);
/* Whee, a level 15 NMI interrupt memory error. Let's have fun... */
asmlinkage void sparc_lvl15_nmi(struct pt_regs *regs, unsigned long serr,
unsigned long svaddr, unsigned long aerr,
unsigned long avaddr)
{
sun4c_complete_all_stores();
printk("FAULT: NMI received\n");
printk("SREGS: Synchronous Error %08lx\n", serr);
printk(" Synchronous Vaddr %08lx\n", svaddr);
printk(" Asynchronous Error %08lx\n", aerr);
printk(" Asynchronous Vaddr %08lx\n", avaddr);
if (sun4c_memerr_reg)
printk(" Memory Parity Error %08lx\n", *sun4c_memerr_reg);
printk("REGISTER DUMP:\n");
show_regs(regs);
prom_halt();
}
static void unhandled_fault(unsigned long, struct task_struct *,
struct pt_regs *) __attribute__ ((noreturn));
static void unhandled_fault(unsigned long address, struct task_struct *tsk,
struct pt_regs *regs)
{
if((unsigned long) address < PAGE_SIZE) {
printk(KERN_ALERT
"Unable to handle kernel NULL pointer dereference\n");
} else {
printk(KERN_ALERT "Unable to handle kernel paging request "
"at virtual address %08lx\n", address);
}
printk(KERN_ALERT "tsk->{mm,active_mm}->context = %08lx\n",
(tsk->mm ? tsk->mm->context : tsk->active_mm->context));
printk(KERN_ALERT "tsk->{mm,active_mm}->pgd = %08lx\n",
(tsk->mm ? (unsigned long) tsk->mm->pgd :
(unsigned long) tsk->active_mm->pgd));
die_if_kernel("Oops", regs);
}
asmlinkage int lookup_fault(unsigned long pc, unsigned long ret_pc,
unsigned long address)
{
struct pt_regs regs;
unsigned long g2;
unsigned int insn;
int i;
i = search_extables_range(ret_pc, &g2);
switch (i) {
case 3:
/* load & store will be handled by fixup */
return 3;
case 1:
/* store will be handled by fixup, load will bump out */
/* for _to_ macros */
insn = *((unsigned int *) pc);
if ((insn >> 21) & 1)
return 1;
break;
case 2:
/* load will be handled by fixup, store will bump out */
/* for _from_ macros */
insn = *((unsigned int *) pc);
if (!((insn >> 21) & 1) || ((insn>>19)&0x3f) == 15)
return 2;
break;
default:
break;
}
memset(®s, 0, sizeof (regs));
regs.pc = pc;
regs.npc = pc + 4;
__asm__ __volatile__(
"rd %%psr, %0\n\t"
"nop\n\t"
"nop\n\t"
"nop\n" : "=r" (regs.psr));
unhandled_fault(address, current, ®s);
/* Not reached */
return 0;
}
static inline void
show_signal_msg(struct pt_regs *regs, int sig, int code,
unsigned long address, struct task_struct *tsk)
{
if (!unhandled_signal(tsk, sig))
return;
if (!printk_ratelimit())
return;
printk("%s%s[%d]: segfault at %lx ip %p (rpc %p) sp %p error %x",
task_pid_nr(tsk) > 1 ? KERN_INFO : KERN_EMERG,
tsk->comm, task_pid_nr(tsk), address,
(void *)regs->pc, (void *)regs->u_regs[UREG_I7],
(void *)regs->u_regs[UREG_FP], code);
print_vma_addr(KERN_CONT " in ", regs->pc);
printk(KERN_CONT "\n");
}
static void __do_fault_siginfo(int code, int sig, struct pt_regs *regs,
unsigned long addr)
{
siginfo_t info;
info.si_signo = sig;
info.si_code = code;
info.si_errno = 0;
info.si_addr = (void __user *) addr;
info.si_trapno = 0;
if (unlikely(show_unhandled_signals))
show_signal_msg(regs, sig, info.si_code,
addr, current);
force_sig_info (sig, &info, current);
}
extern unsigned long safe_compute_effective_address(struct pt_regs *,
unsigned int);
static unsigned long compute_si_addr(struct pt_regs *regs, int text_fault)
{
unsigned int insn;
if (text_fault)
return regs->pc;
if (regs->psr & PSR_PS) {
insn = *(unsigned int *) regs->pc;
} else {
__get_user(insn, (unsigned int *) regs->pc);
}
return safe_compute_effective_address(regs, insn);
}
static noinline void do_fault_siginfo(int code, int sig, struct pt_regs *regs,
int text_fault)
{
unsigned long addr = compute_si_addr(regs, text_fault);
__do_fault_siginfo(code, sig, regs, addr);
}
asmlinkage void do_sparc_fault(struct pt_regs *regs, int text_fault, int write,
unsigned long address)
{
struct vm_area_struct *vma;
struct task_struct *tsk = current;
struct mm_struct *mm = tsk->mm;
unsigned int fixup;
unsigned long g2;
int from_user = !(regs->psr & PSR_PS);
int fault, code;
if(text_fault)
address = regs->pc;
/*
* We fault-in kernel-space virtual memory on-demand. The
* 'reference' page table is init_mm.pgd.
*
* NOTE! We MUST NOT take any locks for this case. We may
* be in an interrupt or a critical region, and should
* only copy the information from the master page table,
* nothing more.
*/
code = SEGV_MAPERR;
if (!ARCH_SUN4C && address >= TASK_SIZE)
goto vmalloc_fault;
/*
* If we're in an interrupt or have no user
* context, we must not take the fault..
*/
if (in_atomic() || !mm)
goto no_context;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, address);
down_read(&mm->mmap_sem);
/*
* The kernel referencing a bad kernel pointer can lock up
* a sun4c machine completely, so we must attempt recovery.
*/
if(!from_user && address >= PAGE_OFFSET)
goto bad_area;
vma = find_vma(mm, address);
if(!vma)
goto bad_area;
if(vma->vm_start <= address)
goto good_area;
if(!(vma->vm_flags & VM_GROWSDOWN))
goto bad_area;
if(expand_stack(vma, address))
goto bad_area;
/*
* Ok, we have a good vm_area for this memory access, so
* we can handle it..
*/
good_area:
code = SEGV_ACCERR;
if(write) {
if(!(vma->vm_flags & VM_WRITE))
goto bad_area;
} else {
/* Allow reads even for write-only mappings */
if(!(vma->vm_flags & (VM_READ | VM_EXEC)))
goto bad_area;
}
/*
* If for any reason at all we couldn't handle the fault,
* make sure we exit gracefully rather than endlessly redo
* the fault.
*/
fault = handle_mm_fault(mm, vma, address, write ? FAULT_FLAG_WRITE : 0);
if (unlikely(fault & VM_FAULT_ERROR)) {
if (fault & VM_FAULT_OOM)
goto out_of_memory;
else if (fault & VM_FAULT_SIGBUS)
goto do_sigbus;
BUG();
}
if (fault & VM_FAULT_MAJOR) {
current->maj_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0,
regs, address);
} else {
current->min_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0,
regs, address);
}
up_read(&mm->mmap_sem);
return;
/*
* Something tried to access memory that isn't in our memory map..
* Fix it, but check if it's kernel or user first..
*/
bad_area:
up_read(&mm->mmap_sem);
bad_area_nosemaphore:
/* User mode accesses just cause a SIGSEGV */
if (from_user) {
do_fault_siginfo(code, SIGSEGV, regs, text_fault);
return;
}
/* Is this in ex_table? */
no_context:
g2 = regs->u_regs[UREG_G2];
if (!from_user) {
fixup = search_extables_range(regs->pc, &g2);
if (fixup > 10) { /* Values below are reserved for other things */
extern const unsigned __memset_start[];
extern const unsigned __memset_end[];
extern const unsigned __csum_partial_copy_start[];
extern const unsigned __csum_partial_copy_end[];
#ifdef DEBUG_EXCEPTIONS
printk("Exception: PC<%08lx> faddr<%08lx>\n", regs->pc, address);
printk("EX_TABLE: insn<%08lx> fixup<%08x> g2<%08lx>\n",
regs->pc, fixup, g2);
#endif
if ((regs->pc >= (unsigned long)__memset_start &&
regs->pc < (unsigned long)__memset_end) ||
(regs->pc >= (unsigned long)__csum_partial_copy_start &&
regs->pc < (unsigned long)__csum_partial_copy_end)) {
regs->u_regs[UREG_I4] = address;
regs->u_regs[UREG_I5] = regs->pc;
}
regs->u_regs[UREG_G2] = g2;
regs->pc = fixup;
regs->npc = regs->pc + 4;
return;
}
}
unhandled_fault (address, tsk, regs);
do_exit(SIGKILL);
/*
* We ran out of memory, or some other thing happened to us that made
* us unable to handle the page fault gracefully.
*/
out_of_memory:
up_read(&mm->mmap_sem);
if (from_user) {
pagefault_out_of_memory();
return;
}
goto no_context;
do_sigbus:
up_read(&mm->mmap_sem);
do_fault_siginfo(BUS_ADRERR, SIGBUS, regs, text_fault);
if (!from_user)
goto no_context;
vmalloc_fault:
{
/*
* Synchronize this task's top level page-table
* with the 'reference' page table.
*/
int offset = pgd_index(address);
pgd_t *pgd, *pgd_k;
pmd_t *pmd, *pmd_k;
pgd = tsk->active_mm->pgd + offset;
pgd_k = init_mm.pgd + offset;
if (!pgd_present(*pgd)) {
if (!pgd_present(*pgd_k))
goto bad_area_nosemaphore;
pgd_val(*pgd) = pgd_val(*pgd_k);
return;
}
pmd = pmd_offset(pgd, address);
pmd_k = pmd_offset(pgd_k, address);
if (pmd_present(*pmd) || !pmd_present(*pmd_k))
goto bad_area_nosemaphore;
*pmd = *pmd_k;
return;
}
}
asmlinkage void do_sun4c_fault(struct pt_regs *regs, int text_fault, int write,
unsigned long address)
{
extern void sun4c_update_mmu_cache(struct vm_area_struct *,
unsigned long,pte_t *);
extern pte_t *sun4c_pte_offset_kernel(pmd_t *,unsigned long);
struct task_struct *tsk = current;
struct mm_struct *mm = tsk->mm;
pgd_t *pgdp;
pte_t *ptep;
if (text_fault) {
address = regs->pc;
} else if (!write &&
!(regs->psr & PSR_PS)) {
unsigned int insn, __user *ip;
ip = (unsigned int __user *)regs->pc;
if (!get_user(insn, ip)) {
if ((insn & 0xc1680000) == 0xc0680000)
write = 1;
}
}
if (!mm) {
/* We are oopsing. */
do_sparc_fault(regs, text_fault, write, address);
BUG(); /* P3 Oops already, you bitch */
}
pgdp = pgd_offset(mm, address);
ptep = sun4c_pte_offset_kernel((pmd_t *) pgdp, address);
if (pgd_val(*pgdp)) {
if (write) {
if ((pte_val(*ptep) & (_SUN4C_PAGE_WRITE|_SUN4C_PAGE_PRESENT))
== (_SUN4C_PAGE_WRITE|_SUN4C_PAGE_PRESENT)) {
unsigned long flags;
*ptep = __pte(pte_val(*ptep) | _SUN4C_PAGE_ACCESSED |
_SUN4C_PAGE_MODIFIED |
_SUN4C_PAGE_VALID |
_SUN4C_PAGE_DIRTY);
local_irq_save(flags);
if (sun4c_get_segmap(address) != invalid_segment) {
sun4c_put_pte(address, pte_val(*ptep));
local_irq_restore(flags);
return;
}
local_irq_restore(flags);
}
} else {
if ((pte_val(*ptep) & (_SUN4C_PAGE_READ|_SUN4C_PAGE_PRESENT))
== (_SUN4C_PAGE_READ|_SUN4C_PAGE_PRESENT)) {
unsigned long flags;
*ptep = __pte(pte_val(*ptep) | _SUN4C_PAGE_ACCESSED |
_SUN4C_PAGE_VALID);
local_irq_save(flags);
if (sun4c_get_segmap(address) != invalid_segment) {
sun4c_put_pte(address, pte_val(*ptep));
local_irq_restore(flags);
return;
}
local_irq_restore(flags);
}
}
}
/* This conditional is 'interesting'. */
if (pgd_val(*pgdp) && !(write && !(pte_val(*ptep) & _SUN4C_PAGE_WRITE))
&& (pte_val(*ptep) & _SUN4C_PAGE_VALID))
/* Note: It is safe to not grab the MMAP semaphore here because
* we know that update_mmu_cache() will not sleep for
* any reason (at least not in the current implementation)
* and therefore there is no danger of another thread getting
* on the CPU and doing a shrink_mmap() on this vma.
*/
sun4c_update_mmu_cache (find_vma(current->mm, address), address,
ptep);
else
do_sparc_fault(regs, text_fault, write, address);
}
/* This always deals with user addresses. */
static void force_user_fault(unsigned long address, int write)
{
struct vm_area_struct *vma;
struct task_struct *tsk = current;
struct mm_struct *mm = tsk->mm;
int code;
code = SEGV_MAPERR;
down_read(&mm->mmap_sem);
vma = find_vma(mm, address);
if(!vma)
goto bad_area;
if(vma->vm_start <= address)
goto good_area;
if(!(vma->vm_flags & VM_GROWSDOWN))
goto bad_area;
if(expand_stack(vma, address))
goto bad_area;
good_area:
code = SEGV_ACCERR;
if(write) {
if(!(vma->vm_flags & VM_WRITE))
goto bad_area;
} else {
if(!(vma->vm_flags & (VM_READ | VM_EXEC)))
goto bad_area;
}
switch (handle_mm_fault(mm, vma, address, write ? FAULT_FLAG_WRITE : 0)) {
case VM_FAULT_SIGBUS:
case VM_FAULT_OOM:
goto do_sigbus;
}
up_read(&mm->mmap_sem);
return;
bad_area:
up_read(&mm->mmap_sem);
__do_fault_siginfo(code, SIGSEGV, tsk->thread.kregs, address);
return;
do_sigbus:
up_read(&mm->mmap_sem);
__do_fault_siginfo(BUS_ADRERR, SIGBUS, tsk->thread.kregs, address);
}
static void check_stack_aligned(unsigned long sp)
{
if (sp & 0x7UL)
force_sig(SIGILL, current);
}
void window_overflow_fault(void)
{
unsigned long sp;
sp = current_thread_info()->rwbuf_stkptrs[0];
if(((sp + 0x38) & PAGE_MASK) != (sp & PAGE_MASK))
force_user_fault(sp + 0x38, 1);
force_user_fault(sp, 1);
check_stack_aligned(sp);
}
void window_underflow_fault(unsigned long sp)
{
if(((sp + 0x38) & PAGE_MASK) != (sp & PAGE_MASK))
force_user_fault(sp + 0x38, 0);
force_user_fault(sp, 0);
check_stack_aligned(sp);
}
void window_ret_fault(struct pt_regs *regs)
{
unsigned long sp;
sp = regs->u_regs[UREG_FP];
if(((sp + 0x38) & PAGE_MASK) != (sp & PAGE_MASK))
force_user_fault(sp + 0x38, 0);
force_user_fault(sp, 0);
check_stack_aligned(sp);
}
| gpl-2.0 |
cbolumar/android_kernel_samsung_a3ulte | tools/perf/ui/gtk/progress.c | 2425 | 1497 | #include <inttypes.h>
#include "gtk.h"
#include "../progress.h"
#include "util.h"
static GtkWidget *dialog;
static GtkWidget *progress;
static void gtk_progress_update(u64 curr, u64 total, const char *title)
{
double fraction = total ? 1.0 * curr / total : 0.0;
char buf[1024];
if (dialog == NULL) {
GtkWidget *vbox = gtk_vbox_new(TRUE, 5);
GtkWidget *label = gtk_label_new(title);
dialog = gtk_window_new(GTK_WINDOW_TOPLEVEL);
progress = gtk_progress_bar_new();
gtk_box_pack_start(GTK_BOX(vbox), label, TRUE, FALSE, 3);
gtk_box_pack_start(GTK_BOX(vbox), progress, TRUE, TRUE, 3);
gtk_container_add(GTK_CONTAINER(dialog), vbox);
gtk_window_set_title(GTK_WINDOW(dialog), "perf");
gtk_window_resize(GTK_WINDOW(dialog), 300, 80);
gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER);
gtk_widget_show_all(dialog);
}
gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(progress), fraction);
snprintf(buf, sizeof(buf), "%"PRIu64" / %"PRIu64, curr, total);
gtk_progress_bar_set_text(GTK_PROGRESS_BAR(progress), buf);
/* we didn't call gtk_main yet, so do it manually */
while (gtk_events_pending())
gtk_main_iteration();
}
static void gtk_progress_finish(void)
{
/* this will also destroy all of its children */
gtk_widget_destroy(dialog);
dialog = NULL;
}
static struct ui_progress gtk_progress_fns = {
.update = gtk_progress_update,
.finish = gtk_progress_finish,
};
void perf_gtk__init_progress(void)
{
progress_fns = >k_progress_fns;
}
| gpl-2.0 |
shumashv1/android_kernel_hp_tenderloin | sound/soc/blackfin/bf5xx-ac97.c | 2937 | 9875 | /*
* bf5xx-ac97.c -- AC97 support for the ADI blackfin chip.
*
* Author: Roy Huang
* Created: 11th. June 2007
* Copyright: Analog Device Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/wait.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/ac97_codec.h>
#include <sound/initval.h>
#include <sound/soc.h>
#include <asm/irq.h>
#include <asm/portmux.h>
#include <linux/mutex.h>
#include <linux/gpio.h>
#include "bf5xx-sport.h"
#include "bf5xx-ac97.h"
/* Anomaly notes:
* 05000250 - AD1980 is running in TDM mode and RFS/TFS are generated by SPORT
* contrtoller. But, RFSDIV and TFSDIV are always set to 16*16-1,
* while the max AC97 data size is 13*16. The DIV is always larger
* than data size. AD73311 and ad2602 are not running in TDM mode.
* AD1836 and AD73322 depend on external RFS/TFS only. So, this
* anomaly does not affect blackfin sound drivers.
*/
static struct sport_device *ac97_sport_handle;
void bf5xx_pcm_to_ac97(struct ac97_frame *dst, const __u16 *src,
size_t count, unsigned int chan_mask)
{
while (count--) {
dst->ac97_tag = TAG_VALID;
if (chan_mask & SP_FL) {
dst->ac97_pcm_r = *src++;
dst->ac97_tag |= TAG_PCM_RIGHT;
}
if (chan_mask & SP_FR) {
dst->ac97_pcm_l = *src++;
dst->ac97_tag |= TAG_PCM_LEFT;
}
#if defined(CONFIG_SND_BF5XX_MULTICHAN_SUPPORT)
if (chan_mask & SP_SR) {
dst->ac97_sl = *src++;
dst->ac97_tag |= TAG_PCM_SL;
}
if (chan_mask & SP_SL) {
dst->ac97_sr = *src++;
dst->ac97_tag |= TAG_PCM_SR;
}
if (chan_mask & SP_LFE) {
dst->ac97_lfe = *src++;
dst->ac97_tag |= TAG_PCM_LFE;
}
if (chan_mask & SP_FC) {
dst->ac97_center = *src++;
dst->ac97_tag |= TAG_PCM_CENTER;
}
#endif
dst++;
}
}
EXPORT_SYMBOL(bf5xx_pcm_to_ac97);
void bf5xx_ac97_to_pcm(const struct ac97_frame *src, __u16 *dst,
size_t count)
{
while (count--) {
*(dst++) = src->ac97_pcm_l;
*(dst++) = src->ac97_pcm_r;
src++;
}
}
EXPORT_SYMBOL(bf5xx_ac97_to_pcm);
static unsigned int sport_tx_curr_frag(struct sport_device *sport)
{
return sport->tx_curr_frag = sport_curr_offset_tx(sport) /
sport->tx_fragsize;
}
static void enqueue_cmd(struct snd_ac97 *ac97, __u16 addr, __u16 data)
{
struct sport_device *sport = ac97_sport_handle;
int *cmd_count = sport->private_data;
int nextfrag = sport_tx_curr_frag(sport);
struct ac97_frame *nextwrite;
sport_incfrag(sport, &nextfrag, 1);
nextwrite = (struct ac97_frame *)(sport->tx_buf +
nextfrag * sport->tx_fragsize);
pr_debug("sport->tx_buf:%p, nextfrag:0x%x nextwrite:%p, cmd_count:%d\n",
sport->tx_buf, nextfrag, nextwrite, cmd_count[nextfrag]);
nextwrite[cmd_count[nextfrag]].ac97_tag |= TAG_CMD;
nextwrite[cmd_count[nextfrag]].ac97_addr = addr;
nextwrite[cmd_count[nextfrag]].ac97_data = data;
++cmd_count[nextfrag];
pr_debug("ac97_sport: Inserting %02x/%04x into fragment %d\n",
addr >> 8, data, nextfrag);
}
static unsigned short bf5xx_ac97_read(struct snd_ac97 *ac97,
unsigned short reg)
{
struct sport_device *sport_handle = ac97_sport_handle;
struct ac97_frame out_frame[2], in_frame[2];
pr_debug("%s enter 0x%x\n", __func__, reg);
/* When dma descriptor is enabled, the register should not be read */
if (sport_handle->tx_run || sport_handle->rx_run) {
pr_err("Could you send a mail to cliff.cai@analog.com "
"to report this?\n");
return -EFAULT;
}
memset(&out_frame, 0, 2 * sizeof(struct ac97_frame));
memset(&in_frame, 0, 2 * sizeof(struct ac97_frame));
out_frame[0].ac97_tag = TAG_VALID | TAG_CMD;
out_frame[0].ac97_addr = ((reg << 8) | 0x8000);
sport_send_and_recv(sport_handle, (unsigned char *)&out_frame,
(unsigned char *)&in_frame,
2 * sizeof(struct ac97_frame));
return in_frame[1].ac97_data;
}
void bf5xx_ac97_write(struct snd_ac97 *ac97, unsigned short reg,
unsigned short val)
{
struct sport_device *sport_handle = ac97_sport_handle;
pr_debug("%s enter 0x%x:0x%04x\n", __func__, reg, val);
if (sport_handle->tx_run) {
enqueue_cmd(ac97, (reg << 8), val); /* write */
enqueue_cmd(ac97, (reg << 8) | 0x8000, 0); /* read back */
} else {
struct ac97_frame frame;
memset(&frame, 0, sizeof(struct ac97_frame));
frame.ac97_tag = TAG_VALID | TAG_CMD;
frame.ac97_addr = (reg << 8);
frame.ac97_data = val;
sport_send_and_recv(sport_handle, (unsigned char *)&frame, \
NULL, sizeof(struct ac97_frame));
}
}
static void bf5xx_ac97_warm_reset(struct snd_ac97 *ac97)
{
struct sport_device *sport_handle = ac97_sport_handle;
u16 gpio = P_IDENT(sport_handle->pin_req[3]);
pr_debug("%s enter\n", __func__);
peripheral_free_list(sport_handle->pin_req);
gpio_request(gpio, "bf5xx-ac97");
gpio_direction_output(gpio, 1);
udelay(2);
gpio_set_value(gpio, 0);
udelay(1);
gpio_free(gpio);
peripheral_request_list(sport_handle->pin_req, "soc-audio");
}
static void bf5xx_ac97_cold_reset(struct snd_ac97 *ac97)
{
#ifdef CONFIG_SND_BF5XX_HAVE_COLD_RESET
pr_debug("%s enter\n", __func__);
/* It is specified for bf548-ezkit */
gpio_set_value(CONFIG_SND_BF5XX_RESET_GPIO_NUM, 0);
/* Keep reset pin low for 1 ms */
mdelay(1);
gpio_set_value(CONFIG_SND_BF5XX_RESET_GPIO_NUM, 1);
/* Wait for bit clock recover */
mdelay(1);
#else
pr_info("%s: Not implemented\n", __func__);
#endif
}
struct snd_ac97_bus_ops soc_ac97_ops = {
.read = bf5xx_ac97_read,
.write = bf5xx_ac97_write,
.warm_reset = bf5xx_ac97_warm_reset,
.reset = bf5xx_ac97_cold_reset,
};
EXPORT_SYMBOL_GPL(soc_ac97_ops);
#ifdef CONFIG_PM
static int bf5xx_ac97_suspend(struct snd_soc_dai *dai)
{
struct sport_device *sport = snd_soc_dai_get_drvdata(dai);
pr_debug("%s : sport %d\n", __func__, dai->id);
if (!dai->active)
return 0;
if (dai->capture_active)
sport_rx_stop(sport);
if (dai->playback_active)
sport_tx_stop(sport);
return 0;
}
static int bf5xx_ac97_resume(struct snd_soc_dai *dai)
{
int ret;
struct sport_device *sport = snd_soc_dai_get_drvdata(dai);
pr_debug("%s : sport %d\n", __func__, dai->id);
if (!dai->active)
return 0;
#if defined(CONFIG_SND_BF5XX_MULTICHAN_SUPPORT)
ret = sport_set_multichannel(sport, 16, 0x3FF, 1);
#else
ret = sport_set_multichannel(sport, 16, 0x1F, 1);
#endif
if (ret) {
pr_err("SPORT is busy!\n");
return -EBUSY;
}
ret = sport_config_rx(sport, IRFS, 0xF, 0, (16*16-1));
if (ret) {
pr_err("SPORT is busy!\n");
return -EBUSY;
}
ret = sport_config_tx(sport, ITFS, 0xF, 0, (16*16-1));
if (ret) {
pr_err("SPORT is busy!\n");
return -EBUSY;
}
return 0;
}
#else
#define bf5xx_ac97_suspend NULL
#define bf5xx_ac97_resume NULL
#endif
static struct snd_soc_dai_driver bfin_ac97_dai = {
.ac97_control = 1,
.suspend = bf5xx_ac97_suspend,
.resume = bf5xx_ac97_resume,
.playback = {
.stream_name = "AC97 Playback",
.channels_min = 2,
#if defined(CONFIG_SND_BF5XX_MULTICHAN_SUPPORT)
.channels_max = 6,
#else
.channels_max = 2,
#endif
.rates = SNDRV_PCM_RATE_48000,
.formats = SNDRV_PCM_FMTBIT_S16_LE, },
.capture = {
.stream_name = "AC97 Capture",
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_48000,
.formats = SNDRV_PCM_FMTBIT_S16_LE, },
};
static int __devinit asoc_bfin_ac97_probe(struct platform_device *pdev)
{
struct sport_device *sport_handle;
int ret;
#ifdef CONFIG_SND_BF5XX_HAVE_COLD_RESET
/* Request PB3 as reset pin */
if (gpio_request(CONFIG_SND_BF5XX_RESET_GPIO_NUM, "SND_AD198x RESET")) {
pr_err("Failed to request GPIO_%d for reset\n",
CONFIG_SND_BF5XX_RESET_GPIO_NUM);
ret = -1;
goto gpio_err;
}
gpio_direction_output(CONFIG_SND_BF5XX_RESET_GPIO_NUM, 1);
#endif
sport_handle = sport_init(pdev, 2, sizeof(struct ac97_frame),
PAGE_SIZE);
if (!sport_handle) {
ret = -ENODEV;
goto sport_err;
}
/*SPORT works in TDM mode to simulate AC97 transfers*/
#if defined(CONFIG_SND_BF5XX_MULTICHAN_SUPPORT)
ret = sport_set_multichannel(sport_handle, 16, 0x3FF, 1);
#else
ret = sport_set_multichannel(sport_handle, 16, 0x1F, 1);
#endif
if (ret) {
pr_err("SPORT is busy!\n");
ret = -EBUSY;
goto sport_config_err;
}
ret = sport_config_rx(sport_handle, IRFS, 0xF, 0, (16*16-1));
if (ret) {
pr_err("SPORT is busy!\n");
ret = -EBUSY;
goto sport_config_err;
}
ret = sport_config_tx(sport_handle, ITFS, 0xF, 0, (16*16-1));
if (ret) {
pr_err("SPORT is busy!\n");
ret = -EBUSY;
goto sport_config_err;
}
ret = snd_soc_register_dai(&pdev->dev, &bfin_ac97_dai);
if (ret) {
pr_err("Failed to register DAI: %d\n", ret);
goto sport_config_err;
}
ac97_sport_handle = sport_handle;
return 0;
sport_config_err:
sport_done(sport_handle);
sport_err:
#ifdef CONFIG_SND_BF5XX_HAVE_COLD_RESET
gpio_free(CONFIG_SND_BF5XX_RESET_GPIO_NUM);
gpio_err:
#endif
return ret;
}
static int __devexit asoc_bfin_ac97_remove(struct platform_device *pdev)
{
struct sport_device *sport_handle = platform_get_drvdata(pdev);
snd_soc_unregister_dai(&pdev->dev);
sport_done(sport_handle);
#ifdef CONFIG_SND_BF5XX_HAVE_COLD_RESET
gpio_free(CONFIG_SND_BF5XX_RESET_GPIO_NUM);
#endif
return 0;
}
static struct platform_driver asoc_bfin_ac97_driver = {
.driver = {
.name = "bfin-ac97",
.owner = THIS_MODULE,
},
.probe = asoc_bfin_ac97_probe,
.remove = __devexit_p(asoc_bfin_ac97_remove),
};
static int __init bfin_ac97_init(void)
{
return platform_driver_register(&asoc_bfin_ac97_driver);
}
module_init(bfin_ac97_init);
static void __exit bfin_ac97_exit(void)
{
platform_driver_unregister(&asoc_bfin_ac97_driver);
}
module_exit(bfin_ac97_exit);
MODULE_AUTHOR("Roy Huang");
MODULE_DESCRIPTION("AC97 driver for ADI Blackfin");
MODULE_LICENSE("GPL");
| gpl-2.0 |
neobuddy89/vibrant_fluid_kernel | sound/soc/blackfin/bf5xx-tdm.c | 2937 | 8089 | /*
* File: sound/soc/blackfin/bf5xx-tdm.c
* Author: Barry Song <Barry.Song@analog.com>
*
* Created: Thurs June 04 2009
* Description: Blackfin I2S(TDM) CPU DAI driver
* Even though TDM mode can be as part of I2S DAI, but there
* are so much difference in configuration and data flow,
* it's very ugly to integrate I2S and TDM into a module
*
* Modified:
* Copyright 2009 Analog Devices Inc.
*
* Bugs: Enter bugs at http://blackfin.uclinux.org/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see the file COPYING, or write
* to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/initval.h>
#include <sound/soc.h>
#include <asm/irq.h>
#include <asm/portmux.h>
#include <linux/mutex.h>
#include <linux/gpio.h>
#include "bf5xx-sport.h"
#include "bf5xx-tdm.h"
static int bf5xx_tdm_set_dai_fmt(struct snd_soc_dai *cpu_dai,
unsigned int fmt)
{
int ret = 0;
/* interface format:support TDM,slave mode */
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_DSP_A:
break;
default:
printk(KERN_ERR "%s: Unknown DAI format type\n", __func__);
ret = -EINVAL;
break;
}
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
break;
case SND_SOC_DAIFMT_CBS_CFS:
case SND_SOC_DAIFMT_CBM_CFS:
case SND_SOC_DAIFMT_CBS_CFM:
ret = -EINVAL;
break;
default:
printk(KERN_ERR "%s: Unknown DAI master type\n", __func__);
ret = -EINVAL;
break;
}
return ret;
}
static int bf5xx_tdm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct sport_device *sport_handle = snd_soc_dai_get_drvdata(dai);
struct bf5xx_tdm_port *bf5xx_tdm = sport_handle->private_data;
int ret = 0;
bf5xx_tdm->tcr2 &= ~0x1f;
bf5xx_tdm->rcr2 &= ~0x1f;
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S32_LE:
bf5xx_tdm->tcr2 |= 31;
bf5xx_tdm->rcr2 |= 31;
sport_handle->wdsize = 4;
break;
/* at present, we only support 32bit transfer */
default:
pr_err("not supported PCM format yet\n");
return -EINVAL;
break;
}
if (!bf5xx_tdm->configured) {
/*
* TX and RX are not independent,they are enabled at the
* same time, even if only one side is running. So, we
* need to configure both of them at the time when the first
* stream is opened.
*
* CPU DAI:slave mode.
*/
ret = sport_config_rx(sport_handle, bf5xx_tdm->rcr1,
bf5xx_tdm->rcr2, 0, 0);
if (ret) {
pr_err("SPORT is busy!\n");
return -EBUSY;
}
ret = sport_config_tx(sport_handle, bf5xx_tdm->tcr1,
bf5xx_tdm->tcr2, 0, 0);
if (ret) {
pr_err("SPORT is busy!\n");
return -EBUSY;
}
bf5xx_tdm->configured = 1;
}
return 0;
}
static void bf5xx_tdm_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct sport_device *sport_handle = snd_soc_dai_get_drvdata(dai);
struct bf5xx_tdm_port *bf5xx_tdm = sport_handle->private_data;
/* No active stream, SPORT is allowed to be configured again. */
if (!dai->active)
bf5xx_tdm->configured = 0;
}
static int bf5xx_tdm_set_channel_map(struct snd_soc_dai *dai,
unsigned int tx_num, unsigned int *tx_slot,
unsigned int rx_num, unsigned int *rx_slot)
{
struct sport_device *sport_handle = snd_soc_dai_get_drvdata(dai);
struct bf5xx_tdm_port *bf5xx_tdm = sport_handle->private_data;
int i;
unsigned int slot;
unsigned int tx_mapped = 0, rx_mapped = 0;
if ((tx_num > BFIN_TDM_DAI_MAX_SLOTS) ||
(rx_num > BFIN_TDM_DAI_MAX_SLOTS))
return -EINVAL;
for (i = 0; i < tx_num; i++) {
slot = tx_slot[i];
if ((slot < BFIN_TDM_DAI_MAX_SLOTS) &&
(!(tx_mapped & (1 << slot)))) {
bf5xx_tdm->tx_map[i] = slot;
tx_mapped |= 1 << slot;
} else
return -EINVAL;
}
for (i = 0; i < rx_num; i++) {
slot = rx_slot[i];
if ((slot < BFIN_TDM_DAI_MAX_SLOTS) &&
(!(rx_mapped & (1 << slot)))) {
bf5xx_tdm->rx_map[i] = slot;
rx_mapped |= 1 << slot;
} else
return -EINVAL;
}
return 0;
}
#ifdef CONFIG_PM
static int bf5xx_tdm_suspend(struct snd_soc_dai *dai)
{
struct sport_device *sport = snd_soc_dai_get_drvdata(dai);
if (dai->playback_active)
sport_tx_stop(sport);
if (dai->capture_active)
sport_rx_stop(sport);
/* isolate sync/clock pins from codec while sports resume */
peripheral_free_list(sport->pin_req);
return 0;
}
static int bf5xx_tdm_resume(struct snd_soc_dai *dai)
{
int ret;
struct sport_device *sport = snd_soc_dai_get_drvdata(dai);
ret = sport_set_multichannel(sport, 8, 0xFF, 1);
if (ret) {
pr_err("SPORT is busy!\n");
ret = -EBUSY;
}
ret = sport_config_rx(sport, 0, 0x1F, 0, 0);
if (ret) {
pr_err("SPORT is busy!\n");
ret = -EBUSY;
}
ret = sport_config_tx(sport, 0, 0x1F, 0, 0);
if (ret) {
pr_err("SPORT is busy!\n");
ret = -EBUSY;
}
peripheral_request_list(sport->pin_req, "soc-audio");
return 0;
}
#else
#define bf5xx_tdm_suspend NULL
#define bf5xx_tdm_resume NULL
#endif
static struct snd_soc_dai_ops bf5xx_tdm_dai_ops = {
.hw_params = bf5xx_tdm_hw_params,
.set_fmt = bf5xx_tdm_set_dai_fmt,
.shutdown = bf5xx_tdm_shutdown,
.set_channel_map = bf5xx_tdm_set_channel_map,
};
static struct snd_soc_dai_driver bf5xx_tdm_dai = {
.suspend = bf5xx_tdm_suspend,
.resume = bf5xx_tdm_resume,
.playback = {
.channels_min = 2,
.channels_max = 8,
.rates = SNDRV_PCM_RATE_48000,
.formats = SNDRV_PCM_FMTBIT_S32_LE,},
.capture = {
.channels_min = 2,
.channels_max = 8,
.rates = SNDRV_PCM_RATE_48000,
.formats = SNDRV_PCM_FMTBIT_S32_LE,},
.ops = &bf5xx_tdm_dai_ops,
};
static int __devinit bfin_tdm_probe(struct platform_device *pdev)
{
struct sport_device *sport_handle;
int ret;
/* configure SPORT for TDM */
sport_handle = sport_init(pdev, 4, 8 * sizeof(u32),
sizeof(struct bf5xx_tdm_port));
if (!sport_handle)
return -ENODEV;
/* SPORT works in TDM mode */
ret = sport_set_multichannel(sport_handle, 8, 0xFF, 1);
if (ret) {
pr_err("SPORT is busy!\n");
ret = -EBUSY;
goto sport_config_err;
}
ret = sport_config_rx(sport_handle, 0, 0x1F, 0, 0);
if (ret) {
pr_err("SPORT is busy!\n");
ret = -EBUSY;
goto sport_config_err;
}
ret = sport_config_tx(sport_handle, 0, 0x1F, 0, 0);
if (ret) {
pr_err("SPORT is busy!\n");
ret = -EBUSY;
goto sport_config_err;
}
ret = snd_soc_register_dai(&pdev->dev, &bf5xx_tdm_dai);
if (ret) {
pr_err("Failed to register DAI: %d\n", ret);
goto sport_config_err;
}
return 0;
sport_config_err:
sport_done(sport_handle);
return ret;
}
static int __devexit bfin_tdm_remove(struct platform_device *pdev)
{
struct sport_device *sport_handle = platform_get_drvdata(pdev);
snd_soc_unregister_dai(&pdev->dev);
sport_done(sport_handle);
return 0;
}
static struct platform_driver bfin_tdm_driver = {
.probe = bfin_tdm_probe,
.remove = __devexit_p(bfin_tdm_remove),
.driver = {
.name = "bfin-tdm",
.owner = THIS_MODULE,
},
};
static int __init bfin_tdm_init(void)
{
return platform_driver_register(&bfin_tdm_driver);
}
module_init(bfin_tdm_init);
static void __exit bfin_tdm_exit(void)
{
platform_driver_unregister(&bfin_tdm_driver);
}
module_exit(bfin_tdm_exit);
/* Module information */
MODULE_AUTHOR("Barry Song");
MODULE_DESCRIPTION("TDM driver for ADI Blackfin");
MODULE_LICENSE("GPL");
| gpl-2.0 |
acuicultor/android_kernel_oneplus_msm8974-1 | arch/sparc/mm/highmem.c | 4473 | 3201 | /*
* highmem.c: virtual kernel memory mappings for high memory
*
* Provides kernel-static versions of atomic kmap functions originally
* found as inlines in include/asm-sparc/highmem.h. These became
* needed as kmap_atomic() and kunmap_atomic() started getting
* called from within modules.
* -- Tomas Szepe <szepe@pinerecords.com>, September 2002
*
* But kmap_atomic() and kunmap_atomic() cannot be inlined in
* modules because they are loaded with btfixup-ped functions.
*/
/*
* The use of kmap_atomic/kunmap_atomic is discouraged - kmap/kunmap
* gives a more generic (and caching) interface. But kmap_atomic can
* be used in IRQ contexts, so in some (very limited) cases we need it.
*
* XXX This is an old text. Actually, it's good to use atomic kmaps,
* provided you remember that they are atomic and not try to sleep
* with a kmap taken, much like a spinlock. Non-atomic kmaps are
* shared by CPUs, and so precious, and establishing them requires IPI.
* Atomic kmaps are lightweight and we may have NCPUS more of them.
*/
#include <linux/mm.h>
#include <linux/highmem.h>
#include <linux/export.h>
#include <asm/pgalloc.h>
#include <asm/cacheflush.h>
#include <asm/tlbflush.h>
#include <asm/fixmap.h>
void *kmap_atomic(struct page *page)
{
unsigned long vaddr;
long idx, type;
/* even !CONFIG_PREEMPT needs this, for in_atomic in do_page_fault */
pagefault_disable();
if (!PageHighMem(page))
return page_address(page);
type = kmap_atomic_idx_push();
idx = type + KM_TYPE_NR*smp_processor_id();
vaddr = __fix_to_virt(FIX_KMAP_BEGIN + idx);
/* XXX Fix - Anton */
#if 0
__flush_cache_one(vaddr);
#else
flush_cache_all();
#endif
#ifdef CONFIG_DEBUG_HIGHMEM
BUG_ON(!pte_none(*(kmap_pte-idx)));
#endif
set_pte(kmap_pte-idx, mk_pte(page, kmap_prot));
/* XXX Fix - Anton */
#if 0
__flush_tlb_one(vaddr);
#else
flush_tlb_all();
#endif
return (void*) vaddr;
}
EXPORT_SYMBOL(kmap_atomic);
void __kunmap_atomic(void *kvaddr)
{
unsigned long vaddr = (unsigned long) kvaddr & PAGE_MASK;
int type;
if (vaddr < FIXADDR_START) { // FIXME
pagefault_enable();
return;
}
type = kmap_atomic_idx();
#ifdef CONFIG_DEBUG_HIGHMEM
{
unsigned long idx;
idx = type + KM_TYPE_NR * smp_processor_id();
BUG_ON(vaddr != __fix_to_virt(FIX_KMAP_BEGIN+idx));
/* XXX Fix - Anton */
#if 0
__flush_cache_one(vaddr);
#else
flush_cache_all();
#endif
/*
* force other mappings to Oops if they'll try to access
* this pte without first remap it
*/
pte_clear(&init_mm, vaddr, kmap_pte-idx);
/* XXX Fix - Anton */
#if 0
__flush_tlb_one(vaddr);
#else
flush_tlb_all();
#endif
}
#endif
kmap_atomic_idx_pop();
pagefault_enable();
}
EXPORT_SYMBOL(__kunmap_atomic);
/* We may be fed a pagetable here by ptep_to_xxx and others. */
struct page *kmap_atomic_to_page(void *ptr)
{
unsigned long idx, vaddr = (unsigned long)ptr;
pte_t *pte;
if (vaddr < SRMMU_NOCACHE_VADDR)
return virt_to_page(ptr);
if (vaddr < PKMAP_BASE)
return pfn_to_page(__nocache_pa(vaddr) >> PAGE_SHIFT);
BUG_ON(vaddr < FIXADDR_START);
BUG_ON(vaddr > FIXADDR_TOP);
idx = virt_to_fix(vaddr);
pte = kmap_pte - (idx - FIX_KMAP_BEGIN);
return pte_page(*pte);
}
| gpl-2.0 |
boa19861105/android_LP5.0.2_kernel_htc_dlxpul | arch/arm/mach-imx/clock-imx27.c | 4729 | 22834 | /*
* Copyright 2004-2007 Freescale Semiconductor, Inc. All Rights Reserved.
* Copyright 2008 Juergen Beisert, kernel@pengutronix.de
* Copyright 2008 Martin Fuzzey, mfuzzey@gmail.com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/clkdev.h>
#include <linux/of.h>
#include <asm/div64.h>
#include <mach/clock.h>
#include <mach/common.h>
#include <mach/hardware.h>
#define IO_ADDR_CCM(off) (MX27_IO_ADDRESS(MX27_CCM_BASE_ADDR + (off)))
/* Register offsets */
#define CCM_CSCR IO_ADDR_CCM(0x0)
#define CCM_MPCTL0 IO_ADDR_CCM(0x4)
#define CCM_MPCTL1 IO_ADDR_CCM(0x8)
#define CCM_SPCTL0 IO_ADDR_CCM(0xc)
#define CCM_SPCTL1 IO_ADDR_CCM(0x10)
#define CCM_OSC26MCTL IO_ADDR_CCM(0x14)
#define CCM_PCDR0 IO_ADDR_CCM(0x18)
#define CCM_PCDR1 IO_ADDR_CCM(0x1c)
#define CCM_PCCR0 IO_ADDR_CCM(0x20)
#define CCM_PCCR1 IO_ADDR_CCM(0x24)
#define CCM_CCSR IO_ADDR_CCM(0x28)
#define CCM_PMCTL IO_ADDR_CCM(0x2c)
#define CCM_PMCOUNT IO_ADDR_CCM(0x30)
#define CCM_WKGDCTL IO_ADDR_CCM(0x34)
#define CCM_CSCR_UPDATE_DIS (1 << 31)
#define CCM_CSCR_SSI2 (1 << 23)
#define CCM_CSCR_SSI1 (1 << 22)
#define CCM_CSCR_VPU (1 << 21)
#define CCM_CSCR_MSHC (1 << 20)
#define CCM_CSCR_SPLLRES (1 << 19)
#define CCM_CSCR_MPLLRES (1 << 18)
#define CCM_CSCR_SP (1 << 17)
#define CCM_CSCR_MCU (1 << 16)
#define CCM_CSCR_OSC26MDIV (1 << 4)
#define CCM_CSCR_OSC26M (1 << 3)
#define CCM_CSCR_FPM (1 << 2)
#define CCM_CSCR_SPEN (1 << 1)
#define CCM_CSCR_MPEN (1 << 0)
/* i.MX27 TO 2+ */
#define CCM_CSCR_ARM_SRC (1 << 15)
#define CCM_SPCTL1_LF (1 << 15)
#define CCM_SPCTL1_BRMO (1 << 6)
static struct clk mpll_main1_clk, mpll_main2_clk;
static int clk_pccr_enable(struct clk *clk)
{
unsigned long reg;
if (!clk->enable_reg)
return 0;
reg = __raw_readl(clk->enable_reg);
reg |= 1 << clk->enable_shift;
__raw_writel(reg, clk->enable_reg);
return 0;
}
static void clk_pccr_disable(struct clk *clk)
{
unsigned long reg;
if (!clk->enable_reg)
return;
reg = __raw_readl(clk->enable_reg);
reg &= ~(1 << clk->enable_shift);
__raw_writel(reg, clk->enable_reg);
}
static int clk_spll_enable(struct clk *clk)
{
unsigned long reg;
reg = __raw_readl(CCM_CSCR);
reg |= CCM_CSCR_SPEN;
__raw_writel(reg, CCM_CSCR);
while (!(__raw_readl(CCM_SPCTL1) & CCM_SPCTL1_LF));
return 0;
}
static void clk_spll_disable(struct clk *clk)
{
unsigned long reg;
reg = __raw_readl(CCM_CSCR);
reg &= ~CCM_CSCR_SPEN;
__raw_writel(reg, CCM_CSCR);
}
static int clk_cpu_set_parent(struct clk *clk, struct clk *parent)
{
int cscr = __raw_readl(CCM_CSCR);
if (clk->parent == parent)
return 0;
if (mx27_revision() >= IMX_CHIP_REVISION_2_0) {
if (parent == &mpll_main1_clk) {
cscr |= CCM_CSCR_ARM_SRC;
} else {
if (parent == &mpll_main2_clk)
cscr &= ~CCM_CSCR_ARM_SRC;
else
return -EINVAL;
}
__raw_writel(cscr, CCM_CSCR);
clk->parent = parent;
return 0;
}
return -ENODEV;
}
static unsigned long round_rate_cpu(struct clk *clk, unsigned long rate)
{
int div;
unsigned long parent_rate;
parent_rate = clk_get_rate(clk->parent);
div = parent_rate / rate;
if (parent_rate % rate)
div++;
if (div > 4)
div = 4;
return parent_rate / div;
}
static int set_rate_cpu(struct clk *clk, unsigned long rate)
{
unsigned int div;
uint32_t reg;
unsigned long parent_rate;
parent_rate = clk_get_rate(clk->parent);
div = parent_rate / rate;
if (div > 4 || div < 1 || ((parent_rate / div) != rate))
return -EINVAL;
div--;
reg = __raw_readl(CCM_CSCR);
if (mx27_revision() >= IMX_CHIP_REVISION_2_0) {
reg &= ~(3 << 12);
reg |= div << 12;
reg &= ~(CCM_CSCR_FPM | CCM_CSCR_SPEN);
__raw_writel(reg | CCM_CSCR_UPDATE_DIS, CCM_CSCR);
} else {
printk(KERN_ERR "Can't set CPU frequency!\n");
}
return 0;
}
static unsigned long round_rate_per(struct clk *clk, unsigned long rate)
{
u32 div;
unsigned long parent_rate;
parent_rate = clk_get_rate(clk->parent);
div = parent_rate / rate;
if (parent_rate % rate)
div++;
if (div > 64)
div = 64;
return parent_rate / div;
}
static int set_rate_per(struct clk *clk, unsigned long rate)
{
u32 reg;
u32 div;
unsigned long parent_rate;
parent_rate = clk_get_rate(clk->parent);
if (clk->id < 0 || clk->id > 3)
return -EINVAL;
div = parent_rate / rate;
if (div > 64 || div < 1 || ((parent_rate / div) != rate))
return -EINVAL;
div--;
reg = __raw_readl(CCM_PCDR1) & ~(0x3f << (clk->id << 3));
reg |= div << (clk->id << 3);
__raw_writel(reg, CCM_PCDR1);
return 0;
}
static unsigned long get_rate_usb(struct clk *clk)
{
unsigned long usb_pdf;
unsigned long parent_rate;
parent_rate = clk_get_rate(clk->parent);
usb_pdf = (__raw_readl(CCM_CSCR) >> 28) & 0x7;
return parent_rate / (usb_pdf + 1U);
}
static unsigned long get_rate_ssix(struct clk *clk, unsigned long pdf)
{
unsigned long parent_rate;
parent_rate = clk_get_rate(clk->parent);
if (mx27_revision() >= IMX_CHIP_REVISION_2_0)
pdf += 4; /* MX27 TO2+ */
else
pdf = (pdf < 2) ? 124UL : pdf; /* MX21 & MX27 TO1 */
return 2UL * parent_rate / pdf;
}
static unsigned long get_rate_ssi1(struct clk *clk)
{
return get_rate_ssix(clk, (__raw_readl(CCM_PCDR0) >> 16) & 0x3f);
}
static unsigned long get_rate_ssi2(struct clk *clk)
{
return get_rate_ssix(clk, (__raw_readl(CCM_PCDR0) >> 26) & 0x3f);
}
static unsigned long get_rate_nfc(struct clk *clk)
{
unsigned long nfc_pdf;
unsigned long parent_rate;
parent_rate = clk_get_rate(clk->parent);
if (mx27_revision() >= IMX_CHIP_REVISION_2_0)
nfc_pdf = (__raw_readl(CCM_PCDR0) >> 6) & 0xf;
else
nfc_pdf = (__raw_readl(CCM_PCDR0) >> 12) & 0xf;
return parent_rate / (nfc_pdf + 1);
}
static unsigned long get_rate_vpu(struct clk *clk)
{
unsigned long vpu_pdf;
unsigned long parent_rate;
parent_rate = clk_get_rate(clk->parent);
if (mx27_revision() >= IMX_CHIP_REVISION_2_0) {
vpu_pdf = (__raw_readl(CCM_PCDR0) >> 10) & 0x3f;
vpu_pdf += 4;
} else {
vpu_pdf = (__raw_readl(CCM_PCDR0) >> 8) & 0xf;
vpu_pdf = (vpu_pdf < 2) ? 124 : vpu_pdf;
}
return 2UL * parent_rate / vpu_pdf;
}
static unsigned long round_rate_parent(struct clk *clk, unsigned long rate)
{
return clk->parent->round_rate(clk->parent, rate);
}
static unsigned long get_rate_parent(struct clk *clk)
{
return clk_get_rate(clk->parent);
}
static int set_rate_parent(struct clk *clk, unsigned long rate)
{
return clk->parent->set_rate(clk->parent, rate);
}
/* in Hz */
static unsigned long external_high_reference = 26000000;
static unsigned long get_rate_high_reference(struct clk *clk)
{
return external_high_reference;
}
/* in Hz */
static unsigned long external_low_reference = 32768;
static unsigned long get_rate_low_reference(struct clk *clk)
{
return external_low_reference;
}
static unsigned long get_rate_fpm(struct clk *clk)
{
return clk_get_rate(clk->parent) * 1024;
}
static unsigned long get_rate_mpll(struct clk *clk)
{
return mxc_decode_pll(__raw_readl(CCM_MPCTL0),
clk_get_rate(clk->parent));
}
static unsigned long get_rate_mpll_main(struct clk *clk)
{
unsigned long parent_rate;
parent_rate = clk_get_rate(clk->parent);
/* i.MX27 TO2:
* clk->id == 0: arm clock source path 1 which is from 2 * MPLL / 2
* clk->id == 1: arm clock source path 2 which is from 2 * MPLL / 3
*/
if (mx27_revision() >= IMX_CHIP_REVISION_2_0 && clk->id == 1)
return 2UL * parent_rate / 3UL;
return parent_rate;
}
static unsigned long get_rate_spll(struct clk *clk)
{
uint32_t reg;
unsigned long rate;
rate = clk_get_rate(clk->parent);
reg = __raw_readl(CCM_SPCTL0);
/* On TO2 we have to write the value back. Otherwise we
* read 0 from this register the next time.
*/
if (mx27_revision() >= IMX_CHIP_REVISION_2_0)
__raw_writel(reg, CCM_SPCTL0);
return mxc_decode_pll(reg, rate);
}
static unsigned long get_rate_cpu(struct clk *clk)
{
u32 div;
unsigned long rate;
if (mx27_revision() >= IMX_CHIP_REVISION_2_0)
div = (__raw_readl(CCM_CSCR) >> 12) & 0x3;
else
div = (__raw_readl(CCM_CSCR) >> 13) & 0x7;
rate = clk_get_rate(clk->parent);
return rate / (div + 1);
}
static unsigned long get_rate_ahb(struct clk *clk)
{
unsigned long rate, bclk_pdf;
if (mx27_revision() >= IMX_CHIP_REVISION_2_0)
bclk_pdf = (__raw_readl(CCM_CSCR) >> 8) & 0x3;
else
bclk_pdf = (__raw_readl(CCM_CSCR) >> 9) & 0xf;
rate = clk_get_rate(clk->parent);
return rate / (bclk_pdf + 1);
}
static unsigned long get_rate_ipg(struct clk *clk)
{
unsigned long rate, ipg_pdf;
if (mx27_revision() >= IMX_CHIP_REVISION_2_0)
return clk_get_rate(clk->parent);
else
ipg_pdf = (__raw_readl(CCM_CSCR) >> 8) & 1;
rate = clk_get_rate(clk->parent);
return rate / (ipg_pdf + 1);
}
static unsigned long get_rate_per(struct clk *clk)
{
unsigned long perclk_pdf, parent_rate;
parent_rate = clk_get_rate(clk->parent);
if (clk->id < 0 || clk->id > 3)
return 0;
perclk_pdf = (__raw_readl(CCM_PCDR1) >> (clk->id << 3)) & 0x3f;
return parent_rate / (perclk_pdf + 1);
}
/*
* the high frequency external clock reference
* Default case is 26MHz. Could be changed at runtime
* with a call to change_external_high_reference()
*/
static struct clk ckih_clk = {
.get_rate = get_rate_high_reference,
};
static struct clk mpll_clk = {
.parent = &ckih_clk,
.get_rate = get_rate_mpll,
};
/* For i.MX27 TO2, it is the MPLL path 1 of ARM core
* It provides the clock source whose rate is same as MPLL
*/
static struct clk mpll_main1_clk = {
.id = 0,
.parent = &mpll_clk,
.get_rate = get_rate_mpll_main,
};
/* For i.MX27 TO2, it is the MPLL path 2 of ARM core
* It provides the clock source whose rate is same MPLL * 2 / 3
*/
static struct clk mpll_main2_clk = {
.id = 1,
.parent = &mpll_clk,
.get_rate = get_rate_mpll_main,
};
static struct clk ahb_clk = {
.parent = &mpll_main2_clk,
.get_rate = get_rate_ahb,
};
static struct clk ipg_clk = {
.parent = &ahb_clk,
.get_rate = get_rate_ipg,
};
static struct clk cpu_clk = {
.parent = &mpll_main2_clk,
.set_parent = clk_cpu_set_parent,
.round_rate = round_rate_cpu,
.get_rate = get_rate_cpu,
.set_rate = set_rate_cpu,
};
static struct clk spll_clk = {
.parent = &ckih_clk,
.get_rate = get_rate_spll,
.enable = clk_spll_enable,
.disable = clk_spll_disable,
};
/*
* the low frequency external clock reference
* Default case is 32.768kHz.
*/
static struct clk ckil_clk = {
.get_rate = get_rate_low_reference,
};
/* Output of frequency pre multiplier */
static struct clk fpm_clk = {
.parent = &ckil_clk,
.get_rate = get_rate_fpm,
};
#define PCCR0 CCM_PCCR0
#define PCCR1 CCM_PCCR1
#define DEFINE_CLOCK(name, i, er, es, gr, s, p) \
static struct clk name = { \
.id = i, \
.enable_reg = er, \
.enable_shift = es, \
.get_rate = gr, \
.enable = clk_pccr_enable, \
.disable = clk_pccr_disable, \
.secondary = s, \
.parent = p, \
}
#define DEFINE_CLOCK1(name, i, er, es, getsetround, s, p) \
static struct clk name = { \
.id = i, \
.enable_reg = er, \
.enable_shift = es, \
.get_rate = get_rate_##getsetround, \
.set_rate = set_rate_##getsetround, \
.round_rate = round_rate_##getsetround, \
.enable = clk_pccr_enable, \
.disable = clk_pccr_disable, \
.secondary = s, \
.parent = p, \
}
/* Forward declaration to keep the following list in order */
static struct clk slcdc_clk1, sahara2_clk1, rtic_clk1, fec_clk1, emma_clk1,
dma_clk1, lcdc_clk2, vpu_clk1;
/* All clocks we can gate through PCCRx in the order of PCCRx bits */
DEFINE_CLOCK(ssi2_clk1, 1, PCCR0, 0, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(ssi1_clk1, 0, PCCR0, 1, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(slcdc_clk, 0, PCCR0, 2, NULL, &slcdc_clk1, &ahb_clk);
DEFINE_CLOCK(sdhc3_clk1, 0, PCCR0, 3, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(sdhc2_clk1, 0, PCCR0, 4, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(sdhc1_clk1, 0, PCCR0, 5, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(scc_clk, 0, PCCR0, 6, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(sahara2_clk, 0, PCCR0, 7, NULL, &sahara2_clk1, &ahb_clk);
DEFINE_CLOCK(rtic_clk, 0, PCCR0, 8, NULL, &rtic_clk1, &ahb_clk);
DEFINE_CLOCK(rtc_clk, 0, PCCR0, 9, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(pwm_clk1, 0, PCCR0, 11, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(owire_clk, 0, PCCR0, 12, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(mstick_clk1, 0, PCCR0, 13, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(lcdc_clk1, 0, PCCR0, 14, NULL, &lcdc_clk2, &ipg_clk);
DEFINE_CLOCK(kpp_clk, 0, PCCR0, 15, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(iim_clk, 0, PCCR0, 16, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(i2c2_clk, 1, PCCR0, 17, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(i2c1_clk, 0, PCCR0, 18, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(gpt6_clk1, 0, PCCR0, 29, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(gpt5_clk1, 0, PCCR0, 20, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(gpt4_clk1, 0, PCCR0, 21, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(gpt3_clk1, 0, PCCR0, 22, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(gpt2_clk1, 0, PCCR0, 23, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(gpt1_clk1, 0, PCCR0, 24, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(gpio_clk, 0, PCCR0, 25, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(fec_clk, 0, PCCR0, 26, NULL, &fec_clk1, &ahb_clk);
DEFINE_CLOCK(emma_clk, 0, PCCR0, 27, NULL, &emma_clk1, &ahb_clk);
DEFINE_CLOCK(dma_clk, 0, PCCR0, 28, NULL, &dma_clk1, &ahb_clk);
DEFINE_CLOCK(cspi13_clk1, 0, PCCR0, 29, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(cspi2_clk1, 0, PCCR0, 30, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(cspi1_clk1, 0, PCCR0, 31, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(mstick_clk, 0, PCCR1, 2, NULL, &mstick_clk1, &ipg_clk);
DEFINE_CLOCK(nfc_clk, 0, PCCR1, 3, get_rate_nfc, NULL, &cpu_clk);
DEFINE_CLOCK(ssi2_clk, 1, PCCR1, 4, get_rate_ssi2, &ssi2_clk1, &mpll_main2_clk);
DEFINE_CLOCK(ssi1_clk, 0, PCCR1, 5, get_rate_ssi1, &ssi1_clk1, &mpll_main2_clk);
DEFINE_CLOCK(vpu_clk, 0, PCCR1, 6, get_rate_vpu, &vpu_clk1, &mpll_main2_clk);
DEFINE_CLOCK1(per4_clk, 3, PCCR1, 7, per, NULL, &mpll_main2_clk);
DEFINE_CLOCK1(per3_clk, 2, PCCR1, 8, per, NULL, &mpll_main2_clk);
DEFINE_CLOCK1(per2_clk, 1, PCCR1, 9, per, NULL, &mpll_main2_clk);
DEFINE_CLOCK1(per1_clk, 0, PCCR1, 10, per, NULL, &mpll_main2_clk);
DEFINE_CLOCK(usb_clk1, 0, PCCR1, 11, NULL, NULL, &ahb_clk);
DEFINE_CLOCK(slcdc_clk1, 0, PCCR1, 12, NULL, NULL, &ahb_clk);
DEFINE_CLOCK(sahara2_clk1, 0, PCCR1, 13, NULL, NULL, &ahb_clk);
DEFINE_CLOCK(rtic_clk1, 0, PCCR1, 14, NULL, NULL, &ahb_clk);
DEFINE_CLOCK(lcdc_clk2, 0, PCCR1, 15, NULL, NULL, &ahb_clk);
DEFINE_CLOCK(vpu_clk1, 0, PCCR1, 16, NULL, NULL, &ahb_clk);
DEFINE_CLOCK(fec_clk1, 0, PCCR1, 17, NULL, NULL, &ahb_clk);
DEFINE_CLOCK(emma_clk1, 0, PCCR1, 18, NULL, NULL, &ahb_clk);
DEFINE_CLOCK(emi_clk, 0, PCCR1, 19, NULL, NULL, &ahb_clk);
DEFINE_CLOCK(dma_clk1, 0, PCCR1, 20, NULL, NULL, &ahb_clk);
DEFINE_CLOCK(csi_clk1, 0, PCCR1, 21, NULL, NULL, &ahb_clk);
DEFINE_CLOCK(brom_clk, 0, PCCR1, 22, NULL, NULL, &ahb_clk);
DEFINE_CLOCK(pata_clk, 0, PCCR1, 23, NULL, NULL, &ahb_clk);
DEFINE_CLOCK(wdog_clk, 0, PCCR1, 24, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(usb_clk, 0, PCCR1, 25, get_rate_usb, &usb_clk1, &spll_clk);
DEFINE_CLOCK(uart6_clk1, 0, PCCR1, 26, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(uart5_clk1, 0, PCCR1, 27, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(uart4_clk1, 0, PCCR1, 28, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(uart3_clk1, 0, PCCR1, 29, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(uart2_clk1, 0, PCCR1, 30, NULL, NULL, &ipg_clk);
DEFINE_CLOCK(uart1_clk1, 0, PCCR1, 31, NULL, NULL, &ipg_clk);
/* Clocks we cannot directly gate, but drivers need their rates */
DEFINE_CLOCK(cspi1_clk, 0, NULL, 0, NULL, &cspi1_clk1, &per2_clk);
DEFINE_CLOCK(cspi2_clk, 1, NULL, 0, NULL, &cspi2_clk1, &per2_clk);
DEFINE_CLOCK(cspi3_clk, 2, NULL, 0, NULL, &cspi13_clk1, &per2_clk);
DEFINE_CLOCK(sdhc1_clk, 0, NULL, 0, NULL, &sdhc1_clk1, &per2_clk);
DEFINE_CLOCK(sdhc2_clk, 1, NULL, 0, NULL, &sdhc2_clk1, &per2_clk);
DEFINE_CLOCK(sdhc3_clk, 2, NULL, 0, NULL, &sdhc3_clk1, &per2_clk);
DEFINE_CLOCK(pwm_clk, 0, NULL, 0, NULL, &pwm_clk1, &per1_clk);
DEFINE_CLOCK(gpt1_clk, 0, NULL, 0, NULL, &gpt1_clk1, &per1_clk);
DEFINE_CLOCK(gpt2_clk, 1, NULL, 0, NULL, &gpt2_clk1, &per1_clk);
DEFINE_CLOCK(gpt3_clk, 2, NULL, 0, NULL, &gpt3_clk1, &per1_clk);
DEFINE_CLOCK(gpt4_clk, 3, NULL, 0, NULL, &gpt4_clk1, &per1_clk);
DEFINE_CLOCK(gpt5_clk, 4, NULL, 0, NULL, &gpt5_clk1, &per1_clk);
DEFINE_CLOCK(gpt6_clk, 5, NULL, 0, NULL, &gpt6_clk1, &per1_clk);
DEFINE_CLOCK(uart1_clk, 0, NULL, 0, NULL, &uart1_clk1, &per1_clk);
DEFINE_CLOCK(uart2_clk, 1, NULL, 0, NULL, &uart2_clk1, &per1_clk);
DEFINE_CLOCK(uart3_clk, 2, NULL, 0, NULL, &uart3_clk1, &per1_clk);
DEFINE_CLOCK(uart4_clk, 3, NULL, 0, NULL, &uart4_clk1, &per1_clk);
DEFINE_CLOCK(uart5_clk, 4, NULL, 0, NULL, &uart5_clk1, &per1_clk);
DEFINE_CLOCK(uart6_clk, 5, NULL, 0, NULL, &uart6_clk1, &per1_clk);
DEFINE_CLOCK1(lcdc_clk, 0, NULL, 0, parent, &lcdc_clk1, &per3_clk);
DEFINE_CLOCK1(csi_clk, 0, NULL, 0, parent, &csi_clk1, &per4_clk);
#define _REGISTER_CLOCK(d, n, c) \
{ \
.dev_id = d, \
.con_id = n, \
.clk = &c, \
},
static struct clk_lookup lookups[] = {
/* i.mx27 has the i.mx21 type uart */
_REGISTER_CLOCK("imx21-uart.0", NULL, uart1_clk)
_REGISTER_CLOCK("imx21-uart.1", NULL, uart2_clk)
_REGISTER_CLOCK("imx21-uart.2", NULL, uart3_clk)
_REGISTER_CLOCK("imx21-uart.3", NULL, uart4_clk)
_REGISTER_CLOCK("imx21-uart.4", NULL, uart5_clk)
_REGISTER_CLOCK("imx21-uart.5", NULL, uart6_clk)
_REGISTER_CLOCK(NULL, "gpt1", gpt1_clk)
_REGISTER_CLOCK(NULL, "gpt2", gpt2_clk)
_REGISTER_CLOCK(NULL, "gpt3", gpt3_clk)
_REGISTER_CLOCK(NULL, "gpt4", gpt4_clk)
_REGISTER_CLOCK(NULL, "gpt5", gpt5_clk)
_REGISTER_CLOCK(NULL, "gpt6", gpt6_clk)
_REGISTER_CLOCK("mxc_pwm.0", NULL, pwm_clk)
_REGISTER_CLOCK("mxc-mmc.0", NULL, sdhc1_clk)
_REGISTER_CLOCK("mxc-mmc.1", NULL, sdhc2_clk)
_REGISTER_CLOCK("mxc-mmc.2", NULL, sdhc3_clk)
_REGISTER_CLOCK("imx27-cspi.0", NULL, cspi1_clk)
_REGISTER_CLOCK("imx27-cspi.1", NULL, cspi2_clk)
_REGISTER_CLOCK("imx27-cspi.2", NULL, cspi3_clk)
_REGISTER_CLOCK("imx-fb.0", NULL, lcdc_clk)
_REGISTER_CLOCK("mx2-camera.0", NULL, csi_clk)
_REGISTER_CLOCK("fsl-usb2-udc", "usb", usb_clk)
_REGISTER_CLOCK("fsl-usb2-udc", "usb_ahb", usb_clk1)
_REGISTER_CLOCK("mxc-ehci.0", "usb", usb_clk)
_REGISTER_CLOCK("mxc-ehci.0", "usb_ahb", usb_clk1)
_REGISTER_CLOCK("mxc-ehci.1", "usb", usb_clk)
_REGISTER_CLOCK("mxc-ehci.1", "usb_ahb", usb_clk1)
_REGISTER_CLOCK("mxc-ehci.2", "usb", usb_clk)
_REGISTER_CLOCK("mxc-ehci.2", "usb_ahb", usb_clk1)
_REGISTER_CLOCK("imx-ssi.0", NULL, ssi1_clk)
_REGISTER_CLOCK("imx-ssi.1", NULL, ssi2_clk)
_REGISTER_CLOCK("mxc_nand.0", NULL, nfc_clk)
_REGISTER_CLOCK(NULL, "vpu", vpu_clk)
_REGISTER_CLOCK(NULL, "dma", dma_clk)
_REGISTER_CLOCK(NULL, "rtic", rtic_clk)
_REGISTER_CLOCK(NULL, "brom", brom_clk)
_REGISTER_CLOCK(NULL, "emma", emma_clk)
_REGISTER_CLOCK("m2m-emmaprp.0", NULL, emma_clk)
_REGISTER_CLOCK(NULL, "slcdc", slcdc_clk)
_REGISTER_CLOCK("imx27-fec.0", NULL, fec_clk)
_REGISTER_CLOCK(NULL, "emi", emi_clk)
_REGISTER_CLOCK(NULL, "sahara2", sahara2_clk)
_REGISTER_CLOCK("pata_imx", NULL, pata_clk)
_REGISTER_CLOCK(NULL, "mstick", mstick_clk)
_REGISTER_CLOCK("imx2-wdt.0", NULL, wdog_clk)
_REGISTER_CLOCK(NULL, "gpio", gpio_clk)
_REGISTER_CLOCK("imx-i2c.0", NULL, i2c1_clk)
_REGISTER_CLOCK("imx-i2c.1", NULL, i2c2_clk)
_REGISTER_CLOCK(NULL, "iim", iim_clk)
_REGISTER_CLOCK(NULL, "kpp", kpp_clk)
_REGISTER_CLOCK("mxc_w1.0", NULL, owire_clk)
_REGISTER_CLOCK(NULL, "rtc", rtc_clk)
_REGISTER_CLOCK(NULL, "scc", scc_clk)
};
/* Adjust the clock path for TO2 and later */
static void __init to2_adjust_clocks(void)
{
unsigned long cscr = __raw_readl(CCM_CSCR);
if (mx27_revision() >= IMX_CHIP_REVISION_2_0) {
if (cscr & CCM_CSCR_ARM_SRC)
cpu_clk.parent = &mpll_main1_clk;
if (!(cscr & CCM_CSCR_SSI2))
ssi1_clk.parent = &spll_clk;
if (!(cscr & CCM_CSCR_SSI1))
ssi1_clk.parent = &spll_clk;
if (!(cscr & CCM_CSCR_VPU))
vpu_clk.parent = &spll_clk;
} else {
cpu_clk.parent = &mpll_clk;
cpu_clk.set_parent = NULL;
cpu_clk.round_rate = NULL;
cpu_clk.set_rate = NULL;
ahb_clk.parent = &mpll_clk;
per1_clk.parent = &mpll_clk;
per2_clk.parent = &mpll_clk;
per3_clk.parent = &mpll_clk;
per4_clk.parent = &mpll_clk;
ssi1_clk.parent = &mpll_clk;
ssi2_clk.parent = &mpll_clk;
vpu_clk.parent = &mpll_clk;
}
}
/*
* must be called very early to get information about the
* available clock rate when the timer framework starts
*/
int __init mx27_clocks_init(unsigned long fref)
{
u32 cscr = __raw_readl(CCM_CSCR);
external_high_reference = fref;
/* detect clock reference for both system PLLs */
if (cscr & CCM_CSCR_MCU)
mpll_clk.parent = &ckih_clk;
else
mpll_clk.parent = &fpm_clk;
if (cscr & CCM_CSCR_SP)
spll_clk.parent = &ckih_clk;
else
spll_clk.parent = &fpm_clk;
to2_adjust_clocks();
clkdev_add_table(lookups, ARRAY_SIZE(lookups));
/* Turn off all clocks we do not need */
__raw_writel(0, CCM_PCCR0);
__raw_writel((1 << 10) | (1 << 19), CCM_PCCR1);
spll_clk.disable(&spll_clk);
/* enable basic clocks */
clk_enable(&per1_clk);
clk_enable(&gpio_clk);
clk_enable(&emi_clk);
clk_enable(&iim_clk);
imx_print_silicon_rev("i.MX27", mx27_revision());
clk_disable(&iim_clk);
#if defined(CONFIG_DEBUG_LL) && !defined(CONFIG_DEBUG_ICEDCC)
clk_enable(&uart1_clk);
#endif
mxc_timer_init(&gpt1_clk, MX27_IO_ADDRESS(MX27_GPT1_BASE_ADDR),
MX27_INT_GPT1);
return 0;
}
#ifdef CONFIG_OF
int __init mx27_clocks_init_dt(void)
{
struct device_node *np;
u32 fref = 26000000; /* default */
for_each_compatible_node(np, NULL, "fixed-clock") {
if (!of_device_is_compatible(np, "fsl,imx-osc26m"))
continue;
if (!of_property_read_u32(np, "clock-frequency", &fref))
break;
}
return mx27_clocks_init(fref);
}
#endif
| gpl-2.0 |
KaSt/Kappa34 | arch/arm/mach-shmobile/setup-r8a7740.c | 4729 | 9030 | /*
* R8A7740 processor support
*
* Copyright (C) 2011 Renesas Solutions Corp.
* Copyright (C) 2011 Kuninori Morimoto <kuninori.morimoto.gx@renesas.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/serial_sci.h>
#include <linux/sh_timer.h>
#include <mach/r8a7740.h>
#include <mach/common.h>
#include <mach/irqs.h>
#include <asm/mach-types.h>
#include <asm/mach/map.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
static struct map_desc r8a7740_io_desc[] __initdata = {
/*
* for CPGA/INTC/PFC
* 0xe6000000-0xefffffff -> 0xe6000000-0xefffffff
*/
{
.virtual = 0xe6000000,
.pfn = __phys_to_pfn(0xe6000000),
.length = 160 << 20,
.type = MT_DEVICE_NONSHARED
},
#ifdef CONFIG_CACHE_L2X0
/*
* for l2x0_init()
* 0xf0100000-0xf0101000 -> 0xf0002000-0xf0003000
*/
{
.virtual = 0xf0002000,
.pfn = __phys_to_pfn(0xf0100000),
.length = PAGE_SIZE,
.type = MT_DEVICE_NONSHARED
},
#endif
};
void __init r8a7740_map_io(void)
{
iotable_init(r8a7740_io_desc, ARRAY_SIZE(r8a7740_io_desc));
}
/* SCIFA0 */
static struct plat_sci_port scif0_platform_data = {
.mapbase = 0xe6c40000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE,
.scbrr_algo_id = SCBRR_ALGO_4,
.type = PORT_SCIFA,
.irqs = SCIx_IRQ_MUXED(evt2irq(0x0c00)),
};
static struct platform_device scif0_device = {
.name = "sh-sci",
.id = 0,
.dev = {
.platform_data = &scif0_platform_data,
},
};
/* SCIFA1 */
static struct plat_sci_port scif1_platform_data = {
.mapbase = 0xe6c50000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE,
.scbrr_algo_id = SCBRR_ALGO_4,
.type = PORT_SCIFA,
.irqs = SCIx_IRQ_MUXED(evt2irq(0x0c20)),
};
static struct platform_device scif1_device = {
.name = "sh-sci",
.id = 1,
.dev = {
.platform_data = &scif1_platform_data,
},
};
/* SCIFA2 */
static struct plat_sci_port scif2_platform_data = {
.mapbase = 0xe6c60000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE,
.scbrr_algo_id = SCBRR_ALGO_4,
.type = PORT_SCIFA,
.irqs = SCIx_IRQ_MUXED(evt2irq(0x0c40)),
};
static struct platform_device scif2_device = {
.name = "sh-sci",
.id = 2,
.dev = {
.platform_data = &scif2_platform_data,
},
};
/* SCIFA3 */
static struct plat_sci_port scif3_platform_data = {
.mapbase = 0xe6c70000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE,
.scbrr_algo_id = SCBRR_ALGO_4,
.type = PORT_SCIFA,
.irqs = SCIx_IRQ_MUXED(evt2irq(0x0c60)),
};
static struct platform_device scif3_device = {
.name = "sh-sci",
.id = 3,
.dev = {
.platform_data = &scif3_platform_data,
},
};
/* SCIFA4 */
static struct plat_sci_port scif4_platform_data = {
.mapbase = 0xe6c80000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE,
.scbrr_algo_id = SCBRR_ALGO_4,
.type = PORT_SCIFA,
.irqs = SCIx_IRQ_MUXED(evt2irq(0x0d20)),
};
static struct platform_device scif4_device = {
.name = "sh-sci",
.id = 4,
.dev = {
.platform_data = &scif4_platform_data,
},
};
/* SCIFA5 */
static struct plat_sci_port scif5_platform_data = {
.mapbase = 0xe6cb0000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE,
.scbrr_algo_id = SCBRR_ALGO_4,
.type = PORT_SCIFA,
.irqs = SCIx_IRQ_MUXED(evt2irq(0x0d40)),
};
static struct platform_device scif5_device = {
.name = "sh-sci",
.id = 5,
.dev = {
.platform_data = &scif5_platform_data,
},
};
/* SCIFA6 */
static struct plat_sci_port scif6_platform_data = {
.mapbase = 0xe6cc0000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE,
.scbrr_algo_id = SCBRR_ALGO_4,
.type = PORT_SCIFA,
.irqs = SCIx_IRQ_MUXED(evt2irq(0x04c0)),
};
static struct platform_device scif6_device = {
.name = "sh-sci",
.id = 6,
.dev = {
.platform_data = &scif6_platform_data,
},
};
/* SCIFA7 */
static struct plat_sci_port scif7_platform_data = {
.mapbase = 0xe6cd0000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE,
.scbrr_algo_id = SCBRR_ALGO_4,
.type = PORT_SCIFA,
.irqs = SCIx_IRQ_MUXED(evt2irq(0x04e0)),
};
static struct platform_device scif7_device = {
.name = "sh-sci",
.id = 7,
.dev = {
.platform_data = &scif7_platform_data,
},
};
/* SCIFB */
static struct plat_sci_port scifb_platform_data = {
.mapbase = 0xe6c30000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE,
.scbrr_algo_id = SCBRR_ALGO_4,
.type = PORT_SCIFB,
.irqs = SCIx_IRQ_MUXED(evt2irq(0x0d60)),
};
static struct platform_device scifb_device = {
.name = "sh-sci",
.id = 8,
.dev = {
.platform_data = &scifb_platform_data,
},
};
/* CMT */
static struct sh_timer_config cmt10_platform_data = {
.name = "CMT10",
.channel_offset = 0x10,
.timer_bit = 0,
.clockevent_rating = 125,
.clocksource_rating = 125,
};
static struct resource cmt10_resources[] = {
[0] = {
.name = "CMT10",
.start = 0xe6138010,
.end = 0xe613801b,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x0b00),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device cmt10_device = {
.name = "sh_cmt",
.id = 10,
.dev = {
.platform_data = &cmt10_platform_data,
},
.resource = cmt10_resources,
.num_resources = ARRAY_SIZE(cmt10_resources),
};
static struct platform_device *r8a7740_early_devices[] __initdata = {
&scif0_device,
&scif1_device,
&scif2_device,
&scif3_device,
&scif4_device,
&scif5_device,
&scif6_device,
&scif7_device,
&scifb_device,
&cmt10_device,
};
/* I2C */
static struct resource i2c0_resources[] = {
[0] = {
.name = "IIC0",
.start = 0xfff20000,
.end = 0xfff20425 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = intcs_evt2irq(0xe00),
.end = intcs_evt2irq(0xe60),
.flags = IORESOURCE_IRQ,
},
};
static struct resource i2c1_resources[] = {
[0] = {
.name = "IIC1",
.start = 0xe6c20000,
.end = 0xe6c20425 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x780), /* IIC1_ALI1 */
.end = evt2irq(0x7e0), /* IIC1_DTEI1 */
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device i2c0_device = {
.name = "i2c-sh_mobile",
.id = 0,
.resource = i2c0_resources,
.num_resources = ARRAY_SIZE(i2c0_resources),
};
static struct platform_device i2c1_device = {
.name = "i2c-sh_mobile",
.id = 1,
.resource = i2c1_resources,
.num_resources = ARRAY_SIZE(i2c1_resources),
};
static struct platform_device *r8a7740_late_devices[] __initdata = {
&i2c0_device,
&i2c1_device,
};
#define ICCR 0x0004
#define ICSTART 0x0070
#define i2c_read(reg, offset) ioread8(reg + offset)
#define i2c_write(reg, offset, data) iowrite8(data, reg + offset)
/*
* r8a7740 chip has lasting errata on I2C I/O pad reset.
* this is work-around for it.
*/
static void r8a7740_i2c_workaround(struct platform_device *pdev)
{
struct resource *res;
void __iomem *reg;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (unlikely(!res)) {
pr_err("r8a7740 i2c workaround fail (cannot find resource)\n");
return;
}
reg = ioremap(res->start, resource_size(res));
if (unlikely(!reg)) {
pr_err("r8a7740 i2c workaround fail (cannot map IO)\n");
return;
}
i2c_write(reg, ICCR, i2c_read(reg, ICCR) | 0x80);
i2c_read(reg, ICCR); /* dummy read */
i2c_write(reg, ICSTART, i2c_read(reg, ICSTART) | 0x10);
i2c_read(reg, ICSTART); /* dummy read */
mdelay(100);
i2c_write(reg, ICCR, 0x01);
i2c_read(reg, ICCR);
i2c_write(reg, ICSTART, 0x00);
i2c_read(reg, ICSTART);
i2c_write(reg, ICCR, 0x10);
mdelay(100);
i2c_write(reg, ICCR, 0x00);
mdelay(100);
i2c_write(reg, ICCR, 0x10);
mdelay(100);
iounmap(reg);
}
void __init r8a7740_add_standard_devices(void)
{
/* I2C work-around */
r8a7740_i2c_workaround(&i2c0_device);
r8a7740_i2c_workaround(&i2c1_device);
platform_add_devices(r8a7740_early_devices,
ARRAY_SIZE(r8a7740_early_devices));
platform_add_devices(r8a7740_late_devices,
ARRAY_SIZE(r8a7740_late_devices));
}
static void __init r8a7740_earlytimer_init(void)
{
r8a7740_clock_init(0);
shmobile_earlytimer_init();
}
void __init r8a7740_add_early_devices(void)
{
early_platform_add_devices(r8a7740_early_devices,
ARRAY_SIZE(r8a7740_early_devices));
/* setup early console here as well */
shmobile_setup_console();
/* override timer setup with soc-specific code */
shmobile_timer.init = r8a7740_earlytimer_init;
}
| gpl-2.0 |
FrancescoCG/CrazySuperKernel-CM14.1-KLTE | drivers/input/misc/adxl34x-i2c.c | 4985 | 3526 | /*
* ADLX345/346 Three-Axis Digital Accelerometers (I2C Interface)
*
* Enter bugs at http://blackfin.uclinux.org/
*
* Copyright (C) 2009 Michael Hennerich, Analog Devices Inc.
* Licensed under the GPL-2 or later.
*/
#include <linux/input.h> /* BUS_I2C */
#include <linux/i2c.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/pm.h>
#include "adxl34x.h"
static int adxl34x_smbus_read(struct device *dev, unsigned char reg)
{
struct i2c_client *client = to_i2c_client(dev);
return i2c_smbus_read_byte_data(client, reg);
}
static int adxl34x_smbus_write(struct device *dev,
unsigned char reg, unsigned char val)
{
struct i2c_client *client = to_i2c_client(dev);
return i2c_smbus_write_byte_data(client, reg, val);
}
static int adxl34x_smbus_read_block(struct device *dev,
unsigned char reg, int count,
void *buf)
{
struct i2c_client *client = to_i2c_client(dev);
return i2c_smbus_read_i2c_block_data(client, reg, count, buf);
}
static int adxl34x_i2c_read_block(struct device *dev,
unsigned char reg, int count,
void *buf)
{
struct i2c_client *client = to_i2c_client(dev);
int ret;
ret = i2c_master_send(client, ®, 1);
if (ret < 0)
return ret;
ret = i2c_master_recv(client, buf, count);
if (ret < 0)
return ret;
if (ret != count)
return -EIO;
return 0;
}
static const struct adxl34x_bus_ops adxl34x_smbus_bops = {
.bustype = BUS_I2C,
.write = adxl34x_smbus_write,
.read = adxl34x_smbus_read,
.read_block = adxl34x_smbus_read_block,
};
static const struct adxl34x_bus_ops adxl34x_i2c_bops = {
.bustype = BUS_I2C,
.write = adxl34x_smbus_write,
.read = adxl34x_smbus_read,
.read_block = adxl34x_i2c_read_block,
};
static int __devinit adxl34x_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct adxl34x *ac;
int error;
error = i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_BYTE_DATA);
if (!error) {
dev_err(&client->dev, "SMBUS Byte Data not Supported\n");
return -EIO;
}
ac = adxl34x_probe(&client->dev, client->irq, false,
i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_READ_I2C_BLOCK) ?
&adxl34x_smbus_bops : &adxl34x_i2c_bops);
if (IS_ERR(ac))
return PTR_ERR(ac);
i2c_set_clientdata(client, ac);
return 0;
}
static int __devexit adxl34x_i2c_remove(struct i2c_client *client)
{
struct adxl34x *ac = i2c_get_clientdata(client);
return adxl34x_remove(ac);
}
#ifdef CONFIG_PM
static int adxl34x_i2c_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct adxl34x *ac = i2c_get_clientdata(client);
adxl34x_suspend(ac);
return 0;
}
static int adxl34x_i2c_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct adxl34x *ac = i2c_get_clientdata(client);
adxl34x_resume(ac);
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(adxl34x_i2c_pm, adxl34x_i2c_suspend,
adxl34x_i2c_resume);
static const struct i2c_device_id adxl34x_id[] = {
{ "adxl34x", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, adxl34x_id);
static struct i2c_driver adxl34x_driver = {
.driver = {
.name = "adxl34x",
.owner = THIS_MODULE,
.pm = &adxl34x_i2c_pm,
},
.probe = adxl34x_i2c_probe,
.remove = __devexit_p(adxl34x_i2c_remove),
.id_table = adxl34x_id,
};
module_i2c_driver(adxl34x_driver);
MODULE_AUTHOR("Michael Hennerich <hennerich@blackfin.uclinux.org>");
MODULE_DESCRIPTION("ADXL345/346 Three-Axis Digital Accelerometer I2C Bus Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
evil-god/runbo-q5x6 | kernel/drivers/misc/isl29003.c | 4985 | 11711 | /*
* isl29003.c - Linux kernel module for
* Intersil ISL29003 ambient light sensor
*
* See file:Documentation/misc-devices/isl29003
*
* Copyright (c) 2009 Daniel Mack <daniel@caiaq.de>
*
* Based on code written by
* Rodolfo Giometti <giometti@linux.it>
* Eurotech S.p.A. <info@eurotech.it>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/mutex.h>
#include <linux/delay.h>
#define ISL29003_DRV_NAME "isl29003"
#define DRIVER_VERSION "1.0"
#define ISL29003_REG_COMMAND 0x00
#define ISL29003_ADC_ENABLED (1 << 7)
#define ISL29003_ADC_PD (1 << 6)
#define ISL29003_TIMING_INT (1 << 5)
#define ISL29003_MODE_SHIFT (2)
#define ISL29003_MODE_MASK (0x3 << ISL29003_MODE_SHIFT)
#define ISL29003_RES_SHIFT (0)
#define ISL29003_RES_MASK (0x3 << ISL29003_RES_SHIFT)
#define ISL29003_REG_CONTROL 0x01
#define ISL29003_INT_FLG (1 << 5)
#define ISL29003_RANGE_SHIFT (2)
#define ISL29003_RANGE_MASK (0x3 << ISL29003_RANGE_SHIFT)
#define ISL29003_INT_PERSISTS_SHIFT (0)
#define ISL29003_INT_PERSISTS_MASK (0xf << ISL29003_INT_PERSISTS_SHIFT)
#define ISL29003_REG_IRQ_THRESH_HI 0x02
#define ISL29003_REG_IRQ_THRESH_LO 0x03
#define ISL29003_REG_LSB_SENSOR 0x04
#define ISL29003_REG_MSB_SENSOR 0x05
#define ISL29003_REG_LSB_TIMER 0x06
#define ISL29003_REG_MSB_TIMER 0x07
#define ISL29003_NUM_CACHABLE_REGS 4
struct isl29003_data {
struct i2c_client *client;
struct mutex lock;
u8 reg_cache[ISL29003_NUM_CACHABLE_REGS];
u8 power_state_before_suspend;
};
static int gain_range[] = {
1000, 4000, 16000, 64000
};
/*
* register access helpers
*/
static int __isl29003_read_reg(struct i2c_client *client,
u32 reg, u8 mask, u8 shift)
{
struct isl29003_data *data = i2c_get_clientdata(client);
return (data->reg_cache[reg] & mask) >> shift;
}
static int __isl29003_write_reg(struct i2c_client *client,
u32 reg, u8 mask, u8 shift, u8 val)
{
struct isl29003_data *data = i2c_get_clientdata(client);
int ret = 0;
u8 tmp;
if (reg >= ISL29003_NUM_CACHABLE_REGS)
return -EINVAL;
mutex_lock(&data->lock);
tmp = data->reg_cache[reg];
tmp &= ~mask;
tmp |= val << shift;
ret = i2c_smbus_write_byte_data(client, reg, tmp);
if (!ret)
data->reg_cache[reg] = tmp;
mutex_unlock(&data->lock);
return ret;
}
/*
* internally used functions
*/
/* range */
static int isl29003_get_range(struct i2c_client *client)
{
return __isl29003_read_reg(client, ISL29003_REG_CONTROL,
ISL29003_RANGE_MASK, ISL29003_RANGE_SHIFT);
}
static int isl29003_set_range(struct i2c_client *client, int range)
{
return __isl29003_write_reg(client, ISL29003_REG_CONTROL,
ISL29003_RANGE_MASK, ISL29003_RANGE_SHIFT, range);
}
/* resolution */
static int isl29003_get_resolution(struct i2c_client *client)
{
return __isl29003_read_reg(client, ISL29003_REG_COMMAND,
ISL29003_RES_MASK, ISL29003_RES_SHIFT);
}
static int isl29003_set_resolution(struct i2c_client *client, int res)
{
return __isl29003_write_reg(client, ISL29003_REG_COMMAND,
ISL29003_RES_MASK, ISL29003_RES_SHIFT, res);
}
/* mode */
static int isl29003_get_mode(struct i2c_client *client)
{
return __isl29003_read_reg(client, ISL29003_REG_COMMAND,
ISL29003_RES_MASK, ISL29003_RES_SHIFT);
}
static int isl29003_set_mode(struct i2c_client *client, int mode)
{
return __isl29003_write_reg(client, ISL29003_REG_COMMAND,
ISL29003_RES_MASK, ISL29003_RES_SHIFT, mode);
}
/* power_state */
static int isl29003_set_power_state(struct i2c_client *client, int state)
{
return __isl29003_write_reg(client, ISL29003_REG_COMMAND,
ISL29003_ADC_ENABLED | ISL29003_ADC_PD, 0,
state ? ISL29003_ADC_ENABLED : ISL29003_ADC_PD);
}
static int isl29003_get_power_state(struct i2c_client *client)
{
struct isl29003_data *data = i2c_get_clientdata(client);
u8 cmdreg = data->reg_cache[ISL29003_REG_COMMAND];
return ~cmdreg & ISL29003_ADC_PD;
}
static int isl29003_get_adc_value(struct i2c_client *client)
{
struct isl29003_data *data = i2c_get_clientdata(client);
int lsb, msb, range, bitdepth;
mutex_lock(&data->lock);
lsb = i2c_smbus_read_byte_data(client, ISL29003_REG_LSB_SENSOR);
if (lsb < 0) {
mutex_unlock(&data->lock);
return lsb;
}
msb = i2c_smbus_read_byte_data(client, ISL29003_REG_MSB_SENSOR);
mutex_unlock(&data->lock);
if (msb < 0)
return msb;
range = isl29003_get_range(client);
bitdepth = (4 - isl29003_get_resolution(client)) * 4;
return (((msb << 8) | lsb) * gain_range[range]) >> bitdepth;
}
/*
* sysfs layer
*/
/* range */
static ssize_t isl29003_show_range(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
return sprintf(buf, "%i\n", isl29003_get_range(client));
}
static ssize_t isl29003_store_range(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
unsigned long val;
int ret;
if ((strict_strtoul(buf, 10, &val) < 0) || (val > 3))
return -EINVAL;
ret = isl29003_set_range(client, val);
if (ret < 0)
return ret;
return count;
}
static DEVICE_ATTR(range, S_IWUSR | S_IRUGO,
isl29003_show_range, isl29003_store_range);
/* resolution */
static ssize_t isl29003_show_resolution(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
return sprintf(buf, "%d\n", isl29003_get_resolution(client));
}
static ssize_t isl29003_store_resolution(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
unsigned long val;
int ret;
if ((strict_strtoul(buf, 10, &val) < 0) || (val > 3))
return -EINVAL;
ret = isl29003_set_resolution(client, val);
if (ret < 0)
return ret;
return count;
}
static DEVICE_ATTR(resolution, S_IWUSR | S_IRUGO,
isl29003_show_resolution, isl29003_store_resolution);
/* mode */
static ssize_t isl29003_show_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
return sprintf(buf, "%d\n", isl29003_get_mode(client));
}
static ssize_t isl29003_store_mode(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
unsigned long val;
int ret;
if ((strict_strtoul(buf, 10, &val) < 0) || (val > 2))
return -EINVAL;
ret = isl29003_set_mode(client, val);
if (ret < 0)
return ret;
return count;
}
static DEVICE_ATTR(mode, S_IWUSR | S_IRUGO,
isl29003_show_mode, isl29003_store_mode);
/* power state */
static ssize_t isl29003_show_power_state(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
return sprintf(buf, "%d\n", isl29003_get_power_state(client));
}
static ssize_t isl29003_store_power_state(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
unsigned long val;
int ret;
if ((strict_strtoul(buf, 10, &val) < 0) || (val > 1))
return -EINVAL;
ret = isl29003_set_power_state(client, val);
return ret ? ret : count;
}
static DEVICE_ATTR(power_state, S_IWUSR | S_IRUGO,
isl29003_show_power_state, isl29003_store_power_state);
/* lux */
static ssize_t isl29003_show_lux(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
/* No LUX data if not operational */
if (!isl29003_get_power_state(client))
return -EBUSY;
return sprintf(buf, "%d\n", isl29003_get_adc_value(client));
}
static DEVICE_ATTR(lux, S_IRUGO, isl29003_show_lux, NULL);
static struct attribute *isl29003_attributes[] = {
&dev_attr_range.attr,
&dev_attr_resolution.attr,
&dev_attr_mode.attr,
&dev_attr_power_state.attr,
&dev_attr_lux.attr,
NULL
};
static const struct attribute_group isl29003_attr_group = {
.attrs = isl29003_attributes,
};
static int isl29003_init_client(struct i2c_client *client)
{
struct isl29003_data *data = i2c_get_clientdata(client);
int i;
/* read all the registers once to fill the cache.
* if one of the reads fails, we consider the init failed */
for (i = 0; i < ARRAY_SIZE(data->reg_cache); i++) {
int v = i2c_smbus_read_byte_data(client, i);
if (v < 0)
return -ENODEV;
data->reg_cache[i] = v;
}
/* set defaults */
isl29003_set_range(client, 0);
isl29003_set_resolution(client, 0);
isl29003_set_mode(client, 0);
isl29003_set_power_state(client, 0);
return 0;
}
/*
* I2C layer
*/
static int __devinit isl29003_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
struct isl29003_data *data;
int err = 0;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE))
return -EIO;
data = kzalloc(sizeof(struct isl29003_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
data->client = client;
i2c_set_clientdata(client, data);
mutex_init(&data->lock);
/* initialize the ISL29003 chip */
err = isl29003_init_client(client);
if (err)
goto exit_kfree;
/* register sysfs hooks */
err = sysfs_create_group(&client->dev.kobj, &isl29003_attr_group);
if (err)
goto exit_kfree;
dev_info(&client->dev, "driver version %s enabled\n", DRIVER_VERSION);
return 0;
exit_kfree:
kfree(data);
return err;
}
static int __devexit isl29003_remove(struct i2c_client *client)
{
sysfs_remove_group(&client->dev.kobj, &isl29003_attr_group);
isl29003_set_power_state(client, 0);
kfree(i2c_get_clientdata(client));
return 0;
}
#ifdef CONFIG_PM
static int isl29003_suspend(struct i2c_client *client, pm_message_t mesg)
{
struct isl29003_data *data = i2c_get_clientdata(client);
data->power_state_before_suspend = isl29003_get_power_state(client);
return isl29003_set_power_state(client, 0);
}
static int isl29003_resume(struct i2c_client *client)
{
int i;
struct isl29003_data *data = i2c_get_clientdata(client);
/* restore registers from cache */
for (i = 0; i < ARRAY_SIZE(data->reg_cache); i++)
if (i2c_smbus_write_byte_data(client, i, data->reg_cache[i]))
return -EIO;
return isl29003_set_power_state(client,
data->power_state_before_suspend);
}
#else
#define isl29003_suspend NULL
#define isl29003_resume NULL
#endif /* CONFIG_PM */
static const struct i2c_device_id isl29003_id[] = {
{ "isl29003", 0 },
{}
};
MODULE_DEVICE_TABLE(i2c, isl29003_id);
static struct i2c_driver isl29003_driver = {
.driver = {
.name = ISL29003_DRV_NAME,
.owner = THIS_MODULE,
},
.suspend = isl29003_suspend,
.resume = isl29003_resume,
.probe = isl29003_probe,
.remove = __devexit_p(isl29003_remove),
.id_table = isl29003_id,
};
module_i2c_driver(isl29003_driver);
MODULE_AUTHOR("Daniel Mack <daniel@caiaq.de>");
MODULE_DESCRIPTION("ISL29003 ambient light sensor driver");
MODULE_LICENSE("GPL v2");
MODULE_VERSION(DRIVER_VERSION);
| gpl-2.0 |
moddingg33k/deprecated_android_kernel_synopsis | sound/drivers/vx/vx_hwdep.c | 5241 | 6188 | /*
* Driver for Digigram VX soundcards
*
* DSP firmware management
*
* Copyright (c) 2002 by Takashi Iwai <tiwai@suse.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/device.h>
#include <linux/firmware.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/hwdep.h>
#include <sound/vx_core.h>
#ifdef SND_VX_FW_LOADER
MODULE_FIRMWARE("vx/bx_1_vxp.b56");
MODULE_FIRMWARE("vx/bx_1_vp4.b56");
MODULE_FIRMWARE("vx/x1_1_vx2.xlx");
MODULE_FIRMWARE("vx/x1_2_v22.xlx");
MODULE_FIRMWARE("vx/x1_1_vxp.xlx");
MODULE_FIRMWARE("vx/x1_1_vp4.xlx");
MODULE_FIRMWARE("vx/bd56002.boot");
MODULE_FIRMWARE("vx/bd563v2.boot");
MODULE_FIRMWARE("vx/bd563s3.boot");
MODULE_FIRMWARE("vx/l_1_vx2.d56");
MODULE_FIRMWARE("vx/l_1_v22.d56");
MODULE_FIRMWARE("vx/l_1_vxp.d56");
MODULE_FIRMWARE("vx/l_1_vp4.d56");
int snd_vx_setup_firmware(struct vx_core *chip)
{
static char *fw_files[VX_TYPE_NUMS][4] = {
[VX_TYPE_BOARD] = {
NULL, "x1_1_vx2.xlx", "bd56002.boot", "l_1_vx2.d56",
},
[VX_TYPE_V2] = {
NULL, "x1_2_v22.xlx", "bd563v2.boot", "l_1_v22.d56",
},
[VX_TYPE_MIC] = {
NULL, "x1_2_v22.xlx", "bd563v2.boot", "l_1_v22.d56",
},
[VX_TYPE_VXPOCKET] = {
"bx_1_vxp.b56", "x1_1_vxp.xlx", "bd563s3.boot", "l_1_vxp.d56"
},
[VX_TYPE_VXP440] = {
"bx_1_vp4.b56", "x1_1_vp4.xlx", "bd563s3.boot", "l_1_vp4.d56"
},
};
int i, err;
for (i = 0; i < 4; i++) {
char path[32];
const struct firmware *fw;
if (! fw_files[chip->type][i])
continue;
sprintf(path, "vx/%s", fw_files[chip->type][i]);
if (request_firmware(&fw, path, chip->dev)) {
snd_printk(KERN_ERR "vx: can't load firmware %s\n", path);
return -ENOENT;
}
err = chip->ops->load_dsp(chip, i, fw);
if (err < 0) {
release_firmware(fw);
return err;
}
if (i == 1)
chip->chip_status |= VX_STAT_XILINX_LOADED;
#ifdef CONFIG_PM
chip->firmware[i] = fw;
#else
release_firmware(fw);
#endif
}
/* ok, we reached to the last one */
/* create the devices if not built yet */
if ((err = snd_vx_pcm_new(chip)) < 0)
return err;
if ((err = snd_vx_mixer_new(chip)) < 0)
return err;
if (chip->ops->add_controls)
if ((err = chip->ops->add_controls(chip)) < 0)
return err;
chip->chip_status |= VX_STAT_DEVICE_INIT;
chip->chip_status |= VX_STAT_CHIP_INIT;
return snd_card_register(chip->card);
}
/* exported */
void snd_vx_free_firmware(struct vx_core *chip)
{
#ifdef CONFIG_PM
int i;
for (i = 0; i < 4; i++)
release_firmware(chip->firmware[i]);
#endif
}
#else /* old style firmware loading */
static int vx_hwdep_dsp_status(struct snd_hwdep *hw,
struct snd_hwdep_dsp_status *info)
{
static char *type_ids[VX_TYPE_NUMS] = {
[VX_TYPE_BOARD] = "vxboard",
[VX_TYPE_V2] = "vx222",
[VX_TYPE_MIC] = "vx222",
[VX_TYPE_VXPOCKET] = "vxpocket",
[VX_TYPE_VXP440] = "vxp440",
};
struct vx_core *vx = hw->private_data;
if (snd_BUG_ON(!type_ids[vx->type]))
return -EINVAL;
strcpy(info->id, type_ids[vx->type]);
if (vx_is_pcmcia(vx))
info->num_dsps = 4;
else
info->num_dsps = 3;
if (vx->chip_status & VX_STAT_CHIP_INIT)
info->chip_ready = 1;
info->version = VX_DRIVER_VERSION;
return 0;
}
static void free_fw(const struct firmware *fw)
{
if (fw) {
vfree(fw->data);
kfree(fw);
}
}
static int vx_hwdep_dsp_load(struct snd_hwdep *hw,
struct snd_hwdep_dsp_image *dsp)
{
struct vx_core *vx = hw->private_data;
int index, err;
struct firmware *fw;
if (snd_BUG_ON(!vx->ops->load_dsp))
return -ENXIO;
fw = kmalloc(sizeof(*fw), GFP_KERNEL);
if (! fw) {
snd_printk(KERN_ERR "cannot allocate firmware\n");
return -ENOMEM;
}
fw->size = dsp->length;
fw->data = vmalloc(fw->size);
if (! fw->data) {
snd_printk(KERN_ERR "cannot allocate firmware image (length=%d)\n",
(int)fw->size);
kfree(fw);
return -ENOMEM;
}
if (copy_from_user((void *)fw->data, dsp->image, dsp->length)) {
free_fw(fw);
return -EFAULT;
}
index = dsp->index;
if (! vx_is_pcmcia(vx))
index++;
err = vx->ops->load_dsp(vx, index, fw);
if (err < 0) {
free_fw(fw);
return err;
}
#ifdef CONFIG_PM
vx->firmware[index] = fw;
#else
free_fw(fw);
#endif
if (index == 1)
vx->chip_status |= VX_STAT_XILINX_LOADED;
if (index < 3)
return 0;
/* ok, we reached to the last one */
/* create the devices if not built yet */
if (! (vx->chip_status & VX_STAT_DEVICE_INIT)) {
if ((err = snd_vx_pcm_new(vx)) < 0)
return err;
if ((err = snd_vx_mixer_new(vx)) < 0)
return err;
if (vx->ops->add_controls)
if ((err = vx->ops->add_controls(vx)) < 0)
return err;
if ((err = snd_card_register(vx->card)) < 0)
return err;
vx->chip_status |= VX_STAT_DEVICE_INIT;
}
vx->chip_status |= VX_STAT_CHIP_INIT;
return 0;
}
/* exported */
int snd_vx_setup_firmware(struct vx_core *chip)
{
int err;
struct snd_hwdep *hw;
if ((err = snd_hwdep_new(chip->card, SND_VX_HWDEP_ID, 0, &hw)) < 0)
return err;
hw->iface = SNDRV_HWDEP_IFACE_VX;
hw->private_data = chip;
hw->ops.dsp_status = vx_hwdep_dsp_status;
hw->ops.dsp_load = vx_hwdep_dsp_load;
hw->exclusive = 1;
sprintf(hw->name, "VX Loader (%s)", chip->card->driver);
chip->hwdep = hw;
return snd_card_register(chip->card);
}
/* exported */
void snd_vx_free_firmware(struct vx_core *chip)
{
#ifdef CONFIG_PM
int i;
for (i = 0; i < 4; i++)
free_fw(chip->firmware[i]);
#endif
}
#endif /* SND_VX_FW_LOADER */
EXPORT_SYMBOL(snd_vx_setup_firmware);
EXPORT_SYMBOL(snd_vx_free_firmware);
| gpl-2.0 |
SerenityS/android_kernel_pantech_msm8974 | drivers/gpio/gpio-max7301.c | 5753 | 2769 | /*
* Copyright (C) 2006 Juergen Beisert, Pengutronix
* Copyright (C) 2008 Guennadi Liakhovetski, Pengutronix
* Copyright (C) 2009 Wolfram Sang, Pengutronix
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Check max730x.c for further details.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/spi/spi.h>
#include <linux/spi/max7301.h>
/* A write to the MAX7301 means one message with one transfer */
static int max7301_spi_write(struct device *dev, unsigned int reg,
unsigned int val)
{
struct spi_device *spi = to_spi_device(dev);
u16 word = ((reg & 0x7F) << 8) | (val & 0xFF);
return spi_write(spi, (const u8 *)&word, sizeof(word));
}
/* A read from the MAX7301 means two transfers; here, one message each */
static int max7301_spi_read(struct device *dev, unsigned int reg)
{
int ret;
u16 word;
struct spi_device *spi = to_spi_device(dev);
word = 0x8000 | (reg << 8);
ret = spi_write(spi, (const u8 *)&word, sizeof(word));
if (ret)
return ret;
/*
* This relies on the fact, that a transfer with NULL tx_buf shifts out
* zero bytes (=NOOP for MAX7301)
*/
ret = spi_read(spi, (u8 *)&word, sizeof(word));
if (ret)
return ret;
return word & 0xff;
}
static int __devinit max7301_probe(struct spi_device *spi)
{
struct max7301 *ts;
int ret;
/* bits_per_word cannot be configured in platform data */
spi->bits_per_word = 16;
ret = spi_setup(spi);
if (ret < 0)
return ret;
ts = kzalloc(sizeof(struct max7301), GFP_KERNEL);
if (!ts)
return -ENOMEM;
ts->read = max7301_spi_read;
ts->write = max7301_spi_write;
ts->dev = &spi->dev;
ret = __max730x_probe(ts);
if (ret)
kfree(ts);
return ret;
}
static int __devexit max7301_remove(struct spi_device *spi)
{
return __max730x_remove(&spi->dev);
}
static const struct spi_device_id max7301_id[] = {
{ "max7301", 0 },
{ }
};
MODULE_DEVICE_TABLE(spi, max7301_id);
static struct spi_driver max7301_driver = {
.driver = {
.name = "max7301",
.owner = THIS_MODULE,
},
.probe = max7301_probe,
.remove = __devexit_p(max7301_remove),
.id_table = max7301_id,
};
static int __init max7301_init(void)
{
return spi_register_driver(&max7301_driver);
}
/* register after spi postcore initcall and before
* subsys initcalls that may rely on these GPIOs
*/
subsys_initcall(max7301_init);
static void __exit max7301_exit(void)
{
spi_unregister_driver(&max7301_driver);
}
module_exit(max7301_exit);
MODULE_AUTHOR("Juergen Beisert, Wolfram Sang");
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("MAX7301 GPIO-Expander");
| gpl-2.0 |
RepoBackups/kernel_lge_g3 | sound/soc/pxa/raumfeld.c | 8313 | 8090 | /*
* raumfeld_audio.c -- SoC audio for Raumfeld audio devices
*
* Copyright (c) 2009 Daniel Mack <daniel@caiaq.de>
*
* based on code from:
*
* Wolfson Microelectronics PLC.
* Openedhand Ltd.
* 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.
*/
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <asm/mach-types.h>
#include "pxa-ssp.h"
#define GPIO_SPDIF_RESET (38)
#define GPIO_MCLK_RESET (111)
#define GPIO_CODEC_RESET (120)
static struct i2c_client *max9486_client;
static struct i2c_board_info max9486_hwmon_info = {
I2C_BOARD_INFO("max9485", 0x63),
};
#define MAX9485_MCLK_FREQ_112896 0x22
#define MAX9485_MCLK_FREQ_122880 0x23
#define MAX9485_MCLK_FREQ_225792 0x32
#define MAX9485_MCLK_FREQ_245760 0x33
static void set_max9485_clk(char clk)
{
i2c_master_send(max9486_client, &clk, 1);
}
static void raumfeld_enable_audio(bool en)
{
if (en) {
gpio_set_value(GPIO_MCLK_RESET, 1);
/* wait some time to let the clocks become stable */
msleep(100);
gpio_set_value(GPIO_SPDIF_RESET, 1);
gpio_set_value(GPIO_CODEC_RESET, 1);
} else {
gpio_set_value(GPIO_MCLK_RESET, 0);
gpio_set_value(GPIO_SPDIF_RESET, 0);
gpio_set_value(GPIO_CODEC_RESET, 0);
}
}
/* CS4270 */
static int raumfeld_cs4270_startup(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
/* set freq to 0 to enable all possible codec sample rates */
return snd_soc_dai_set_sysclk(codec_dai, 0, 0, 0);
}
static void raumfeld_cs4270_shutdown(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
/* set freq to 0 to enable all possible codec sample rates */
snd_soc_dai_set_sysclk(codec_dai, 0, 0, 0);
}
static int raumfeld_cs4270_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
unsigned int fmt, clk = 0;
int ret = 0;
switch (params_rate(params)) {
case 44100:
set_max9485_clk(MAX9485_MCLK_FREQ_112896);
clk = 11289600;
break;
case 48000:
set_max9485_clk(MAX9485_MCLK_FREQ_122880);
clk = 12288000;
break;
case 88200:
set_max9485_clk(MAX9485_MCLK_FREQ_225792);
clk = 22579200;
break;
case 96000:
set_max9485_clk(MAX9485_MCLK_FREQ_245760);
clk = 24576000;
break;
default:
return -EINVAL;
}
fmt = SND_SOC_DAIFMT_I2S |
SND_SOC_DAIFMT_NB_NF |
SND_SOC_DAIFMT_CBS_CFS;
/* setup the CODEC DAI */
ret = snd_soc_dai_set_fmt(codec_dai, fmt);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_sysclk(codec_dai, 0, clk, 0);
if (ret < 0)
return ret;
/* setup the CPU DAI */
ret = snd_soc_dai_set_pll(cpu_dai, 0, 0, 0, clk);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_fmt(cpu_dai, fmt);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_clkdiv(cpu_dai, PXA_SSP_DIV_SCR, 4);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_sysclk(cpu_dai, PXA_SSP_CLK_EXT, clk, 1);
if (ret < 0)
return ret;
return 0;
}
static struct snd_soc_ops raumfeld_cs4270_ops = {
.startup = raumfeld_cs4270_startup,
.shutdown = raumfeld_cs4270_shutdown,
.hw_params = raumfeld_cs4270_hw_params,
};
static int raumfeld_analog_suspend(struct snd_soc_card *card)
{
raumfeld_enable_audio(false);
return 0;
}
static int raumfeld_analog_resume(struct snd_soc_card *card)
{
raumfeld_enable_audio(true);
return 0;
}
/* AK4104 */
static int raumfeld_ak4104_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
int fmt, ret = 0, clk = 0;
switch (params_rate(params)) {
case 44100:
set_max9485_clk(MAX9485_MCLK_FREQ_112896);
clk = 11289600;
break;
case 48000:
set_max9485_clk(MAX9485_MCLK_FREQ_122880);
clk = 12288000;
break;
case 88200:
set_max9485_clk(MAX9485_MCLK_FREQ_225792);
clk = 22579200;
break;
case 96000:
set_max9485_clk(MAX9485_MCLK_FREQ_245760);
clk = 24576000;
break;
default:
return -EINVAL;
}
fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF;
/* setup the CODEC DAI */
ret = snd_soc_dai_set_fmt(codec_dai, fmt | SND_SOC_DAIFMT_CBS_CFS);
if (ret < 0)
return ret;
/* setup the CPU DAI */
ret = snd_soc_dai_set_pll(cpu_dai, 0, 0, 0, clk);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_fmt(cpu_dai, fmt | SND_SOC_DAIFMT_CBS_CFS);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_clkdiv(cpu_dai, PXA_SSP_DIV_SCR, 4);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_sysclk(cpu_dai, PXA_SSP_CLK_EXT, clk, 1);
if (ret < 0)
return ret;
return 0;
}
static struct snd_soc_ops raumfeld_ak4104_ops = {
.hw_params = raumfeld_ak4104_hw_params,
};
#define DAI_LINK_CS4270 \
{ \
.name = "CS4270", \
.stream_name = "CS4270", \
.cpu_dai_name = "pxa-ssp-dai.0", \
.platform_name = "pxa-pcm-audio", \
.codec_dai_name = "cs4270-hifi", \
.codec_name = "cs4270.0-0048", \
.ops = &raumfeld_cs4270_ops, \
}
#define DAI_LINK_AK4104 \
{ \
.name = "ak4104", \
.stream_name = "Playback", \
.cpu_dai_name = "pxa-ssp-dai.1", \
.codec_dai_name = "ak4104-hifi", \
.platform_name = "pxa-pcm-audio", \
.ops = &raumfeld_ak4104_ops, \
.codec_name = "spi0.0", \
}
static struct snd_soc_dai_link snd_soc_raumfeld_connector_dai[] =
{
DAI_LINK_CS4270,
DAI_LINK_AK4104,
};
static struct snd_soc_dai_link snd_soc_raumfeld_speaker_dai[] =
{
DAI_LINK_CS4270,
};
static struct snd_soc_card snd_soc_raumfeld_connector = {
.name = "Raumfeld Connector",
.owner = THIS_MODULE,
.dai_link = snd_soc_raumfeld_connector_dai,
.num_links = ARRAY_SIZE(snd_soc_raumfeld_connector_dai),
.suspend_post = raumfeld_analog_suspend,
.resume_pre = raumfeld_analog_resume,
};
static struct snd_soc_card snd_soc_raumfeld_speaker = {
.name = "Raumfeld Speaker",
.owner = THIS_MODULE,
.dai_link = snd_soc_raumfeld_speaker_dai,
.num_links = ARRAY_SIZE(snd_soc_raumfeld_speaker_dai),
.suspend_post = raumfeld_analog_suspend,
.resume_pre = raumfeld_analog_resume,
};
static struct platform_device *raumfeld_audio_device;
static int __init raumfeld_audio_init(void)
{
int ret;
if (!machine_is_raumfeld_speaker() &&
!machine_is_raumfeld_connector())
return 0;
max9486_client = i2c_new_device(i2c_get_adapter(0),
&max9486_hwmon_info);
if (!max9486_client)
return -ENOMEM;
set_max9485_clk(MAX9485_MCLK_FREQ_122880);
/* Register analog device */
raumfeld_audio_device = platform_device_alloc("soc-audio", 0);
if (!raumfeld_audio_device)
return -ENOMEM;
if (machine_is_raumfeld_speaker())
platform_set_drvdata(raumfeld_audio_device,
&snd_soc_raumfeld_speaker);
if (machine_is_raumfeld_connector())
platform_set_drvdata(raumfeld_audio_device,
&snd_soc_raumfeld_connector);
ret = platform_device_add(raumfeld_audio_device);
if (ret < 0) {
platform_device_put(raumfeld_audio_device);
return ret;
}
raumfeld_enable_audio(true);
return 0;
}
static void __exit raumfeld_audio_exit(void)
{
raumfeld_enable_audio(false);
platform_device_unregister(raumfeld_audio_device);
i2c_unregister_device(max9486_client);
gpio_free(GPIO_MCLK_RESET);
gpio_free(GPIO_CODEC_RESET);
gpio_free(GPIO_SPDIF_RESET);
}
module_init(raumfeld_audio_init);
module_exit(raumfeld_audio_exit);
/* Module information */
MODULE_AUTHOR("Daniel Mack <daniel@caiaq.de>");
MODULE_DESCRIPTION("Raumfeld audio SoC");
MODULE_LICENSE("GPL");
| gpl-2.0 |
grogg/platform_device_asus_flo-kernel_kernel | arch/powerpc/boot/epapr.c | 9593 | 1896 | /*
* Bootwrapper for ePAPR compliant firmwares
*
* Copyright 2010 David Gibson <david@gibson.dropbear.id.au>, IBM Corporation.
*
* Based on earlier bootwrappers by:
* (c) Benjamin Herrenschmidt <benh@kernel.crashing.org>, IBM Corp,\
* and
* Scott Wood <scottwood@freescale.com>
* Copyright (c) 2007 Freescale Semiconductor, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include "ops.h"
#include "stdio.h"
#include "io.h"
#include <libfdt.h>
BSS_STACK(4096);
#define EPAPR_SMAGIC 0x65504150
#define EPAPR_EMAGIC 0x45504150
static unsigned epapr_magic;
static unsigned long ima_size;
static unsigned long fdt_addr;
static void platform_fixups(void)
{
if ((epapr_magic != EPAPR_EMAGIC)
&& (epapr_magic != EPAPR_SMAGIC))
fatal("r6 contained 0x%08x instead of ePAPR magic number\n",
epapr_magic);
if (ima_size < (unsigned long)_end)
printf("WARNING: Image loaded outside IMA!"
" (_end=%p, ima_size=0x%lx)\n", _end, ima_size);
if (ima_size < fdt_addr)
printf("WARNING: Device tree address is outside IMA!"
"(fdt_addr=0x%lx, ima_size=0x%lx)\n", fdt_addr,
ima_size);
if (ima_size < fdt_addr + fdt_totalsize((void *)fdt_addr))
printf("WARNING: Device tree extends outside IMA!"
" (fdt_addr=0x%lx, size=0x%x, ima_size=0x%lx\n",
fdt_addr, fdt_totalsize((void *)fdt_addr), ima_size);
}
void platform_init(unsigned long r3, unsigned long r4, unsigned long r5,
unsigned long r6, unsigned long r7)
{
epapr_magic = r6;
ima_size = r7;
fdt_addr = r3;
/* FIXME: we should process reserve entries */
simple_alloc_init(_end, ima_size - (unsigned long)_end, 32, 64);
fdt_init((void *)fdt_addr);
serial_console_init();
platform_ops.fixups = platform_fixups;
}
| gpl-2.0 |
TheGreatSega/KernelSEGA | drivers/gpu/drm/drm_edid.c | 122 | 42911 | /*
* Copyright (c) 2006 Luc Verhaegen (quirks list)
* Copyright (c) 2007-2008 Intel Corporation
* Jesse Barnes <jesse.barnes@intel.com>
*
* DDC probing routines (drm_ddc_read & drm_do_probe_ddc_edid) originally from
* FB layer.
* Copyright (C) 2006 Dennis Munsie <dmunsie@cecropia.com>
*
* 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, sub license,
* 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 NON-INFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <linux/kernel.h>
#include <linux/i2c.h>
#include <linux/i2c-algo-bit.h>
#include "drmP.h"
#include "drm_edid.h"
/*
* TODO:
* - support EDID 1.4 (incl. CE blocks)
*/
/*
* EDID blocks out in the wild have a variety of bugs, try to collect
* them here (note that userspace may work around broken monitors first,
* but fixes should make their way here so that the kernel "just works"
* on as many displays as possible).
*/
/* First detailed mode wrong, use largest 60Hz mode */
#define EDID_QUIRK_PREFER_LARGE_60 (1 << 0)
/* Reported 135MHz pixel clock is too high, needs adjustment */
#define EDID_QUIRK_135_CLOCK_TOO_HIGH (1 << 1)
/* Prefer the largest mode at 75 Hz */
#define EDID_QUIRK_PREFER_LARGE_75 (1 << 2)
/* Detail timing is in cm not mm */
#define EDID_QUIRK_DETAILED_IN_CM (1 << 3)
/* Detailed timing descriptors have bogus size values, so just take the
* maximum size and use that.
*/
#define EDID_QUIRK_DETAILED_USE_MAXIMUM_SIZE (1 << 4)
/* Monitor forgot to set the first detailed is preferred bit. */
#define EDID_QUIRK_FIRST_DETAILED_PREFERRED (1 << 5)
/* use +hsync +vsync for detailed mode */
#define EDID_QUIRK_DETAILED_SYNC_PP (1 << 6)
/* define the number of Extension EDID block */
#define MAX_EDID_EXT_NUM 4
#define LEVEL_DMT 0
#define LEVEL_GTF 1
#define LEVEL_CVT 2
static struct edid_quirk {
char *vendor;
int product_id;
u32 quirks;
} edid_quirk_list[] = {
/* Acer AL1706 */
{ "ACR", 44358, EDID_QUIRK_PREFER_LARGE_60 },
/* Acer F51 */
{ "API", 0x7602, EDID_QUIRK_PREFER_LARGE_60 },
/* Unknown Acer */
{ "ACR", 2423, EDID_QUIRK_FIRST_DETAILED_PREFERRED },
/* Belinea 10 15 55 */
{ "MAX", 1516, EDID_QUIRK_PREFER_LARGE_60 },
{ "MAX", 0x77e, EDID_QUIRK_PREFER_LARGE_60 },
/* Envision Peripherals, Inc. EN-7100e */
{ "EPI", 59264, EDID_QUIRK_135_CLOCK_TOO_HIGH },
/* Funai Electronics PM36B */
{ "FCM", 13600, EDID_QUIRK_PREFER_LARGE_75 |
EDID_QUIRK_DETAILED_IN_CM },
/* LG Philips LCD LP154W01-A5 */
{ "LPL", 0, EDID_QUIRK_DETAILED_USE_MAXIMUM_SIZE },
{ "LPL", 0x2a00, EDID_QUIRK_DETAILED_USE_MAXIMUM_SIZE },
/* Philips 107p5 CRT */
{ "PHL", 57364, EDID_QUIRK_FIRST_DETAILED_PREFERRED },
/* Proview AY765C */
{ "PTS", 765, EDID_QUIRK_FIRST_DETAILED_PREFERRED },
/* Samsung SyncMaster 205BW. Note: irony */
{ "SAM", 541, EDID_QUIRK_DETAILED_SYNC_PP },
/* Samsung SyncMaster 22[5-6]BW */
{ "SAM", 596, EDID_QUIRK_PREFER_LARGE_60 },
{ "SAM", 638, EDID_QUIRK_PREFER_LARGE_60 },
};
/* Valid EDID header has these bytes */
static const u8 edid_header[] = {
0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00
};
/**
* edid_is_valid - sanity check EDID data
* @edid: EDID data
*
* Sanity check the EDID block by looking at the header, the version number
* and the checksum. Return 0 if the EDID doesn't check out, or 1 if it's
* valid.
*/
static bool edid_is_valid(struct edid *edid)
{
int i;
u8 csum = 0;
u8 *raw_edid = (u8 *)edid;
if (memcmp(edid->header, edid_header, sizeof(edid_header)))
goto bad;
if (edid->version != 1) {
DRM_ERROR("EDID has major version %d, instead of 1\n", edid->version);
goto bad;
}
if (edid->revision > 4)
DRM_DEBUG("EDID minor > 4, assuming backward compatibility\n");
for (i = 0; i < EDID_LENGTH; i++)
csum += raw_edid[i];
if (csum) {
DRM_ERROR("EDID checksum is invalid, remainder is %d\n", csum);
goto bad;
}
return 1;
bad:
if (raw_edid) {
DRM_ERROR("Raw EDID:\n");
print_hex_dump_bytes(KERN_ERR, DUMP_PREFIX_NONE, raw_edid, EDID_LENGTH);
printk("\n");
}
return 0;
}
/**
* edid_vendor - match a string against EDID's obfuscated vendor field
* @edid: EDID to match
* @vendor: vendor string
*
* Returns true if @vendor is in @edid, false otherwise
*/
static bool edid_vendor(struct edid *edid, char *vendor)
{
char edid_vendor[3];
edid_vendor[0] = ((edid->mfg_id[0] & 0x7c) >> 2) + '@';
edid_vendor[1] = (((edid->mfg_id[0] & 0x3) << 3) |
((edid->mfg_id[1] & 0xe0) >> 5)) + '@';
edid_vendor[2] = (edid->mfg_id[1] & 0x1f) + '@';
return !strncmp(edid_vendor, vendor, 3);
}
/**
* edid_get_quirks - return quirk flags for a given EDID
* @edid: EDID to process
*
* This tells subsequent routines what fixes they need to apply.
*/
static u32 edid_get_quirks(struct edid *edid)
{
struct edid_quirk *quirk;
int i;
for (i = 0; i < ARRAY_SIZE(edid_quirk_list); i++) {
quirk = &edid_quirk_list[i];
if (edid_vendor(edid, quirk->vendor) &&
(EDID_PRODUCT_ID(edid) == quirk->product_id))
return quirk->quirks;
}
return 0;
}
#define MODE_SIZE(m) ((m)->hdisplay * (m)->vdisplay)
#define MODE_REFRESH_DIFF(m,r) (abs((m)->vrefresh - target_refresh))
/**
* edid_fixup_preferred - set preferred modes based on quirk list
* @connector: has mode list to fix up
* @quirks: quirks list
*
* Walk the mode list for @connector, clearing the preferred status
* on existing modes and setting it anew for the right mode ala @quirks.
*/
static void edid_fixup_preferred(struct drm_connector *connector,
u32 quirks)
{
struct drm_display_mode *t, *cur_mode, *preferred_mode;
int target_refresh = 0;
if (list_empty(&connector->probed_modes))
return;
if (quirks & EDID_QUIRK_PREFER_LARGE_60)
target_refresh = 60;
if (quirks & EDID_QUIRK_PREFER_LARGE_75)
target_refresh = 75;
preferred_mode = list_first_entry(&connector->probed_modes,
struct drm_display_mode, head);
list_for_each_entry_safe(cur_mode, t, &connector->probed_modes, head) {
cur_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
if (cur_mode == preferred_mode)
continue;
/* Largest mode is preferred */
if (MODE_SIZE(cur_mode) > MODE_SIZE(preferred_mode))
preferred_mode = cur_mode;
/* At a given size, try to get closest to target refresh */
if ((MODE_SIZE(cur_mode) == MODE_SIZE(preferred_mode)) &&
MODE_REFRESH_DIFF(cur_mode, target_refresh) <
MODE_REFRESH_DIFF(preferred_mode, target_refresh)) {
preferred_mode = cur_mode;
}
}
preferred_mode->type |= DRM_MODE_TYPE_PREFERRED;
}
/*
* Add the Autogenerated from the DMT spec.
* This table is copied from xfree86/modes/xf86EdidModes.c.
* But the mode with Reduced blank feature is deleted.
*/
static struct drm_display_mode drm_dmt_modes[] = {
/* 640x350@85Hz */
{ DRM_MODE("640x350", DRM_MODE_TYPE_DRIVER, 31500, 640, 672,
736, 832, 0, 350, 382, 385, 445, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NVSYNC) },
/* 640x400@85Hz */
{ DRM_MODE("640x400", DRM_MODE_TYPE_DRIVER, 31500, 640, 672,
736, 832, 0, 400, 401, 404, 445, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 720x400@85Hz */
{ DRM_MODE("720x400", DRM_MODE_TYPE_DRIVER, 35500, 720, 756,
828, 936, 0, 400, 401, 404, 446, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 640x480@60Hz */
{ DRM_MODE("640x480", DRM_MODE_TYPE_DRIVER, 25175, 640, 656,
752, 800, 0, 480, 489, 492, 525, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC) },
/* 640x480@72Hz */
{ DRM_MODE("640x480", DRM_MODE_TYPE_DRIVER, 31500, 640, 664,
704, 832, 0, 480, 489, 492, 520, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC) },
/* 640x480@75Hz */
{ DRM_MODE("640x480", DRM_MODE_TYPE_DRIVER, 31500, 640, 656,
720, 840, 0, 480, 481, 484, 500, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC) },
/* 640x480@85Hz */
{ DRM_MODE("640x480", DRM_MODE_TYPE_DRIVER, 36000, 640, 696,
752, 832, 0, 480, 481, 484, 509, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC) },
/* 800x600@56Hz */
{ DRM_MODE("800x600", DRM_MODE_TYPE_DRIVER, 36000, 800, 824,
896, 1024, 0, 600, 601, 603, 625, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 800x600@60Hz */
{ DRM_MODE("800x600", DRM_MODE_TYPE_DRIVER, 40000, 800, 840,
968, 1056, 0, 600, 601, 605, 628, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 800x600@72Hz */
{ DRM_MODE("800x600", DRM_MODE_TYPE_DRIVER, 50000, 800, 856,
976, 1040, 0, 600, 637, 643, 666, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 800x600@75Hz */
{ DRM_MODE("800x600", DRM_MODE_TYPE_DRIVER, 49500, 800, 816,
896, 1056, 0, 600, 601, 604, 625, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 800x600@85Hz */
{ DRM_MODE("800x600", DRM_MODE_TYPE_DRIVER, 56250, 800, 832,
896, 1048, 0, 600, 601, 604, 631, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 848x480@60Hz */
{ DRM_MODE("848x480", DRM_MODE_TYPE_DRIVER, 33750, 848, 864,
976, 1088, 0, 480, 486, 494, 517, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1024x768@43Hz, interlace */
{ DRM_MODE("1024x768", DRM_MODE_TYPE_DRIVER, 44900, 1024, 1032,
1208, 1264, 0, 768, 768, 772, 817, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC |
DRM_MODE_FLAG_INTERLACE) },
/* 1024x768@60Hz */
{ DRM_MODE("1024x768", DRM_MODE_TYPE_DRIVER, 65000, 1024, 1048,
1184, 1344, 0, 768, 771, 777, 806, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC) },
/* 1024x768@70Hz */
{ DRM_MODE("1024x768", DRM_MODE_TYPE_DRIVER, 75000, 1024, 1048,
1184, 1328, 0, 768, 771, 777, 806, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC) },
/* 1024x768@75Hz */
{ DRM_MODE("1024x768", DRM_MODE_TYPE_DRIVER, 78750, 1024, 1040,
1136, 1312, 0, 768, 769, 772, 800, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1024x768@85Hz */
{ DRM_MODE("1024x768", DRM_MODE_TYPE_DRIVER, 94500, 1024, 1072,
1072, 1376, 0, 768, 769, 772, 808, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1152x864@75Hz */
{ DRM_MODE("1152x864", DRM_MODE_TYPE_DRIVER, 108000, 1152, 1216,
1344, 1600, 0, 864, 865, 868, 900, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1280x768@60Hz */
{ DRM_MODE("1280x768", DRM_MODE_TYPE_DRIVER, 79500, 1280, 1344,
1472, 1664, 0, 768, 771, 778, 798, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1280x768@75Hz */
{ DRM_MODE("1280x768", DRM_MODE_TYPE_DRIVER, 102250, 1280, 1360,
1488, 1696, 0, 768, 771, 778, 805, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NVSYNC) },
/* 1280x768@85Hz */
{ DRM_MODE("1280x768", DRM_MODE_TYPE_DRIVER, 117500, 1280, 1360,
1496, 1712, 0, 768, 771, 778, 809, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1280x800@60Hz */
{ DRM_MODE("1280x800", DRM_MODE_TYPE_DRIVER, 83500, 1280, 1352,
1480, 1680, 0, 800, 803, 809, 831, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NVSYNC) },
/* 1280x800@75Hz */
{ DRM_MODE("1280x800", DRM_MODE_TYPE_DRIVER, 106500, 1280, 1360,
1488, 1696, 0, 800, 803, 809, 838, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1280x800@85Hz */
{ DRM_MODE("1280x800", DRM_MODE_TYPE_DRIVER, 122500, 1280, 1360,
1496, 1712, 0, 800, 803, 809, 843, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1280x960@60Hz */
{ DRM_MODE("1280x960", DRM_MODE_TYPE_DRIVER, 108000, 1280, 1376,
1488, 1800, 0, 960, 961, 964, 1000, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1280x960@85Hz */
{ DRM_MODE("1280x960", DRM_MODE_TYPE_DRIVER, 148500, 1280, 1344,
1504, 1728, 0, 960, 961, 964, 1011, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1280x1024@60Hz */
{ DRM_MODE("1280x1024", DRM_MODE_TYPE_DRIVER, 108000, 1280, 1328,
1440, 1688, 0, 1024, 1025, 1028, 1066, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1280x1024@75Hz */
{ DRM_MODE("1280x1024", DRM_MODE_TYPE_DRIVER, 135000, 1280, 1296,
1440, 1688, 0, 1024, 1025, 1028, 1066, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1280x1024@85Hz */
{ DRM_MODE("1280x1024", DRM_MODE_TYPE_DRIVER, 157500, 1280, 1344,
1504, 1728, 0, 1024, 1025, 1028, 1072, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1360x768@60Hz */
{ DRM_MODE("1360x768", DRM_MODE_TYPE_DRIVER, 85500, 1360, 1424,
1536, 1792, 0, 768, 771, 777, 795, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1440x1050@60Hz */
{ DRM_MODE("1400x1050", DRM_MODE_TYPE_DRIVER, 121750, 1400, 1488,
1632, 1864, 0, 1050, 1053, 1057, 1089, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1440x1050@75Hz */
{ DRM_MODE("1400x1050", DRM_MODE_TYPE_DRIVER, 156000, 1400, 1504,
1648, 1896, 0, 1050, 1053, 1057, 1099, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1440x1050@85Hz */
{ DRM_MODE("1400x1050", DRM_MODE_TYPE_DRIVER, 179500, 1400, 1504,
1656, 1912, 0, 1050, 1053, 1057, 1105, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1440x900@60Hz */
{ DRM_MODE("1440x900", DRM_MODE_TYPE_DRIVER, 106500, 1440, 1520,
1672, 1904, 0, 900, 903, 909, 934, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1440x900@75Hz */
{ DRM_MODE("1440x900", DRM_MODE_TYPE_DRIVER, 136750, 1440, 1536,
1688, 1936, 0, 900, 903, 909, 942, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1440x900@85Hz */
{ DRM_MODE("1440x900", DRM_MODE_TYPE_DRIVER, 157000, 1440, 1544,
1696, 1952, 0, 900, 903, 909, 948, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1600x1200@60Hz */
{ DRM_MODE("1600x1200", DRM_MODE_TYPE_DRIVER, 162000, 1600, 1664,
1856, 2160, 0, 1200, 1201, 1204, 1250, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1600x1200@65Hz */
{ DRM_MODE("1600x1200", DRM_MODE_TYPE_DRIVER, 175500, 1600, 1664,
1856, 2160, 0, 1200, 1201, 1204, 1250, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1600x1200@70Hz */
{ DRM_MODE("1600x1200", DRM_MODE_TYPE_DRIVER, 189000, 1600, 1664,
1856, 2160, 0, 1200, 1201, 1204, 1250, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1600x1200@75Hz */
{ DRM_MODE("1600x1200", DRM_MODE_TYPE_DRIVER, 2025000, 1600, 1664,
1856, 2160, 0, 1200, 1201, 1204, 1250, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1600x1200@85Hz */
{ DRM_MODE("1600x1200", DRM_MODE_TYPE_DRIVER, 229500, 1600, 1664,
1856, 2160, 0, 1200, 1201, 1204, 1250, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1680x1050@60Hz */
{ DRM_MODE("1680x1050", DRM_MODE_TYPE_DRIVER, 146250, 1680, 1784,
1960, 2240, 0, 1050, 1053, 1059, 1089, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1680x1050@75Hz */
{ DRM_MODE("1680x1050", DRM_MODE_TYPE_DRIVER, 187000, 1680, 1800,
1976, 2272, 0, 1050, 1053, 1059, 1099, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1680x1050@85Hz */
{ DRM_MODE("1680x1050", DRM_MODE_TYPE_DRIVER, 214750, 1680, 1808,
1984, 2288, 0, 1050, 1053, 1059, 1105, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1792x1344@60Hz */
{ DRM_MODE("1792x1344", DRM_MODE_TYPE_DRIVER, 204750, 1792, 1920,
2120, 2448, 0, 1344, 1345, 1348, 1394, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1729x1344@75Hz */
{ DRM_MODE("1792x1344", DRM_MODE_TYPE_DRIVER, 261000, 1792, 1888,
2104, 2456, 0, 1344, 1345, 1348, 1417, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1853x1392@60Hz */
{ DRM_MODE("1856x1392", DRM_MODE_TYPE_DRIVER, 218250, 1856, 1952,
2176, 2528, 0, 1392, 1393, 1396, 1439, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1856x1392@75Hz */
{ DRM_MODE("1856x1392", DRM_MODE_TYPE_DRIVER, 288000, 1856, 1984,
2208, 2560, 0, 1392, 1395, 1399, 1500, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1920x1200@60Hz */
{ DRM_MODE("1920x1200", DRM_MODE_TYPE_DRIVER, 193250, 1920, 2056,
2256, 2592, 0, 1200, 1203, 1209, 1245, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1920x1200@75Hz */
{ DRM_MODE("1920x1200", DRM_MODE_TYPE_DRIVER, 245250, 1920, 2056,
2264, 2608, 0, 1200, 1203, 1209, 1255, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1920x1200@85Hz */
{ DRM_MODE("1920x1200", DRM_MODE_TYPE_DRIVER, 281250, 1920, 2064,
2272, 2624, 0, 1200, 1203, 1209, 1262, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1920x1440@60Hz */
{ DRM_MODE("1920x1440", DRM_MODE_TYPE_DRIVER, 234000, 1920, 2048,
2256, 2600, 0, 1440, 1441, 1444, 1500, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 1920x1440@75Hz */
{ DRM_MODE("1920x1440", DRM_MODE_TYPE_DRIVER, 297000, 1920, 2064,
2288, 2640, 0, 1440, 1441, 1444, 1500, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 2560x1600@60Hz */
{ DRM_MODE("2560x1600", DRM_MODE_TYPE_DRIVER, 348500, 2560, 2752,
3032, 3504, 0, 1600, 1603, 1609, 1658, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 2560x1600@75HZ */
{ DRM_MODE("2560x1600", DRM_MODE_TYPE_DRIVER, 443250, 2560, 2768,
3048, 3536, 0, 1600, 1603, 1609, 1672, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
/* 2560x1600@85HZ */
{ DRM_MODE("2560x1600", DRM_MODE_TYPE_DRIVER, 505250, 2560, 2768,
3048, 3536, 0, 1600, 1603, 1609, 1682, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
};
static struct drm_display_mode *drm_find_dmt(struct drm_device *dev,
int hsize, int vsize, int fresh)
{
int i, count;
struct drm_display_mode *ptr, *mode;
count = sizeof(drm_dmt_modes) / sizeof(struct drm_display_mode);
mode = NULL;
for (i = 0; i < count; i++) {
ptr = &drm_dmt_modes[i];
if (hsize == ptr->hdisplay &&
vsize == ptr->vdisplay &&
fresh == drm_mode_vrefresh(ptr)) {
/* get the expected default mode */
mode = drm_mode_duplicate(dev, ptr);
break;
}
}
return mode;
}
/*
* 0 is reserved. The spec says 0x01 fill for unused timings. Some old
* monitors fill with ascii space (0x20) instead.
*/
static int
bad_std_timing(u8 a, u8 b)
{
return (a == 0x00 && b == 0x00) ||
(a == 0x01 && b == 0x01) ||
(a == 0x20 && b == 0x20);
}
/**
* drm_mode_std - convert standard mode info (width, height, refresh) into mode
* @t: standard timing params
* @timing_level: standard timing level
*
* Take the standard timing params (in this case width, aspect, and refresh)
* and convert them into a real mode using CVT/GTF/DMT.
*
* Punts for now, but should eventually use the FB layer's CVT based mode
* generation code.
*/
struct drm_display_mode *drm_mode_std(struct drm_device *dev,
struct std_timing *t,
int revision,
int timing_level)
{
struct drm_display_mode *mode;
int hsize, vsize;
int vrefresh_rate;
unsigned aspect_ratio = (t->vfreq_aspect & EDID_TIMING_ASPECT_MASK)
>> EDID_TIMING_ASPECT_SHIFT;
unsigned vfreq = (t->vfreq_aspect & EDID_TIMING_VFREQ_MASK)
>> EDID_TIMING_VFREQ_SHIFT;
if (bad_std_timing(t->hsize, t->vfreq_aspect))
return NULL;
/* According to the EDID spec, the hdisplay = hsize * 8 + 248 */
hsize = t->hsize * 8 + 248;
/* vrefresh_rate = vfreq + 60 */
vrefresh_rate = vfreq + 60;
/* the vdisplay is calculated based on the aspect ratio */
if (aspect_ratio == 0) {
if (revision < 3)
vsize = hsize;
else
vsize = (hsize * 10) / 16;
} else if (aspect_ratio == 1)
vsize = (hsize * 3) / 4;
else if (aspect_ratio == 2)
vsize = (hsize * 4) / 5;
else
vsize = (hsize * 9) / 16;
/* HDTV hack */
if (hsize == 1360 && vsize == 765 && vrefresh_rate == 60) {
mode = drm_cvt_mode(dev, hsize, vsize, vrefresh_rate, 0, 0,
false);
mode->hdisplay = 1366;
mode->vsync_start = mode->vsync_start - 1;
mode->vsync_end = mode->vsync_end - 1;
return mode;
}
mode = NULL;
/* check whether it can be found in default mode table */
mode = drm_find_dmt(dev, hsize, vsize, vrefresh_rate);
if (mode)
return mode;
switch (timing_level) {
case LEVEL_DMT:
break;
case LEVEL_GTF:
mode = drm_gtf_mode(dev, hsize, vsize, vrefresh_rate, 0, 0);
break;
case LEVEL_CVT:
mode = drm_cvt_mode(dev, hsize, vsize, vrefresh_rate, 0, 0,
false);
break;
}
return mode;
}
/**
* drm_mode_detailed - create a new mode from an EDID detailed timing section
* @dev: DRM device (needed to create new mode)
* @edid: EDID block
* @timing: EDID detailed timing info
* @quirks: quirks to apply
*
* An EDID detailed timing block contains enough info for us to create and
* return a new struct drm_display_mode.
*/
static struct drm_display_mode *drm_mode_detailed(struct drm_device *dev,
struct edid *edid,
struct detailed_timing *timing,
u32 quirks)
{
struct drm_display_mode *mode;
struct detailed_pixel_timing *pt = &timing->data.pixel_data;
unsigned hactive = (pt->hactive_hblank_hi & 0xf0) << 4 | pt->hactive_lo;
unsigned vactive = (pt->vactive_vblank_hi & 0xf0) << 4 | pt->vactive_lo;
unsigned hblank = (pt->hactive_hblank_hi & 0xf) << 8 | pt->hblank_lo;
unsigned vblank = (pt->vactive_vblank_hi & 0xf) << 8 | pt->vblank_lo;
unsigned hsync_offset = (pt->hsync_vsync_offset_pulse_width_hi & 0xc0) << 2 | pt->hsync_offset_lo;
unsigned hsync_pulse_width = (pt->hsync_vsync_offset_pulse_width_hi & 0x30) << 4 | pt->hsync_pulse_width_lo;
unsigned vsync_offset = (pt->hsync_vsync_offset_pulse_width_hi & 0xc) >> 2 | pt->vsync_offset_pulse_width_lo >> 4;
unsigned vsync_pulse_width = (pt->hsync_vsync_offset_pulse_width_hi & 0x3) << 4 | (pt->vsync_offset_pulse_width_lo & 0xf);
/* ignore tiny modes */
if (hactive < 64 || vactive < 64)
return NULL;
if (pt->misc & DRM_EDID_PT_STEREO) {
printk(KERN_WARNING "stereo mode not supported\n");
return NULL;
}
if (!(pt->misc & DRM_EDID_PT_SEPARATE_SYNC)) {
printk(KERN_WARNING "integrated sync not supported\n");
return NULL;
}
/* it is incorrect if hsync/vsync width is zero */
if (!hsync_pulse_width || !vsync_pulse_width) {
DRM_DEBUG_KMS("Incorrect Detailed timing. "
"Wrong Hsync/Vsync pulse width\n");
return NULL;
}
mode = drm_mode_create(dev);
if (!mode)
return NULL;
mode->type = DRM_MODE_TYPE_DRIVER;
if (quirks & EDID_QUIRK_135_CLOCK_TOO_HIGH)
timing->pixel_clock = cpu_to_le16(1088);
mode->clock = le16_to_cpu(timing->pixel_clock) * 10;
mode->hdisplay = hactive;
mode->hsync_start = mode->hdisplay + hsync_offset;
mode->hsync_end = mode->hsync_start + hsync_pulse_width;
mode->htotal = mode->hdisplay + hblank;
mode->vdisplay = vactive;
mode->vsync_start = mode->vdisplay + vsync_offset;
mode->vsync_end = mode->vsync_start + vsync_pulse_width;
mode->vtotal = mode->vdisplay + vblank;
/* perform the basic check for the detailed timing */
if (mode->hsync_end > mode->htotal ||
mode->vsync_end > mode->vtotal) {
drm_mode_destroy(dev, mode);
DRM_DEBUG_KMS("Incorrect detailed timing. "
"Sync is beyond the blank.\n");
return NULL;
}
/* Some EDIDs have bogus h/vtotal values */
if (mode->hsync_end > mode->htotal)
mode->htotal = mode->hsync_end + 1;
if (mode->vsync_end > mode->vtotal)
mode->vtotal = mode->vsync_end + 1;
drm_mode_set_name(mode);
if (pt->misc & DRM_EDID_PT_INTERLACED)
mode->flags |= DRM_MODE_FLAG_INTERLACE;
if (quirks & EDID_QUIRK_DETAILED_SYNC_PP) {
pt->misc |= DRM_EDID_PT_HSYNC_POSITIVE | DRM_EDID_PT_VSYNC_POSITIVE;
}
mode->flags |= (pt->misc & DRM_EDID_PT_HSYNC_POSITIVE) ?
DRM_MODE_FLAG_PHSYNC : DRM_MODE_FLAG_NHSYNC;
mode->flags |= (pt->misc & DRM_EDID_PT_VSYNC_POSITIVE) ?
DRM_MODE_FLAG_PVSYNC : DRM_MODE_FLAG_NVSYNC;
mode->width_mm = pt->width_mm_lo | (pt->width_height_mm_hi & 0xf0) << 4;
mode->height_mm = pt->height_mm_lo | (pt->width_height_mm_hi & 0xf) << 8;
if (quirks & EDID_QUIRK_DETAILED_IN_CM) {
mode->width_mm *= 10;
mode->height_mm *= 10;
}
if (quirks & EDID_QUIRK_DETAILED_USE_MAXIMUM_SIZE) {
mode->width_mm = edid->width_cm * 10;
mode->height_mm = edid->height_cm * 10;
}
return mode;
}
/*
* Detailed mode info for the EDID "established modes" data to use.
*/
static struct drm_display_mode edid_est_modes[] = {
{ DRM_MODE("800x600", DRM_MODE_TYPE_DRIVER, 40000, 800, 840,
968, 1056, 0, 600, 601, 605, 628, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) }, /* 800x600@60Hz */
{ DRM_MODE("800x600", DRM_MODE_TYPE_DRIVER, 36000, 800, 824,
896, 1024, 0, 600, 601, 603, 625, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) }, /* 800x600@56Hz */
{ DRM_MODE("640x480", DRM_MODE_TYPE_DRIVER, 31500, 640, 656,
720, 840, 0, 480, 481, 484, 500, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC) }, /* 640x480@75Hz */
{ DRM_MODE("640x480", DRM_MODE_TYPE_DRIVER, 31500, 640, 664,
704, 832, 0, 480, 489, 491, 520, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC) }, /* 640x480@72Hz */
{ DRM_MODE("640x480", DRM_MODE_TYPE_DRIVER, 30240, 640, 704,
768, 864, 0, 480, 483, 486, 525, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC) }, /* 640x480@67Hz */
{ DRM_MODE("640x480", DRM_MODE_TYPE_DRIVER, 25200, 640, 656,
752, 800, 0, 480, 490, 492, 525, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC) }, /* 640x480@60Hz */
{ DRM_MODE("720x400", DRM_MODE_TYPE_DRIVER, 35500, 720, 738,
846, 900, 0, 400, 421, 423, 449, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC) }, /* 720x400@88Hz */
{ DRM_MODE("720x400", DRM_MODE_TYPE_DRIVER, 28320, 720, 738,
846, 900, 0, 400, 412, 414, 449, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) }, /* 720x400@70Hz */
{ DRM_MODE("1280x1024", DRM_MODE_TYPE_DRIVER, 135000, 1280, 1296,
1440, 1688, 0, 1024, 1025, 1028, 1066, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) }, /* 1280x1024@75Hz */
{ DRM_MODE("1024x768", DRM_MODE_TYPE_DRIVER, 78800, 1024, 1040,
1136, 1312, 0, 768, 769, 772, 800, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) }, /* 1024x768@75Hz */
{ DRM_MODE("1024x768", DRM_MODE_TYPE_DRIVER, 75000, 1024, 1048,
1184, 1328, 0, 768, 771, 777, 806, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC) }, /* 1024x768@70Hz */
{ DRM_MODE("1024x768", DRM_MODE_TYPE_DRIVER, 65000, 1024, 1048,
1184, 1344, 0, 768, 771, 777, 806, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC) }, /* 1024x768@60Hz */
{ DRM_MODE("1024x768", DRM_MODE_TYPE_DRIVER,44900, 1024, 1032,
1208, 1264, 0, 768, 768, 776, 817, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_INTERLACE) }, /* 1024x768@43Hz */
{ DRM_MODE("832x624", DRM_MODE_TYPE_DRIVER, 57284, 832, 864,
928, 1152, 0, 624, 625, 628, 667, 0,
DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC) }, /* 832x624@75Hz */
{ DRM_MODE("800x600", DRM_MODE_TYPE_DRIVER, 49500, 800, 816,
896, 1056, 0, 600, 601, 604, 625, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) }, /* 800x600@75Hz */
{ DRM_MODE("800x600", DRM_MODE_TYPE_DRIVER, 50000, 800, 856,
976, 1040, 0, 600, 637, 643, 666, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) }, /* 800x600@72Hz */
{ DRM_MODE("1152x864", DRM_MODE_TYPE_DRIVER, 108000, 1152, 1216,
1344, 1600, 0, 864, 865, 868, 900, 0,
DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) }, /* 1152x864@75Hz */
};
#define EDID_EST_TIMINGS 16
#define EDID_STD_TIMINGS 8
#define EDID_DETAILED_TIMINGS 4
/**
* add_established_modes - get est. modes from EDID and add them
* @edid: EDID block to scan
*
* Each EDID block contains a bitmap of the supported "established modes" list
* (defined above). Tease them out and add them to the global modes list.
*/
static int add_established_modes(struct drm_connector *connector, struct edid *edid)
{
struct drm_device *dev = connector->dev;
unsigned long est_bits = edid->established_timings.t1 |
(edid->established_timings.t2 << 8) |
((edid->established_timings.mfg_rsvd & 0x80) << 9);
int i, modes = 0;
for (i = 0; i <= EDID_EST_TIMINGS; i++)
if (est_bits & (1<<i)) {
struct drm_display_mode *newmode;
newmode = drm_mode_duplicate(dev, &edid_est_modes[i]);
if (newmode) {
drm_mode_probed_add(connector, newmode);
modes++;
}
}
return modes;
}
/**
* stanard_timing_level - get std. timing level(CVT/GTF/DMT)
* @edid: EDID block to scan
*/
static int standard_timing_level(struct edid *edid)
{
if (edid->revision >= 2) {
if (edid->revision >= 4 && (edid->features & DRM_EDID_FEATURE_DEFAULT_GTF))
return LEVEL_CVT;
return LEVEL_GTF;
}
return LEVEL_DMT;
}
/**
* add_standard_modes - get std. modes from EDID and add them
* @edid: EDID block to scan
*
* Standard modes can be calculated using the CVT standard. Grab them from
* @edid, calculate them, and add them to the list.
*/
static int add_standard_modes(struct drm_connector *connector, struct edid *edid)
{
struct drm_device *dev = connector->dev;
int i, modes = 0;
int timing_level;
timing_level = standard_timing_level(edid);
for (i = 0; i < EDID_STD_TIMINGS; i++) {
struct std_timing *t = &edid->standard_timings[i];
struct drm_display_mode *newmode;
/* If std timings bytes are 1, 1 it's empty */
if (t->hsize == 1 && t->vfreq_aspect == 1)
continue;
newmode = drm_mode_std(dev, &edid->standard_timings[i],
edid->revision, timing_level);
if (newmode) {
drm_mode_probed_add(connector, newmode);
modes++;
}
}
return modes;
}
/**
* add_detailed_modes - get detailed mode info from EDID data
* @connector: attached connector
* @edid: EDID block to scan
* @quirks: quirks to apply
*
* Some of the detailed timing sections may contain mode information. Grab
* it and add it to the list.
*/
static int add_detailed_info(struct drm_connector *connector,
struct edid *edid, u32 quirks)
{
struct drm_device *dev = connector->dev;
int i, j, modes = 0;
int timing_level;
timing_level = standard_timing_level(edid);
for (i = 0; i < EDID_DETAILED_TIMINGS; i++) {
struct detailed_timing *timing = &edid->detailed_timings[i];
struct detailed_non_pixel *data = &timing->data.other_data;
struct drm_display_mode *newmode;
/* X server check is version 1.1 or higher */
if (edid->version == 1 && edid->revision >= 1 &&
!timing->pixel_clock) {
/* Other timing or info */
switch (data->type) {
case EDID_DETAIL_MONITOR_SERIAL:
break;
case EDID_DETAIL_MONITOR_STRING:
break;
case EDID_DETAIL_MONITOR_RANGE:
/* Get monitor range data */
break;
case EDID_DETAIL_MONITOR_NAME:
break;
case EDID_DETAIL_MONITOR_CPDATA:
break;
case EDID_DETAIL_STD_MODES:
for (j = 0; j < 6; i++) {
struct std_timing *std;
struct drm_display_mode *newmode;
std = &data->data.timings[j];
newmode = drm_mode_std(dev, std,
edid->revision,
timing_level);
if (newmode) {
drm_mode_probed_add(connector, newmode);
modes++;
}
}
break;
default:
break;
}
} else {
newmode = drm_mode_detailed(dev, edid, timing, quirks);
if (!newmode)
continue;
/* First detailed mode is preferred */
if (i == 0 && (edid->features & DRM_EDID_FEATURE_PREFERRED_TIMING))
newmode->type |= DRM_MODE_TYPE_PREFERRED;
drm_mode_probed_add(connector, newmode);
modes++;
}
}
return modes;
}
/**
* add_detailed_mode_eedid - get detailed mode info from addtional timing
* EDID block
* @connector: attached connector
* @edid: EDID block to scan(It is only to get addtional timing EDID block)
* @quirks: quirks to apply
*
* Some of the detailed timing sections may contain mode information. Grab
* it and add it to the list.
*/
static int add_detailed_info_eedid(struct drm_connector *connector,
struct edid *edid, u32 quirks)
{
struct drm_device *dev = connector->dev;
int i, j, modes = 0;
char *edid_ext = NULL;
struct detailed_timing *timing;
struct detailed_non_pixel *data;
struct drm_display_mode *newmode;
int edid_ext_num;
int start_offset, end_offset;
int timing_level;
if (edid->version == 1 && edid->revision < 3) {
/* If the EDID version is less than 1.3, there is no
* extension EDID.
*/
return 0;
}
if (!edid->extensions) {
/* if there is no extension EDID, it is unnecessary to
* parse the E-EDID to get detailed info
*/
return 0;
}
/* Chose real EDID extension number */
edid_ext_num = edid->extensions > MAX_EDID_EXT_NUM ?
MAX_EDID_EXT_NUM : edid->extensions;
/* Find CEA extension */
for (i = 0; i < edid_ext_num; i++) {
edid_ext = (char *)edid + EDID_LENGTH * (i + 1);
/* This block is CEA extension */
if (edid_ext[0] == 0x02)
break;
}
if (i == edid_ext_num) {
/* if there is no additional timing EDID block, return */
return 0;
}
/* Get the start offset of detailed timing block */
start_offset = edid_ext[2];
if (start_offset == 0) {
/* If the start_offset is zero, it means that neither detailed
* info nor data block exist. In such case it is also
* unnecessary to parse the detailed timing info.
*/
return 0;
}
timing_level = standard_timing_level(edid);
end_offset = EDID_LENGTH;
end_offset -= sizeof(struct detailed_timing);
for (i = start_offset; i < end_offset;
i += sizeof(struct detailed_timing)) {
timing = (struct detailed_timing *)(edid_ext + i);
data = &timing->data.other_data;
/* Detailed mode timing */
if (timing->pixel_clock) {
newmode = drm_mode_detailed(dev, edid, timing, quirks);
if (!newmode)
continue;
drm_mode_probed_add(connector, newmode);
modes++;
continue;
}
/* Other timing or info */
switch (data->type) {
case EDID_DETAIL_MONITOR_SERIAL:
break;
case EDID_DETAIL_MONITOR_STRING:
break;
case EDID_DETAIL_MONITOR_RANGE:
/* Get monitor range data */
break;
case EDID_DETAIL_MONITOR_NAME:
break;
case EDID_DETAIL_MONITOR_CPDATA:
break;
case EDID_DETAIL_STD_MODES:
/* Five modes per detailed section */
for (j = 0; j < 5; i++) {
struct std_timing *std;
struct drm_display_mode *newmode;
std = &data->data.timings[j];
newmode = drm_mode_std(dev, std,
edid->revision,
timing_level);
if (newmode) {
drm_mode_probed_add(connector, newmode);
modes++;
}
}
break;
default:
break;
}
}
return modes;
}
#define DDC_ADDR 0x50
/**
* Get EDID information via I2C.
*
* \param adapter : i2c device adaptor
* \param buf : EDID data buffer to be filled
* \param len : EDID data buffer length
* \return 0 on success or -1 on failure.
*
* Try to fetch EDID information by calling i2c driver function.
*/
int drm_do_probe_ddc_edid(struct i2c_adapter *adapter,
unsigned char *buf, int len)
{
unsigned char start = 0x0;
struct i2c_msg msgs[] = {
{
.addr = DDC_ADDR,
.flags = 0,
.len = 1,
.buf = &start,
}, {
.addr = DDC_ADDR,
.flags = I2C_M_RD,
.len = len,
.buf = buf,
}
};
if (i2c_transfer(adapter, msgs, 2) == 2)
return 0;
return -1;
}
EXPORT_SYMBOL(drm_do_probe_ddc_edid);
static int drm_ddc_read_edid(struct drm_connector *connector,
struct i2c_adapter *adapter,
char *buf, int len)
{
int ret;
ret = drm_do_probe_ddc_edid(adapter, buf, len);
if (ret != 0) {
goto end;
}
if (!edid_is_valid((struct edid *)buf)) {
dev_warn(&connector->dev->pdev->dev, "%s: EDID invalid.\n",
drm_get_connector_name(connector));
ret = -1;
}
end:
return ret;
}
/**
* drm_get_edid - get EDID data, if available
* @connector: connector we're probing
* @adapter: i2c adapter to use for DDC
*
* Poke the given connector's i2c channel to grab EDID data if possible.
*
* Return edid data or NULL if we couldn't find any.
*/
struct edid *drm_get_edid(struct drm_connector *connector,
struct i2c_adapter *adapter)
{
int ret;
struct edid *edid;
if (drm_core_check_feature(connector->dev, DRIVER_USE_PLATFORM_DEVICE))
return NULL;
edid = kmalloc(EDID_LENGTH * (MAX_EDID_EXT_NUM + 1),
GFP_KERNEL);
if (edid == NULL) {
dev_warn(&connector->dev->pdev->dev,
"Failed to allocate EDID\n");
goto end;
}
/* Read first EDID block */
ret = drm_ddc_read_edid(connector, adapter,
(unsigned char *)edid, EDID_LENGTH);
if (ret != 0)
goto clean_up;
/* There are EDID extensions to be read */
if (edid->extensions != 0) {
int edid_ext_num = edid->extensions;
if (edid_ext_num > MAX_EDID_EXT_NUM) {
dev_warn(&connector->dev->pdev->dev,
"The number of extension(%d) is "
"over max (%d), actually read number (%d)\n",
edid_ext_num, MAX_EDID_EXT_NUM,
MAX_EDID_EXT_NUM);
/* Reset EDID extension number to be read */
edid_ext_num = MAX_EDID_EXT_NUM;
}
/* Read EDID including extensions too */
ret = drm_ddc_read_edid(connector, adapter, (char *)edid,
EDID_LENGTH * (edid_ext_num + 1));
if (ret != 0)
goto clean_up;
}
connector->display_info.raw_edid = (char *)edid;
goto end;
clean_up:
kfree(edid);
edid = NULL;
end:
return edid;
}
EXPORT_SYMBOL(drm_get_edid);
#define HDMI_IDENTIFIER 0x000C03
#define VENDOR_BLOCK 0x03
/**
* drm_detect_hdmi_monitor - detect whether monitor is hdmi.
* @edid: monitor EDID information
*
* Parse the CEA extension according to CEA-861-B.
* Return true if HDMI, false if not or unknown.
*/
bool drm_detect_hdmi_monitor(struct edid *edid)
{
char *edid_ext = NULL;
int i, hdmi_id, edid_ext_num;
int start_offset, end_offset;
bool is_hdmi = false;
/* No EDID or EDID extensions */
if (edid == NULL || edid->extensions == 0)
goto end;
/* Chose real EDID extension number */
edid_ext_num = edid->extensions > MAX_EDID_EXT_NUM ?
MAX_EDID_EXT_NUM : edid->extensions;
/* Find CEA extension */
for (i = 0; i < edid_ext_num; i++) {
edid_ext = (char *)edid + EDID_LENGTH * (i + 1);
/* This block is CEA extension */
if (edid_ext[0] == 0x02)
break;
}
if (i == edid_ext_num)
goto end;
/* Data block offset in CEA extension block */
start_offset = 4;
end_offset = edid_ext[2];
/*
* Because HDMI identifier is in Vendor Specific Block,
* search it from all data blocks of CEA extension.
*/
for (i = start_offset; i < end_offset;
/* Increased by data block len */
i += ((edid_ext[i] & 0x1f) + 1)) {
/* Find vendor specific block */
if ((edid_ext[i] >> 5) == VENDOR_BLOCK) {
hdmi_id = edid_ext[i + 1] | (edid_ext[i + 2] << 8) |
edid_ext[i + 3] << 16;
/* Find HDMI identifier */
if (hdmi_id == HDMI_IDENTIFIER)
is_hdmi = true;
break;
}
}
end:
return is_hdmi;
}
EXPORT_SYMBOL(drm_detect_hdmi_monitor);
/**
* drm_add_edid_modes - add modes from EDID data, if available
* @connector: connector we're probing
* @edid: edid data
*
* Add the specified modes to the connector's mode list.
*
* Return number of modes added or 0 if we couldn't find any.
*/
int drm_add_edid_modes(struct drm_connector *connector, struct edid *edid)
{
int num_modes = 0;
u32 quirks;
if (edid == NULL) {
return 0;
}
if (!edid_is_valid(edid)) {
dev_warn(&connector->dev->pdev->dev, "%s: EDID invalid.\n",
drm_get_connector_name(connector));
return 0;
}
quirks = edid_get_quirks(edid);
num_modes += add_established_modes(connector, edid);
num_modes += add_standard_modes(connector, edid);
num_modes += add_detailed_info(connector, edid, quirks);
num_modes += add_detailed_info_eedid(connector, edid, quirks);
if (quirks & (EDID_QUIRK_PREFER_LARGE_60 | EDID_QUIRK_PREFER_LARGE_75))
edid_fixup_preferred(connector, quirks);
connector->display_info.serration_vsync = (edid->input & DRM_EDID_INPUT_SERRATION_VSYNC) ? 1 : 0;
connector->display_info.sync_on_green = (edid->input & DRM_EDID_INPUT_SYNC_ON_GREEN) ? 1 : 0;
connector->display_info.composite_sync = (edid->input & DRM_EDID_INPUT_COMPOSITE_SYNC) ? 1 : 0;
connector->display_info.separate_syncs = (edid->input & DRM_EDID_INPUT_SEPARATE_SYNCS) ? 1 : 0;
connector->display_info.blank_to_black = (edid->input & DRM_EDID_INPUT_BLANK_TO_BLACK) ? 1 : 0;
connector->display_info.video_level = (edid->input & DRM_EDID_INPUT_VIDEO_LEVEL) >> 5;
connector->display_info.digital = (edid->input & DRM_EDID_INPUT_DIGITAL) ? 1 : 0;
connector->display_info.width_mm = edid->width_cm * 10;
connector->display_info.height_mm = edid->height_cm * 10;
connector->display_info.gamma = edid->gamma;
connector->display_info.gtf_supported = (edid->features & DRM_EDID_FEATURE_DEFAULT_GTF) ? 1 : 0;
connector->display_info.standard_color = (edid->features & DRM_EDID_FEATURE_STANDARD_COLOR) ? 1 : 0;
connector->display_info.display_type = (edid->features & DRM_EDID_FEATURE_DISPLAY_TYPE) >> 3;
connector->display_info.active_off_supported = (edid->features & DRM_EDID_FEATURE_PM_ACTIVE_OFF) ? 1 : 0;
connector->display_info.suspend_supported = (edid->features & DRM_EDID_FEATURE_PM_SUSPEND) ? 1 : 0;
connector->display_info.standby_supported = (edid->features & DRM_EDID_FEATURE_PM_STANDBY) ? 1 : 0;
connector->display_info.gamma = edid->gamma;
return num_modes;
}
EXPORT_SYMBOL(drm_add_edid_modes);
/**
* drm_add_modes_noedid - add modes for the connectors without EDID
* @connector: connector we're probing
* @hdisplay: the horizontal display limit
* @vdisplay: the vertical display limit
*
* Add the specified modes to the connector's mode list. Only when the
* hdisplay/vdisplay is not beyond the given limit, it will be added.
*
* Return number of modes added or 0 if we couldn't find any.
*/
int drm_add_modes_noedid(struct drm_connector *connector,
int hdisplay, int vdisplay)
{
int i, count, num_modes = 0;
struct drm_display_mode *mode, *ptr;
struct drm_device *dev = connector->dev;
count = sizeof(drm_dmt_modes) / sizeof(struct drm_display_mode);
if (hdisplay < 0)
hdisplay = 0;
if (vdisplay < 0)
vdisplay = 0;
for (i = 0; i < count; i++) {
ptr = &drm_dmt_modes[i];
if (hdisplay && vdisplay) {
/*
* Only when two are valid, they will be used to check
* whether the mode should be added to the mode list of
* the connector.
*/
if (ptr->hdisplay > hdisplay ||
ptr->vdisplay > vdisplay)
continue;
}
mode = drm_mode_duplicate(dev, ptr);
if (mode) {
drm_mode_probed_add(connector, mode);
num_modes++;
}
}
return num_modes;
}
EXPORT_SYMBOL(drm_add_modes_noedid);
| gpl-2.0 |
sh95119/linux | fs/9p/vfs_inode_dotl.c | 378 | 25400 | /*
* linux/fs/9p/vfs_inode_dotl.c
*
* This file contains vfs inode ops for the 9P2000.L protocol.
*
* Copyright (C) 2004 by Eric Van Hensbergen <ericvh@gmail.com>
* Copyright (C) 2002 by Ron Minnich <rminnich@lanl.gov>
*
* 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:
* Free Software Foundation
* 51 Franklin Street, Fifth Floor
* Boston, MA 02111-1301 USA
*
*/
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/pagemap.h>
#include <linux/stat.h>
#include <linux/string.h>
#include <linux/inet.h>
#include <linux/namei.h>
#include <linux/idr.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/xattr.h>
#include <linux/posix_acl.h>
#include <net/9p/9p.h>
#include <net/9p/client.h>
#include "v9fs.h"
#include "v9fs_vfs.h"
#include "fid.h"
#include "cache.h"
#include "xattr.h"
#include "acl.h"
static int
v9fs_vfs_mknod_dotl(struct inode *dir, struct dentry *dentry, umode_t omode,
dev_t rdev);
/**
* v9fs_get_fsgid_for_create - Helper function to get the gid for creating a
* new file system object. This checks the S_ISGID to determine the owning
* group of the new file system object.
*/
static kgid_t v9fs_get_fsgid_for_create(struct inode *dir_inode)
{
BUG_ON(dir_inode == NULL);
if (dir_inode->i_mode & S_ISGID) {
/* set_gid bit is set.*/
return dir_inode->i_gid;
}
return current_fsgid();
}
static int v9fs_test_inode_dotl(struct inode *inode, void *data)
{
struct v9fs_inode *v9inode = V9FS_I(inode);
struct p9_stat_dotl *st = (struct p9_stat_dotl *)data;
/* don't match inode of different type */
if ((inode->i_mode & S_IFMT) != (st->st_mode & S_IFMT))
return 0;
if (inode->i_generation != st->st_gen)
return 0;
/* compare qid details */
if (memcmp(&v9inode->qid.version,
&st->qid.version, sizeof(v9inode->qid.version)))
return 0;
if (v9inode->qid.type != st->qid.type)
return 0;
return 1;
}
/* Always get a new inode */
static int v9fs_test_new_inode_dotl(struct inode *inode, void *data)
{
return 0;
}
static int v9fs_set_inode_dotl(struct inode *inode, void *data)
{
struct v9fs_inode *v9inode = V9FS_I(inode);
struct p9_stat_dotl *st = (struct p9_stat_dotl *)data;
memcpy(&v9inode->qid, &st->qid, sizeof(st->qid));
inode->i_generation = st->st_gen;
return 0;
}
static struct inode *v9fs_qid_iget_dotl(struct super_block *sb,
struct p9_qid *qid,
struct p9_fid *fid,
struct p9_stat_dotl *st,
int new)
{
int retval;
unsigned long i_ino;
struct inode *inode;
struct v9fs_session_info *v9ses = sb->s_fs_info;
int (*test)(struct inode *, void *);
if (new)
test = v9fs_test_new_inode_dotl;
else
test = v9fs_test_inode_dotl;
i_ino = v9fs_qid2ino(qid);
inode = iget5_locked(sb, i_ino, test, v9fs_set_inode_dotl, st);
if (!inode)
return ERR_PTR(-ENOMEM);
if (!(inode->i_state & I_NEW))
return inode;
/*
* initialize the inode with the stat info
* FIXME!! we may need support for stale inodes
* later.
*/
inode->i_ino = i_ino;
retval = v9fs_init_inode(v9ses, inode,
st->st_mode, new_decode_dev(st->st_rdev));
if (retval)
goto error;
v9fs_stat2inode_dotl(st, inode);
v9fs_cache_inode_get_cookie(inode);
retval = v9fs_get_acl(inode, fid);
if (retval)
goto error;
unlock_new_inode(inode);
return inode;
error:
iget_failed(inode);
return ERR_PTR(retval);
}
struct inode *
v9fs_inode_from_fid_dotl(struct v9fs_session_info *v9ses, struct p9_fid *fid,
struct super_block *sb, int new)
{
struct p9_stat_dotl *st;
struct inode *inode = NULL;
st = p9_client_getattr_dotl(fid, P9_STATS_BASIC | P9_STATS_GEN);
if (IS_ERR(st))
return ERR_CAST(st);
inode = v9fs_qid_iget_dotl(sb, &st->qid, fid, st, new);
kfree(st);
return inode;
}
struct dotl_openflag_map {
int open_flag;
int dotl_flag;
};
static int v9fs_mapped_dotl_flags(int flags)
{
int i;
int rflags = 0;
struct dotl_openflag_map dotl_oflag_map[] = {
{ O_CREAT, P9_DOTL_CREATE },
{ O_EXCL, P9_DOTL_EXCL },
{ O_NOCTTY, P9_DOTL_NOCTTY },
{ O_APPEND, P9_DOTL_APPEND },
{ O_NONBLOCK, P9_DOTL_NONBLOCK },
{ O_DSYNC, P9_DOTL_DSYNC },
{ FASYNC, P9_DOTL_FASYNC },
{ O_DIRECT, P9_DOTL_DIRECT },
{ O_LARGEFILE, P9_DOTL_LARGEFILE },
{ O_DIRECTORY, P9_DOTL_DIRECTORY },
{ O_NOFOLLOW, P9_DOTL_NOFOLLOW },
{ O_NOATIME, P9_DOTL_NOATIME },
{ O_CLOEXEC, P9_DOTL_CLOEXEC },
{ O_SYNC, P9_DOTL_SYNC},
};
for (i = 0; i < ARRAY_SIZE(dotl_oflag_map); i++) {
if (flags & dotl_oflag_map[i].open_flag)
rflags |= dotl_oflag_map[i].dotl_flag;
}
return rflags;
}
/**
* v9fs_open_to_dotl_flags- convert Linux specific open flags to
* plan 9 open flag.
* @flags: flags to convert
*/
int v9fs_open_to_dotl_flags(int flags)
{
int rflags = 0;
/*
* We have same bits for P9_DOTL_READONLY, P9_DOTL_WRONLY
* and P9_DOTL_NOACCESS
*/
rflags |= flags & O_ACCMODE;
rflags |= v9fs_mapped_dotl_flags(flags);
return rflags;
}
/**
* v9fs_vfs_create_dotl - VFS hook to create files for 9P2000.L protocol.
* @dir: directory inode that is being created
* @dentry: dentry that is being deleted
* @omode: create permissions
*
*/
static int
v9fs_vfs_create_dotl(struct inode *dir, struct dentry *dentry, umode_t omode,
bool excl)
{
return v9fs_vfs_mknod_dotl(dir, dentry, omode, 0);
}
static int
v9fs_vfs_atomic_open_dotl(struct inode *dir, struct dentry *dentry,
struct file *file, unsigned flags, umode_t omode,
int *opened)
{
int err = 0;
kgid_t gid;
umode_t mode;
char *name = NULL;
struct p9_qid qid;
struct inode *inode;
struct p9_fid *fid = NULL;
struct v9fs_inode *v9inode;
struct p9_fid *dfid, *ofid, *inode_fid;
struct v9fs_session_info *v9ses;
struct posix_acl *pacl = NULL, *dacl = NULL;
struct dentry *res = NULL;
if (d_unhashed(dentry)) {
res = v9fs_vfs_lookup(dir, dentry, 0);
if (IS_ERR(res))
return PTR_ERR(res);
if (res)
dentry = res;
}
/* Only creates */
if (!(flags & O_CREAT) || d_really_is_positive(dentry))
return finish_no_open(file, res);
v9ses = v9fs_inode2v9ses(dir);
name = (char *) dentry->d_name.name;
p9_debug(P9_DEBUG_VFS, "name:%s flags:0x%x mode:0x%hx\n",
name, flags, omode);
dfid = v9fs_fid_lookup(dentry->d_parent);
if (IS_ERR(dfid)) {
err = PTR_ERR(dfid);
p9_debug(P9_DEBUG_VFS, "fid lookup failed %d\n", err);
goto out;
}
/* clone a fid to use for creation */
ofid = p9_client_walk(dfid, 0, NULL, 1);
if (IS_ERR(ofid)) {
err = PTR_ERR(ofid);
p9_debug(P9_DEBUG_VFS, "p9_client_walk failed %d\n", err);
goto out;
}
gid = v9fs_get_fsgid_for_create(dir);
mode = omode;
/* Update mode based on ACL value */
err = v9fs_acl_mode(dir, &mode, &dacl, &pacl);
if (err) {
p9_debug(P9_DEBUG_VFS, "Failed to get acl values in creat %d\n",
err);
goto error;
}
err = p9_client_create_dotl(ofid, name, v9fs_open_to_dotl_flags(flags),
mode, gid, &qid);
if (err < 0) {
p9_debug(P9_DEBUG_VFS, "p9_client_open_dotl failed in creat %d\n",
err);
goto error;
}
v9fs_invalidate_inode_attr(dir);
/* instantiate inode and assign the unopened fid to the dentry */
fid = p9_client_walk(dfid, 1, &name, 1);
if (IS_ERR(fid)) {
err = PTR_ERR(fid);
p9_debug(P9_DEBUG_VFS, "p9_client_walk failed %d\n", err);
fid = NULL;
goto error;
}
inode = v9fs_get_new_inode_from_fid(v9ses, fid, dir->i_sb);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
p9_debug(P9_DEBUG_VFS, "inode creation failed %d\n", err);
goto error;
}
/* Now set the ACL based on the default value */
v9fs_set_create_acl(inode, fid, dacl, pacl);
v9fs_fid_add(dentry, fid);
d_instantiate(dentry, inode);
v9inode = V9FS_I(inode);
mutex_lock(&v9inode->v_mutex);
if ((v9ses->cache == CACHE_LOOSE || v9ses->cache == CACHE_FSCACHE) &&
!v9inode->writeback_fid &&
((flags & O_ACCMODE) != O_RDONLY)) {
/*
* clone a fid and add it to writeback_fid
* we do it during open time instead of
* page dirty time via write_begin/page_mkwrite
* because we want write after unlink usecase
* to work.
*/
inode_fid = v9fs_writeback_fid(dentry);
if (IS_ERR(inode_fid)) {
err = PTR_ERR(inode_fid);
mutex_unlock(&v9inode->v_mutex);
goto err_clunk_old_fid;
}
v9inode->writeback_fid = (void *) inode_fid;
}
mutex_unlock(&v9inode->v_mutex);
/* Since we are opening a file, assign the open fid to the file */
err = finish_open(file, dentry, generic_file_open, opened);
if (err)
goto err_clunk_old_fid;
file->private_data = ofid;
if (v9ses->cache == CACHE_LOOSE || v9ses->cache == CACHE_FSCACHE)
v9fs_cache_inode_set_cookie(inode, file);
*opened |= FILE_CREATED;
out:
v9fs_put_acl(dacl, pacl);
dput(res);
return err;
error:
if (fid)
p9_client_clunk(fid);
err_clunk_old_fid:
if (ofid)
p9_client_clunk(ofid);
goto out;
}
/**
* v9fs_vfs_mkdir_dotl - VFS mkdir hook to create a directory
* @dir: inode that is being unlinked
* @dentry: dentry that is being unlinked
* @omode: mode for new directory
*
*/
static int v9fs_vfs_mkdir_dotl(struct inode *dir,
struct dentry *dentry, umode_t omode)
{
int err;
struct v9fs_session_info *v9ses;
struct p9_fid *fid = NULL, *dfid = NULL;
kgid_t gid;
char *name;
umode_t mode;
struct inode *inode;
struct p9_qid qid;
struct dentry *dir_dentry;
struct posix_acl *dacl = NULL, *pacl = NULL;
p9_debug(P9_DEBUG_VFS, "name %pd\n", dentry);
err = 0;
v9ses = v9fs_inode2v9ses(dir);
omode |= S_IFDIR;
if (dir->i_mode & S_ISGID)
omode |= S_ISGID;
dir_dentry = dentry->d_parent;
dfid = v9fs_fid_lookup(dir_dentry);
if (IS_ERR(dfid)) {
err = PTR_ERR(dfid);
p9_debug(P9_DEBUG_VFS, "fid lookup failed %d\n", err);
dfid = NULL;
goto error;
}
gid = v9fs_get_fsgid_for_create(dir);
mode = omode;
/* Update mode based on ACL value */
err = v9fs_acl_mode(dir, &mode, &dacl, &pacl);
if (err) {
p9_debug(P9_DEBUG_VFS, "Failed to get acl values in mkdir %d\n",
err);
goto error;
}
name = (char *) dentry->d_name.name;
err = p9_client_mkdir_dotl(dfid, name, mode, gid, &qid);
if (err < 0)
goto error;
fid = p9_client_walk(dfid, 1, &name, 1);
if (IS_ERR(fid)) {
err = PTR_ERR(fid);
p9_debug(P9_DEBUG_VFS, "p9_client_walk failed %d\n",
err);
fid = NULL;
goto error;
}
/* instantiate inode and assign the unopened fid to the dentry */
if (v9ses->cache == CACHE_LOOSE || v9ses->cache == CACHE_FSCACHE) {
inode = v9fs_get_new_inode_from_fid(v9ses, fid, dir->i_sb);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
p9_debug(P9_DEBUG_VFS, "inode creation failed %d\n",
err);
goto error;
}
v9fs_fid_add(dentry, fid);
v9fs_set_create_acl(inode, fid, dacl, pacl);
d_instantiate(dentry, inode);
fid = NULL;
err = 0;
} else {
/*
* Not in cached mode. No need to populate
* inode with stat. We need to get an inode
* so that we can set the acl with dentry
*/
inode = v9fs_get_inode(dir->i_sb, mode, 0);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
goto error;
}
v9fs_set_create_acl(inode, fid, dacl, pacl);
d_instantiate(dentry, inode);
}
inc_nlink(dir);
v9fs_invalidate_inode_attr(dir);
error:
if (fid)
p9_client_clunk(fid);
v9fs_put_acl(dacl, pacl);
return err;
}
static int
v9fs_vfs_getattr_dotl(struct vfsmount *mnt, struct dentry *dentry,
struct kstat *stat)
{
struct v9fs_session_info *v9ses;
struct p9_fid *fid;
struct p9_stat_dotl *st;
p9_debug(P9_DEBUG_VFS, "dentry: %p\n", dentry);
v9ses = v9fs_dentry2v9ses(dentry);
if (v9ses->cache == CACHE_LOOSE || v9ses->cache == CACHE_FSCACHE) {
generic_fillattr(d_inode(dentry), stat);
return 0;
}
fid = v9fs_fid_lookup(dentry);
if (IS_ERR(fid))
return PTR_ERR(fid);
/* Ask for all the fields in stat structure. Server will return
* whatever it supports
*/
st = p9_client_getattr_dotl(fid, P9_STATS_ALL);
if (IS_ERR(st))
return PTR_ERR(st);
v9fs_stat2inode_dotl(st, d_inode(dentry));
generic_fillattr(d_inode(dentry), stat);
/* Change block size to what the server returned */
stat->blksize = st->st_blksize;
kfree(st);
return 0;
}
/*
* Attribute flags.
*/
#define P9_ATTR_MODE (1 << 0)
#define P9_ATTR_UID (1 << 1)
#define P9_ATTR_GID (1 << 2)
#define P9_ATTR_SIZE (1 << 3)
#define P9_ATTR_ATIME (1 << 4)
#define P9_ATTR_MTIME (1 << 5)
#define P9_ATTR_CTIME (1 << 6)
#define P9_ATTR_ATIME_SET (1 << 7)
#define P9_ATTR_MTIME_SET (1 << 8)
struct dotl_iattr_map {
int iattr_valid;
int p9_iattr_valid;
};
static int v9fs_mapped_iattr_valid(int iattr_valid)
{
int i;
int p9_iattr_valid = 0;
struct dotl_iattr_map dotl_iattr_map[] = {
{ ATTR_MODE, P9_ATTR_MODE },
{ ATTR_UID, P9_ATTR_UID },
{ ATTR_GID, P9_ATTR_GID },
{ ATTR_SIZE, P9_ATTR_SIZE },
{ ATTR_ATIME, P9_ATTR_ATIME },
{ ATTR_MTIME, P9_ATTR_MTIME },
{ ATTR_CTIME, P9_ATTR_CTIME },
{ ATTR_ATIME_SET, P9_ATTR_ATIME_SET },
{ ATTR_MTIME_SET, P9_ATTR_MTIME_SET },
};
for (i = 0; i < ARRAY_SIZE(dotl_iattr_map); i++) {
if (iattr_valid & dotl_iattr_map[i].iattr_valid)
p9_iattr_valid |= dotl_iattr_map[i].p9_iattr_valid;
}
return p9_iattr_valid;
}
/**
* v9fs_vfs_setattr_dotl - set file metadata
* @dentry: file whose metadata to set
* @iattr: metadata assignment structure
*
*/
int v9fs_vfs_setattr_dotl(struct dentry *dentry, struct iattr *iattr)
{
int retval;
struct p9_fid *fid;
struct p9_iattr_dotl p9attr;
struct inode *inode = d_inode(dentry);
p9_debug(P9_DEBUG_VFS, "\n");
retval = inode_change_ok(inode, iattr);
if (retval)
return retval;
p9attr.valid = v9fs_mapped_iattr_valid(iattr->ia_valid);
p9attr.mode = iattr->ia_mode;
p9attr.uid = iattr->ia_uid;
p9attr.gid = iattr->ia_gid;
p9attr.size = iattr->ia_size;
p9attr.atime_sec = iattr->ia_atime.tv_sec;
p9attr.atime_nsec = iattr->ia_atime.tv_nsec;
p9attr.mtime_sec = iattr->ia_mtime.tv_sec;
p9attr.mtime_nsec = iattr->ia_mtime.tv_nsec;
fid = v9fs_fid_lookup(dentry);
if (IS_ERR(fid))
return PTR_ERR(fid);
/* Write all dirty data */
if (S_ISREG(inode->i_mode))
filemap_write_and_wait(inode->i_mapping);
retval = p9_client_setattr(fid, &p9attr);
if (retval < 0)
return retval;
if ((iattr->ia_valid & ATTR_SIZE) &&
iattr->ia_size != i_size_read(inode))
truncate_setsize(inode, iattr->ia_size);
v9fs_invalidate_inode_attr(inode);
setattr_copy(inode, iattr);
mark_inode_dirty(inode);
if (iattr->ia_valid & ATTR_MODE) {
/* We also want to update ACL when we update mode bits */
retval = v9fs_acl_chmod(inode, fid);
if (retval < 0)
return retval;
}
return 0;
}
/**
* v9fs_stat2inode_dotl - populate an inode structure with stat info
* @stat: stat structure
* @inode: inode to populate
*
*/
void
v9fs_stat2inode_dotl(struct p9_stat_dotl *stat, struct inode *inode)
{
umode_t mode;
struct v9fs_inode *v9inode = V9FS_I(inode);
if ((stat->st_result_mask & P9_STATS_BASIC) == P9_STATS_BASIC) {
inode->i_atime.tv_sec = stat->st_atime_sec;
inode->i_atime.tv_nsec = stat->st_atime_nsec;
inode->i_mtime.tv_sec = stat->st_mtime_sec;
inode->i_mtime.tv_nsec = stat->st_mtime_nsec;
inode->i_ctime.tv_sec = stat->st_ctime_sec;
inode->i_ctime.tv_nsec = stat->st_ctime_nsec;
inode->i_uid = stat->st_uid;
inode->i_gid = stat->st_gid;
set_nlink(inode, stat->st_nlink);
mode = stat->st_mode & S_IALLUGO;
mode |= inode->i_mode & ~S_IALLUGO;
inode->i_mode = mode;
i_size_write(inode, stat->st_size);
inode->i_blocks = stat->st_blocks;
} else {
if (stat->st_result_mask & P9_STATS_ATIME) {
inode->i_atime.tv_sec = stat->st_atime_sec;
inode->i_atime.tv_nsec = stat->st_atime_nsec;
}
if (stat->st_result_mask & P9_STATS_MTIME) {
inode->i_mtime.tv_sec = stat->st_mtime_sec;
inode->i_mtime.tv_nsec = stat->st_mtime_nsec;
}
if (stat->st_result_mask & P9_STATS_CTIME) {
inode->i_ctime.tv_sec = stat->st_ctime_sec;
inode->i_ctime.tv_nsec = stat->st_ctime_nsec;
}
if (stat->st_result_mask & P9_STATS_UID)
inode->i_uid = stat->st_uid;
if (stat->st_result_mask & P9_STATS_GID)
inode->i_gid = stat->st_gid;
if (stat->st_result_mask & P9_STATS_NLINK)
set_nlink(inode, stat->st_nlink);
if (stat->st_result_mask & P9_STATS_MODE) {
inode->i_mode = stat->st_mode;
if ((S_ISBLK(inode->i_mode)) ||
(S_ISCHR(inode->i_mode)))
init_special_inode(inode, inode->i_mode,
inode->i_rdev);
}
if (stat->st_result_mask & P9_STATS_RDEV)
inode->i_rdev = new_decode_dev(stat->st_rdev);
if (stat->st_result_mask & P9_STATS_SIZE)
i_size_write(inode, stat->st_size);
if (stat->st_result_mask & P9_STATS_BLOCKS)
inode->i_blocks = stat->st_blocks;
}
if (stat->st_result_mask & P9_STATS_GEN)
inode->i_generation = stat->st_gen;
/* Currently we don't support P9_STATS_BTIME and P9_STATS_DATA_VERSION
* because the inode structure does not have fields for them.
*/
v9inode->cache_validity &= ~V9FS_INO_INVALID_ATTR;
}
static int
v9fs_vfs_symlink_dotl(struct inode *dir, struct dentry *dentry,
const char *symname)
{
int err;
kgid_t gid;
char *name;
struct p9_qid qid;
struct inode *inode;
struct p9_fid *dfid;
struct p9_fid *fid = NULL;
struct v9fs_session_info *v9ses;
name = (char *) dentry->d_name.name;
p9_debug(P9_DEBUG_VFS, "%lu,%s,%s\n", dir->i_ino, name, symname);
v9ses = v9fs_inode2v9ses(dir);
dfid = v9fs_fid_lookup(dentry->d_parent);
if (IS_ERR(dfid)) {
err = PTR_ERR(dfid);
p9_debug(P9_DEBUG_VFS, "fid lookup failed %d\n", err);
return err;
}
gid = v9fs_get_fsgid_for_create(dir);
/* Server doesn't alter fid on TSYMLINK. Hence no need to clone it. */
err = p9_client_symlink(dfid, name, (char *)symname, gid, &qid);
if (err < 0) {
p9_debug(P9_DEBUG_VFS, "p9_client_symlink failed %d\n", err);
goto error;
}
v9fs_invalidate_inode_attr(dir);
if (v9ses->cache == CACHE_LOOSE || v9ses->cache == CACHE_FSCACHE) {
/* Now walk from the parent so we can get an unopened fid. */
fid = p9_client_walk(dfid, 1, &name, 1);
if (IS_ERR(fid)) {
err = PTR_ERR(fid);
p9_debug(P9_DEBUG_VFS, "p9_client_walk failed %d\n",
err);
fid = NULL;
goto error;
}
/* instantiate inode and assign the unopened fid to dentry */
inode = v9fs_get_new_inode_from_fid(v9ses, fid, dir->i_sb);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
p9_debug(P9_DEBUG_VFS, "inode creation failed %d\n",
err);
goto error;
}
v9fs_fid_add(dentry, fid);
d_instantiate(dentry, inode);
fid = NULL;
err = 0;
} else {
/* Not in cached mode. No need to populate inode with stat */
inode = v9fs_get_inode(dir->i_sb, S_IFLNK, 0);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
goto error;
}
d_instantiate(dentry, inode);
}
error:
if (fid)
p9_client_clunk(fid);
return err;
}
/**
* v9fs_vfs_link_dotl - create a hardlink for dotl
* @old_dentry: dentry for file to link to
* @dir: inode destination for new link
* @dentry: dentry for link
*
*/
static int
v9fs_vfs_link_dotl(struct dentry *old_dentry, struct inode *dir,
struct dentry *dentry)
{
int err;
struct dentry *dir_dentry;
struct p9_fid *dfid, *oldfid;
struct v9fs_session_info *v9ses;
p9_debug(P9_DEBUG_VFS, "dir ino: %lu, old_name: %pd, new_name: %pd\n",
dir->i_ino, old_dentry, dentry);
v9ses = v9fs_inode2v9ses(dir);
dir_dentry = dentry->d_parent;
dfid = v9fs_fid_lookup(dir_dentry);
if (IS_ERR(dfid))
return PTR_ERR(dfid);
oldfid = v9fs_fid_lookup(old_dentry);
if (IS_ERR(oldfid))
return PTR_ERR(oldfid);
err = p9_client_link(dfid, oldfid, (char *)dentry->d_name.name);
if (err < 0) {
p9_debug(P9_DEBUG_VFS, "p9_client_link failed %d\n", err);
return err;
}
v9fs_invalidate_inode_attr(dir);
if (v9ses->cache == CACHE_LOOSE || v9ses->cache == CACHE_FSCACHE) {
/* Get the latest stat info from server. */
struct p9_fid *fid;
fid = v9fs_fid_lookup(old_dentry);
if (IS_ERR(fid))
return PTR_ERR(fid);
v9fs_refresh_inode_dotl(fid, d_inode(old_dentry));
}
ihold(d_inode(old_dentry));
d_instantiate(dentry, d_inode(old_dentry));
return err;
}
/**
* v9fs_vfs_mknod_dotl - create a special file
* @dir: inode destination for new link
* @dentry: dentry for file
* @omode: mode for creation
* @rdev: device associated with special file
*
*/
static int
v9fs_vfs_mknod_dotl(struct inode *dir, struct dentry *dentry, umode_t omode,
dev_t rdev)
{
int err;
kgid_t gid;
char *name;
umode_t mode;
struct v9fs_session_info *v9ses;
struct p9_fid *fid = NULL, *dfid = NULL;
struct inode *inode;
struct p9_qid qid;
struct dentry *dir_dentry;
struct posix_acl *dacl = NULL, *pacl = NULL;
p9_debug(P9_DEBUG_VFS, " %lu,%pd mode: %hx MAJOR: %u MINOR: %u\n",
dir->i_ino, dentry, omode,
MAJOR(rdev), MINOR(rdev));
if (!new_valid_dev(rdev))
return -EINVAL;
v9ses = v9fs_inode2v9ses(dir);
dir_dentry = dentry->d_parent;
dfid = v9fs_fid_lookup(dir_dentry);
if (IS_ERR(dfid)) {
err = PTR_ERR(dfid);
p9_debug(P9_DEBUG_VFS, "fid lookup failed %d\n", err);
dfid = NULL;
goto error;
}
gid = v9fs_get_fsgid_for_create(dir);
mode = omode;
/* Update mode based on ACL value */
err = v9fs_acl_mode(dir, &mode, &dacl, &pacl);
if (err) {
p9_debug(P9_DEBUG_VFS, "Failed to get acl values in mknod %d\n",
err);
goto error;
}
name = (char *) dentry->d_name.name;
err = p9_client_mknod_dotl(dfid, name, mode, rdev, gid, &qid);
if (err < 0)
goto error;
v9fs_invalidate_inode_attr(dir);
fid = p9_client_walk(dfid, 1, &name, 1);
if (IS_ERR(fid)) {
err = PTR_ERR(fid);
p9_debug(P9_DEBUG_VFS, "p9_client_walk failed %d\n",
err);
fid = NULL;
goto error;
}
/* instantiate inode and assign the unopened fid to the dentry */
if (v9ses->cache == CACHE_LOOSE || v9ses->cache == CACHE_FSCACHE) {
inode = v9fs_get_new_inode_from_fid(v9ses, fid, dir->i_sb);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
p9_debug(P9_DEBUG_VFS, "inode creation failed %d\n",
err);
goto error;
}
v9fs_set_create_acl(inode, fid, dacl, pacl);
v9fs_fid_add(dentry, fid);
d_instantiate(dentry, inode);
fid = NULL;
err = 0;
} else {
/*
* Not in cached mode. No need to populate inode with stat.
* socket syscall returns a fd, so we need instantiate
*/
inode = v9fs_get_inode(dir->i_sb, mode, rdev);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
goto error;
}
v9fs_set_create_acl(inode, fid, dacl, pacl);
d_instantiate(dentry, inode);
}
error:
if (fid)
p9_client_clunk(fid);
v9fs_put_acl(dacl, pacl);
return err;
}
/**
* v9fs_vfs_follow_link_dotl - follow a symlink path
* @dentry: dentry for symlink
* @cookie: place to pass the data to put_link()
*/
static const char *
v9fs_vfs_follow_link_dotl(struct dentry *dentry, void **cookie)
{
struct p9_fid *fid = v9fs_fid_lookup(dentry);
char *target;
int retval;
p9_debug(P9_DEBUG_VFS, "%pd\n", dentry);
if (IS_ERR(fid))
return ERR_CAST(fid);
retval = p9_client_readlink(fid, &target);
if (retval)
return ERR_PTR(retval);
return *cookie = target;
}
int v9fs_refresh_inode_dotl(struct p9_fid *fid, struct inode *inode)
{
loff_t i_size;
struct p9_stat_dotl *st;
struct v9fs_session_info *v9ses;
v9ses = v9fs_inode2v9ses(inode);
st = p9_client_getattr_dotl(fid, P9_STATS_ALL);
if (IS_ERR(st))
return PTR_ERR(st);
/*
* Don't update inode if the file type is different
*/
if ((inode->i_mode & S_IFMT) != (st->st_mode & S_IFMT))
goto out;
spin_lock(&inode->i_lock);
/*
* We don't want to refresh inode->i_size,
* because we may have cached data
*/
i_size = inode->i_size;
v9fs_stat2inode_dotl(st, inode);
if (v9ses->cache == CACHE_LOOSE || v9ses->cache == CACHE_FSCACHE)
inode->i_size = i_size;
spin_unlock(&inode->i_lock);
out:
kfree(st);
return 0;
}
const struct inode_operations v9fs_dir_inode_operations_dotl = {
.create = v9fs_vfs_create_dotl,
.atomic_open = v9fs_vfs_atomic_open_dotl,
.lookup = v9fs_vfs_lookup,
.link = v9fs_vfs_link_dotl,
.symlink = v9fs_vfs_symlink_dotl,
.unlink = v9fs_vfs_unlink,
.mkdir = v9fs_vfs_mkdir_dotl,
.rmdir = v9fs_vfs_rmdir,
.mknod = v9fs_vfs_mknod_dotl,
.rename = v9fs_vfs_rename,
.getattr = v9fs_vfs_getattr_dotl,
.setattr = v9fs_vfs_setattr_dotl,
.setxattr = generic_setxattr,
.getxattr = generic_getxattr,
.removexattr = generic_removexattr,
.listxattr = v9fs_listxattr,
.get_acl = v9fs_iop_get_acl,
};
const struct inode_operations v9fs_file_inode_operations_dotl = {
.getattr = v9fs_vfs_getattr_dotl,
.setattr = v9fs_vfs_setattr_dotl,
.setxattr = generic_setxattr,
.getxattr = generic_getxattr,
.removexattr = generic_removexattr,
.listxattr = v9fs_listxattr,
.get_acl = v9fs_iop_get_acl,
};
const struct inode_operations v9fs_symlink_inode_operations_dotl = {
.readlink = generic_readlink,
.follow_link = v9fs_vfs_follow_link_dotl,
.put_link = kfree_put_link,
.getattr = v9fs_vfs_getattr_dotl,
.setattr = v9fs_vfs_setattr_dotl,
.setxattr = generic_setxattr,
.getxattr = generic_getxattr,
.removexattr = generic_removexattr,
.listxattr = v9fs_listxattr,
};
| gpl-2.0 |
zachwick/linux | fs/bad_inode.c | 890 | 4812 | /*
* linux/fs/bad_inode.c
*
* Copyright (C) 1997, Stephen Tweedie
*
* Provide stub functions for unreadable inodes
*
* Fabian Frederick : August 2003 - All file operations assigned to EIO
*/
#include <linux/fs.h>
#include <linux/export.h>
#include <linux/stat.h>
#include <linux/time.h>
#include <linux/namei.h>
#include <linux/poll.h>
static int bad_file_open(struct inode *inode, struct file *filp)
{
return -EIO;
}
static const struct file_operations bad_file_ops =
{
.open = bad_file_open,
};
static int bad_inode_create (struct inode *dir, struct dentry *dentry,
umode_t mode, bool excl)
{
return -EIO;
}
static struct dentry *bad_inode_lookup(struct inode *dir,
struct dentry *dentry, unsigned int flags)
{
return ERR_PTR(-EIO);
}
static int bad_inode_link (struct dentry *old_dentry, struct inode *dir,
struct dentry *dentry)
{
return -EIO;
}
static int bad_inode_unlink(struct inode *dir, struct dentry *dentry)
{
return -EIO;
}
static int bad_inode_symlink (struct inode *dir, struct dentry *dentry,
const char *symname)
{
return -EIO;
}
static int bad_inode_mkdir(struct inode *dir, struct dentry *dentry,
umode_t mode)
{
return -EIO;
}
static int bad_inode_rmdir (struct inode *dir, struct dentry *dentry)
{
return -EIO;
}
static int bad_inode_mknod (struct inode *dir, struct dentry *dentry,
umode_t mode, dev_t rdev)
{
return -EIO;
}
static int bad_inode_rename2(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry,
unsigned int flags)
{
return -EIO;
}
static int bad_inode_readlink(struct dentry *dentry, char __user *buffer,
int buflen)
{
return -EIO;
}
static int bad_inode_permission(struct inode *inode, int mask)
{
return -EIO;
}
static int bad_inode_getattr(struct vfsmount *mnt, struct dentry *dentry,
struct kstat *stat)
{
return -EIO;
}
static int bad_inode_setattr(struct dentry *direntry, struct iattr *attrs)
{
return -EIO;
}
static int bad_inode_setxattr(struct dentry *dentry, const char *name,
const void *value, size_t size, int flags)
{
return -EIO;
}
static ssize_t bad_inode_getxattr(struct dentry *dentry, const char *name,
void *buffer, size_t size)
{
return -EIO;
}
static ssize_t bad_inode_listxattr(struct dentry *dentry, char *buffer,
size_t buffer_size)
{
return -EIO;
}
static int bad_inode_removexattr(struct dentry *dentry, const char *name)
{
return -EIO;
}
static const struct inode_operations bad_inode_ops =
{
.create = bad_inode_create,
.lookup = bad_inode_lookup,
.link = bad_inode_link,
.unlink = bad_inode_unlink,
.symlink = bad_inode_symlink,
.mkdir = bad_inode_mkdir,
.rmdir = bad_inode_rmdir,
.mknod = bad_inode_mknod,
.rename2 = bad_inode_rename2,
.readlink = bad_inode_readlink,
/* follow_link must be no-op, otherwise unmounting this inode
won't work */
/* put_link returns void */
/* truncate returns void */
.permission = bad_inode_permission,
.getattr = bad_inode_getattr,
.setattr = bad_inode_setattr,
.setxattr = bad_inode_setxattr,
.getxattr = bad_inode_getxattr,
.listxattr = bad_inode_listxattr,
.removexattr = bad_inode_removexattr,
};
/*
* When a filesystem is unable to read an inode due to an I/O error in
* its read_inode() function, it can call make_bad_inode() to return a
* set of stubs which will return EIO errors as required.
*
* We only need to do limited initialisation: all other fields are
* preinitialised to zero automatically.
*/
/**
* make_bad_inode - mark an inode bad due to an I/O error
* @inode: Inode to mark bad
*
* When an inode cannot be read due to a media or remote network
* failure this function makes the inode "bad" and causes I/O operations
* on it to fail from this point on.
*/
void make_bad_inode(struct inode *inode)
{
remove_inode_hash(inode);
inode->i_mode = S_IFREG;
inode->i_atime = inode->i_mtime = inode->i_ctime =
current_fs_time(inode->i_sb);
inode->i_op = &bad_inode_ops;
inode->i_fop = &bad_file_ops;
}
EXPORT_SYMBOL(make_bad_inode);
/*
* This tests whether an inode has been flagged as bad. The test uses
* &bad_inode_ops to cover the case of invalidated inodes as well as
* those created by make_bad_inode() above.
*/
/**
* is_bad_inode - is an inode errored
* @inode: inode to test
*
* Returns true if the inode in question has been marked as bad.
*/
int is_bad_inode(struct inode *inode)
{
return (inode->i_op == &bad_inode_ops);
}
EXPORT_SYMBOL(is_bad_inode);
/**
* iget_failed - Mark an under-construction inode as dead and release it
* @inode: The inode to discard
*
* Mark an under-construction inode as dead and release it.
*/
void iget_failed(struct inode *inode)
{
make_bad_inode(inode);
unlock_new_inode(inode);
iput(inode);
}
EXPORT_SYMBOL(iget_failed);
| gpl-2.0 |
bozont/2.6.35 | fs/gfs2/lock_dlm.c | 890 | 5567 | /*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2009 Red Hat, Inc. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*/
#include <linux/fs.h>
#include <linux/dlm.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/gfs2_ondisk.h>
#include "incore.h"
#include "glock.h"
#include "util.h"
static void gdlm_ast(void *arg)
{
struct gfs2_glock *gl = arg;
unsigned ret = gl->gl_state;
struct gfs2_sbd *sdp = gl->gl_sbd;
BUG_ON(gl->gl_lksb.sb_flags & DLM_SBF_DEMOTED);
if (gl->gl_lksb.sb_flags & DLM_SBF_VALNOTVALID)
memset(gl->gl_lvb, 0, GDLM_LVB_SIZE);
switch (gl->gl_lksb.sb_status) {
case -DLM_EUNLOCK: /* Unlocked, so glock can be freed */
if (gl->gl_ops->go_flags & GLOF_ASPACE)
kmem_cache_free(gfs2_glock_aspace_cachep, gl);
else
kmem_cache_free(gfs2_glock_cachep, gl);
if (atomic_dec_and_test(&sdp->sd_glock_disposal))
wake_up(&sdp->sd_glock_wait);
return;
case -DLM_ECANCEL: /* Cancel while getting lock */
ret |= LM_OUT_CANCELED;
goto out;
case -EAGAIN: /* Try lock fails */
goto out;
case -EINVAL: /* Invalid */
case -ENOMEM: /* Out of memory */
ret |= LM_OUT_ERROR;
goto out;
case 0: /* Success */
break;
default: /* Something unexpected */
BUG();
}
ret = gl->gl_req;
if (gl->gl_lksb.sb_flags & DLM_SBF_ALTMODE) {
if (gl->gl_req == LM_ST_SHARED)
ret = LM_ST_DEFERRED;
else if (gl->gl_req == LM_ST_DEFERRED)
ret = LM_ST_SHARED;
else
BUG();
}
set_bit(GLF_INITIAL, &gl->gl_flags);
gfs2_glock_complete(gl, ret);
return;
out:
if (!test_bit(GLF_INITIAL, &gl->gl_flags))
gl->gl_lksb.sb_lkid = 0;
gfs2_glock_complete(gl, ret);
}
static void gdlm_bast(void *arg, int mode)
{
struct gfs2_glock *gl = arg;
switch (mode) {
case DLM_LOCK_EX:
gfs2_glock_cb(gl, LM_ST_UNLOCKED);
break;
case DLM_LOCK_CW:
gfs2_glock_cb(gl, LM_ST_DEFERRED);
break;
case DLM_LOCK_PR:
gfs2_glock_cb(gl, LM_ST_SHARED);
break;
default:
printk(KERN_ERR "unknown bast mode %d", mode);
BUG();
}
}
/* convert gfs lock-state to dlm lock-mode */
static int make_mode(const unsigned int lmstate)
{
switch (lmstate) {
case LM_ST_UNLOCKED:
return DLM_LOCK_NL;
case LM_ST_EXCLUSIVE:
return DLM_LOCK_EX;
case LM_ST_DEFERRED:
return DLM_LOCK_CW;
case LM_ST_SHARED:
return DLM_LOCK_PR;
}
printk(KERN_ERR "unknown LM state %d", lmstate);
BUG();
return -1;
}
static u32 make_flags(const u32 lkid, const unsigned int gfs_flags,
const int req)
{
u32 lkf = 0;
if (gfs_flags & LM_FLAG_TRY)
lkf |= DLM_LKF_NOQUEUE;
if (gfs_flags & LM_FLAG_TRY_1CB) {
lkf |= DLM_LKF_NOQUEUE;
lkf |= DLM_LKF_NOQUEUEBAST;
}
if (gfs_flags & LM_FLAG_PRIORITY) {
lkf |= DLM_LKF_NOORDER;
lkf |= DLM_LKF_HEADQUE;
}
if (gfs_flags & LM_FLAG_ANY) {
if (req == DLM_LOCK_PR)
lkf |= DLM_LKF_ALTCW;
else if (req == DLM_LOCK_CW)
lkf |= DLM_LKF_ALTPR;
else
BUG();
}
if (lkid != 0)
lkf |= DLM_LKF_CONVERT;
lkf |= DLM_LKF_VALBLK;
return lkf;
}
static unsigned int gdlm_lock(struct gfs2_glock *gl,
unsigned int req_state, unsigned int flags)
{
struct lm_lockstruct *ls = &gl->gl_sbd->sd_lockstruct;
int error;
int req;
u32 lkf;
gl->gl_req = req_state;
req = make_mode(req_state);
lkf = make_flags(gl->gl_lksb.sb_lkid, flags, req);
/*
* Submit the actual lock request.
*/
error = dlm_lock(ls->ls_dlm, req, &gl->gl_lksb, lkf, gl->gl_strname,
GDLM_STRNAME_BYTES - 1, 0, gdlm_ast, gl, gdlm_bast);
if (error == -EAGAIN)
return 0;
if (error)
return LM_OUT_ERROR;
return LM_OUT_ASYNC;
}
static void gdlm_put_lock(struct kmem_cache *cachep, struct gfs2_glock *gl)
{
struct gfs2_sbd *sdp = gl->gl_sbd;
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
int error;
if (gl->gl_lksb.sb_lkid == 0) {
kmem_cache_free(cachep, gl);
if (atomic_dec_and_test(&sdp->sd_glock_disposal))
wake_up(&sdp->sd_glock_wait);
return;
}
error = dlm_unlock(ls->ls_dlm, gl->gl_lksb.sb_lkid, DLM_LKF_VALBLK,
NULL, gl);
if (error) {
printk(KERN_ERR "gdlm_unlock %x,%llx err=%d\n",
gl->gl_name.ln_type,
(unsigned long long)gl->gl_name.ln_number, error);
return;
}
}
static void gdlm_cancel(struct gfs2_glock *gl)
{
struct lm_lockstruct *ls = &gl->gl_sbd->sd_lockstruct;
dlm_unlock(ls->ls_dlm, gl->gl_lksb.sb_lkid, DLM_LKF_CANCEL, NULL, gl);
}
static int gdlm_mount(struct gfs2_sbd *sdp, const char *fsname)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
int error;
if (fsname == NULL) {
fs_info(sdp, "no fsname found\n");
return -EINVAL;
}
error = dlm_new_lockspace(fsname, strlen(fsname), &ls->ls_dlm,
DLM_LSFL_FS | DLM_LSFL_NEWEXCL |
(ls->ls_nodir ? DLM_LSFL_NODIR : 0),
GDLM_LVB_SIZE);
if (error)
printk(KERN_ERR "dlm_new_lockspace error %d", error);
return error;
}
static void gdlm_unmount(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
if (ls->ls_dlm) {
dlm_release_lockspace(ls->ls_dlm, 2);
ls->ls_dlm = NULL;
}
}
static const match_table_t dlm_tokens = {
{ Opt_jid, "jid=%d"},
{ Opt_id, "id=%d"},
{ Opt_first, "first=%d"},
{ Opt_nodir, "nodir=%d"},
{ Opt_err, NULL },
};
const struct lm_lockops gfs2_dlm_ops = {
.lm_proto_name = "lock_dlm",
.lm_mount = gdlm_mount,
.lm_unmount = gdlm_unmount,
.lm_put_lock = gdlm_put_lock,
.lm_lock = gdlm_lock,
.lm_cancel = gdlm_cancel,
.lm_tokens = &dlm_tokens,
};
| gpl-2.0 |
pjknkda/linux | drivers/iio/magnetometer/mag3110.c | 890 | 10718 | /*
* mag3110.c - Support for Freescale MAG3110 magnetometer sensor
*
* Copyright (c) 2013 Peter Meerwald <pmeerw@pmeerw.net>
*
* This file is subject to the terms and conditions of version 2 of
* the GNU General Public License. See the file COPYING in the main
* directory of this archive for more details.
*
* (7-bit I2C slave address 0x0e)
*
* TODO: irq, user offset, oversampling, continuous mode
*/
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/iio/iio.h>
#include <linux/iio/sysfs.h>
#include <linux/iio/trigger_consumer.h>
#include <linux/iio/buffer.h>
#include <linux/iio/triggered_buffer.h>
#include <linux/delay.h>
#define MAG3110_STATUS 0x00
#define MAG3110_OUT_X 0x01 /* MSB first */
#define MAG3110_OUT_Y 0x03
#define MAG3110_OUT_Z 0x05
#define MAG3110_WHO_AM_I 0x07
#define MAG3110_OFF_X 0x09 /* MSB first */
#define MAG3110_OFF_Y 0x0b
#define MAG3110_OFF_Z 0x0d
#define MAG3110_DIE_TEMP 0x0f
#define MAG3110_CTRL_REG1 0x10
#define MAG3110_CTRL_REG2 0x11
#define MAG3110_STATUS_DRDY (BIT(2) | BIT(1) | BIT(0))
#define MAG3110_CTRL_DR_MASK (BIT(7) | BIT(6) | BIT(5))
#define MAG3110_CTRL_DR_SHIFT 5
#define MAG3110_CTRL_DR_DEFAULT 0
#define MAG3110_CTRL_TM BIT(1) /* trigger single measurement */
#define MAG3110_CTRL_AC BIT(0) /* continuous measurements */
#define MAG3110_CTRL_AUTO_MRST_EN BIT(7) /* magnetic auto-reset */
#define MAG3110_CTRL_RAW BIT(5) /* measurements not user-offset corrected */
#define MAG3110_DEVICE_ID 0xc4
/* Each client has this additional data */
struct mag3110_data {
struct i2c_client *client;
struct mutex lock;
u8 ctrl_reg1;
};
static int mag3110_request(struct mag3110_data *data)
{
int ret, tries = 150;
/* trigger measurement */
ret = i2c_smbus_write_byte_data(data->client, MAG3110_CTRL_REG1,
data->ctrl_reg1 | MAG3110_CTRL_TM);
if (ret < 0)
return ret;
while (tries-- > 0) {
ret = i2c_smbus_read_byte_data(data->client, MAG3110_STATUS);
if (ret < 0)
return ret;
/* wait for data ready */
if ((ret & MAG3110_STATUS_DRDY) == MAG3110_STATUS_DRDY)
break;
msleep(20);
}
if (tries < 0) {
dev_err(&data->client->dev, "data not ready\n");
return -EIO;
}
return 0;
}
static int mag3110_read(struct mag3110_data *data, __be16 buf[3])
{
int ret;
mutex_lock(&data->lock);
ret = mag3110_request(data);
if (ret < 0) {
mutex_unlock(&data->lock);
return ret;
}
ret = i2c_smbus_read_i2c_block_data(data->client,
MAG3110_OUT_X, 3 * sizeof(__be16), (u8 *) buf);
mutex_unlock(&data->lock);
return ret;
}
static ssize_t mag3110_show_int_plus_micros(char *buf,
const int (*vals)[2], int n)
{
size_t len = 0;
while (n-- > 0)
len += scnprintf(buf + len, PAGE_SIZE - len,
"%d.%06d ", vals[n][0], vals[n][1]);
/* replace trailing space by newline */
buf[len - 1] = '\n';
return len;
}
static int mag3110_get_int_plus_micros_index(const int (*vals)[2], int n,
int val, int val2)
{
while (n-- > 0)
if (val == vals[n][0] && val2 == vals[n][1])
return n;
return -EINVAL;
}
static const int mag3110_samp_freq[8][2] = {
{80, 0}, {40, 0}, {20, 0}, {10, 0}, {5, 0}, {2, 500000},
{1, 250000}, {0, 625000}
};
static ssize_t mag3110_show_samp_freq_avail(struct device *dev,
struct device_attribute *attr, char *buf)
{
return mag3110_show_int_plus_micros(buf, mag3110_samp_freq, 8);
}
static IIO_DEV_ATTR_SAMP_FREQ_AVAIL(mag3110_show_samp_freq_avail);
static int mag3110_get_samp_freq_index(struct mag3110_data *data,
int val, int val2)
{
return mag3110_get_int_plus_micros_index(mag3110_samp_freq, 8, val,
val2);
}
static int mag3110_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int *val, int *val2, long mask)
{
struct mag3110_data *data = iio_priv(indio_dev);
__be16 buffer[3];
int i, ret;
switch (mask) {
case IIO_CHAN_INFO_RAW:
if (iio_buffer_enabled(indio_dev))
return -EBUSY;
switch (chan->type) {
case IIO_MAGN: /* in 0.1 uT / LSB */
ret = mag3110_read(data, buffer);
if (ret < 0)
return ret;
*val = sign_extend32(
be16_to_cpu(buffer[chan->scan_index]), 15);
return IIO_VAL_INT;
case IIO_TEMP: /* in 1 C / LSB */
mutex_lock(&data->lock);
ret = mag3110_request(data);
if (ret < 0) {
mutex_unlock(&data->lock);
return ret;
}
ret = i2c_smbus_read_byte_data(data->client,
MAG3110_DIE_TEMP);
mutex_unlock(&data->lock);
if (ret < 0)
return ret;
*val = sign_extend32(ret, 7);
return IIO_VAL_INT;
default:
return -EINVAL;
}
case IIO_CHAN_INFO_SCALE:
switch (chan->type) {
case IIO_MAGN:
*val = 0;
*val2 = 1000;
return IIO_VAL_INT_PLUS_MICRO;
case IIO_TEMP:
*val = 1000;
return IIO_VAL_INT;
default:
return -EINVAL;
}
case IIO_CHAN_INFO_SAMP_FREQ:
i = data->ctrl_reg1 >> MAG3110_CTRL_DR_SHIFT;
*val = mag3110_samp_freq[i][0];
*val2 = mag3110_samp_freq[i][1];
return IIO_VAL_INT_PLUS_MICRO;
case IIO_CHAN_INFO_CALIBBIAS:
ret = i2c_smbus_read_word_swapped(data->client,
MAG3110_OFF_X + 2 * chan->scan_index);
if (ret < 0)
return ret;
*val = sign_extend32(ret >> 1, 14);
return IIO_VAL_INT;
}
return -EINVAL;
}
static int mag3110_write_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int val, int val2, long mask)
{
struct mag3110_data *data = iio_priv(indio_dev);
int rate;
if (iio_buffer_enabled(indio_dev))
return -EBUSY;
switch (mask) {
case IIO_CHAN_INFO_SAMP_FREQ:
rate = mag3110_get_samp_freq_index(data, val, val2);
if (rate < 0)
return -EINVAL;
data->ctrl_reg1 &= ~MAG3110_CTRL_DR_MASK;
data->ctrl_reg1 |= rate << MAG3110_CTRL_DR_SHIFT;
return i2c_smbus_write_byte_data(data->client,
MAG3110_CTRL_REG1, data->ctrl_reg1);
case IIO_CHAN_INFO_CALIBBIAS:
if (val < -10000 || val > 10000)
return -EINVAL;
return i2c_smbus_write_word_swapped(data->client,
MAG3110_OFF_X + 2 * chan->scan_index, val << 1);
default:
return -EINVAL;
}
}
static irqreturn_t mag3110_trigger_handler(int irq, void *p)
{
struct iio_poll_func *pf = p;
struct iio_dev *indio_dev = pf->indio_dev;
struct mag3110_data *data = iio_priv(indio_dev);
u8 buffer[16]; /* 3 16-bit channels + 1 byte temp + padding + ts */
int ret;
ret = mag3110_read(data, (__be16 *) buffer);
if (ret < 0)
goto done;
if (test_bit(3, indio_dev->active_scan_mask)) {
ret = i2c_smbus_read_byte_data(data->client,
MAG3110_DIE_TEMP);
if (ret < 0)
goto done;
buffer[6] = ret;
}
iio_push_to_buffers_with_timestamp(indio_dev, buffer,
iio_get_time_ns());
done:
iio_trigger_notify_done(indio_dev->trig);
return IRQ_HANDLED;
}
#define MAG3110_CHANNEL(axis, idx) { \
.type = IIO_MAGN, \
.modified = 1, \
.channel2 = IIO_MOD_##axis, \
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
BIT(IIO_CHAN_INFO_CALIBBIAS), \
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SAMP_FREQ) | \
BIT(IIO_CHAN_INFO_SCALE), \
.scan_index = idx, \
.scan_type = { \
.sign = 's', \
.realbits = 16, \
.storagebits = 16, \
.endianness = IIO_BE, \
}, \
}
static const struct iio_chan_spec mag3110_channels[] = {
MAG3110_CHANNEL(X, 0),
MAG3110_CHANNEL(Y, 1),
MAG3110_CHANNEL(Z, 2),
{
.type = IIO_TEMP,
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
BIT(IIO_CHAN_INFO_SCALE),
.scan_index = 3,
.scan_type = {
.sign = 's',
.realbits = 8,
.storagebits = 8,
},
},
IIO_CHAN_SOFT_TIMESTAMP(4),
};
static struct attribute *mag3110_attributes[] = {
&iio_dev_attr_sampling_frequency_available.dev_attr.attr,
NULL
};
static const struct attribute_group mag3110_group = {
.attrs = mag3110_attributes,
};
static const struct iio_info mag3110_info = {
.attrs = &mag3110_group,
.read_raw = &mag3110_read_raw,
.write_raw = &mag3110_write_raw,
.driver_module = THIS_MODULE,
};
static const unsigned long mag3110_scan_masks[] = {0x7, 0xf, 0};
static int mag3110_standby(struct mag3110_data *data)
{
return i2c_smbus_write_byte_data(data->client, MAG3110_CTRL_REG1,
data->ctrl_reg1 & ~MAG3110_CTRL_AC);
}
static int mag3110_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct mag3110_data *data;
struct iio_dev *indio_dev;
int ret;
ret = i2c_smbus_read_byte_data(client, MAG3110_WHO_AM_I);
if (ret < 0)
return ret;
if (ret != MAG3110_DEVICE_ID)
return -ENODEV;
indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*data));
if (!indio_dev)
return -ENOMEM;
data = iio_priv(indio_dev);
data->client = client;
mutex_init(&data->lock);
i2c_set_clientdata(client, indio_dev);
indio_dev->info = &mag3110_info;
indio_dev->name = id->name;
indio_dev->dev.parent = &client->dev;
indio_dev->modes = INDIO_DIRECT_MODE;
indio_dev->channels = mag3110_channels;
indio_dev->num_channels = ARRAY_SIZE(mag3110_channels);
indio_dev->available_scan_masks = mag3110_scan_masks;
data->ctrl_reg1 = MAG3110_CTRL_DR_DEFAULT << MAG3110_CTRL_DR_SHIFT;
ret = i2c_smbus_write_byte_data(client, MAG3110_CTRL_REG1,
data->ctrl_reg1);
if (ret < 0)
return ret;
ret = i2c_smbus_write_byte_data(client, MAG3110_CTRL_REG2,
MAG3110_CTRL_AUTO_MRST_EN);
if (ret < 0)
goto standby_on_error;
ret = iio_triggered_buffer_setup(indio_dev, NULL,
mag3110_trigger_handler, NULL);
if (ret < 0)
goto standby_on_error;
ret = iio_device_register(indio_dev);
if (ret < 0)
goto buffer_cleanup;
return 0;
buffer_cleanup:
iio_triggered_buffer_cleanup(indio_dev);
standby_on_error:
mag3110_standby(iio_priv(indio_dev));
return ret;
}
static int mag3110_remove(struct i2c_client *client)
{
struct iio_dev *indio_dev = i2c_get_clientdata(client);
iio_device_unregister(indio_dev);
iio_triggered_buffer_cleanup(indio_dev);
mag3110_standby(iio_priv(indio_dev));
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int mag3110_suspend(struct device *dev)
{
return mag3110_standby(iio_priv(i2c_get_clientdata(
to_i2c_client(dev))));
}
static int mag3110_resume(struct device *dev)
{
struct mag3110_data *data = iio_priv(i2c_get_clientdata(
to_i2c_client(dev)));
return i2c_smbus_write_byte_data(data->client, MAG3110_CTRL_REG1,
data->ctrl_reg1);
}
static SIMPLE_DEV_PM_OPS(mag3110_pm_ops, mag3110_suspend, mag3110_resume);
#define MAG3110_PM_OPS (&mag3110_pm_ops)
#else
#define MAG3110_PM_OPS NULL
#endif
static const struct i2c_device_id mag3110_id[] = {
{ "mag3110", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, mag3110_id);
static struct i2c_driver mag3110_driver = {
.driver = {
.name = "mag3110",
.pm = MAG3110_PM_OPS,
},
.probe = mag3110_probe,
.remove = mag3110_remove,
.id_table = mag3110_id,
};
module_i2c_driver(mag3110_driver);
MODULE_AUTHOR("Peter Meerwald <pmeerw@pmeerw.net>");
MODULE_DESCRIPTION("Freescale MAG3110 magnetometer driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
rezvorck/android_kernel_s450m_4g_mm | drivers/w1/w1_int.c | 1146 | 6537 | /*
* w1_int.c
*
* Copyright (c) 2004 Evgeniy Polyakov <zbr@ioremap.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <linux/moduleparam.h>
#include "w1.h"
#include "w1_log.h"
#include "w1_netlink.h"
#include "w1_int.h"
static int w1_search_count = -1; /* Default is continual scan */
module_param_named(search_count, w1_search_count, int, 0);
static int w1_enable_pullup = 1;
module_param_named(enable_pullup, w1_enable_pullup, int, 0);
static struct w1_master *w1_alloc_dev(u32 id, int slave_count, int slave_ttl,
struct device_driver *driver,
struct device *device)
{
struct w1_master *dev;
int err;
/*
* We are in process context(kernel thread), so can sleep.
*/
dev = kzalloc(sizeof(struct w1_master) + sizeof(struct w1_bus_master), GFP_KERNEL);
if (!dev) {
pr_err("Failed to allocate %zd bytes for new w1 device.\n",
sizeof(struct w1_master));
return NULL;
}
dev->bus_master = (struct w1_bus_master *)(dev + 1);
dev->owner = THIS_MODULE;
dev->max_slave_count = slave_count;
dev->slave_count = 0;
dev->attempts = 0;
dev->initialized = 0;
dev->id = id;
dev->slave_ttl = slave_ttl;
dev->search_count = w1_search_count;
dev->enable_pullup = w1_enable_pullup;
/* 1 for w1_process to decrement
* 1 for __w1_remove_master_device to decrement
*/
atomic_set(&dev->refcnt, 2);
INIT_LIST_HEAD(&dev->slist);
INIT_LIST_HEAD(&dev->async_list);
mutex_init(&dev->mutex);
mutex_init(&dev->bus_mutex);
mutex_init(&dev->list_mutex);
memcpy(&dev->dev, device, sizeof(struct device));
dev_set_name(&dev->dev, "w1_bus_master%u", dev->id);
snprintf(dev->name, sizeof(dev->name), "w1_bus_master%u", dev->id);
dev->dev.init_name = dev->name;
dev->driver = driver;
dev->seq = 1;
err = device_register(&dev->dev);
if (err) {
pr_err("Failed to register master device. err=%d\n", err);
memset(dev, 0, sizeof(struct w1_master));
kfree(dev);
dev = NULL;
}
return dev;
}
static void w1_free_dev(struct w1_master *dev)
{
device_unregister(&dev->dev);
}
/**
* w1_add_master_device() - registers a new master device
* @master: master bus device to register
*/
int w1_add_master_device(struct w1_bus_master *master)
{
struct w1_master *dev, *entry;
int retval = 0;
struct w1_netlink_msg msg;
int id, found;
/* validate minimum functionality */
if (!(master->touch_bit && master->reset_bus) &&
!(master->write_bit && master->read_bit) &&
!(master->write_byte && master->read_byte && master->reset_bus)) {
pr_err("w1_add_master_device: invalid function set\n");
return(-EINVAL);
}
/* Lock until the device is added (or not) to w1_masters. */
mutex_lock(&w1_mlock);
/* Search for the first available id (starting at 1). */
id = 0;
do {
++id;
found = 0;
list_for_each_entry(entry, &w1_masters, w1_master_entry) {
if (entry->id == id) {
found = 1;
break;
}
}
} while (found);
dev = w1_alloc_dev(id, w1_max_slave_count, w1_max_slave_ttl,
&w1_master_driver, &w1_master_device);
if (!dev) {
mutex_unlock(&w1_mlock);
return -ENOMEM;
}
retval = w1_create_master_attributes(dev);
if (retval) {
mutex_unlock(&w1_mlock);
goto err_out_free_dev;
}
memcpy(dev->bus_master, master, sizeof(struct w1_bus_master));
dev->initialized = 1;
dev->thread = kthread_run(&w1_process, dev, "%s", dev->name);
if (IS_ERR(dev->thread)) {
retval = PTR_ERR(dev->thread);
dev_err(&dev->dev,
"Failed to create new kernel thread. err=%d\n",
retval);
mutex_unlock(&w1_mlock);
goto err_out_rm_attr;
}
list_add(&dev->w1_master_entry, &w1_masters);
mutex_unlock(&w1_mlock);
memset(&msg, 0, sizeof(msg));
msg.id.mst.id = dev->id;
msg.type = W1_MASTER_ADD;
w1_netlink_send(dev, &msg);
return 0;
#if 0 /* Thread cleanup code, not required currently. */
err_out_kill_thread:
set_bit(W1_ABORT_SEARCH, &dev->flags);
kthread_stop(dev->thread);
#endif
err_out_rm_attr:
w1_destroy_master_attributes(dev);
err_out_free_dev:
w1_free_dev(dev);
return retval;
}
void __w1_remove_master_device(struct w1_master *dev)
{
struct w1_netlink_msg msg;
struct w1_slave *sl, *sln;
mutex_lock(&w1_mlock);
list_del(&dev->w1_master_entry);
mutex_unlock(&w1_mlock);
set_bit(W1_ABORT_SEARCH, &dev->flags);
kthread_stop(dev->thread);
mutex_lock(&dev->mutex);
mutex_lock(&dev->list_mutex);
list_for_each_entry_safe(sl, sln, &dev->slist, w1_slave_entry) {
mutex_unlock(&dev->list_mutex);
w1_slave_detach(sl);
mutex_lock(&dev->list_mutex);
}
w1_destroy_master_attributes(dev);
mutex_unlock(&dev->list_mutex);
mutex_unlock(&dev->mutex);
atomic_dec(&dev->refcnt);
while (atomic_read(&dev->refcnt)) {
dev_info(&dev->dev, "Waiting for %s to become free: refcnt=%d.\n",
dev->name, atomic_read(&dev->refcnt));
if (msleep_interruptible(1000))
flush_signals(current);
mutex_lock(&dev->list_mutex);
w1_process_callbacks(dev);
mutex_unlock(&dev->list_mutex);
}
mutex_lock(&dev->list_mutex);
w1_process_callbacks(dev);
mutex_unlock(&dev->list_mutex);
memset(&msg, 0, sizeof(msg));
msg.id.mst.id = dev->id;
msg.type = W1_MASTER_REMOVE;
w1_netlink_send(dev, &msg);
w1_free_dev(dev);
}
/**
* w1_remove_master_device() - unregister a master device
* @bm: master bus device to remove
*/
void w1_remove_master_device(struct w1_bus_master *bm)
{
struct w1_master *dev, *found = NULL;
list_for_each_entry(dev, &w1_masters, w1_master_entry) {
if (!dev->initialized)
continue;
if (dev->bus_master->data == bm->data) {
found = dev;
break;
}
}
if (!found) {
pr_err("Device doesn't exist.\n");
return;
}
__w1_remove_master_device(found);
}
EXPORT_SYMBOL(w1_add_master_device);
EXPORT_SYMBOL(w1_remove_master_device);
| gpl-2.0 |
AshishNamdev/linux | arch/um/os-Linux/skas/mem.c | 1146 | 5188 | /*
* Copyright (C) 2002 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL
*/
#include <stddef.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/mman.h>
#include <init.h>
#include <as-layout.h>
#include <mm_id.h>
#include <os.h>
#include <ptrace_user.h>
#include <registers.h>
#include <skas.h>
#include <sysdep/ptrace.h>
#include <sysdep/stub.h>
extern char batch_syscall_stub[], __syscall_stub_start[];
extern void wait_stub_done(int pid);
static inline unsigned long *check_init_stack(struct mm_id * mm_idp,
unsigned long *stack)
{
if (stack == NULL) {
stack = (unsigned long *) mm_idp->stack + 2;
*stack = 0;
}
return stack;
}
static unsigned long syscall_regs[MAX_REG_NR];
static int __init init_syscall_regs(void)
{
get_safe_registers(syscall_regs, NULL);
syscall_regs[REGS_IP_INDEX] = STUB_CODE +
((unsigned long) batch_syscall_stub -
(unsigned long) __syscall_stub_start);
return 0;
}
__initcall(init_syscall_regs);
static inline long do_syscall_stub(struct mm_id * mm_idp, void **addr)
{
int n, i;
long ret, offset;
unsigned long * data;
unsigned long * syscall;
int err, pid = mm_idp->u.pid;
n = ptrace_setregs(pid, syscall_regs);
if (n < 0) {
printk(UM_KERN_ERR "Registers - \n");
for (i = 0; i < MAX_REG_NR; i++)
printk(UM_KERN_ERR "\t%d\t0x%lx\n", i, syscall_regs[i]);
panic("do_syscall_stub : PTRACE_SETREGS failed, errno = %d\n",
-n);
}
err = ptrace(PTRACE_CONT, pid, 0, 0);
if (err)
panic("Failed to continue stub, pid = %d, errno = %d\n", pid,
errno);
wait_stub_done(pid);
/*
* When the stub stops, we find the following values on the
* beginning of the stack:
* (long )return_value
* (long )offset to failed sycall-data (0, if no error)
*/
ret = *((unsigned long *) mm_idp->stack);
offset = *((unsigned long *) mm_idp->stack + 1);
if (offset) {
data = (unsigned long *)(mm_idp->stack + offset - STUB_DATA);
printk(UM_KERN_ERR "do_syscall_stub : ret = %ld, offset = %ld, "
"data = %p\n", ret, offset, data);
syscall = (unsigned long *)((unsigned long)data + data[0]);
printk(UM_KERN_ERR "do_syscall_stub: syscall %ld failed, "
"return value = 0x%lx, expected return value = 0x%lx\n",
syscall[0], ret, syscall[7]);
printk(UM_KERN_ERR " syscall parameters: "
"0x%lx 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx\n",
syscall[1], syscall[2], syscall[3],
syscall[4], syscall[5], syscall[6]);
for (n = 1; n < data[0]/sizeof(long); n++) {
if (n == 1)
printk(UM_KERN_ERR " additional syscall "
"data:");
if (n % 4 == 1)
printk("\n" UM_KERN_ERR " ");
printk(" 0x%lx", data[n]);
}
if (n > 1)
printk("\n");
}
else ret = 0;
*addr = check_init_stack(mm_idp, NULL);
return ret;
}
long run_syscall_stub(struct mm_id * mm_idp, int syscall,
unsigned long *args, long expected, void **addr,
int done)
{
unsigned long *stack = check_init_stack(mm_idp, *addr);
*stack += sizeof(long);
stack += *stack / sizeof(long);
*stack++ = syscall;
*stack++ = args[0];
*stack++ = args[1];
*stack++ = args[2];
*stack++ = args[3];
*stack++ = args[4];
*stack++ = args[5];
*stack++ = expected;
*stack = 0;
if (!done && ((((unsigned long) stack) & ~UM_KERN_PAGE_MASK) <
UM_KERN_PAGE_SIZE - 10 * sizeof(long))) {
*addr = stack;
return 0;
}
return do_syscall_stub(mm_idp, addr);
}
long syscall_stub_data(struct mm_id * mm_idp,
unsigned long *data, int data_count,
void **addr, void **stub_addr)
{
unsigned long *stack;
int ret = 0;
/*
* If *addr still is uninitialized, it *must* contain NULL.
* Thus in this case do_syscall_stub correctly won't be called.
*/
if ((((unsigned long) *addr) & ~UM_KERN_PAGE_MASK) >=
UM_KERN_PAGE_SIZE - (10 + data_count) * sizeof(long)) {
ret = do_syscall_stub(mm_idp, addr);
/* in case of error, don't overwrite data on stack */
if (ret)
return ret;
}
stack = check_init_stack(mm_idp, *addr);
*addr = stack;
*stack = data_count * sizeof(long);
memcpy(stack + 1, data, data_count * sizeof(long));
*stub_addr = (void *)(((unsigned long)(stack + 1) &
~UM_KERN_PAGE_MASK) + STUB_DATA);
return 0;
}
int map(struct mm_id * mm_idp, unsigned long virt, unsigned long len, int prot,
int phys_fd, unsigned long long offset, int done, void **data)
{
int ret;
unsigned long args[] = { virt, len, prot,
MAP_SHARED | MAP_FIXED, phys_fd,
MMAP_OFFSET(offset) };
ret = run_syscall_stub(mm_idp, STUB_MMAP_NR, args, virt,
data, done);
return ret;
}
int unmap(struct mm_id * mm_idp, unsigned long addr, unsigned long len,
int done, void **data)
{
int ret;
unsigned long args[] = { (unsigned long) addr, len, 0, 0, 0,
0 };
ret = run_syscall_stub(mm_idp, __NR_munmap, args, 0,
data, done);
return ret;
}
int protect(struct mm_id * mm_idp, unsigned long addr, unsigned long len,
unsigned int prot, int done, void **data)
{
int ret;
unsigned long args[] = { addr, len, prot, 0, 0, 0 };
ret = run_syscall_stub(mm_idp, __NR_mprotect, args, 0,
data, done);
return ret;
}
| gpl-2.0 |
miquelmartos/geeksphone-kernel-zero-3.0 | drivers/leds/leds-pca9532.c | 2938 | 12526 | /*
* pca9532.c - 16-bit Led dimmer
*
* Copyright (C) 2011 Jan Weitzel
* Copyright (C) 2008 Riku Voipio
*
* 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.
*
* Datasheet: http://www.nxp.com/documents/data_sheet/PCA9532.pdf
*
*/
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/leds.h>
#include <linux/input.h>
#include <linux/mutex.h>
#include <linux/workqueue.h>
#include <linux/leds-pca9532.h>
#include <linux/gpio.h>
/* m = num_leds*/
#define PCA9532_REG_INPUT(i) ((i) >> 3)
#define PCA9532_REG_OFFSET(m) ((m) >> 4)
#define PCA9532_REG_PSC(m, i) (PCA9532_REG_OFFSET(m) + 0x1 + (i) * 2)
#define PCA9532_REG_PWM(m, i) (PCA9532_REG_OFFSET(m) + 0x2 + (i) * 2)
#define LED_REG(m, led) (PCA9532_REG_OFFSET(m) + 0x5 + (led >> 2))
#define LED_NUM(led) (led & 0x3)
#define ldev_to_led(c) container_of(c, struct pca9532_led, ldev)
struct pca9532_chip_info {
u8 num_leds;
};
struct pca9532_data {
struct i2c_client *client;
struct pca9532_led leds[16];
struct mutex update_lock;
struct input_dev *idev;
struct work_struct work;
#ifdef CONFIG_LEDS_PCA9532_GPIO
struct gpio_chip gpio;
#endif
const struct pca9532_chip_info *chip_info;
u8 pwm[2];
u8 psc[2];
};
static int pca9532_probe(struct i2c_client *client,
const struct i2c_device_id *id);
static int pca9532_remove(struct i2c_client *client);
enum {
pca9530,
pca9531,
pca9532,
pca9533,
};
static const struct i2c_device_id pca9532_id[] = {
{ "pca9530", pca9530 },
{ "pca9531", pca9531 },
{ "pca9532", pca9532 },
{ "pca9533", pca9533 },
{ }
};
MODULE_DEVICE_TABLE(i2c, pca9532_id);
static const struct pca9532_chip_info pca9532_chip_info_tbl[] = {
[pca9530] = {
.num_leds = 2,
},
[pca9531] = {
.num_leds = 8,
},
[pca9532] = {
.num_leds = 16,
},
[pca9533] = {
.num_leds = 4,
},
};
static struct i2c_driver pca9532_driver = {
.driver = {
.name = "leds-pca953x",
},
.probe = pca9532_probe,
.remove = pca9532_remove,
.id_table = pca9532_id,
};
/* We have two pwm/blinkers, but 16 possible leds to drive. Additionally,
* the clever Thecus people are using one pwm to drive the beeper. So,
* as a compromise we average one pwm to the values requested by all
* leds that are not ON/OFF.
* */
static int pca9532_calcpwm(struct i2c_client *client, int pwm, int blink,
enum led_brightness value)
{
int a = 0, b = 0, i = 0;
struct pca9532_data *data = i2c_get_clientdata(client);
for (i = 0; i < data->chip_info->num_leds; i++) {
if (data->leds[i].type == PCA9532_TYPE_LED &&
data->leds[i].state == PCA9532_PWM0+pwm) {
a++;
b += data->leds[i].ldev.brightness;
}
}
if (a == 0) {
dev_err(&client->dev,
"fear of division by zero %d/%d, wanted %d\n",
b, a, value);
return -EINVAL;
}
b = b/a;
if (b > 0xFF)
return -EINVAL;
data->pwm[pwm] = b;
data->psc[pwm] = blink;
return 0;
}
static int pca9532_setpwm(struct i2c_client *client, int pwm)
{
struct pca9532_data *data = i2c_get_clientdata(client);
u8 maxleds = data->chip_info->num_leds;
mutex_lock(&data->update_lock);
i2c_smbus_write_byte_data(client, PCA9532_REG_PWM(maxleds, pwm),
data->pwm[pwm]);
i2c_smbus_write_byte_data(client, PCA9532_REG_PSC(maxleds, pwm),
data->psc[pwm]);
mutex_unlock(&data->update_lock);
return 0;
}
/* Set LED routing */
static void pca9532_setled(struct pca9532_led *led)
{
struct i2c_client *client = led->client;
struct pca9532_data *data = i2c_get_clientdata(client);
u8 maxleds = data->chip_info->num_leds;
char reg;
mutex_lock(&data->update_lock);
reg = i2c_smbus_read_byte_data(client, LED_REG(maxleds, led->id));
/* zero led bits */
reg = reg & ~(0x3<<LED_NUM(led->id)*2);
/* set the new value */
reg = reg | (led->state << LED_NUM(led->id)*2);
i2c_smbus_write_byte_data(client, LED_REG(maxleds, led->id), reg);
mutex_unlock(&data->update_lock);
}
static void pca9532_set_brightness(struct led_classdev *led_cdev,
enum led_brightness value)
{
int err = 0;
struct pca9532_led *led = ldev_to_led(led_cdev);
if (value == LED_OFF)
led->state = PCA9532_OFF;
else if (value == LED_FULL)
led->state = PCA9532_ON;
else {
led->state = PCA9532_PWM0; /* Thecus: hardcode one pwm */
err = pca9532_calcpwm(led->client, 0, 0, value);
if (err)
return; /* XXX: led api doesn't allow error code? */
}
schedule_work(&led->work);
}
static int pca9532_set_blink(struct led_classdev *led_cdev,
unsigned long *delay_on, unsigned long *delay_off)
{
struct pca9532_led *led = ldev_to_led(led_cdev);
struct i2c_client *client = led->client;
int psc;
int err = 0;
if (*delay_on == 0 && *delay_off == 0) {
/* led subsystem ask us for a blink rate */
*delay_on = 1000;
*delay_off = 1000;
}
if (*delay_on != *delay_off || *delay_on > 1690 || *delay_on < 6)
return -EINVAL;
/* Thecus specific: only use PSC/PWM 0 */
psc = (*delay_on * 152-1)/1000;
err = pca9532_calcpwm(client, 0, psc, led_cdev->brightness);
if (err)
return err;
schedule_work(&led->work);
return 0;
}
static int pca9532_event(struct input_dev *dev, unsigned int type,
unsigned int code, int value)
{
struct pca9532_data *data = input_get_drvdata(dev);
if (!(type == EV_SND && (code == SND_BELL || code == SND_TONE)))
return -1;
/* XXX: allow different kind of beeps with psc/pwm modifications */
if (value > 1 && value < 32767)
data->pwm[1] = 127;
else
data->pwm[1] = 0;
schedule_work(&data->work);
return 0;
}
static void pca9532_input_work(struct work_struct *work)
{
struct pca9532_data *data =
container_of(work, struct pca9532_data, work);
u8 maxleds = data->chip_info->num_leds;
mutex_lock(&data->update_lock);
i2c_smbus_write_byte_data(data->client, PCA9532_REG_PWM(maxleds, 1),
data->pwm[1]);
mutex_unlock(&data->update_lock);
}
static void pca9532_led_work(struct work_struct *work)
{
struct pca9532_led *led;
led = container_of(work, struct pca9532_led, work);
if (led->state == PCA9532_PWM0)
pca9532_setpwm(led->client, 0);
pca9532_setled(led);
}
#ifdef CONFIG_LEDS_PCA9532_GPIO
static int pca9532_gpio_request_pin(struct gpio_chip *gc, unsigned offset)
{
struct pca9532_data *data = container_of(gc, struct pca9532_data, gpio);
struct pca9532_led *led = &data->leds[offset];
if (led->type == PCA9532_TYPE_GPIO)
return 0;
return -EBUSY;
}
static void pca9532_gpio_set_value(struct gpio_chip *gc, unsigned offset, int val)
{
struct pca9532_data *data = container_of(gc, struct pca9532_data, gpio);
struct pca9532_led *led = &data->leds[offset];
if (val)
led->state = PCA9532_ON;
else
led->state = PCA9532_OFF;
pca9532_setled(led);
}
static int pca9532_gpio_get_value(struct gpio_chip *gc, unsigned offset)
{
struct pca9532_data *data = container_of(gc, struct pca9532_data, gpio);
unsigned char reg;
reg = i2c_smbus_read_byte_data(data->client, PCA9532_REG_INPUT(offset));
return !!(reg & (1 << (offset % 8)));
}
static int pca9532_gpio_direction_input(struct gpio_chip *gc, unsigned offset)
{
/* To use as input ensure pin is not driven */
pca9532_gpio_set_value(gc, offset, 0);
return 0;
}
static int pca9532_gpio_direction_output(struct gpio_chip *gc, unsigned offset, int val)
{
pca9532_gpio_set_value(gc, offset, val);
return 0;
}
#endif /* CONFIG_LEDS_PCA9532_GPIO */
static int pca9532_destroy_devices(struct pca9532_data *data, int n_devs)
{
int i = n_devs;
if (!data)
return -EINVAL;
while (--i >= 0) {
switch (data->leds[i].type) {
case PCA9532_TYPE_NONE:
case PCA9532_TYPE_GPIO:
break;
case PCA9532_TYPE_LED:
led_classdev_unregister(&data->leds[i].ldev);
cancel_work_sync(&data->leds[i].work);
break;
case PCA9532_TYPE_N2100_BEEP:
if (data->idev != NULL) {
input_unregister_device(data->idev);
cancel_work_sync(&data->work);
data->idev = NULL;
}
break;
}
}
#ifdef CONFIG_LEDS_PCA9532_GPIO
if (data->gpio.dev) {
int err = gpiochip_remove(&data->gpio);
if (err) {
dev_err(&data->client->dev, "%s failed, %d\n",
"gpiochip_remove()", err);
return err;
}
}
#endif
return 0;
}
static int pca9532_configure(struct i2c_client *client,
struct pca9532_data *data, struct pca9532_platform_data *pdata)
{
int i, err = 0;
int gpios = 0;
u8 maxleds = data->chip_info->num_leds;
for (i = 0; i < 2; i++) {
data->pwm[i] = pdata->pwm[i];
data->psc[i] = pdata->psc[i];
i2c_smbus_write_byte_data(client, PCA9532_REG_PWM(maxleds, i),
data->pwm[i]);
i2c_smbus_write_byte_data(client, PCA9532_REG_PSC(maxleds, i),
data->psc[i]);
}
for (i = 0; i < data->chip_info->num_leds; i++) {
struct pca9532_led *led = &data->leds[i];
struct pca9532_led *pled = &pdata->leds[i];
led->client = client;
led->id = i;
led->type = pled->type;
switch (led->type) {
case PCA9532_TYPE_NONE:
break;
case PCA9532_TYPE_GPIO:
gpios++;
break;
case PCA9532_TYPE_LED:
led->state = pled->state;
led->name = pled->name;
led->ldev.name = led->name;
led->ldev.brightness = LED_OFF;
led->ldev.brightness_set = pca9532_set_brightness;
led->ldev.blink_set = pca9532_set_blink;
INIT_WORK(&led->work, pca9532_led_work);
err = led_classdev_register(&client->dev, &led->ldev);
if (err < 0) {
dev_err(&client->dev,
"couldn't register LED %s\n",
led->name);
goto exit;
}
pca9532_setled(led);
break;
case PCA9532_TYPE_N2100_BEEP:
BUG_ON(data->idev);
led->state = PCA9532_PWM1;
pca9532_setled(led);
data->idev = input_allocate_device();
if (data->idev == NULL) {
err = -ENOMEM;
goto exit;
}
data->idev->name = pled->name;
data->idev->phys = "i2c/pca9532";
data->idev->id.bustype = BUS_HOST;
data->idev->id.vendor = 0x001f;
data->idev->id.product = 0x0001;
data->idev->id.version = 0x0100;
data->idev->evbit[0] = BIT_MASK(EV_SND);
data->idev->sndbit[0] = BIT_MASK(SND_BELL) |
BIT_MASK(SND_TONE);
data->idev->event = pca9532_event;
input_set_drvdata(data->idev, data);
INIT_WORK(&data->work, pca9532_input_work);
err = input_register_device(data->idev);
if (err) {
input_free_device(data->idev);
cancel_work_sync(&data->work);
data->idev = NULL;
goto exit;
}
break;
}
}
#ifdef CONFIG_LEDS_PCA9532_GPIO
if (gpios) {
data->gpio.label = "gpio-pca9532";
data->gpio.direction_input = pca9532_gpio_direction_input;
data->gpio.direction_output = pca9532_gpio_direction_output;
data->gpio.set = pca9532_gpio_set_value;
data->gpio.get = pca9532_gpio_get_value;
data->gpio.request = pca9532_gpio_request_pin;
data->gpio.can_sleep = 1;
data->gpio.base = pdata->gpio_base;
data->gpio.ngpio = data->chip_info->num_leds;
data->gpio.dev = &client->dev;
data->gpio.owner = THIS_MODULE;
err = gpiochip_add(&data->gpio);
if (err) {
/* Use data->gpio.dev as a flag for freeing gpiochip */
data->gpio.dev = NULL;
dev_warn(&client->dev, "could not add gpiochip\n");
} else {
dev_info(&client->dev, "gpios %i...%i\n",
data->gpio.base, data->gpio.base +
data->gpio.ngpio - 1);
}
}
#endif
return 0;
exit:
pca9532_destroy_devices(data, i);
return err;
}
static int pca9532_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct pca9532_data *data = i2c_get_clientdata(client);
struct pca9532_platform_data *pca9532_pdata = client->dev.platform_data;
int err;
if (!pca9532_pdata)
return -EIO;
if (!i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_BYTE_DATA))
return -EIO;
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (!data)
return -ENOMEM;
data->chip_info = &pca9532_chip_info_tbl[id->driver_data];
dev_info(&client->dev, "setting platform data\n");
i2c_set_clientdata(client, data);
data->client = client;
mutex_init(&data->update_lock);
err = pca9532_configure(client, data, pca9532_pdata);
if (err)
kfree(data);
return err;
}
static int pca9532_remove(struct i2c_client *client)
{
struct pca9532_data *data = i2c_get_clientdata(client);
int err;
err = pca9532_destroy_devices(data, data->chip_info->num_leds);
if (err)
return err;
kfree(data);
return 0;
}
static int __init pca9532_init(void)
{
return i2c_add_driver(&pca9532_driver);
}
static void __exit pca9532_exit(void)
{
i2c_del_driver(&pca9532_driver);
}
MODULE_AUTHOR("Riku Voipio");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("PCA 9532 LED dimmer");
module_init(pca9532_init);
module_exit(pca9532_exit);
| gpl-2.0 |
ajfink/android_kernel_lge_e7lte | arch/arm/mach-msm/proc_comm.c | 3194 | 3925 | /* arch/arm/mach-msm/proc_comm.c
*
* Copyright (C) 2007-2008 Google, Inc.
* Copyright (c) 2009-2012, The Linux Foundation. All rights reserved.
* Author: Brian Swetland <swetland@google.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/io.h>
#include <linux/spinlock.h>
#include <linux/module.h>
#include <mach/msm_iomap.h>
#include <mach/system.h>
#include <mach/proc_comm.h>
#include "smd_private.h"
static inline void notify_other_proc_comm(void)
{
/* Make sure the write completes before interrupt */
wmb();
#if defined(CONFIG_ARCH_MSM7X30)
__raw_writel(1 << 6, MSM_APCS_GCC_BASE + 0x8);
#elif defined(CONFIG_ARCH_MSM8X60)
__raw_writel(1 << 5, MSM_GCC_BASE + 0x8);
#else
__raw_writel(1, MSM_CSR_BASE + 0x400 + (6) * 4);
#endif
}
#define APP_COMMAND 0x00
#define APP_STATUS 0x04
#define APP_DATA1 0x08
#define APP_DATA2 0x0C
#define MDM_COMMAND 0x10
#define MDM_STATUS 0x14
#define MDM_DATA1 0x18
#define MDM_DATA2 0x1C
static DEFINE_SPINLOCK(proc_comm_lock);
static int msm_proc_comm_disable;
/* Poll for a state change, checking for possible
* modem crashes along the way (so we don't wait
* forever while the ARM9 is blowing up.
*
* Return an error in the event of a modem crash and
* restart so the msm_proc_comm() routine can restart
* the operation from the beginning.
*/
static int proc_comm_wait_for(unsigned addr, unsigned value)
{
while (1) {
/* Barrier here prevents excessive spinning */
mb();
if (readl_relaxed(addr) == value)
return 0;
if (smsm_check_for_modem_crash())
return -EAGAIN;
udelay(5);
}
}
void msm_proc_comm_reset_modem_now(void)
{
unsigned base = (unsigned)MSM_SHARED_RAM_BASE;
unsigned long flags;
spin_lock_irqsave(&proc_comm_lock, flags);
again:
if (proc_comm_wait_for(base + MDM_STATUS, PCOM_READY))
goto again;
writel_relaxed(PCOM_RESET_MODEM, base + APP_COMMAND);
writel_relaxed(0, base + APP_DATA1);
writel_relaxed(0, base + APP_DATA2);
spin_unlock_irqrestore(&proc_comm_lock, flags);
/* Make sure the writes complete before notifying the other side */
wmb();
notify_other_proc_comm();
return;
}
EXPORT_SYMBOL(msm_proc_comm_reset_modem_now);
int msm_proc_comm(unsigned cmd, unsigned *data1, unsigned *data2)
{
unsigned base = (unsigned)MSM_SHARED_RAM_BASE;
unsigned long flags;
int ret;
spin_lock_irqsave(&proc_comm_lock, flags);
if (msm_proc_comm_disable) {
ret = -EIO;
goto end;
}
again:
if (proc_comm_wait_for(base + MDM_STATUS, PCOM_READY))
goto again;
writel_relaxed(cmd, base + APP_COMMAND);
writel_relaxed(data1 ? *data1 : 0, base + APP_DATA1);
writel_relaxed(data2 ? *data2 : 0, base + APP_DATA2);
/* Make sure the writes complete before notifying the other side */
wmb();
notify_other_proc_comm();
if (proc_comm_wait_for(base + APP_COMMAND, PCOM_CMD_DONE))
goto again;
if (readl_relaxed(base + APP_STATUS) == PCOM_CMD_SUCCESS) {
if (data1)
*data1 = readl_relaxed(base + APP_DATA1);
if (data2)
*data2 = readl_relaxed(base + APP_DATA2);
ret = 0;
} else {
ret = -EIO;
}
writel_relaxed(PCOM_CMD_IDLE, base + APP_COMMAND);
switch (cmd) {
case PCOM_RESET_CHIP:
case PCOM_RESET_CHIP_IMM:
case PCOM_RESET_APPS:
msm_proc_comm_disable = 1;
printk(KERN_ERR "msm: proc_comm: proc comm disabled\n");
break;
}
end:
/* Make sure the writes complete before returning */
wmb();
spin_unlock_irqrestore(&proc_comm_lock, flags);
return ret;
}
EXPORT_SYMBOL(msm_proc_comm);
| gpl-2.0 |
crazyleen/Linux-Crystal | arch/arm/mach-omap1/leds-h2p2-debug.c | 3962 | 3222 | /*
* linux/arch/arm/mach-omap1/leds-h2p2-debug.c
*
* Copyright 2003 by Texas Instruments Incorporated
*
* There are 16 LEDs on the debug board (all green); four may be used
* for logical 'green', 'amber', 'red', and 'blue' (after "claiming").
*
* The "surfer" expansion board and H2 sample board also have two-color
* green+red LEDs (in parallel), used here for timer and idle indicators.
*/
#include <linux/init.h>
#include <linux/kernel_stat.h>
#include <linux/sched.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <asm/leds.h>
#include <asm/system.h>
#include <asm/mach-types.h>
#include <plat/fpga.h>
#include <mach/gpio.h>
#include "leds.h"
#define GPIO_LED_RED 3
#define GPIO_LED_GREEN OMAP_MPUIO(4)
#define LED_STATE_ENABLED 0x01
#define LED_STATE_CLAIMED 0x02
#define LED_TIMER_ON 0x04
#define GPIO_IDLE GPIO_LED_GREEN
#define GPIO_TIMER GPIO_LED_RED
void h2p2_dbg_leds_event(led_event_t evt)
{
unsigned long flags;
static struct h2p2_dbg_fpga __iomem *fpga;
static u16 led_state, hw_led_state;
local_irq_save(flags);
if (!(led_state & LED_STATE_ENABLED) && evt != led_start)
goto done;
switch (evt) {
case led_start:
if (!fpga)
fpga = ioremap(H2P2_DBG_FPGA_START,
H2P2_DBG_FPGA_SIZE);
if (fpga) {
led_state |= LED_STATE_ENABLED;
__raw_writew(~0, &fpga->leds);
}
break;
case led_stop:
case led_halted:
/* all leds off during suspend or shutdown */
if (! machine_is_omap_perseus2()) {
gpio_set_value(GPIO_TIMER, 0);
gpio_set_value(GPIO_IDLE, 0);
}
__raw_writew(~0, &fpga->leds);
led_state &= ~LED_STATE_ENABLED;
if (evt == led_halted) {
iounmap(fpga);
fpga = NULL;
}
goto done;
case led_claim:
led_state |= LED_STATE_CLAIMED;
hw_led_state = 0;
break;
case led_release:
led_state &= ~LED_STATE_CLAIMED;
break;
#ifdef CONFIG_LEDS_TIMER
case led_timer:
led_state ^= LED_TIMER_ON;
if (machine_is_omap_perseus2())
hw_led_state ^= H2P2_DBG_FPGA_P2_LED_TIMER;
else {
gpio_set_value(GPIO_TIMER, led_state & LED_TIMER_ON);
goto done;
}
break;
#endif
#ifdef CONFIG_LEDS_CPU
case led_idle_start:
if (machine_is_omap_perseus2())
hw_led_state |= H2P2_DBG_FPGA_P2_LED_IDLE;
else {
gpio_set_value(GPIO_IDLE, 1);
goto done;
}
break;
case led_idle_end:
if (machine_is_omap_perseus2())
hw_led_state &= ~H2P2_DBG_FPGA_P2_LED_IDLE;
else {
gpio_set_value(GPIO_IDLE, 0);
goto done;
}
break;
#endif
case led_green_on:
hw_led_state |= H2P2_DBG_FPGA_LED_GREEN;
break;
case led_green_off:
hw_led_state &= ~H2P2_DBG_FPGA_LED_GREEN;
break;
case led_amber_on:
hw_led_state |= H2P2_DBG_FPGA_LED_AMBER;
break;
case led_amber_off:
hw_led_state &= ~H2P2_DBG_FPGA_LED_AMBER;
break;
case led_red_on:
hw_led_state |= H2P2_DBG_FPGA_LED_RED;
break;
case led_red_off:
hw_led_state &= ~H2P2_DBG_FPGA_LED_RED;
break;
case led_blue_on:
hw_led_state |= H2P2_DBG_FPGA_LED_BLUE;
break;
case led_blue_off:
hw_led_state &= ~H2P2_DBG_FPGA_LED_BLUE;
break;
default:
break;
}
/*
* Actually burn the LEDs
*/
if (led_state & LED_STATE_ENABLED)
__raw_writew(~hw_led_state, &fpga->leds);
done:
local_irq_restore(flags);
}
| gpl-2.0 |
NoelMacwan/android_kernel_sony_u8500 | arch/arm/mach-at91/at91sam9rl.c | 4730 | 8981 | /*
* arch/arm/mach-at91/at91sam9rl.c
*
* Copyright (C) 2005 SAN People
* Copyright (C) 2007 Atmel Corporation
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*/
#include <linux/module.h>
#include <asm/proc-fns.h>
#include <asm/irq.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/system_misc.h>
#include <mach/cpu.h>
#include <mach/at91_dbgu.h>
#include <mach/at91sam9rl.h>
#include <mach/at91_pmc.h>
#include <mach/at91_rstc.h>
#include "soc.h"
#include "generic.h"
#include "clock.h"
#include "sam9_smc.h"
/* --------------------------------------------------------------------
* Clocks
* -------------------------------------------------------------------- */
/*
* The peripheral clocks.
*/
static struct clk pioA_clk = {
.name = "pioA_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_PIOA,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk pioB_clk = {
.name = "pioB_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_PIOB,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk pioC_clk = {
.name = "pioC_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_PIOC,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk pioD_clk = {
.name = "pioD_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_PIOD,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk usart0_clk = {
.name = "usart0_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_US0,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk usart1_clk = {
.name = "usart1_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_US1,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk usart2_clk = {
.name = "usart2_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_US2,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk usart3_clk = {
.name = "usart3_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_US3,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk mmc_clk = {
.name = "mci_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_MCI,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk twi0_clk = {
.name = "twi0_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_TWI0,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk twi1_clk = {
.name = "twi1_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_TWI1,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk spi_clk = {
.name = "spi_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_SPI,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk ssc0_clk = {
.name = "ssc0_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_SSC0,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk ssc1_clk = {
.name = "ssc1_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_SSC1,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk tc0_clk = {
.name = "tc0_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_TC0,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk tc1_clk = {
.name = "tc1_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_TC1,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk tc2_clk = {
.name = "tc2_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_TC2,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk pwm_clk = {
.name = "pwm_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_PWMC,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk tsc_clk = {
.name = "tsc_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_TSC,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk dma_clk = {
.name = "dma_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_DMA,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk udphs_clk = {
.name = "udphs_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_UDPHS,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk lcdc_clk = {
.name = "lcdc_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_LCDC,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk ac97_clk = {
.name = "ac97_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_AC97C,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk *periph_clocks[] __initdata = {
&pioA_clk,
&pioB_clk,
&pioC_clk,
&pioD_clk,
&usart0_clk,
&usart1_clk,
&usart2_clk,
&usart3_clk,
&mmc_clk,
&twi0_clk,
&twi1_clk,
&spi_clk,
&ssc0_clk,
&ssc1_clk,
&tc0_clk,
&tc1_clk,
&tc2_clk,
&pwm_clk,
&tsc_clk,
&dma_clk,
&udphs_clk,
&lcdc_clk,
&ac97_clk,
// irq0
};
static struct clk_lookup periph_clocks_lookups[] = {
CLKDEV_CON_DEV_ID("hclk", "atmel_usba_udc", &utmi_clk),
CLKDEV_CON_DEV_ID("pclk", "atmel_usba_udc", &udphs_clk),
CLKDEV_CON_DEV_ID("t0_clk", "atmel_tcb.0", &tc0_clk),
CLKDEV_CON_DEV_ID("t1_clk", "atmel_tcb.0", &tc1_clk),
CLKDEV_CON_DEV_ID("t2_clk", "atmel_tcb.0", &tc2_clk),
CLKDEV_CON_DEV_ID("pclk", "ssc.0", &ssc0_clk),
CLKDEV_CON_DEV_ID("pclk", "ssc.1", &ssc1_clk),
CLKDEV_CON_ID("pioA", &pioA_clk),
CLKDEV_CON_ID("pioB", &pioB_clk),
CLKDEV_CON_ID("pioC", &pioC_clk),
CLKDEV_CON_ID("pioD", &pioD_clk),
};
static struct clk_lookup usart_clocks_lookups[] = {
CLKDEV_CON_DEV_ID("usart", "atmel_usart.0", &mck),
CLKDEV_CON_DEV_ID("usart", "atmel_usart.1", &usart0_clk),
CLKDEV_CON_DEV_ID("usart", "atmel_usart.2", &usart1_clk),
CLKDEV_CON_DEV_ID("usart", "atmel_usart.3", &usart2_clk),
CLKDEV_CON_DEV_ID("usart", "atmel_usart.4", &usart3_clk),
};
/*
* The two programmable clocks.
* You must configure pin multiplexing to bring these signals out.
*/
static struct clk pck0 = {
.name = "pck0",
.pmc_mask = AT91_PMC_PCK0,
.type = CLK_TYPE_PROGRAMMABLE,
.id = 0,
};
static struct clk pck1 = {
.name = "pck1",
.pmc_mask = AT91_PMC_PCK1,
.type = CLK_TYPE_PROGRAMMABLE,
.id = 1,
};
static void __init at91sam9rl_register_clocks(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(periph_clocks); i++)
clk_register(periph_clocks[i]);
clkdev_add_table(periph_clocks_lookups,
ARRAY_SIZE(periph_clocks_lookups));
clkdev_add_table(usart_clocks_lookups,
ARRAY_SIZE(usart_clocks_lookups));
clk_register(&pck0);
clk_register(&pck1);
}
static struct clk_lookup console_clock_lookup;
void __init at91sam9rl_set_console_clock(int id)
{
if (id >= ARRAY_SIZE(usart_clocks_lookups))
return;
console_clock_lookup.con_id = "usart";
console_clock_lookup.clk = usart_clocks_lookups[id].clk;
clkdev_add(&console_clock_lookup);
}
/* --------------------------------------------------------------------
* GPIO
* -------------------------------------------------------------------- */
static struct at91_gpio_bank at91sam9rl_gpio[] __initdata = {
{
.id = AT91SAM9RL_ID_PIOA,
.regbase = AT91SAM9RL_BASE_PIOA,
}, {
.id = AT91SAM9RL_ID_PIOB,
.regbase = AT91SAM9RL_BASE_PIOB,
}, {
.id = AT91SAM9RL_ID_PIOC,
.regbase = AT91SAM9RL_BASE_PIOC,
}, {
.id = AT91SAM9RL_ID_PIOD,
.regbase = AT91SAM9RL_BASE_PIOD,
}
};
/* --------------------------------------------------------------------
* AT91SAM9RL processor initialization
* -------------------------------------------------------------------- */
static void __init at91sam9rl_map_io(void)
{
unsigned long sram_size;
switch (at91_soc_initdata.cidr & AT91_CIDR_SRAMSIZ) {
case AT91_CIDR_SRAMSIZ_32K:
sram_size = 2 * SZ_16K;
break;
case AT91_CIDR_SRAMSIZ_16K:
default:
sram_size = SZ_16K;
}
/* Map SRAM */
at91_init_sram(0, AT91SAM9RL_SRAM_BASE, sram_size);
}
static void __init at91sam9rl_ioremap_registers(void)
{
at91_ioremap_shdwc(AT91SAM9RL_BASE_SHDWC);
at91_ioremap_rstc(AT91SAM9RL_BASE_RSTC);
at91_ioremap_ramc(0, AT91SAM9RL_BASE_SDRAMC, 512);
at91sam926x_ioremap_pit(AT91SAM9RL_BASE_PIT);
at91sam9_ioremap_smc(0, AT91SAM9RL_BASE_SMC);
at91_ioremap_matrix(AT91SAM9RL_BASE_MATRIX);
}
static void __init at91sam9rl_initialize(void)
{
arm_pm_idle = at91sam9_idle;
arm_pm_restart = at91sam9_alt_restart;
at91_extern_irq = (1 << AT91SAM9RL_ID_IRQ0);
/* Register GPIO subsystem */
at91_gpio_init(at91sam9rl_gpio, 4);
}
/* --------------------------------------------------------------------
* Interrupt initialization
* -------------------------------------------------------------------- */
/*
* The default interrupt priority levels (0 = lowest, 7 = highest).
*/
static unsigned int at91sam9rl_default_irq_priority[NR_AIC_IRQS] __initdata = {
7, /* Advanced Interrupt Controller */
7, /* System Peripherals */
1, /* Parallel IO Controller A */
1, /* Parallel IO Controller B */
1, /* Parallel IO Controller C */
1, /* Parallel IO Controller D */
5, /* USART 0 */
5, /* USART 1 */
5, /* USART 2 */
5, /* USART 3 */
0, /* Multimedia Card Interface */
6, /* Two-Wire Interface 0 */
6, /* Two-Wire Interface 1 */
5, /* Serial Peripheral Interface */
4, /* Serial Synchronous Controller 0 */
4, /* Serial Synchronous Controller 1 */
0, /* Timer Counter 0 */
0, /* Timer Counter 1 */
0, /* Timer Counter 2 */
0,
0, /* Touch Screen Controller */
0, /* DMA Controller */
2, /* USB Device High speed port */
2, /* LCD Controller */
6, /* AC97 Controller */
0,
0,
0,
0,
0,
0,
0, /* Advanced Interrupt Controller */
};
struct at91_init_soc __initdata at91sam9rl_soc = {
.map_io = at91sam9rl_map_io,
.default_irq_priority = at91sam9rl_default_irq_priority,
.ioremap_registers = at91sam9rl_ioremap_registers,
.register_clocks = at91sam9rl_register_clocks,
.init = at91sam9rl_initialize,
};
| gpl-2.0 |
HighwindONE/android_kernel_lge_msm8226 | arch/mips/vr41xx/common/rtc.c | 4986 | 2620 | /*
* NEC VR4100 series RTC platform device.
*
* Copyright (C) 2007 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/errno.h>
#include <linux/init.h>
#include <linux/smp.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <asm/cpu.h>
#include <asm/vr41xx/irq.h>
static struct resource rtc_type1_resource[] __initdata = {
{
.start = 0x0b0000c0,
.end = 0x0b0000df,
.flags = IORESOURCE_MEM,
},
{
.start = 0x0b0001c0,
.end = 0x0b0001df,
.flags = IORESOURCE_MEM,
},
{
.start = ELAPSEDTIME_IRQ,
.end = ELAPSEDTIME_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = RTCLONG1_IRQ,
.end = RTCLONG1_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static struct resource rtc_type2_resource[] __initdata = {
{
.start = 0x0f000100,
.end = 0x0f00011f,
.flags = IORESOURCE_MEM,
},
{
.start = 0x0f000120,
.end = 0x0f00013f,
.flags = IORESOURCE_MEM,
},
{
.start = ELAPSEDTIME_IRQ,
.end = ELAPSEDTIME_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = RTCLONG1_IRQ,
.end = RTCLONG1_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static int __init vr41xx_rtc_add(void)
{
struct platform_device *pdev;
struct resource *res;
unsigned int num;
int retval;
pdev = platform_device_alloc("RTC", -1);
if (!pdev)
return -ENOMEM;
switch (current_cpu_type()) {
case CPU_VR4111:
case CPU_VR4121:
res = rtc_type1_resource;
num = ARRAY_SIZE(rtc_type1_resource);
break;
case CPU_VR4122:
case CPU_VR4131:
case CPU_VR4133:
res = rtc_type2_resource;
num = ARRAY_SIZE(rtc_type2_resource);
break;
default:
retval = -ENODEV;
goto err_free_device;
}
retval = platform_device_add_resources(pdev, res, num);
if (retval)
goto err_free_device;
retval = platform_device_add(pdev);
if (retval)
goto err_free_device;
return 0;
err_free_device:
platform_device_put(pdev);
return retval;
}
device_initcall(vr41xx_rtc_add);
| gpl-2.0 |
shazzl/TW_i9205_JB | drivers/platform/x86/intel_scu_ipc.c | 7290 | 16554 | /*
* intel_scu_ipc.c: Driver for the Intel SCU IPC mechanism
*
* (C) Copyright 2008-2010 Intel Corporation
* Author: Sreedhara DS (sreedhara.ds@intel.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License.
*
* SCU running in ARC processor communicates with other entity running in IA
* core through IPC mechanism which in turn messaging between IA core ad SCU.
* SCU has two IPC mechanism IPC-1 and IPC-2. IPC-1 is used between IA32 and
* SCU where IPC-2 is used between P-Unit and SCU. This driver delas with
* IPC-1 Driver provides an API for power control unit registers (e.g. MSIC)
* along with other APIs.
*/
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/pm.h>
#include <linux/pci.h>
#include <linux/interrupt.h>
#include <linux/sfi.h>
#include <linux/module.h>
#include <asm/mrst.h>
#include <asm/intel_scu_ipc.h>
/* IPC defines the following message types */
#define IPCMSG_WATCHDOG_TIMER 0xF8 /* Set Kernel Watchdog Threshold */
#define IPCMSG_BATTERY 0xEF /* Coulomb Counter Accumulator */
#define IPCMSG_FW_UPDATE 0xFE /* Firmware update */
#define IPCMSG_PCNTRL 0xFF /* Power controller unit read/write */
#define IPCMSG_FW_REVISION 0xF4 /* Get firmware revision */
/* Command id associated with message IPCMSG_PCNTRL */
#define IPC_CMD_PCNTRL_W 0 /* Register write */
#define IPC_CMD_PCNTRL_R 1 /* Register read */
#define IPC_CMD_PCNTRL_M 2 /* Register read-modify-write */
/*
* IPC register summary
*
* IPC register blocks are memory mapped at fixed address of 0xFF11C000
* To read or write information to the SCU, driver writes to IPC-1 memory
* mapped registers (base address 0xFF11C000). The following is the IPC
* mechanism
*
* 1. IA core cDMI interface claims this transaction and converts it to a
* Transaction Layer Packet (TLP) message which is sent across the cDMI.
*
* 2. South Complex cDMI block receives this message and writes it to
* the IPC-1 register block, causing an interrupt to the SCU
*
* 3. SCU firmware decodes this interrupt and IPC message and the appropriate
* message handler is called within firmware.
*/
#define IPC_BASE_ADDR 0xFF11C000 /* IPC1 base register address */
#define IPC_MAX_ADDR 0x100 /* Maximum IPC regisers */
#define IPC_WWBUF_SIZE 20 /* IPC Write buffer Size */
#define IPC_RWBUF_SIZE 20 /* IPC Read buffer Size */
#define IPC_I2C_BASE 0xFF12B000 /* I2C control register base address */
#define IPC_I2C_MAX_ADDR 0x10 /* Maximum I2C regisers */
static int ipc_probe(struct pci_dev *dev, const struct pci_device_id *id);
static void ipc_remove(struct pci_dev *pdev);
struct intel_scu_ipc_dev {
struct pci_dev *pdev;
void __iomem *ipc_base;
void __iomem *i2c_base;
};
static struct intel_scu_ipc_dev ipcdev; /* Only one for now */
static int platform; /* Platform type */
/*
* IPC Read Buffer (Read Only):
* 16 byte buffer for receiving data from SCU, if IPC command
* processing results in response data
*/
#define IPC_READ_BUFFER 0x90
#define IPC_I2C_CNTRL_ADDR 0
#define I2C_DATA_ADDR 0x04
static DEFINE_MUTEX(ipclock); /* lock used to prevent multiple call to SCU */
/*
* Command Register (Write Only):
* A write to this register results in an interrupt to the SCU core processor
* Format:
* |rfu2(8) | size(8) | command id(4) | rfu1(3) | ioc(1) | command(8)|
*/
static inline void ipc_command(u32 cmd) /* Send ipc command */
{
writel(cmd, ipcdev.ipc_base);
}
/*
* IPC Write Buffer (Write Only):
* 16-byte buffer for sending data associated with IPC command to
* SCU. Size of the data is specified in the IPC_COMMAND_REG register
*/
static inline void ipc_data_writel(u32 data, u32 offset) /* Write ipc data */
{
writel(data, ipcdev.ipc_base + 0x80 + offset);
}
/*
* Status Register (Read Only):
* Driver will read this register to get the ready/busy status of the IPC
* block and error status of the IPC command that was just processed by SCU
* Format:
* |rfu3(8)|error code(8)|initiator id(8)|cmd id(4)|rfu1(2)|error(1)|busy(1)|
*/
static inline u8 ipc_read_status(void)
{
return __raw_readl(ipcdev.ipc_base + 0x04);
}
static inline u8 ipc_data_readb(u32 offset) /* Read ipc byte data */
{
return readb(ipcdev.ipc_base + IPC_READ_BUFFER + offset);
}
static inline u32 ipc_data_readl(u32 offset) /* Read ipc u32 data */
{
return readl(ipcdev.ipc_base + IPC_READ_BUFFER + offset);
}
static inline int busy_loop(void) /* Wait till scu status is busy */
{
u32 status = 0;
u32 loop_count = 0;
status = ipc_read_status();
while (status & 1) {
udelay(1); /* scu processing time is in few u secods */
status = ipc_read_status();
loop_count++;
/* break if scu doesn't reset busy bit after huge retry */
if (loop_count > 100000) {
dev_err(&ipcdev.pdev->dev, "IPC timed out");
return -ETIMEDOUT;
}
}
if ((status >> 1) & 1)
return -EIO;
return 0;
}
/* Read/Write power control(PMIC in Langwell, MSIC in PenWell) registers */
static int pwr_reg_rdwr(u16 *addr, u8 *data, u32 count, u32 op, u32 id)
{
int nc;
u32 offset = 0;
int err;
u8 cbuf[IPC_WWBUF_SIZE] = { };
u32 *wbuf = (u32 *)&cbuf;
mutex_lock(&ipclock);
memset(cbuf, 0, sizeof(cbuf));
if (ipcdev.pdev == NULL) {
mutex_unlock(&ipclock);
return -ENODEV;
}
for (nc = 0; nc < count; nc++, offset += 2) {
cbuf[offset] = addr[nc];
cbuf[offset + 1] = addr[nc] >> 8;
}
if (id == IPC_CMD_PCNTRL_R) {
for (nc = 0, offset = 0; nc < count; nc++, offset += 4)
ipc_data_writel(wbuf[nc], offset);
ipc_command((count*2) << 16 | id << 12 | 0 << 8 | op);
} else if (id == IPC_CMD_PCNTRL_W) {
for (nc = 0; nc < count; nc++, offset += 1)
cbuf[offset] = data[nc];
for (nc = 0, offset = 0; nc < count; nc++, offset += 4)
ipc_data_writel(wbuf[nc], offset);
ipc_command((count*3) << 16 | id << 12 | 0 << 8 | op);
} else if (id == IPC_CMD_PCNTRL_M) {
cbuf[offset] = data[0];
cbuf[offset + 1] = data[1];
ipc_data_writel(wbuf[0], 0); /* Write wbuff */
ipc_command(4 << 16 | id << 12 | 0 << 8 | op);
}
err = busy_loop();
if (id == IPC_CMD_PCNTRL_R) { /* Read rbuf */
/* Workaround: values are read as 0 without memcpy_fromio */
memcpy_fromio(cbuf, ipcdev.ipc_base + 0x90, 16);
for (nc = 0; nc < count; nc++)
data[nc] = ipc_data_readb(nc);
}
mutex_unlock(&ipclock);
return err;
}
/**
* intel_scu_ipc_ioread8 - read a word via the SCU
* @addr: register on SCU
* @data: return pointer for read byte
*
* Read a single register. Returns 0 on success or an error code. All
* locking between SCU accesses is handled for the caller.
*
* This function may sleep.
*/
int intel_scu_ipc_ioread8(u16 addr, u8 *data)
{
return pwr_reg_rdwr(&addr, data, 1, IPCMSG_PCNTRL, IPC_CMD_PCNTRL_R);
}
EXPORT_SYMBOL(intel_scu_ipc_ioread8);
/**
* intel_scu_ipc_ioread16 - read a word via the SCU
* @addr: register on SCU
* @data: return pointer for read word
*
* Read a register pair. Returns 0 on success or an error code. All
* locking between SCU accesses is handled for the caller.
*
* This function may sleep.
*/
int intel_scu_ipc_ioread16(u16 addr, u16 *data)
{
u16 x[2] = {addr, addr + 1 };
return pwr_reg_rdwr(x, (u8 *)data, 2, IPCMSG_PCNTRL, IPC_CMD_PCNTRL_R);
}
EXPORT_SYMBOL(intel_scu_ipc_ioread16);
/**
* intel_scu_ipc_ioread32 - read a dword via the SCU
* @addr: register on SCU
* @data: return pointer for read dword
*
* Read four registers. Returns 0 on success or an error code. All
* locking between SCU accesses is handled for the caller.
*
* This function may sleep.
*/
int intel_scu_ipc_ioread32(u16 addr, u32 *data)
{
u16 x[4] = {addr, addr + 1, addr + 2, addr + 3};
return pwr_reg_rdwr(x, (u8 *)data, 4, IPCMSG_PCNTRL, IPC_CMD_PCNTRL_R);
}
EXPORT_SYMBOL(intel_scu_ipc_ioread32);
/**
* intel_scu_ipc_iowrite8 - write a byte via the SCU
* @addr: register on SCU
* @data: byte to write
*
* Write a single register. Returns 0 on success or an error code. All
* locking between SCU accesses is handled for the caller.
*
* This function may sleep.
*/
int intel_scu_ipc_iowrite8(u16 addr, u8 data)
{
return pwr_reg_rdwr(&addr, &data, 1, IPCMSG_PCNTRL, IPC_CMD_PCNTRL_W);
}
EXPORT_SYMBOL(intel_scu_ipc_iowrite8);
/**
* intel_scu_ipc_iowrite16 - write a word via the SCU
* @addr: register on SCU
* @data: word to write
*
* Write two registers. Returns 0 on success or an error code. All
* locking between SCU accesses is handled for the caller.
*
* This function may sleep.
*/
int intel_scu_ipc_iowrite16(u16 addr, u16 data)
{
u16 x[2] = {addr, addr + 1 };
return pwr_reg_rdwr(x, (u8 *)&data, 2, IPCMSG_PCNTRL, IPC_CMD_PCNTRL_W);
}
EXPORT_SYMBOL(intel_scu_ipc_iowrite16);
/**
* intel_scu_ipc_iowrite32 - write a dword via the SCU
* @addr: register on SCU
* @data: dword to write
*
* Write four registers. Returns 0 on success or an error code. All
* locking between SCU accesses is handled for the caller.
*
* This function may sleep.
*/
int intel_scu_ipc_iowrite32(u16 addr, u32 data)
{
u16 x[4] = {addr, addr + 1, addr + 2, addr + 3};
return pwr_reg_rdwr(x, (u8 *)&data, 4, IPCMSG_PCNTRL, IPC_CMD_PCNTRL_W);
}
EXPORT_SYMBOL(intel_scu_ipc_iowrite32);
/**
* intel_scu_ipc_readvv - read a set of registers
* @addr: register list
* @data: bytes to return
* @len: length of array
*
* Read registers. Returns 0 on success or an error code. All
* locking between SCU accesses is handled for the caller.
*
* The largest array length permitted by the hardware is 5 items.
*
* This function may sleep.
*/
int intel_scu_ipc_readv(u16 *addr, u8 *data, int len)
{
return pwr_reg_rdwr(addr, data, len, IPCMSG_PCNTRL, IPC_CMD_PCNTRL_R);
}
EXPORT_SYMBOL(intel_scu_ipc_readv);
/**
* intel_scu_ipc_writev - write a set of registers
* @addr: register list
* @data: bytes to write
* @len: length of array
*
* Write registers. Returns 0 on success or an error code. All
* locking between SCU accesses is handled for the caller.
*
* The largest array length permitted by the hardware is 5 items.
*
* This function may sleep.
*
*/
int intel_scu_ipc_writev(u16 *addr, u8 *data, int len)
{
return pwr_reg_rdwr(addr, data, len, IPCMSG_PCNTRL, IPC_CMD_PCNTRL_W);
}
EXPORT_SYMBOL(intel_scu_ipc_writev);
/**
* intel_scu_ipc_update_register - r/m/w a register
* @addr: register address
* @bits: bits to update
* @mask: mask of bits to update
*
* Read-modify-write power control unit register. The first data argument
* must be register value and second is mask value
* mask is a bitmap that indicates which bits to update.
* 0 = masked. Don't modify this bit, 1 = modify this bit.
* returns 0 on success or an error code.
*
* This function may sleep. Locking between SCU accesses is handled
* for the caller.
*/
int intel_scu_ipc_update_register(u16 addr, u8 bits, u8 mask)
{
u8 data[2] = { bits, mask };
return pwr_reg_rdwr(&addr, data, 1, IPCMSG_PCNTRL, IPC_CMD_PCNTRL_M);
}
EXPORT_SYMBOL(intel_scu_ipc_update_register);
/**
* intel_scu_ipc_simple_command - send a simple command
* @cmd: command
* @sub: sub type
*
* Issue a simple command to the SCU. Do not use this interface if
* you must then access data as any data values may be overwritten
* by another SCU access by the time this function returns.
*
* This function may sleep. Locking for SCU accesses is handled for
* the caller.
*/
int intel_scu_ipc_simple_command(int cmd, int sub)
{
int err;
mutex_lock(&ipclock);
if (ipcdev.pdev == NULL) {
mutex_unlock(&ipclock);
return -ENODEV;
}
ipc_command(sub << 12 | cmd);
err = busy_loop();
mutex_unlock(&ipclock);
return err;
}
EXPORT_SYMBOL(intel_scu_ipc_simple_command);
/**
* intel_scu_ipc_command - command with data
* @cmd: command
* @sub: sub type
* @in: input data
* @inlen: input length in dwords
* @out: output data
* @outlein: output length in dwords
*
* Issue a command to the SCU which involves data transfers. Do the
* data copies under the lock but leave it for the caller to interpret
*/
int intel_scu_ipc_command(int cmd, int sub, u32 *in, int inlen,
u32 *out, int outlen)
{
int i, err;
mutex_lock(&ipclock);
if (ipcdev.pdev == NULL) {
mutex_unlock(&ipclock);
return -ENODEV;
}
for (i = 0; i < inlen; i++)
ipc_data_writel(*in++, 4 * i);
ipc_command((inlen << 16) | (sub << 12) | cmd);
err = busy_loop();
for (i = 0; i < outlen; i++)
*out++ = ipc_data_readl(4 * i);
mutex_unlock(&ipclock);
return err;
}
EXPORT_SYMBOL(intel_scu_ipc_command);
/*I2C commands */
#define IPC_I2C_WRITE 1 /* I2C Write command */
#define IPC_I2C_READ 2 /* I2C Read command */
/**
* intel_scu_ipc_i2c_cntrl - I2C read/write operations
* @addr: I2C address + command bits
* @data: data to read/write
*
* Perform an an I2C read/write operation via the SCU. All locking is
* handled for the caller. This function may sleep.
*
* Returns an error code or 0 on success.
*
* This has to be in the IPC driver for the locking.
*/
int intel_scu_ipc_i2c_cntrl(u32 addr, u32 *data)
{
u32 cmd = 0;
mutex_lock(&ipclock);
if (ipcdev.pdev == NULL) {
mutex_unlock(&ipclock);
return -ENODEV;
}
cmd = (addr >> 24) & 0xFF;
if (cmd == IPC_I2C_READ) {
writel(addr, ipcdev.i2c_base + IPC_I2C_CNTRL_ADDR);
/* Write not getting updated without delay */
mdelay(1);
*data = readl(ipcdev.i2c_base + I2C_DATA_ADDR);
} else if (cmd == IPC_I2C_WRITE) {
writel(*data, ipcdev.i2c_base + I2C_DATA_ADDR);
mdelay(1);
writel(addr, ipcdev.i2c_base + IPC_I2C_CNTRL_ADDR);
} else {
dev_err(&ipcdev.pdev->dev,
"intel_scu_ipc: I2C INVALID_CMD = 0x%x\n", cmd);
mutex_unlock(&ipclock);
return -EIO;
}
mutex_unlock(&ipclock);
return 0;
}
EXPORT_SYMBOL(intel_scu_ipc_i2c_cntrl);
/*
* Interrupt handler gets called when ioc bit of IPC_COMMAND_REG set to 1
* When ioc bit is set to 1, caller api must wait for interrupt handler called
* which in turn unlocks the caller api. Currently this is not used
*
* This is edge triggered so we need take no action to clear anything
*/
static irqreturn_t ioc(int irq, void *dev_id)
{
return IRQ_HANDLED;
}
/**
* ipc_probe - probe an Intel SCU IPC
* @dev: the PCI device matching
* @id: entry in the match table
*
* Enable and install an intel SCU IPC. This appears in the PCI space
* but uses some hard coded addresses as well.
*/
static int ipc_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
int err;
resource_size_t pci_resource;
if (ipcdev.pdev) /* We support only one SCU */
return -EBUSY;
ipcdev.pdev = pci_dev_get(dev);
err = pci_enable_device(dev);
if (err)
return err;
err = pci_request_regions(dev, "intel_scu_ipc");
if (err)
return err;
pci_resource = pci_resource_start(dev, 0);
if (!pci_resource)
return -ENOMEM;
if (request_irq(dev->irq, ioc, 0, "intel_scu_ipc", &ipcdev))
return -EBUSY;
ipcdev.ipc_base = ioremap_nocache(IPC_BASE_ADDR, IPC_MAX_ADDR);
if (!ipcdev.ipc_base)
return -ENOMEM;
ipcdev.i2c_base = ioremap_nocache(IPC_I2C_BASE, IPC_I2C_MAX_ADDR);
if (!ipcdev.i2c_base) {
iounmap(ipcdev.ipc_base);
return -ENOMEM;
}
intel_scu_devices_create();
return 0;
}
/**
* ipc_remove - remove a bound IPC device
* @pdev: PCI device
*
* In practice the SCU is not removable but this function is also
* called for each device on a module unload or cleanup which is the
* path that will get used.
*
* Free up the mappings and release the PCI resources
*/
static void ipc_remove(struct pci_dev *pdev)
{
free_irq(pdev->irq, &ipcdev);
pci_release_regions(pdev);
pci_dev_put(ipcdev.pdev);
iounmap(ipcdev.ipc_base);
iounmap(ipcdev.i2c_base);
ipcdev.pdev = NULL;
intel_scu_devices_destroy();
}
static DEFINE_PCI_DEVICE_TABLE(pci_ids) = {
{PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x082a)},
{ 0,}
};
MODULE_DEVICE_TABLE(pci, pci_ids);
static struct pci_driver ipc_driver = {
.name = "intel_scu_ipc",
.id_table = pci_ids,
.probe = ipc_probe,
.remove = ipc_remove,
};
static int __init intel_scu_ipc_init(void)
{
platform = mrst_identify_cpu();
if (platform == 0)
return -ENODEV;
return pci_register_driver(&ipc_driver);
}
static void __exit intel_scu_ipc_exit(void)
{
pci_unregister_driver(&ipc_driver);
}
MODULE_AUTHOR("Sreedhara DS <sreedhara.ds@intel.com>");
MODULE_DESCRIPTION("Intel SCU IPC driver");
MODULE_LICENSE("GPL");
module_init(intel_scu_ipc_init);
module_exit(intel_scu_ipc_exit);
| gpl-2.0 |
RadonX-MM/kernel | lib/prio_heap.c | 12666 | 1477 | /*
* Simple insertion-only static-sized priority heap containing
* pointers, based on CLR, chapter 7
*/
#include <linux/slab.h>
#include <linux/prio_heap.h>
int heap_init(struct ptr_heap *heap, size_t size, gfp_t gfp_mask,
int (*gt)(void *, void *))
{
heap->ptrs = kmalloc(size, gfp_mask);
if (!heap->ptrs)
return -ENOMEM;
heap->size = 0;
heap->max = size / sizeof(void *);
heap->gt = gt;
return 0;
}
void heap_free(struct ptr_heap *heap)
{
kfree(heap->ptrs);
}
void *heap_insert(struct ptr_heap *heap, void *p)
{
void *res;
void **ptrs = heap->ptrs;
int pos;
if (heap->size < heap->max) {
/* Heap insertion */
pos = heap->size++;
while (pos > 0 && heap->gt(p, ptrs[(pos-1)/2])) {
ptrs[pos] = ptrs[(pos-1)/2];
pos = (pos-1)/2;
}
ptrs[pos] = p;
return NULL;
}
/* The heap is full, so something will have to be dropped */
/* If the new pointer is greater than the current max, drop it */
if (heap->gt(p, ptrs[0]))
return p;
/* Replace the current max and heapify */
res = ptrs[0];
ptrs[0] = p;
pos = 0;
while (1) {
int left = 2 * pos + 1;
int right = 2 * pos + 2;
int largest = pos;
if (left < heap->size && heap->gt(ptrs[left], p))
largest = left;
if (right < heap->size && heap->gt(ptrs[right], ptrs[largest]))
largest = right;
if (largest == pos)
break;
/* Push p down the heap one level and bump one up */
ptrs[pos] = ptrs[largest];
ptrs[largest] = p;
pos = largest;
}
return res;
}
| gpl-2.0 |
abenagiel/android_kernel_fih_msm7x30 | lib/prio_heap.c | 12666 | 1477 | /*
* Simple insertion-only static-sized priority heap containing
* pointers, based on CLR, chapter 7
*/
#include <linux/slab.h>
#include <linux/prio_heap.h>
int heap_init(struct ptr_heap *heap, size_t size, gfp_t gfp_mask,
int (*gt)(void *, void *))
{
heap->ptrs = kmalloc(size, gfp_mask);
if (!heap->ptrs)
return -ENOMEM;
heap->size = 0;
heap->max = size / sizeof(void *);
heap->gt = gt;
return 0;
}
void heap_free(struct ptr_heap *heap)
{
kfree(heap->ptrs);
}
void *heap_insert(struct ptr_heap *heap, void *p)
{
void *res;
void **ptrs = heap->ptrs;
int pos;
if (heap->size < heap->max) {
/* Heap insertion */
pos = heap->size++;
while (pos > 0 && heap->gt(p, ptrs[(pos-1)/2])) {
ptrs[pos] = ptrs[(pos-1)/2];
pos = (pos-1)/2;
}
ptrs[pos] = p;
return NULL;
}
/* The heap is full, so something will have to be dropped */
/* If the new pointer is greater than the current max, drop it */
if (heap->gt(p, ptrs[0]))
return p;
/* Replace the current max and heapify */
res = ptrs[0];
ptrs[0] = p;
pos = 0;
while (1) {
int left = 2 * pos + 1;
int right = 2 * pos + 2;
int largest = pos;
if (left < heap->size && heap->gt(ptrs[left], p))
largest = left;
if (right < heap->size && heap->gt(ptrs[right], ptrs[largest]))
largest = right;
if (largest == pos)
break;
/* Push p down the heap one level and bump one up */
ptrs[pos] = ptrs[largest];
ptrs[largest] = p;
pos = largest;
}
return res;
}
| gpl-2.0 |
unixbhaskar/Linux-kernel | arch/arm/kernel/smp_twd.c | 123 | 9024 | /*
* linux/arch/arm/kernel/smp_twd.c
*
* Copyright (C) 2002 ARM Ltd.
* 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.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/smp.h>
#include <linux/jiffies.h>
#include <linux/clockchips.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/of_irq.h>
#include <linux/of_address.h>
#include <asm/smp_plat.h>
#include <asm/smp_twd.h>
#include <asm/localtimer.h>
/* set up by the platform code */
static void __iomem *twd_base;
static struct clk *twd_clk;
static unsigned long twd_timer_rate;
static DEFINE_PER_CPU(bool, percpu_setup_called);
static struct clock_event_device __percpu **twd_evt;
static int twd_ppi;
static void twd_set_mode(enum clock_event_mode mode,
struct clock_event_device *clk)
{
unsigned long ctrl;
switch (mode) {
case CLOCK_EVT_MODE_PERIODIC:
ctrl = TWD_TIMER_CONTROL_ENABLE | TWD_TIMER_CONTROL_IT_ENABLE
| TWD_TIMER_CONTROL_PERIODIC;
__raw_writel(DIV_ROUND_CLOSEST(twd_timer_rate, HZ),
twd_base + TWD_TIMER_LOAD);
break;
case CLOCK_EVT_MODE_ONESHOT:
/* period set, and timer enabled in 'next_event' hook */
ctrl = TWD_TIMER_CONTROL_IT_ENABLE | TWD_TIMER_CONTROL_ONESHOT;
break;
case CLOCK_EVT_MODE_UNUSED:
case CLOCK_EVT_MODE_SHUTDOWN:
default:
ctrl = 0;
}
__raw_writel(ctrl, twd_base + TWD_TIMER_CONTROL);
}
static int twd_set_next_event(unsigned long evt,
struct clock_event_device *unused)
{
unsigned long ctrl = __raw_readl(twd_base + TWD_TIMER_CONTROL);
ctrl |= TWD_TIMER_CONTROL_ENABLE;
__raw_writel(evt, twd_base + TWD_TIMER_COUNTER);
__raw_writel(ctrl, twd_base + TWD_TIMER_CONTROL);
return 0;
}
/*
* local_timer_ack: checks for a local timer interrupt.
*
* If a local timer interrupt has occurred, acknowledge and return 1.
* Otherwise, return 0.
*/
static int twd_timer_ack(void)
{
if (__raw_readl(twd_base + TWD_TIMER_INTSTAT)) {
__raw_writel(1, twd_base + TWD_TIMER_INTSTAT);
return 1;
}
return 0;
}
static void twd_timer_stop(struct clock_event_device *clk)
{
twd_set_mode(CLOCK_EVT_MODE_UNUSED, clk);
disable_percpu_irq(clk->irq);
}
#ifdef CONFIG_COMMON_CLK
/*
* Updates clockevent frequency when the cpu frequency changes.
* Called on the cpu that is changing frequency with interrupts disabled.
*/
static void twd_update_frequency(void *new_rate)
{
twd_timer_rate = *((unsigned long *) new_rate);
clockevents_update_freq(*__this_cpu_ptr(twd_evt), twd_timer_rate);
}
static int twd_rate_change(struct notifier_block *nb,
unsigned long flags, void *data)
{
struct clk_notifier_data *cnd = data;
/*
* The twd clock events must be reprogrammed to account for the new
* frequency. The timer is local to a cpu, so cross-call to the
* changing cpu.
*/
if (flags == POST_RATE_CHANGE)
smp_call_function(twd_update_frequency,
(void *)&cnd->new_rate, 1);
return NOTIFY_OK;
}
static struct notifier_block twd_clk_nb = {
.notifier_call = twd_rate_change,
};
static int twd_clk_init(void)
{
if (twd_evt && *__this_cpu_ptr(twd_evt) && !IS_ERR(twd_clk))
return clk_notifier_register(twd_clk, &twd_clk_nb);
return 0;
}
core_initcall(twd_clk_init);
#elif defined (CONFIG_CPU_FREQ)
#include <linux/cpufreq.h>
/*
* Updates clockevent frequency when the cpu frequency changes.
* Called on the cpu that is changing frequency with interrupts disabled.
*/
static void twd_update_frequency(void *data)
{
twd_timer_rate = clk_get_rate(twd_clk);
clockevents_update_freq(*__this_cpu_ptr(twd_evt), twd_timer_rate);
}
static int twd_cpufreq_transition(struct notifier_block *nb,
unsigned long state, void *data)
{
struct cpufreq_freqs *freqs = data;
/*
* The twd clock events must be reprogrammed to account for the new
* frequency. The timer is local to a cpu, so cross-call to the
* changing cpu.
*/
if (state == CPUFREQ_POSTCHANGE || state == CPUFREQ_RESUMECHANGE)
smp_call_function_single(freqs->cpu, twd_update_frequency,
NULL, 1);
return NOTIFY_OK;
}
static struct notifier_block twd_cpufreq_nb = {
.notifier_call = twd_cpufreq_transition,
};
static int twd_cpufreq_init(void)
{
if (twd_evt && *__this_cpu_ptr(twd_evt) && !IS_ERR(twd_clk))
return cpufreq_register_notifier(&twd_cpufreq_nb,
CPUFREQ_TRANSITION_NOTIFIER);
return 0;
}
core_initcall(twd_cpufreq_init);
#endif
static void __cpuinit twd_calibrate_rate(void)
{
unsigned long count;
u64 waitjiffies;
/*
* If this is the first time round, we need to work out how fast
* the timer ticks
*/
if (twd_timer_rate == 0) {
printk(KERN_INFO "Calibrating local timer... ");
/* Wait for a tick to start */
waitjiffies = get_jiffies_64() + 1;
while (get_jiffies_64() < waitjiffies)
udelay(10);
/* OK, now the tick has started, let's get the timer going */
waitjiffies += 5;
/* enable, no interrupt or reload */
__raw_writel(0x1, twd_base + TWD_TIMER_CONTROL);
/* maximum value */
__raw_writel(0xFFFFFFFFU, twd_base + TWD_TIMER_COUNTER);
while (get_jiffies_64() < waitjiffies)
udelay(10);
count = __raw_readl(twd_base + TWD_TIMER_COUNTER);
twd_timer_rate = (0xFFFFFFFFU - count) * (HZ / 5);
printk("%lu.%02luMHz.\n", twd_timer_rate / 1000000,
(twd_timer_rate / 10000) % 100);
}
}
static irqreturn_t twd_handler(int irq, void *dev_id)
{
struct clock_event_device *evt = *(struct clock_event_device **)dev_id;
if (twd_timer_ack()) {
evt->event_handler(evt);
return IRQ_HANDLED;
}
return IRQ_NONE;
}
static void twd_get_clock(struct device_node *np)
{
int err;
if (np)
twd_clk = of_clk_get(np, 0);
else
twd_clk = clk_get_sys("smp_twd", NULL);
if (IS_ERR(twd_clk)) {
pr_err("smp_twd: clock not found %d\n", (int) PTR_ERR(twd_clk));
return;
}
err = clk_prepare_enable(twd_clk);
if (err) {
pr_err("smp_twd: clock failed to prepare+enable: %d\n", err);
clk_put(twd_clk);
return;
}
twd_timer_rate = clk_get_rate(twd_clk);
}
/*
* Setup the local clock events for a CPU.
*/
static int __cpuinit twd_timer_setup(struct clock_event_device *clk)
{
struct clock_event_device **this_cpu_clk;
int cpu = smp_processor_id();
/*
* If the basic setup for this CPU has been done before don't
* bother with the below.
*/
if (per_cpu(percpu_setup_called, cpu)) {
__raw_writel(0, twd_base + TWD_TIMER_CONTROL);
clockevents_register_device(*__this_cpu_ptr(twd_evt));
enable_percpu_irq(clk->irq, 0);
return 0;
}
per_cpu(percpu_setup_called, cpu) = true;
twd_calibrate_rate();
/*
* The following is done once per CPU the first time .setup() is
* called.
*/
__raw_writel(0, twd_base + TWD_TIMER_CONTROL);
clk->name = "local_timer";
clk->features = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT |
CLOCK_EVT_FEAT_C3STOP;
clk->rating = 350;
clk->set_mode = twd_set_mode;
clk->set_next_event = twd_set_next_event;
clk->irq = twd_ppi;
this_cpu_clk = __this_cpu_ptr(twd_evt);
*this_cpu_clk = clk;
clockevents_config_and_register(clk, twd_timer_rate,
0xf, 0xffffffff);
enable_percpu_irq(clk->irq, 0);
return 0;
}
static struct local_timer_ops twd_lt_ops __cpuinitdata = {
.setup = twd_timer_setup,
.stop = twd_timer_stop,
};
static int __init twd_local_timer_common_register(struct device_node *np)
{
int err;
twd_evt = alloc_percpu(struct clock_event_device *);
if (!twd_evt) {
err = -ENOMEM;
goto out_free;
}
err = request_percpu_irq(twd_ppi, twd_handler, "twd", twd_evt);
if (err) {
pr_err("twd: can't register interrupt %d (%d)\n", twd_ppi, err);
goto out_free;
}
err = local_timer_register(&twd_lt_ops);
if (err)
goto out_irq;
twd_get_clock(np);
return 0;
out_irq:
free_percpu_irq(twd_ppi, twd_evt);
out_free:
iounmap(twd_base);
twd_base = NULL;
free_percpu(twd_evt);
return err;
}
int __init twd_local_timer_register(struct twd_local_timer *tlt)
{
if (twd_base || twd_evt)
return -EBUSY;
twd_ppi = tlt->res[1].start;
twd_base = ioremap(tlt->res[0].start, resource_size(&tlt->res[0]));
if (!twd_base)
return -ENOMEM;
return twd_local_timer_common_register(NULL);
}
#ifdef CONFIG_OF
static void __init twd_local_timer_of_register(struct device_node *np)
{
int err;
if (!is_smp() || !setup_max_cpus)
return;
twd_ppi = irq_of_parse_and_map(np, 0);
if (!twd_ppi) {
err = -EINVAL;
goto out;
}
twd_base = of_iomap(np, 0);
if (!twd_base) {
err = -ENOMEM;
goto out;
}
err = twd_local_timer_common_register(np);
out:
WARN(err, "twd_local_timer_of_register failed (%d)\n", err);
}
CLOCKSOURCE_OF_DECLARE(arm_twd_a9, "arm,cortex-a9-twd-timer", twd_local_timer_of_register);
CLOCKSOURCE_OF_DECLARE(arm_twd_a5, "arm,cortex-a5-twd-timer", twd_local_timer_of_register);
CLOCKSOURCE_OF_DECLARE(arm_twd_11mp, "arm,arm11mp-twd-timer", twd_local_timer_of_register);
#endif
| gpl-2.0 |
nasser-embedded/linux | arch/arm/mach-at91/board-picotux200.c | 1659 | 4544 | /*
* linux/arch/arm/mach-at91/board-picotux200.c
*
* Copyright (C) 2005 SAN People
* Copyright (C) 2007 Kleinhenz Elektronik GmbH
*
* 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/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 <mach/hardware.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/board.h>
#include <mach/gpio.h>
#include <mach/at91rm9200_mc.h>
#include "generic.h"
/*
* Serial port configuration.
* 0 .. 3 = USART0 .. USART3
* 4 = DBGU
*/
static struct at91_uart_config __initdata picotux200_uart_config = {
.console_tty = 0, /* ttyS0 */
.nr_tty = 2,
.tty_map = { 4, 1, -1, -1, -1 } /* ttyS0, ..., ttyS4 */
};
static void __init picotux200_map_io(void)
{
/* Initialize processor: 18.432 MHz crystal */
at91rm9200_initialize(18432000, AT91RM9200_BGA);
/* Setup the serial ports and console */
at91_init_serial(&picotux200_uart_config);
}
static void __init picotux200_init_irq(void)
{
at91rm9200_init_interrupts(NULL);
}
static struct at91_eth_data __initdata picotux200_eth_data = {
.phy_irq_pin = AT91_PIN_PC4,
.is_rmii = 1,
};
static struct at91_usbh_data __initdata picotux200_usbh_data = {
.ports = 1,
};
// static struct at91_udc_data __initdata picotux200_udc_data = {
// .vbus_pin = AT91_PIN_PD4,
// .pullup_pin = AT91_PIN_PD5,
// };
static struct at91_mmc_data __initdata picotux200_mmc_data = {
.det_pin = AT91_PIN_PB27,
.slot_b = 0,
.wire4 = 1,
.wp_pin = AT91_PIN_PA17,
};
// static struct spi_board_info picotux200_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
// };
#define PICOTUX200_FLASH_BASE AT91_CHIPSELECT_0
#define PICOTUX200_FLASH_SIZE SZ_4M
static struct physmap_flash_data picotux200_flash_data = {
.width = 2,
};
static struct resource picotux200_flash_resource = {
.start = PICOTUX200_FLASH_BASE,
.end = PICOTUX200_FLASH_BASE + PICOTUX200_FLASH_SIZE - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device picotux200_flash = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &picotux200_flash_data,
},
.resource = &picotux200_flash_resource,
.num_resources = 1,
};
static void __init picotux200_board_init(void)
{
/* Serial */
at91_add_device_serial();
/* Ethernet */
at91_add_device_eth(&picotux200_eth_data);
/* USB Host */
at91_add_device_usbh(&picotux200_usbh_data);
/* USB Device */
// at91_add_device_udc(&picotux200_udc_data);
// at91_set_multi_drive(picotux200_udc_data.pullup_pin, 1); /* pullup_pin is connected to reset */
/* I2C */
at91_add_device_i2c(NULL, 0);
/* SPI */
// at91_add_device_spi(picotux200_spi_devices, ARRAY_SIZE(picotux200_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, &picotux200_mmc_data);
#endif
/* NOR Flash */
platform_device_register(&picotux200_flash);
}
MACHINE_START(PICOTUX2XX, "picotux 200")
/* Maintainer: Kleinhenz Elektronik GmbH */
.phys_io = AT91_BASE_SYS,
.io_pg_offst = (AT91_VA_BASE_SYS >> 18) & 0xfffc,
.boot_params = AT91_SDRAM_BASE + 0x100,
.timer = &at91rm9200_timer,
.map_io = picotux200_map_io,
.init_irq = picotux200_init_irq,
.init_machine = picotux200_board_init,
MACHINE_END
| gpl-2.0 |
Sangsub/android-samsung-2.6.35-gingerbread | arch/arm/mach-loki/lb88rc8480-setup.c | 1659 | 2594 | /*
* arch/arm/mach-loki/lb88rc8480-setup.c
*
* Marvell LB88RC8480 Development Board Setup
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/irq.h>
#include <linux/mtd/physmap.h>
#include <linux/mtd/nand.h>
#include <linux/timer.h>
#include <linux/ata_platform.h>
#include <linux/mv643xx_eth.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <mach/loki.h>
#include "common.h"
#define LB88RC8480_FLASH_BOOT_CS_BASE 0xf8000000
#define LB88RC8480_FLASH_BOOT_CS_SIZE SZ_128M
#define LB88RC8480_NOR_BOOT_BASE 0xff000000
#define LB88RC8480_NOR_BOOT_SIZE SZ_16M
static struct mtd_partition lb88rc8480_boot_flash_parts[] = {
{
.name = "kernel",
.offset = 0,
.size = SZ_2M,
}, {
.name = "root-fs",
.offset = SZ_2M,
.size = (SZ_8M + SZ_4M + SZ_1M),
}, {
.name = "u-boot",
.offset = (SZ_8M + SZ_4M + SZ_2M + SZ_1M),
.size = SZ_1M,
},
};
static struct physmap_flash_data lb88rc8480_boot_flash_data = {
.parts = lb88rc8480_boot_flash_parts,
.nr_parts = ARRAY_SIZE(lb88rc8480_boot_flash_parts),
.width = 1, /* 8 bit bus width */
};
static struct resource lb88rc8480_boot_flash_resource = {
.flags = IORESOURCE_MEM,
.start = LB88RC8480_NOR_BOOT_BASE,
.end = LB88RC8480_NOR_BOOT_BASE + LB88RC8480_NOR_BOOT_SIZE - 1,
};
static struct platform_device lb88rc8480_boot_flash = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &lb88rc8480_boot_flash_data,
},
.num_resources = 1,
.resource = &lb88rc8480_boot_flash_resource,
};
static struct mv643xx_eth_platform_data lb88rc8480_ge0_data = {
.phy_addr = MV643XX_ETH_PHY_ADDR(1),
.mac_addr = { 0x00, 0x50, 0x43, 0x11, 0x22, 0x33 },
};
static void __init lb88rc8480_init(void)
{
/*
* Basic setup. Needs to be called early.
*/
loki_init();
loki_ge0_init(&lb88rc8480_ge0_data);
loki_sas_init();
loki_uart0_init();
loki_uart1_init();
loki_setup_dev_boot_win(LB88RC8480_FLASH_BOOT_CS_BASE,
LB88RC8480_FLASH_BOOT_CS_SIZE);
platform_device_register(&lb88rc8480_boot_flash);
}
MACHINE_START(LB88RC8480, "Marvell LB88RC8480 Development Board")
/* Maintainer: Ke Wei <kewei@marvell.com> */
.phys_io = LOKI_REGS_PHYS_BASE,
.io_pg_offst = ((LOKI_REGS_VIRT_BASE) >> 18) & 0xfffc,
.boot_params = 0x00000100,
.init_machine = lb88rc8480_init,
.map_io = loki_map_io,
.init_irq = loki_init_irq,
.timer = &loki_timer,
MACHINE_END
| gpl-2.0 |
glewarne/S6-UniKernel | arch/x86/kernel/dumpstack_64.c | 1659 | 7261 | /*
* Copyright (C) 1991, 1992 Linus Torvalds
* Copyright (C) 2000, 2001, 2002 Andi Kleen, SuSE Labs
*/
#include <linux/kallsyms.h>
#include <linux/kprobes.h>
#include <linux/uaccess.h>
#include <linux/hardirq.h>
#include <linux/kdebug.h>
#include <linux/module.h>
#include <linux/ptrace.h>
#include <linux/kexec.h>
#include <linux/sysfs.h>
#include <linux/bug.h>
#include <linux/nmi.h>
#include <asm/stacktrace.h>
#define N_EXCEPTION_STACKS_END \
(N_EXCEPTION_STACKS + DEBUG_STKSZ/EXCEPTION_STKSZ - 2)
static char x86_stack_ids[][8] = {
[ DEBUG_STACK-1 ] = "#DB",
[ NMI_STACK-1 ] = "NMI",
[ DOUBLEFAULT_STACK-1 ] = "#DF",
[ STACKFAULT_STACK-1 ] = "#SS",
[ MCE_STACK-1 ] = "#MC",
#if DEBUG_STKSZ > EXCEPTION_STKSZ
[ N_EXCEPTION_STACKS ...
N_EXCEPTION_STACKS_END ] = "#DB[?]"
#endif
};
static unsigned long *in_exception_stack(unsigned cpu, unsigned long stack,
unsigned *usedp, char **idp)
{
unsigned k;
/*
* Iterate over all exception stacks, and figure out whether
* 'stack' is in one of them:
*/
for (k = 0; k < N_EXCEPTION_STACKS; k++) {
unsigned long end = per_cpu(orig_ist, cpu).ist[k];
/*
* Is 'stack' above this exception frame's end?
* If yes then skip to the next frame.
*/
if (stack >= end)
continue;
/*
* Is 'stack' above this exception frame's start address?
* If yes then we found the right frame.
*/
if (stack >= end - EXCEPTION_STKSZ) {
/*
* Make sure we only iterate through an exception
* stack once. If it comes up for the second time
* then there's something wrong going on - just
* break out and return NULL:
*/
if (*usedp & (1U << k))
break;
*usedp |= 1U << k;
*idp = x86_stack_ids[k];
return (unsigned long *)end;
}
/*
* If this is a debug stack, and if it has a larger size than
* the usual exception stacks, then 'stack' might still
* be within the lower portion of the debug stack:
*/
#if DEBUG_STKSZ > EXCEPTION_STKSZ
if (k == DEBUG_STACK - 1 && stack >= end - DEBUG_STKSZ) {
unsigned j = N_EXCEPTION_STACKS - 1;
/*
* Black magic. A large debug stack is composed of
* multiple exception stack entries, which we
* iterate through now. Dont look:
*/
do {
++j;
end -= EXCEPTION_STKSZ;
x86_stack_ids[j][4] = '1' +
(j - N_EXCEPTION_STACKS);
} while (stack < end - EXCEPTION_STKSZ);
if (*usedp & (1U << j))
break;
*usedp |= 1U << j;
*idp = x86_stack_ids[j];
return (unsigned long *)end;
}
#endif
}
return NULL;
}
static inline int
in_irq_stack(unsigned long *stack, unsigned long *irq_stack,
unsigned long *irq_stack_end)
{
return (stack >= irq_stack && stack < irq_stack_end);
}
/*
* x86-64 can have up to three kernel stacks:
* process stack
* interrupt stack
* severe exception (double fault, nmi, stack fault, debug, mce) hardware stack
*/
void dump_trace(struct task_struct *task, struct pt_regs *regs,
unsigned long *stack, unsigned long bp,
const struct stacktrace_ops *ops, void *data)
{
const unsigned cpu = get_cpu();
unsigned long *irq_stack_end =
(unsigned long *)per_cpu(irq_stack_ptr, cpu);
unsigned used = 0;
struct thread_info *tinfo;
int graph = 0;
unsigned long dummy;
if (!task)
task = current;
if (!stack) {
if (regs)
stack = (unsigned long *)regs->sp;
else if (task != current)
stack = (unsigned long *)task->thread.sp;
else
stack = &dummy;
}
if (!bp)
bp = stack_frame(task, regs);
/*
* Print function call entries in all stacks, starting at the
* current stack address. If the stacks consist of nested
* exceptions
*/
tinfo = task_thread_info(task);
for (;;) {
char *id;
unsigned long *estack_end;
estack_end = in_exception_stack(cpu, (unsigned long)stack,
&used, &id);
if (estack_end) {
if (ops->stack(data, id) < 0)
break;
bp = ops->walk_stack(tinfo, stack, bp, ops,
data, estack_end, &graph);
ops->stack(data, "<EOE>");
/*
* We link to the next stack via the
* second-to-last pointer (index -2 to end) in the
* exception stack:
*/
stack = (unsigned long *) estack_end[-2];
continue;
}
if (irq_stack_end) {
unsigned long *irq_stack;
irq_stack = irq_stack_end -
(IRQ_STACK_SIZE - 64) / sizeof(*irq_stack);
if (in_irq_stack(stack, irq_stack, irq_stack_end)) {
if (ops->stack(data, "IRQ") < 0)
break;
bp = ops->walk_stack(tinfo, stack, bp,
ops, data, irq_stack_end, &graph);
/*
* We link to the next stack (which would be
* the process stack normally) the last
* pointer (index -1 to end) in the IRQ stack:
*/
stack = (unsigned long *) (irq_stack_end[-1]);
irq_stack_end = NULL;
ops->stack(data, "EOI");
continue;
}
}
break;
}
/*
* This handles the process stack:
*/
bp = ops->walk_stack(tinfo, stack, bp, ops, data, NULL, &graph);
put_cpu();
}
EXPORT_SYMBOL(dump_trace);
void
show_stack_log_lvl(struct task_struct *task, struct pt_regs *regs,
unsigned long *sp, unsigned long bp, char *log_lvl)
{
unsigned long *irq_stack_end;
unsigned long *irq_stack;
unsigned long *stack;
int cpu;
int i;
preempt_disable();
cpu = smp_processor_id();
irq_stack_end = (unsigned long *)(per_cpu(irq_stack_ptr, cpu));
irq_stack = (unsigned long *)(per_cpu(irq_stack_ptr, cpu) - IRQ_STACK_SIZE);
/*
* Debugging aid: "show_stack(NULL, NULL);" prints the
* back trace for this cpu:
*/
if (sp == NULL) {
if (task)
sp = (unsigned long *)task->thread.sp;
else
sp = (unsigned long *)&sp;
}
stack = sp;
for (i = 0; i < kstack_depth_to_print; i++) {
if (stack >= irq_stack && stack <= irq_stack_end) {
if (stack == irq_stack_end) {
stack = (unsigned long *) (irq_stack_end[-1]);
pr_cont(" <EOI> ");
}
} else {
if (((long) stack & (THREAD_SIZE-1)) == 0)
break;
}
if (i && ((i % STACKSLOTS_PER_LINE) == 0))
pr_cont("\n");
pr_cont(" %016lx", *stack++);
touch_nmi_watchdog();
}
preempt_enable();
pr_cont("\n");
show_trace_log_lvl(task, regs, sp, bp, log_lvl);
}
void show_regs(struct pt_regs *regs)
{
int i;
unsigned long sp;
sp = regs->sp;
show_regs_print_info(KERN_DEFAULT);
__show_regs(regs, 1);
/*
* When in-kernel, we also print out the stack and code at the
* time of the fault..
*/
if (!user_mode(regs)) {
unsigned int code_prologue = code_bytes * 43 / 64;
unsigned int code_len = code_bytes;
unsigned char c;
u8 *ip;
printk(KERN_DEFAULT "Stack:\n");
show_stack_log_lvl(NULL, regs, (unsigned long *)sp,
0, KERN_DEFAULT);
printk(KERN_DEFAULT "Code: ");
ip = (u8 *)regs->ip - code_prologue;
if (ip < (u8 *)PAGE_OFFSET || probe_kernel_address(ip, c)) {
/* try starting at IP */
ip = (u8 *)regs->ip;
code_len = code_len - code_prologue + 1;
}
for (i = 0; i < code_len; i++, ip++) {
if (ip < (u8 *)PAGE_OFFSET ||
probe_kernel_address(ip, c)) {
pr_cont(" Bad RIP value.");
break;
}
if (ip == (u8 *)regs->ip)
pr_cont("<%02x> ", c);
else
pr_cont("%02x ", c);
}
}
pr_cont("\n");
}
int is_valid_bugaddr(unsigned long ip)
{
unsigned short ud2;
if (__copy_from_user(&ud2, (const void __user *) ip, sizeof(ud2)))
return 0;
return ud2 == 0x0b0f;
}
| gpl-2.0 |
droidsec-cn/android_kernel_oneplus_msm8994 | arch/arm/mach-ep93xx/vision_ep9307.c | 2171 | 10334 | /*
* arch/arm/mach-ep93xx/vision_ep9307.c
* Vision Engraving Systems EP9307 SoM support.
*
* Copyright (C) 2008-2011 Vision Engraving Systems
* H Hartley Sweeten <hsweeten@visionengravers.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.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/irq.h>
#include <linux/gpio.h>
#include <linux/fb.h>
#include <linux/io.h>
#include <linux/mtd/partitions.h>
#include <linux/i2c.h>
#include <linux/i2c-gpio.h>
#include <linux/i2c/pca953x.h>
#include <linux/spi/spi.h>
#include <linux/spi/flash.h>
#include <linux/spi/mmc_spi.h>
#include <linux/mmc/host.h>
#include <mach/hardware.h>
#include <linux/platform_data/video-ep93xx.h>
#include <linux/platform_data/spi-ep93xx.h>
#include <mach/gpio-ep93xx.h>
#include <asm/mach-types.h>
#include <asm/mach/map.h>
#include <asm/mach/arch.h>
#include "soc.h"
/*************************************************************************
* Static I/O mappings for the FPGA
*************************************************************************/
#define VISION_PHYS_BASE EP93XX_CS7_PHYS_BASE
#define VISION_VIRT_BASE 0xfebff000
static struct map_desc vision_io_desc[] __initdata = {
{
.virtual = VISION_VIRT_BASE,
.pfn = __phys_to_pfn(VISION_PHYS_BASE),
.length = SZ_4K,
.type = MT_DEVICE,
},
};
static void __init vision_map_io(void)
{
ep93xx_map_io();
iotable_init(vision_io_desc, ARRAY_SIZE(vision_io_desc));
}
/*************************************************************************
* Ethernet
*************************************************************************/
static struct ep93xx_eth_data vision_eth_data __initdata = {
.phy_id = 1,
};
/*************************************************************************
* Framebuffer
*************************************************************************/
#define VISION_LCD_ENABLE EP93XX_GPIO_LINE_EGPIO1
static int vision_lcd_setup(struct platform_device *pdev)
{
int err;
err = gpio_request_one(VISION_LCD_ENABLE, GPIOF_INIT_HIGH,
dev_name(&pdev->dev));
if (err)
return err;
ep93xx_devcfg_clear_bits(EP93XX_SYSCON_DEVCFG_RAS |
EP93XX_SYSCON_DEVCFG_RASONP3 |
EP93XX_SYSCON_DEVCFG_EXVC);
return 0;
}
static void vision_lcd_teardown(struct platform_device *pdev)
{
gpio_free(VISION_LCD_ENABLE);
}
static void vision_lcd_blank(int blank_mode, struct fb_info *info)
{
if (blank_mode)
gpio_set_value(VISION_LCD_ENABLE, 0);
else
gpio_set_value(VISION_LCD_ENABLE, 1);
}
static struct ep93xxfb_mach_info ep93xxfb_info __initdata = {
.num_modes = EP93XXFB_USE_MODEDB,
.bpp = 16,
.flags = EP93XXFB_USE_SDCSN0 | EP93XXFB_PCLK_FALLING,
.setup = vision_lcd_setup,
.teardown = vision_lcd_teardown,
.blank = vision_lcd_blank,
};
/*************************************************************************
* GPIO Expanders
*************************************************************************/
#define PCA9539_74_GPIO_BASE (EP93XX_GPIO_LINE_MAX + 1)
#define PCA9539_75_GPIO_BASE (PCA9539_74_GPIO_BASE + 16)
#define PCA9539_76_GPIO_BASE (PCA9539_75_GPIO_BASE + 16)
#define PCA9539_77_GPIO_BASE (PCA9539_76_GPIO_BASE + 16)
static struct pca953x_platform_data pca953x_74_gpio_data = {
.gpio_base = PCA9539_74_GPIO_BASE,
.irq_base = EP93XX_BOARD_IRQ(0),
};
static struct pca953x_platform_data pca953x_75_gpio_data = {
.gpio_base = PCA9539_75_GPIO_BASE,
.irq_base = -1,
};
static struct pca953x_platform_data pca953x_76_gpio_data = {
.gpio_base = PCA9539_76_GPIO_BASE,
.irq_base = -1,
};
static struct pca953x_platform_data pca953x_77_gpio_data = {
.gpio_base = PCA9539_77_GPIO_BASE,
.irq_base = -1,
};
/*************************************************************************
* I2C Bus
*************************************************************************/
static struct i2c_gpio_platform_data vision_i2c_gpio_data __initdata = {
.sda_pin = EP93XX_GPIO_LINE_EEDAT,
.scl_pin = EP93XX_GPIO_LINE_EECLK,
};
static struct i2c_board_info vision_i2c_info[] __initdata = {
{
I2C_BOARD_INFO("isl1208", 0x6f),
.irq = IRQ_EP93XX_EXT1,
}, {
I2C_BOARD_INFO("pca9539", 0x74),
.platform_data = &pca953x_74_gpio_data,
}, {
I2C_BOARD_INFO("pca9539", 0x75),
.platform_data = &pca953x_75_gpio_data,
}, {
I2C_BOARD_INFO("pca9539", 0x76),
.platform_data = &pca953x_76_gpio_data,
}, {
I2C_BOARD_INFO("pca9539", 0x77),
.platform_data = &pca953x_77_gpio_data,
},
};
/*************************************************************************
* SPI Flash
*************************************************************************/
#define VISION_SPI_FLASH_CS EP93XX_GPIO_LINE_EGPIO7
static struct mtd_partition vision_spi_flash_partitions[] = {
{
.name = "SPI bootstrap",
.offset = 0,
.size = SZ_4K,
}, {
.name = "Bootstrap config",
.offset = MTDPART_OFS_APPEND,
.size = SZ_4K,
}, {
.name = "System config",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
},
};
static struct flash_platform_data vision_spi_flash_data = {
.name = "SPI Flash",
.parts = vision_spi_flash_partitions,
.nr_parts = ARRAY_SIZE(vision_spi_flash_partitions),
};
static int vision_spi_flash_hw_setup(struct spi_device *spi)
{
return gpio_request_one(VISION_SPI_FLASH_CS, GPIOF_INIT_HIGH,
spi->modalias);
}
static void vision_spi_flash_hw_cleanup(struct spi_device *spi)
{
gpio_free(VISION_SPI_FLASH_CS);
}
static void vision_spi_flash_hw_cs_control(struct spi_device *spi, int value)
{
gpio_set_value(VISION_SPI_FLASH_CS, value);
}
static struct ep93xx_spi_chip_ops vision_spi_flash_hw = {
.setup = vision_spi_flash_hw_setup,
.cleanup = vision_spi_flash_hw_cleanup,
.cs_control = vision_spi_flash_hw_cs_control,
};
/*************************************************************************
* SPI SD/MMC host
*************************************************************************/
#define VISION_SPI_MMC_CS EP93XX_GPIO_LINE_G(2)
#define VISION_SPI_MMC_WP EP93XX_GPIO_LINE_F(0)
#define VISION_SPI_MMC_CD EP93XX_GPIO_LINE_EGPIO15
static struct gpio vision_spi_mmc_gpios[] = {
{ VISION_SPI_MMC_WP, GPIOF_DIR_IN, "mmc_spi:wp" },
{ VISION_SPI_MMC_CD, GPIOF_DIR_IN, "mmc_spi:cd" },
};
static int vision_spi_mmc_init(struct device *pdev,
irqreturn_t (*func)(int, void *), void *pdata)
{
int err;
err = gpio_request_array(vision_spi_mmc_gpios,
ARRAY_SIZE(vision_spi_mmc_gpios));
if (err)
return err;
err = gpio_set_debounce(VISION_SPI_MMC_CD, 1);
if (err)
goto exit_err;
err = request_irq(gpio_to_irq(VISION_SPI_MMC_CD), func,
IRQ_TYPE_EDGE_BOTH, "mmc_spi:cd", pdata);
if (err)
goto exit_err;
return 0;
exit_err:
gpio_free_array(vision_spi_mmc_gpios, ARRAY_SIZE(vision_spi_mmc_gpios));
return err;
}
static void vision_spi_mmc_exit(struct device *pdev, void *pdata)
{
free_irq(gpio_to_irq(VISION_SPI_MMC_CD), pdata);
gpio_free_array(vision_spi_mmc_gpios, ARRAY_SIZE(vision_spi_mmc_gpios));
}
static int vision_spi_mmc_get_ro(struct device *pdev)
{
return !!gpio_get_value(VISION_SPI_MMC_WP);
}
static int vision_spi_mmc_get_cd(struct device *pdev)
{
return !gpio_get_value(VISION_SPI_MMC_CD);
}
static struct mmc_spi_platform_data vision_spi_mmc_data = {
.init = vision_spi_mmc_init,
.exit = vision_spi_mmc_exit,
.get_ro = vision_spi_mmc_get_ro,
.get_cd = vision_spi_mmc_get_cd,
.detect_delay = 100,
.powerup_msecs = 100,
.ocr_mask = MMC_VDD_32_33 | MMC_VDD_33_34,
};
static int vision_spi_mmc_hw_setup(struct spi_device *spi)
{
return gpio_request_one(VISION_SPI_MMC_CS, GPIOF_INIT_HIGH,
spi->modalias);
}
static void vision_spi_mmc_hw_cleanup(struct spi_device *spi)
{
gpio_free(VISION_SPI_MMC_CS);
}
static void vision_spi_mmc_hw_cs_control(struct spi_device *spi, int value)
{
gpio_set_value(VISION_SPI_MMC_CS, value);
}
static struct ep93xx_spi_chip_ops vision_spi_mmc_hw = {
.setup = vision_spi_mmc_hw_setup,
.cleanup = vision_spi_mmc_hw_cleanup,
.cs_control = vision_spi_mmc_hw_cs_control,
};
/*************************************************************************
* SPI Bus
*************************************************************************/
static struct spi_board_info vision_spi_board_info[] __initdata = {
{
.modalias = "sst25l",
.platform_data = &vision_spi_flash_data,
.controller_data = &vision_spi_flash_hw,
.max_speed_hz = 20000000,
.bus_num = 0,
.chip_select = 0,
.mode = SPI_MODE_3,
}, {
.modalias = "mmc_spi",
.platform_data = &vision_spi_mmc_data,
.controller_data = &vision_spi_mmc_hw,
.max_speed_hz = 20000000,
.bus_num = 0,
.chip_select = 1,
.mode = SPI_MODE_3,
},
};
static struct ep93xx_spi_info vision_spi_master __initdata = {
.num_chipselect = ARRAY_SIZE(vision_spi_board_info),
};
/*************************************************************************
* Machine Initialization
*************************************************************************/
static void __init vision_init_machine(void)
{
ep93xx_init_devices();
ep93xx_register_flash(2, EP93XX_CS6_PHYS_BASE, SZ_64M);
ep93xx_register_eth(&vision_eth_data, 1);
ep93xx_register_fb(&ep93xxfb_info);
ep93xx_register_pwm(1, 0);
/*
* Request the gpio expander's interrupt gpio line now to prevent
* the kernel from doing a WARN in gpiolib:gpio_ensure_requested().
*/
if (gpio_request_one(EP93XX_GPIO_LINE_F(7), GPIOF_DIR_IN,
"pca9539:74"))
pr_warn("cannot request interrupt gpio for pca9539:74\n");
vision_i2c_info[1].irq = gpio_to_irq(EP93XX_GPIO_LINE_F(7));
ep93xx_register_i2c(&vision_i2c_gpio_data, vision_i2c_info,
ARRAY_SIZE(vision_i2c_info));
ep93xx_register_spi(&vision_spi_master, vision_spi_board_info,
ARRAY_SIZE(vision_spi_board_info));
}
MACHINE_START(VISION_EP9307, "Vision Engraving Systems EP9307")
/* Maintainer: H Hartley Sweeten <hsweeten@visionengravers.com> */
.atag_offset = 0x100,
.map_io = vision_map_io,
.init_irq = ep93xx_init_irq,
.init_time = ep93xx_timer_init,
.init_machine = vision_init_machine,
.init_late = ep93xx_init_late,
.restart = ep93xx_restart,
MACHINE_END
| gpl-2.0 |
roguesyko/kernel_lge_g3 | arch/arm/mach-msm/rpc_server_handset.c | 2171 | 18489 | /* arch/arm/mach-msm/rpc_server_handset.c
*
* Copyright (c) 2008-2010,2012 The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/switch.h>
#include <asm/mach-types.h>
#include <mach/msm_rpcrouter.h>
#include <mach/board.h>
#include <mach/rpc_server_handset.h>
#define DRIVER_NAME "msm-handset"
#define HS_SERVER_PROG 0x30000062
#define HS_SERVER_VERS 0x00010001
#define HS_RPC_PROG 0x30000091
#define HS_PROCESS_CMD_PROC 0x02
#define HS_SUBSCRIBE_SRVC_PROC 0x03
#define HS_REPORT_EVNT_PROC 0x05
#define HS_EVENT_CB_PROC 1
#define HS_EVENT_DATA_VER 1
#define RPC_KEYPAD_NULL_PROC 0
#define RPC_KEYPAD_PASS_KEY_CODE_PROC 2
#define RPC_KEYPAD_SET_PWR_KEY_STATE_PROC 3
#define HS_PWR_K 0x6F /* Power key */
#define HS_END_K 0x51 /* End key or Power key */
#define HS_STEREO_HEADSET_K 0x82
#define HS_HEADSET_SWITCH_K 0x84
#define HS_HEADSET_SWITCH_2_K 0xF0
#define HS_HEADSET_SWITCH_3_K 0xF1
#define HS_HEADSET_HEADPHONE_K 0xF6
#define HS_HEADSET_MICROPHONE_K 0xF7
#define HS_REL_K 0xFF /* key release */
#define SW_HEADPHONE_INSERT_W_MIC 1 /* HS with mic */
#define KEY(hs_key, input_key) ((hs_key << 24) | input_key)
enum hs_event {
HS_EVNT_EXT_PWR = 0, /* External Power status */
HS_EVNT_HSD, /* Headset Detection */
HS_EVNT_HSTD, /* Headset Type Detection */
HS_EVNT_HSSD, /* Headset Switch Detection */
HS_EVNT_KPD,
HS_EVNT_FLIP, /* Flip / Clamshell status (open/close) */
HS_EVNT_CHARGER, /* Battery is being charged or not */
HS_EVNT_ENV, /* Events from runtime environment like DEM */
HS_EVNT_REM, /* Events received from HS counterpart on a
remote processor*/
HS_EVNT_DIAG, /* Diag Events */
HS_EVNT_LAST, /* Should always be the last event type */
HS_EVNT_MAX /* Force enum to be an 32-bit number */
};
enum hs_src_state {
HS_SRC_STATE_UNKWN = 0,
HS_SRC_STATE_LO,
HS_SRC_STATE_HI,
};
struct hs_event_data {
uint32_t ver; /* Version number */
enum hs_event event_type; /* Event Type */
enum hs_event enum_disc; /* discriminator */
uint32_t data_length; /* length of the next field */
enum hs_src_state data; /* Pointer to data */
uint32_t data_size; /* Elements to be processed in data */
};
enum hs_return_value {
HS_EKPDLOCKED = -2, /* Operation failed because keypad is locked */
HS_ENOTSUPPORTED = -1, /* Functionality not supported */
HS_FALSE = 0, /* Inquired condition is not true */
HS_FAILURE = 0, /* Requested operation was not successful */
HS_TRUE = 1, /* Inquired condition is true */
HS_SUCCESS = 1, /* Requested operation was successful */
HS_MAX_RETURN = 0x7FFFFFFF/* Force enum to be a 32 bit number */
};
struct hs_key_data {
uint32_t ver; /* Version number to track sturcture changes */
uint32_t code; /* which key? */
uint32_t parm; /* key status. Up/down or pressed/released */
};
enum hs_subs_srvc {
HS_SUBS_SEND_CMD = 0, /* Subscribe to send commands to HS */
HS_SUBS_RCV_EVNT, /* Subscribe to receive Events from HS */
HS_SUBS_SRVC_MAX
};
enum hs_subs_req {
HS_SUBS_REGISTER, /* Subscribe */
HS_SUBS_CANCEL, /* Unsubscribe */
HS_SUB_STATUS_MAX
};
enum hs_event_class {
HS_EVNT_CLASS_ALL = 0, /* All HS events */
HS_EVNT_CLASS_LAST, /* Should always be the last class type */
HS_EVNT_CLASS_MAX
};
enum hs_cmd_class {
HS_CMD_CLASS_LCD = 0, /* Send LCD related commands */
HS_CMD_CLASS_KPD, /* Send KPD related commands */
HS_CMD_CLASS_LAST, /* Should always be the last class type */
HS_CMD_CLASS_MAX
};
/*
* Receive events or send command
*/
union hs_subs_class {
enum hs_event_class evnt;
enum hs_cmd_class cmd;
};
struct hs_subs {
uint32_t ver;
enum hs_subs_srvc srvc; /* commands or events */
enum hs_subs_req req; /* subscribe or unsubscribe */
uint32_t host_os;
enum hs_subs_req disc; /* discriminator */
union hs_subs_class id;
};
struct hs_event_cb_recv {
uint32_t cb_id;
uint32_t hs_key_data_ptr;
struct hs_key_data key;
};
enum hs_ext_cmd_type {
HS_EXT_CMD_KPD_SEND_KEY = 0, /* Send Key */
HS_EXT_CMD_KPD_BKLT_CTRL, /* Keypad backlight intensity */
HS_EXT_CMD_LCD_BKLT_CTRL, /* LCD Backlight intensity */
HS_EXT_CMD_DIAG_KEYMAP, /* Emulating a Diag key sequence */
HS_EXT_CMD_DIAG_LOCK, /* Device Lock/Unlock */
HS_EXT_CMD_GET_EVNT_STATUS, /* Get the status for one of the drivers */
HS_EXT_CMD_KPD_GET_KEYS_STATUS,/* Get a list of keys status */
HS_EXT_CMD_KPD_SET_PWR_KEY_RST_THOLD, /* PWR Key HW Reset duration */
HS_EXT_CMD_KPD_SET_PWR_KEY_THOLD, /* Set pwr key threshold duration */
HS_EXT_CMD_LAST, /* Should always be the last command type */
HS_EXT_CMD_MAX = 0x7FFFFFFF /* Force enum to be an 32-bit number */
};
struct hs_cmd_data_type {
uint32_t hs_cmd_data_type_ptr; /* hs_cmd_data_type ptr length */
uint32_t ver; /* version */
enum hs_ext_cmd_type id; /* command id */
uint32_t handle; /* handle returned from subscribe proc */
enum hs_ext_cmd_type disc_id1; /* discriminator id */
uint32_t input_ptr; /* input ptr length */
uint32_t input_val; /* command specific data */
uint32_t input_len; /* length of command input */
enum hs_ext_cmd_type disc_id2; /* discriminator id */
uint32_t output_len; /* length of output data */
uint32_t delayed; /* execution context for modem
true - caller context
false - hs task context*/
};
static const uint32_t hs_key_map[] = {
KEY(HS_PWR_K, KEY_POWER),
KEY(HS_END_K, KEY_END),
KEY(HS_STEREO_HEADSET_K, SW_HEADPHONE_INSERT_W_MIC),
KEY(HS_HEADSET_HEADPHONE_K, SW_HEADPHONE_INSERT),
KEY(HS_HEADSET_MICROPHONE_K, SW_MICROPHONE_INSERT),
KEY(HS_HEADSET_SWITCH_K, KEY_MEDIA),
KEY(HS_HEADSET_SWITCH_2_K, KEY_VOLUMEUP),
KEY(HS_HEADSET_SWITCH_3_K, KEY_VOLUMEDOWN),
0
};
enum {
NO_DEVICE = 0,
MSM_HEADSET = 1,
};
/* Add newer versions at the top of array */
static const unsigned int rpc_vers[] = {
0x00030001,
0x00020001,
0x00010001,
};
/* hs subscription request parameters */
struct hs_subs_rpc_req {
uint32_t hs_subs_ptr;
struct hs_subs hs_subs;
uint32_t hs_cb_id;
uint32_t hs_handle_ptr;
uint32_t hs_handle_data;
};
static struct hs_subs_rpc_req *hs_subs_req;
struct msm_handset {
struct input_dev *ipdev;
struct switch_dev sdev;
struct msm_handset_platform_data *hs_pdata;
bool mic_on, hs_on;
};
static struct msm_rpc_client *rpc_client;
static struct msm_handset *hs;
static int hs_find_key(uint32_t hscode)
{
int i, key;
key = KEY(hscode, 0);
for (i = 0; hs_key_map[i] != 0; i++) {
if ((hs_key_map[i] & 0xff000000) == key)
return hs_key_map[i] & 0x00ffffff;
}
return -1;
}
static void update_state(void)
{
int state;
if (hs->mic_on && hs->hs_on)
state = 1 << 0;
else if (hs->hs_on)
state = 1 << 1;
else if (hs->mic_on)
state = 1 << 2;
else
state = 0;
switch_set_state(&hs->sdev, state);
}
/*
* tuple format: (key_code, key_param)
*
* old-architecture:
* key-press = (key_code, 0)
* key-release = (0xff, key_code)
*
* new-architecutre:
* key-press = (key_code, 0)
* key-release = (key_code, 0xff)
*/
static void report_hs_key(uint32_t key_code, uint32_t key_parm)
{
int key, temp_key_code;
if (key_code == HS_REL_K)
key = hs_find_key(key_parm);
else
key = hs_find_key(key_code);
temp_key_code = key_code;
if (key_parm == HS_REL_K)
key_code = key_parm;
switch (key) {
case KEY_POWER:
case KEY_END:
if (hs->hs_pdata->ignore_end_key)
input_report_key(hs->ipdev, KEY_POWER,
(key_code != HS_REL_K));
else
input_report_key(hs->ipdev, key,
(key_code != HS_REL_K));
break;
case KEY_MEDIA:
case KEY_VOLUMEUP:
case KEY_VOLUMEDOWN:
input_report_key(hs->ipdev, key, (key_code != HS_REL_K));
break;
case SW_HEADPHONE_INSERT_W_MIC:
hs->mic_on = hs->hs_on = (key_code != HS_REL_K) ? 1 : 0;
input_report_switch(hs->ipdev, SW_HEADPHONE_INSERT,
hs->hs_on);
input_report_switch(hs->ipdev, SW_MICROPHONE_INSERT,
hs->mic_on);
update_state();
break;
case SW_HEADPHONE_INSERT:
hs->hs_on = (key_code != HS_REL_K) ? 1 : 0;
input_report_switch(hs->ipdev, key, hs->hs_on);
update_state();
break;
case SW_MICROPHONE_INSERT:
hs->mic_on = (key_code != HS_REL_K) ? 1 : 0;
input_report_switch(hs->ipdev, key, hs->mic_on);
update_state();
break;
case -1:
printk(KERN_ERR "%s: No mapping for remote handset event %d\n",
__func__, temp_key_code);
return;
}
input_sync(hs->ipdev);
}
static int handle_hs_rpc_call(struct msm_rpc_server *server,
struct rpc_request_hdr *req, unsigned len)
{
struct rpc_keypad_pass_key_code_args {
uint32_t key_code;
uint32_t key_parm;
};
switch (req->procedure) {
case RPC_KEYPAD_NULL_PROC:
return 0;
case RPC_KEYPAD_PASS_KEY_CODE_PROC: {
struct rpc_keypad_pass_key_code_args *args;
args = (struct rpc_keypad_pass_key_code_args *)(req + 1);
args->key_code = be32_to_cpu(args->key_code);
args->key_parm = be32_to_cpu(args->key_parm);
report_hs_key(args->key_code, args->key_parm);
return 0;
}
case RPC_KEYPAD_SET_PWR_KEY_STATE_PROC:
/* This RPC function must be available for the ARM9
* to function properly. This function is redundant
* when RPC_KEYPAD_PASS_KEY_CODE_PROC is handled. So
* input_report_key is not needed.
*/
return 0;
default:
return -ENODEV;
}
}
static struct msm_rpc_server hs_rpc_server = {
.prog = HS_SERVER_PROG,
.vers = HS_SERVER_VERS,
.rpc_call = handle_hs_rpc_call,
};
static int process_subs_srvc_callback(struct hs_event_cb_recv *recv)
{
if (!recv)
return -ENODATA;
report_hs_key(be32_to_cpu(recv->key.code), be32_to_cpu(recv->key.parm));
return 0;
}
static void process_hs_rpc_request(uint32_t proc, void *data)
{
if (proc == HS_EVENT_CB_PROC)
process_subs_srvc_callback(data);
else
pr_err("%s: unknown rpc proc %d\n", __func__, proc);
}
static int hs_rpc_report_event_arg(struct msm_rpc_client *client,
void *buffer, void *data)
{
struct hs_event_rpc_req {
uint32_t hs_event_data_ptr;
struct hs_event_data data;
};
struct hs_event_rpc_req *req = buffer;
req->hs_event_data_ptr = cpu_to_be32(0x1);
req->data.ver = cpu_to_be32(HS_EVENT_DATA_VER);
req->data.event_type = cpu_to_be32(HS_EVNT_HSD);
req->data.enum_disc = cpu_to_be32(HS_EVNT_HSD);
req->data.data_length = cpu_to_be32(0x1);
req->data.data = cpu_to_be32(*(enum hs_src_state *)data);
req->data.data_size = cpu_to_be32(sizeof(enum hs_src_state));
return sizeof(*req);
}
static int hs_rpc_report_event_res(struct msm_rpc_client *client,
void *buffer, void *data)
{
enum hs_return_value result;
result = be32_to_cpu(*(enum hs_return_value *)buffer);
pr_debug("%s: request completed: 0x%x\n", __func__, result);
if (result == HS_SUCCESS)
return 0;
return 1;
}
void report_headset_status(bool connected)
{
int rc = -1;
enum hs_src_state status;
if (connected == true)
status = HS_SRC_STATE_HI;
else
status = HS_SRC_STATE_LO;
rc = msm_rpc_client_req(rpc_client, HS_REPORT_EVNT_PROC,
hs_rpc_report_event_arg, &status,
hs_rpc_report_event_res, NULL, -1);
if (rc)
pr_err("%s: couldn't send rpc client request\n", __func__);
}
EXPORT_SYMBOL(report_headset_status);
static int hs_rpc_pwr_cmd_arg(struct msm_rpc_client *client,
void *buffer, void *data)
{
struct hs_cmd_data_type *hs_pwr_cmd = buffer;
hs_pwr_cmd->hs_cmd_data_type_ptr = cpu_to_be32(0x01);
hs_pwr_cmd->ver = cpu_to_be32(0x03);
hs_pwr_cmd->id = cpu_to_be32(HS_EXT_CMD_KPD_SET_PWR_KEY_THOLD);
hs_pwr_cmd->handle = cpu_to_be32(hs_subs_req->hs_handle_data);
hs_pwr_cmd->disc_id1 = cpu_to_be32(HS_EXT_CMD_KPD_SET_PWR_KEY_THOLD);
hs_pwr_cmd->input_ptr = cpu_to_be32(0x01);
hs_pwr_cmd->input_val = cpu_to_be32(hs->hs_pdata->pwr_key_delay_ms);
hs_pwr_cmd->input_len = cpu_to_be32(0x01);
hs_pwr_cmd->disc_id2 = cpu_to_be32(HS_EXT_CMD_KPD_SET_PWR_KEY_THOLD);
hs_pwr_cmd->output_len = cpu_to_be32(0x00);
hs_pwr_cmd->delayed = cpu_to_be32(0x00);
return sizeof(*hs_pwr_cmd);
}
static int hs_rpc_pwr_cmd_res(struct msm_rpc_client *client,
void *buffer, void *data)
{
uint32_t result;
result = be32_to_cpu(*((uint32_t *)buffer));
pr_debug("%s: request completed: 0x%x\n", __func__, result);
return 0;
}
static int hs_rpc_register_subs_arg(struct msm_rpc_client *client,
void *buffer, void *data)
{
hs_subs_req = buffer;
hs_subs_req->hs_subs_ptr = cpu_to_be32(0x1);
hs_subs_req->hs_subs.ver = cpu_to_be32(0x1);
hs_subs_req->hs_subs.srvc = cpu_to_be32(HS_SUBS_RCV_EVNT);
hs_subs_req->hs_subs.req = cpu_to_be32(HS_SUBS_REGISTER);
hs_subs_req->hs_subs.host_os = cpu_to_be32(0x4); /* linux */
hs_subs_req->hs_subs.disc = cpu_to_be32(HS_SUBS_RCV_EVNT);
hs_subs_req->hs_subs.id.evnt = cpu_to_be32(HS_EVNT_CLASS_ALL);
hs_subs_req->hs_cb_id = cpu_to_be32(0x1);
hs_subs_req->hs_handle_ptr = cpu_to_be32(0x1);
hs_subs_req->hs_handle_data = cpu_to_be32(0x0);
return sizeof(*hs_subs_req);
}
static int hs_rpc_register_subs_res(struct msm_rpc_client *client,
void *buffer, void *data)
{
uint32_t result;
result = be32_to_cpu(*((uint32_t *)buffer));
pr_debug("%s: request completed: 0x%x\n", __func__, result);
return 0;
}
static int hs_cb_func(struct msm_rpc_client *client, void *buffer, int in_size)
{
int rc = -1;
struct rpc_request_hdr *hdr = buffer;
hdr->type = be32_to_cpu(hdr->type);
hdr->xid = be32_to_cpu(hdr->xid);
hdr->rpc_vers = be32_to_cpu(hdr->rpc_vers);
hdr->prog = be32_to_cpu(hdr->prog);
hdr->vers = be32_to_cpu(hdr->vers);
hdr->procedure = be32_to_cpu(hdr->procedure);
process_hs_rpc_request(hdr->procedure,
(void *) (hdr + 1));
msm_rpc_start_accepted_reply(client, hdr->xid,
RPC_ACCEPTSTAT_SUCCESS);
rc = msm_rpc_send_accepted_reply(client, 0);
if (rc) {
pr_err("%s: sending reply failed: %d\n", __func__, rc);
return rc;
}
return 0;
}
static int __devinit hs_rpc_cb_init(void)
{
int rc = 0, i, num_vers;
num_vers = ARRAY_SIZE(rpc_vers);
for (i = 0; i < num_vers; i++) {
rpc_client = msm_rpc_register_client("hs",
HS_RPC_PROG, rpc_vers[i], 0, hs_cb_func);
if (IS_ERR(rpc_client))
pr_debug("%s: RPC Client version %d failed, fallback\n",
__func__, rpc_vers[i]);
else
break;
}
if (IS_ERR(rpc_client)) {
pr_err("%s: Incompatible RPC version error %ld\n",
__func__, PTR_ERR(rpc_client));
return PTR_ERR(rpc_client);
}
rc = msm_rpc_client_req(rpc_client, HS_SUBSCRIBE_SRVC_PROC,
hs_rpc_register_subs_arg, NULL,
hs_rpc_register_subs_res, NULL, -1);
if (rc) {
pr_err("%s: RPC client request failed for subscribe services\n",
__func__);
goto err_client_req;
}
rc = msm_rpc_client_req(rpc_client, HS_PROCESS_CMD_PROC,
hs_rpc_pwr_cmd_arg, NULL,
hs_rpc_pwr_cmd_res, NULL, -1);
if (rc)
pr_err("%s: RPC client request failed for pwr key"
" delay cmd, using normal mode\n", __func__);
return 0;
err_client_req:
msm_rpc_unregister_client(rpc_client);
return rc;
}
static int __devinit hs_rpc_init(void)
{
int rc;
rc = hs_rpc_cb_init();
if (rc) {
pr_err("%s: failed to initialize rpc client, try server...\n",
__func__);
rc = msm_rpc_create_server(&hs_rpc_server);
if (rc) {
pr_err("%s: failed to create rpc server\n", __func__);
return rc;
}
}
return rc;
}
static void __devexit hs_rpc_deinit(void)
{
if (rpc_client)
msm_rpc_unregister_client(rpc_client);
}
static ssize_t msm_headset_print_name(struct switch_dev *sdev, char *buf)
{
switch (switch_get_state(&hs->sdev)) {
case NO_DEVICE:
return sprintf(buf, "No Device\n");
case MSM_HEADSET:
return sprintf(buf, "Headset\n");
}
return -EINVAL;
}
static int __devinit hs_probe(struct platform_device *pdev)
{
int rc = 0;
struct input_dev *ipdev;
hs = kzalloc(sizeof(struct msm_handset), GFP_KERNEL);
if (!hs)
return -ENOMEM;
hs->sdev.name = "h2w";
hs->sdev.print_name = msm_headset_print_name;
rc = switch_dev_register(&hs->sdev);
if (rc)
goto err_switch_dev_register;
ipdev = input_allocate_device();
if (!ipdev) {
rc = -ENOMEM;
goto err_alloc_input_dev;
}
input_set_drvdata(ipdev, hs);
hs->ipdev = ipdev;
if (pdev->dev.platform_data)
hs->hs_pdata = pdev->dev.platform_data;
if (hs->hs_pdata->hs_name)
ipdev->name = hs->hs_pdata->hs_name;
else
ipdev->name = DRIVER_NAME;
ipdev->id.vendor = 0x0001;
ipdev->id.product = 1;
ipdev->id.version = 1;
input_set_capability(ipdev, EV_KEY, KEY_MEDIA);
input_set_capability(ipdev, EV_KEY, KEY_VOLUMEUP);
input_set_capability(ipdev, EV_KEY, KEY_VOLUMEDOWN);
input_set_capability(ipdev, EV_SW, SW_HEADPHONE_INSERT);
input_set_capability(ipdev, EV_SW, SW_MICROPHONE_INSERT);
input_set_capability(ipdev, EV_KEY, KEY_POWER);
input_set_capability(ipdev, EV_KEY, KEY_END);
rc = input_register_device(ipdev);
if (rc) {
dev_err(&ipdev->dev,
"hs_probe: input_register_device rc=%d\n", rc);
goto err_reg_input_dev;
}
platform_set_drvdata(pdev, hs);
rc = hs_rpc_init();
if (rc) {
dev_err(&ipdev->dev, "rpc init failure\n");
goto err_hs_rpc_init;
}
return 0;
err_hs_rpc_init:
input_unregister_device(ipdev);
ipdev = NULL;
err_reg_input_dev:
input_free_device(ipdev);
err_alloc_input_dev:
switch_dev_unregister(&hs->sdev);
err_switch_dev_register:
kfree(hs);
return rc;
}
static int __devexit hs_remove(struct platform_device *pdev)
{
struct msm_handset *hs = platform_get_drvdata(pdev);
input_unregister_device(hs->ipdev);
switch_dev_unregister(&hs->sdev);
kfree(hs);
hs_rpc_deinit();
return 0;
}
static struct platform_driver hs_driver = {
.probe = hs_probe,
.remove = __devexit_p(hs_remove),
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
},
};
static int __init hs_init(void)
{
return platform_driver_register(&hs_driver);
}
late_initcall(hs_init);
static void __exit hs_exit(void)
{
platform_driver_unregister(&hs_driver);
}
module_exit(hs_exit);
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:msm-handset");
| gpl-2.0 |
tchaari/android_kernel_samsung_crespo | drivers/usb/host/ehci-tegra.c | 2427 | 20294 | /*
* EHCI-compliant USB host controller driver for NVIDIA Tegra SoCs
*
* Copyright (C) 2010 Google, Inc.
* Copyright (C) 2009 NVIDIA Corporation
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
*/
#include <linux/clk.h>
#include <linux/platform_device.h>
#include <linux/platform_data/tegra_usb.h>
#include <linux/irq.h>
#include <linux/usb/otg.h>
#include <mach/usb_phy.h>
#define TEGRA_USB_DMA_ALIGN 32
struct tegra_ehci_hcd {
struct ehci_hcd *ehci;
struct tegra_usb_phy *phy;
struct clk *clk;
struct clk *emc_clk;
struct otg_transceiver *transceiver;
int host_resumed;
int bus_suspended;
int port_resuming;
int power_down_on_bus_suspend;
enum tegra_usb_phy_port_speed port_speed;
};
static void tegra_ehci_power_up(struct usb_hcd *hcd)
{
struct tegra_ehci_hcd *tegra = dev_get_drvdata(hcd->self.controller);
clk_enable(tegra->emc_clk);
clk_enable(tegra->clk);
tegra_usb_phy_power_on(tegra->phy);
tegra->host_resumed = 1;
}
static void tegra_ehci_power_down(struct usb_hcd *hcd)
{
struct tegra_ehci_hcd *tegra = dev_get_drvdata(hcd->self.controller);
tegra->host_resumed = 0;
tegra_usb_phy_power_off(tegra->phy);
clk_disable(tegra->clk);
clk_disable(tegra->emc_clk);
}
static int tegra_ehci_internal_port_reset(
struct ehci_hcd *ehci,
u32 __iomem *portsc_reg
)
{
u32 temp;
unsigned long flags;
int retval = 0;
int i, tries;
u32 saved_usbintr;
spin_lock_irqsave(&ehci->lock, flags);
saved_usbintr = ehci_readl(ehci, &ehci->regs->intr_enable);
/* disable USB interrupt */
ehci_writel(ehci, 0, &ehci->regs->intr_enable);
spin_unlock_irqrestore(&ehci->lock, flags);
/*
* Here we have to do Port Reset at most twice for
* Port Enable bit to be set.
*/
for (i = 0; i < 2; i++) {
temp = ehci_readl(ehci, portsc_reg);
temp |= PORT_RESET;
ehci_writel(ehci, temp, portsc_reg);
mdelay(10);
temp &= ~PORT_RESET;
ehci_writel(ehci, temp, portsc_reg);
mdelay(1);
tries = 100;
do {
mdelay(1);
/*
* Up to this point, Port Enable bit is
* expected to be set after 2 ms waiting.
* USB1 usually takes extra 45 ms, for safety,
* we take 100 ms as timeout.
*/
temp = ehci_readl(ehci, portsc_reg);
} while (!(temp & PORT_PE) && tries--);
if (temp & PORT_PE)
break;
}
if (i == 2)
retval = -ETIMEDOUT;
/*
* Clear Connect Status Change bit if it's set.
* We can't clear PORT_PEC. It will also cause PORT_PE to be cleared.
*/
if (temp & PORT_CSC)
ehci_writel(ehci, PORT_CSC, portsc_reg);
/*
* Write to clear any interrupt status bits that might be set
* during port reset.
*/
temp = ehci_readl(ehci, &ehci->regs->status);
ehci_writel(ehci, temp, &ehci->regs->status);
/* restore original interrupt enable bits */
ehci_writel(ehci, saved_usbintr, &ehci->regs->intr_enable);
return retval;
}
static int tegra_ehci_hub_control(
struct usb_hcd *hcd,
u16 typeReq,
u16 wValue,
u16 wIndex,
char *buf,
u16 wLength
)
{
struct ehci_hcd *ehci = hcd_to_ehci(hcd);
struct tegra_ehci_hcd *tegra = dev_get_drvdata(hcd->self.controller);
u32 __iomem *status_reg;
u32 temp;
unsigned long flags;
int retval = 0;
status_reg = &ehci->regs->port_status[(wIndex & 0xff) - 1];
spin_lock_irqsave(&ehci->lock, flags);
/*
* In ehci_hub_control() for USB_PORT_FEAT_ENABLE clears the other bits
* that are write on clear, by writing back the register read value, so
* USB_PORT_FEAT_ENABLE is handled by masking the set on clear bits
*/
if (typeReq == ClearPortFeature && wValue == USB_PORT_FEAT_ENABLE) {
temp = ehci_readl(ehci, status_reg) & ~PORT_RWC_BITS;
ehci_writel(ehci, temp & ~PORT_PE, status_reg);
goto done;
}
else if (typeReq == GetPortStatus) {
temp = ehci_readl(ehci, status_reg);
if (tegra->port_resuming && !(temp & PORT_SUSPEND)) {
/* Resume completed, re-enable disconnect detection */
tegra->port_resuming = 0;
tegra_usb_phy_postresume(tegra->phy);
}
}
else if (typeReq == SetPortFeature && wValue == USB_PORT_FEAT_SUSPEND) {
temp = ehci_readl(ehci, status_reg);
if ((temp & PORT_PE) == 0 || (temp & PORT_RESET) != 0) {
retval = -EPIPE;
goto done;
}
temp &= ~PORT_WKCONN_E;
temp |= PORT_WKDISC_E | PORT_WKOC_E;
ehci_writel(ehci, temp | PORT_SUSPEND, status_reg);
/*
* If a transaction is in progress, there may be a delay in
* suspending the port. Poll until the port is suspended.
*/
if (handshake(ehci, status_reg, PORT_SUSPEND,
PORT_SUSPEND, 5000))
pr_err("%s: timeout waiting for SUSPEND\n", __func__);
set_bit((wIndex & 0xff) - 1, &ehci->suspended_ports);
goto done;
}
/* For USB1 port we need to issue Port Reset twice internally */
if (tegra->phy->instance == 0 &&
(typeReq == SetPortFeature && wValue == USB_PORT_FEAT_RESET)) {
spin_unlock_irqrestore(&ehci->lock, flags);
return tegra_ehci_internal_port_reset(ehci, status_reg);
}
/*
* Tegra host controller will time the resume operation to clear the bit
* when the port control state switches to HS or FS Idle. This behavior
* is different from EHCI where the host controller driver is required
* to set this bit to a zero after the resume duration is timed in the
* driver.
*/
else if (typeReq == ClearPortFeature &&
wValue == USB_PORT_FEAT_SUSPEND) {
temp = ehci_readl(ehci, status_reg);
if ((temp & PORT_RESET) || !(temp & PORT_PE)) {
retval = -EPIPE;
goto done;
}
if (!(temp & PORT_SUSPEND))
goto done;
/* Disable disconnect detection during port resume */
tegra_usb_phy_preresume(tegra->phy);
ehci->reset_done[wIndex-1] = jiffies + msecs_to_jiffies(25);
temp &= ~(PORT_RWC_BITS | PORT_WAKE_BITS);
/* start resume signalling */
ehci_writel(ehci, temp | PORT_RESUME, status_reg);
spin_unlock_irqrestore(&ehci->lock, flags);
msleep(20);
spin_lock_irqsave(&ehci->lock, flags);
/* Poll until the controller clears RESUME and SUSPEND */
if (handshake(ehci, status_reg, PORT_RESUME, 0, 2000))
pr_err("%s: timeout waiting for RESUME\n", __func__);
if (handshake(ehci, status_reg, PORT_SUSPEND, 0, 2000))
pr_err("%s: timeout waiting for SUSPEND\n", __func__);
ehci->reset_done[wIndex-1] = 0;
tegra->port_resuming = 1;
goto done;
}
spin_unlock_irqrestore(&ehci->lock, flags);
/* Handle the hub control events here */
return ehci_hub_control(hcd, typeReq, wValue, wIndex, buf, wLength);
done:
spin_unlock_irqrestore(&ehci->lock, flags);
return retval;
}
static void tegra_ehci_restart(struct usb_hcd *hcd)
{
struct ehci_hcd *ehci = hcd_to_ehci(hcd);
ehci_reset(ehci);
/* setup the frame list and Async q heads */
ehci_writel(ehci, ehci->periodic_dma, &ehci->regs->frame_list);
ehci_writel(ehci, (u32)ehci->async->qh_dma, &ehci->regs->async_next);
/* setup the command register and set the controller in RUN mode */
ehci->command &= ~(CMD_LRESET|CMD_IAAD|CMD_PSE|CMD_ASE|CMD_RESET);
ehci->command |= CMD_RUN;
ehci_writel(ehci, ehci->command, &ehci->regs->command);
down_write(&ehci_cf_port_reset_rwsem);
ehci_writel(ehci, FLAG_CF, &ehci->regs->configured_flag);
/* flush posted writes */
ehci_readl(ehci, &ehci->regs->command);
up_write(&ehci_cf_port_reset_rwsem);
}
static int tegra_usb_suspend(struct usb_hcd *hcd)
{
struct tegra_ehci_hcd *tegra = dev_get_drvdata(hcd->self.controller);
struct ehci_regs __iomem *hw = tegra->ehci->regs;
unsigned long flags;
spin_lock_irqsave(&tegra->ehci->lock, flags);
tegra->port_speed = (readl(&hw->port_status[0]) >> 26) & 0x3;
ehci_halt(tegra->ehci);
clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
spin_unlock_irqrestore(&tegra->ehci->lock, flags);
tegra_ehci_power_down(hcd);
return 0;
}
static int tegra_usb_resume(struct usb_hcd *hcd)
{
struct tegra_ehci_hcd *tegra = dev_get_drvdata(hcd->self.controller);
struct ehci_hcd *ehci = hcd_to_ehci(hcd);
struct ehci_regs __iomem *hw = ehci->regs;
unsigned long val;
set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
tegra_ehci_power_up(hcd);
if (tegra->port_speed > TEGRA_USB_PHY_PORT_SPEED_HIGH) {
/* Wait for the phy to detect new devices
* before we restart the controller */
msleep(10);
goto restart;
}
/* Force the phy to keep data lines in suspend state */
tegra_ehci_phy_restore_start(tegra->phy, tegra->port_speed);
/* Enable host mode */
tdi_reset(ehci);
/* Enable Port Power */
val = readl(&hw->port_status[0]);
val |= PORT_POWER;
writel(val, &hw->port_status[0]);
udelay(10);
/* Check if the phy resume from LP0. When the phy resume from LP0
* USB register will be reset. */
if (!readl(&hw->async_next)) {
/* Program the field PTC based on the saved speed mode */
val = readl(&hw->port_status[0]);
val &= ~PORT_TEST(~0);
if (tegra->port_speed == TEGRA_USB_PHY_PORT_SPEED_HIGH)
val |= PORT_TEST_FORCE;
else if (tegra->port_speed == TEGRA_USB_PHY_PORT_SPEED_FULL)
val |= PORT_TEST(6);
else if (tegra->port_speed == TEGRA_USB_PHY_PORT_SPEED_LOW)
val |= PORT_TEST(7);
writel(val, &hw->port_status[0]);
udelay(10);
/* Disable test mode by setting PTC field to NORMAL_OP */
val = readl(&hw->port_status[0]);
val &= ~PORT_TEST(~0);
writel(val, &hw->port_status[0]);
udelay(10);
}
/* Poll until CCS is enabled */
if (handshake(ehci, &hw->port_status[0], PORT_CONNECT,
PORT_CONNECT, 2000)) {
pr_err("%s: timeout waiting for PORT_CONNECT\n", __func__);
goto restart;
}
/* Poll until PE is enabled */
if (handshake(ehci, &hw->port_status[0], PORT_PE,
PORT_PE, 2000)) {
pr_err("%s: timeout waiting for USB_PORTSC1_PE\n", __func__);
goto restart;
}
/* Clear the PCI status, to avoid an interrupt taken upon resume */
val = readl(&hw->status);
val |= STS_PCD;
writel(val, &hw->status);
/* Put controller in suspend mode by writing 1 to SUSP bit of PORTSC */
val = readl(&hw->port_status[0]);
if ((val & PORT_POWER) && (val & PORT_PE)) {
val |= PORT_SUSPEND;
writel(val, &hw->port_status[0]);
/* Wait until port suspend completes */
if (handshake(ehci, &hw->port_status[0], PORT_SUSPEND,
PORT_SUSPEND, 1000)) {
pr_err("%s: timeout waiting for PORT_SUSPEND\n",
__func__);
goto restart;
}
}
tegra_ehci_phy_restore_end(tegra->phy);
return 0;
restart:
if (tegra->port_speed <= TEGRA_USB_PHY_PORT_SPEED_HIGH)
tegra_ehci_phy_restore_end(tegra->phy);
tegra_ehci_restart(hcd);
return 0;
}
static void tegra_ehci_shutdown(struct usb_hcd *hcd)
{
struct tegra_ehci_hcd *tegra = dev_get_drvdata(hcd->self.controller);
/* ehci_shutdown touches the USB controller registers, make sure
* controller has clocks to it */
if (!tegra->host_resumed)
tegra_ehci_power_up(hcd);
ehci_shutdown(hcd);
}
static int tegra_ehci_setup(struct usb_hcd *hcd)
{
struct ehci_hcd *ehci = hcd_to_ehci(hcd);
int retval;
/* EHCI registers start at offset 0x100 */
ehci->caps = hcd->regs + 0x100;
ehci->regs = hcd->regs + 0x100 +
HC_LENGTH(ehci, readl(&ehci->caps->hc_capbase));
dbg_hcs_params(ehci, "reset");
dbg_hcc_params(ehci, "reset");
/* cache this readonly data; minimize chip reads */
ehci->hcs_params = readl(&ehci->caps->hcs_params);
/* switch to host mode */
hcd->has_tt = 1;
ehci_reset(ehci);
retval = ehci_halt(ehci);
if (retval)
return retval;
/* data structure init */
retval = ehci_init(hcd);
if (retval)
return retval;
ehci->sbrn = 0x20;
ehci_port_power(ehci, 1);
return retval;
}
#ifdef CONFIG_PM
static int tegra_ehci_bus_suspend(struct usb_hcd *hcd)
{
struct tegra_ehci_hcd *tegra = dev_get_drvdata(hcd->self.controller);
int error_status = 0;
error_status = ehci_bus_suspend(hcd);
if (!error_status && tegra->power_down_on_bus_suspend) {
tegra_usb_suspend(hcd);
tegra->bus_suspended = 1;
}
return error_status;
}
static int tegra_ehci_bus_resume(struct usb_hcd *hcd)
{
struct tegra_ehci_hcd *tegra = dev_get_drvdata(hcd->self.controller);
if (tegra->bus_suspended && tegra->power_down_on_bus_suspend) {
tegra_usb_resume(hcd);
tegra->bus_suspended = 0;
}
tegra_usb_phy_preresume(tegra->phy);
tegra->port_resuming = 1;
return ehci_bus_resume(hcd);
}
#endif
struct temp_buffer {
void *kmalloc_ptr;
void *old_xfer_buffer;
u8 data[0];
};
static void free_temp_buffer(struct urb *urb)
{
enum dma_data_direction dir;
struct temp_buffer *temp;
if (!(urb->transfer_flags & URB_ALIGNED_TEMP_BUFFER))
return;
dir = usb_urb_dir_in(urb) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
temp = container_of(urb->transfer_buffer, struct temp_buffer,
data);
if (dir == DMA_FROM_DEVICE)
memcpy(temp->old_xfer_buffer, temp->data,
urb->transfer_buffer_length);
urb->transfer_buffer = temp->old_xfer_buffer;
kfree(temp->kmalloc_ptr);
urb->transfer_flags &= ~URB_ALIGNED_TEMP_BUFFER;
}
static int alloc_temp_buffer(struct urb *urb, gfp_t mem_flags)
{
enum dma_data_direction dir;
struct temp_buffer *temp, *kmalloc_ptr;
size_t kmalloc_size;
if (urb->num_sgs || urb->sg ||
urb->transfer_buffer_length == 0 ||
!((uintptr_t)urb->transfer_buffer & (TEGRA_USB_DMA_ALIGN - 1)))
return 0;
dir = usb_urb_dir_in(urb) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
/* Allocate a buffer with enough padding for alignment */
kmalloc_size = urb->transfer_buffer_length +
sizeof(struct temp_buffer) + TEGRA_USB_DMA_ALIGN - 1;
kmalloc_ptr = kmalloc(kmalloc_size, mem_flags);
if (!kmalloc_ptr)
return -ENOMEM;
/* Position our struct temp_buffer such that data is aligned */
temp = PTR_ALIGN(kmalloc_ptr + 1, TEGRA_USB_DMA_ALIGN) - 1;
temp->kmalloc_ptr = kmalloc_ptr;
temp->old_xfer_buffer = urb->transfer_buffer;
if (dir == DMA_TO_DEVICE)
memcpy(temp->data, urb->transfer_buffer,
urb->transfer_buffer_length);
urb->transfer_buffer = temp->data;
urb->transfer_flags |= URB_ALIGNED_TEMP_BUFFER;
return 0;
}
static int tegra_ehci_map_urb_for_dma(struct usb_hcd *hcd, struct urb *urb,
gfp_t mem_flags)
{
int ret;
ret = alloc_temp_buffer(urb, mem_flags);
if (ret)
return ret;
ret = usb_hcd_map_urb_for_dma(hcd, urb, mem_flags);
if (ret)
free_temp_buffer(urb);
return ret;
}
static void tegra_ehci_unmap_urb_for_dma(struct usb_hcd *hcd, struct urb *urb)
{
usb_hcd_unmap_urb_for_dma(hcd, urb);
free_temp_buffer(urb);
}
static const struct hc_driver tegra_ehci_hc_driver = {
.description = hcd_name,
.product_desc = "Tegra EHCI Host Controller",
.hcd_priv_size = sizeof(struct ehci_hcd),
.flags = HCD_USB2 | HCD_MEMORY,
.reset = tegra_ehci_setup,
.irq = ehci_irq,
.start = ehci_run,
.stop = ehci_stop,
.shutdown = tegra_ehci_shutdown,
.urb_enqueue = ehci_urb_enqueue,
.urb_dequeue = ehci_urb_dequeue,
.map_urb_for_dma = tegra_ehci_map_urb_for_dma,
.unmap_urb_for_dma = tegra_ehci_unmap_urb_for_dma,
.endpoint_disable = ehci_endpoint_disable,
.endpoint_reset = ehci_endpoint_reset,
.get_frame_number = ehci_get_frame,
.hub_status_data = ehci_hub_status_data,
.hub_control = tegra_ehci_hub_control,
.clear_tt_buffer_complete = ehci_clear_tt_buffer_complete,
#ifdef CONFIG_PM
.bus_suspend = tegra_ehci_bus_suspend,
.bus_resume = tegra_ehci_bus_resume,
#endif
.relinquish_port = ehci_relinquish_port,
.port_handed_over = ehci_port_handed_over,
};
static int tegra_ehci_probe(struct platform_device *pdev)
{
struct resource *res;
struct usb_hcd *hcd;
struct tegra_ehci_hcd *tegra;
struct tegra_ehci_platform_data *pdata;
int err = 0;
int irq;
int instance = pdev->id;
pdata = pdev->dev.platform_data;
if (!pdata) {
dev_err(&pdev->dev, "Platform data missing\n");
return -EINVAL;
}
tegra = kzalloc(sizeof(struct tegra_ehci_hcd), GFP_KERNEL);
if (!tegra)
return -ENOMEM;
hcd = usb_create_hcd(&tegra_ehci_hc_driver, &pdev->dev,
dev_name(&pdev->dev));
if (!hcd) {
dev_err(&pdev->dev, "Unable to create HCD\n");
err = -ENOMEM;
goto fail_hcd;
}
platform_set_drvdata(pdev, tegra);
tegra->clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(tegra->clk)) {
dev_err(&pdev->dev, "Can't get ehci clock\n");
err = PTR_ERR(tegra->clk);
goto fail_clk;
}
err = clk_enable(tegra->clk);
if (err)
goto fail_clken;
tegra->emc_clk = clk_get(&pdev->dev, "emc");
if (IS_ERR(tegra->emc_clk)) {
dev_err(&pdev->dev, "Can't get emc clock\n");
err = PTR_ERR(tegra->emc_clk);
goto fail_emc_clk;
}
clk_enable(tegra->emc_clk);
clk_set_rate(tegra->emc_clk, 400000000);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "Failed to get I/O memory\n");
err = -ENXIO;
goto fail_io;
}
hcd->rsrc_start = res->start;
hcd->rsrc_len = resource_size(res);
hcd->regs = ioremap(res->start, resource_size(res));
if (!hcd->regs) {
dev_err(&pdev->dev, "Failed to remap I/O memory\n");
err = -ENOMEM;
goto fail_io;
}
tegra->phy = tegra_usb_phy_open(instance, hcd->regs, pdata->phy_config,
TEGRA_USB_PHY_MODE_HOST);
if (IS_ERR(tegra->phy)) {
dev_err(&pdev->dev, "Failed to open USB phy\n");
err = -ENXIO;
goto fail_phy;
}
err = tegra_usb_phy_power_on(tegra->phy);
if (err) {
dev_err(&pdev->dev, "Failed to power on the phy\n");
goto fail;
}
tegra->host_resumed = 1;
tegra->power_down_on_bus_suspend = pdata->power_down_on_bus_suspend;
tegra->ehci = hcd_to_ehci(hcd);
irq = platform_get_irq(pdev, 0);
if (!irq) {
dev_err(&pdev->dev, "Failed to get IRQ\n");
err = -ENODEV;
goto fail;
}
set_irq_flags(irq, IRQF_VALID);
#ifdef CONFIG_USB_OTG_UTILS
if (pdata->operating_mode == TEGRA_USB_OTG) {
tegra->transceiver = otg_get_transceiver();
if (tegra->transceiver)
otg_set_host(tegra->transceiver, &hcd->self);
}
#endif
err = usb_add_hcd(hcd, irq, IRQF_DISABLED | IRQF_SHARED);
if (err) {
dev_err(&pdev->dev, "Failed to add USB HCD\n");
goto fail;
}
return err;
fail:
#ifdef CONFIG_USB_OTG_UTILS
if (tegra->transceiver) {
otg_set_host(tegra->transceiver, NULL);
otg_put_transceiver(tegra->transceiver);
}
#endif
tegra_usb_phy_close(tegra->phy);
fail_phy:
iounmap(hcd->regs);
fail_io:
clk_disable(tegra->emc_clk);
clk_put(tegra->emc_clk);
fail_emc_clk:
clk_disable(tegra->clk);
fail_clken:
clk_put(tegra->clk);
fail_clk:
usb_put_hcd(hcd);
fail_hcd:
kfree(tegra);
return err;
}
#ifdef CONFIG_PM
static int tegra_ehci_resume(struct platform_device *pdev)
{
struct tegra_ehci_hcd *tegra = platform_get_drvdata(pdev);
struct usb_hcd *hcd = ehci_to_hcd(tegra->ehci);
if (tegra->bus_suspended)
return 0;
return tegra_usb_resume(hcd);
}
static int tegra_ehci_suspend(struct platform_device *pdev, pm_message_t state)
{
struct tegra_ehci_hcd *tegra = platform_get_drvdata(pdev);
struct usb_hcd *hcd = ehci_to_hcd(tegra->ehci);
if (tegra->bus_suspended)
return 0;
if (time_before(jiffies, tegra->ehci->next_statechange))
msleep(10);
return tegra_usb_suspend(hcd);
}
#endif
static int tegra_ehci_remove(struct platform_device *pdev)
{
struct tegra_ehci_hcd *tegra = platform_get_drvdata(pdev);
struct usb_hcd *hcd = ehci_to_hcd(tegra->ehci);
if (tegra == NULL || hcd == NULL)
return -EINVAL;
#ifdef CONFIG_USB_OTG_UTILS
if (tegra->transceiver) {
otg_set_host(tegra->transceiver, NULL);
otg_put_transceiver(tegra->transceiver);
}
#endif
usb_remove_hcd(hcd);
usb_put_hcd(hcd);
tegra_usb_phy_close(tegra->phy);
iounmap(hcd->regs);
clk_disable(tegra->clk);
clk_put(tegra->clk);
clk_disable(tegra->emc_clk);
clk_put(tegra->emc_clk);
kfree(tegra);
return 0;
}
static void tegra_ehci_hcd_shutdown(struct platform_device *pdev)
{
struct tegra_ehci_hcd *tegra = platform_get_drvdata(pdev);
struct usb_hcd *hcd = ehci_to_hcd(tegra->ehci);
if (hcd->driver->shutdown)
hcd->driver->shutdown(hcd);
}
static struct platform_driver tegra_ehci_driver = {
.probe = tegra_ehci_probe,
.remove = tegra_ehci_remove,
#ifdef CONFIG_PM
.suspend = tegra_ehci_suspend,
.resume = tegra_ehci_resume,
#endif
.shutdown = tegra_ehci_hcd_shutdown,
.driver = {
.name = "tegra-ehci",
}
};
| gpl-2.0 |
cholokei/msm8660_test_kernel-1 | fs/gfs2/sys.c | 2939 | 16480 | /*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*/
#include <linux/sched.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/module.h>
#include <linux/kobject.h>
#include <asm/uaccess.h>
#include <linux/gfs2_ondisk.h>
#include <linux/genhd.h>
#include "gfs2.h"
#include "incore.h"
#include "sys.h"
#include "super.h"
#include "glock.h"
#include "quota.h"
#include "util.h"
#include "glops.h"
#include "recovery.h"
struct gfs2_attr {
struct attribute attr;
ssize_t (*show)(struct gfs2_sbd *, char *);
ssize_t (*store)(struct gfs2_sbd *, const char *, size_t);
};
static ssize_t gfs2_attr_show(struct kobject *kobj, struct attribute *attr,
char *buf)
{
struct gfs2_sbd *sdp = container_of(kobj, struct gfs2_sbd, sd_kobj);
struct gfs2_attr *a = container_of(attr, struct gfs2_attr, attr);
return a->show ? a->show(sdp, buf) : 0;
}
static ssize_t gfs2_attr_store(struct kobject *kobj, struct attribute *attr,
const char *buf, size_t len)
{
struct gfs2_sbd *sdp = container_of(kobj, struct gfs2_sbd, sd_kobj);
struct gfs2_attr *a = container_of(attr, struct gfs2_attr, attr);
return a->store ? a->store(sdp, buf, len) : len;
}
static const struct sysfs_ops gfs2_attr_ops = {
.show = gfs2_attr_show,
.store = gfs2_attr_store,
};
static struct kset *gfs2_kset;
static ssize_t id_show(struct gfs2_sbd *sdp, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%u:%u\n",
MAJOR(sdp->sd_vfs->s_dev), MINOR(sdp->sd_vfs->s_dev));
}
static ssize_t fsname_show(struct gfs2_sbd *sdp, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", sdp->sd_fsname);
}
static int gfs2_uuid_valid(const u8 *uuid)
{
int i;
for (i = 0; i < 16; i++) {
if (uuid[i])
return 1;
}
return 0;
}
static ssize_t uuid_show(struct gfs2_sbd *sdp, char *buf)
{
struct super_block *s = sdp->sd_vfs;
const u8 *uuid = s->s_uuid;
buf[0] = '\0';
if (!gfs2_uuid_valid(uuid))
return 0;
return snprintf(buf, PAGE_SIZE, "%pUB\n", uuid);
}
static ssize_t freeze_show(struct gfs2_sbd *sdp, char *buf)
{
unsigned int count;
mutex_lock(&sdp->sd_freeze_lock);
count = sdp->sd_freeze_count;
mutex_unlock(&sdp->sd_freeze_lock);
return snprintf(buf, PAGE_SIZE, "%u\n", count);
}
static ssize_t freeze_store(struct gfs2_sbd *sdp, const char *buf, size_t len)
{
ssize_t ret = len;
int error = 0;
int n = simple_strtol(buf, NULL, 0);
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
switch (n) {
case 0:
gfs2_unfreeze_fs(sdp);
break;
case 1:
error = gfs2_freeze_fs(sdp);
break;
default:
ret = -EINVAL;
}
if (error)
fs_warn(sdp, "freeze %d error %d", n, error);
return ret;
}
static ssize_t withdraw_show(struct gfs2_sbd *sdp, char *buf)
{
unsigned int b = test_bit(SDF_SHUTDOWN, &sdp->sd_flags);
return snprintf(buf, PAGE_SIZE, "%u\n", b);
}
static ssize_t withdraw_store(struct gfs2_sbd *sdp, const char *buf, size_t len)
{
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
if (simple_strtol(buf, NULL, 0) != 1)
return -EINVAL;
gfs2_lm_withdraw(sdp,
"GFS2: fsid=%s: withdrawing from cluster at user's request\n",
sdp->sd_fsname);
return len;
}
static ssize_t statfs_sync_store(struct gfs2_sbd *sdp, const char *buf,
size_t len)
{
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
if (simple_strtol(buf, NULL, 0) != 1)
return -EINVAL;
gfs2_statfs_sync(sdp->sd_vfs, 0);
return len;
}
static ssize_t quota_sync_store(struct gfs2_sbd *sdp, const char *buf,
size_t len)
{
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
if (simple_strtol(buf, NULL, 0) != 1)
return -EINVAL;
gfs2_quota_sync(sdp->sd_vfs, 0, 1);
return len;
}
static ssize_t quota_refresh_user_store(struct gfs2_sbd *sdp, const char *buf,
size_t len)
{
int error;
u32 id;
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
id = simple_strtoul(buf, NULL, 0);
error = gfs2_quota_refresh(sdp, 1, id);
return error ? error : len;
}
static ssize_t quota_refresh_group_store(struct gfs2_sbd *sdp, const char *buf,
size_t len)
{
int error;
u32 id;
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
id = simple_strtoul(buf, NULL, 0);
error = gfs2_quota_refresh(sdp, 0, id);
return error ? error : len;
}
static ssize_t demote_rq_store(struct gfs2_sbd *sdp, const char *buf, size_t len)
{
struct gfs2_glock *gl;
const struct gfs2_glock_operations *glops;
unsigned int glmode;
unsigned int gltype;
unsigned long long glnum;
char mode[16];
int rv;
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
rv = sscanf(buf, "%u:%llu %15s", &gltype, &glnum,
mode);
if (rv != 3)
return -EINVAL;
if (strcmp(mode, "EX") == 0)
glmode = LM_ST_UNLOCKED;
else if ((strcmp(mode, "CW") == 0) || (strcmp(mode, "DF") == 0))
glmode = LM_ST_DEFERRED;
else if ((strcmp(mode, "PR") == 0) || (strcmp(mode, "SH") == 0))
glmode = LM_ST_SHARED;
else
return -EINVAL;
if (gltype > LM_TYPE_JOURNAL)
return -EINVAL;
if (gltype == LM_TYPE_NONDISK && glnum == GFS2_TRANS_LOCK)
glops = &gfs2_trans_glops;
else
glops = gfs2_glops_list[gltype];
if (glops == NULL)
return -EINVAL;
if (!test_and_set_bit(SDF_DEMOTE, &sdp->sd_flags))
fs_info(sdp, "demote interface used\n");
rv = gfs2_glock_get(sdp, glnum, glops, 0, &gl);
if (rv)
return rv;
gfs2_glock_cb(gl, glmode);
gfs2_glock_put(gl);
return len;
}
#define GFS2_ATTR(name, mode, show, store) \
static struct gfs2_attr gfs2_attr_##name = __ATTR(name, mode, show, store)
GFS2_ATTR(id, 0444, id_show, NULL);
GFS2_ATTR(fsname, 0444, fsname_show, NULL);
GFS2_ATTR(uuid, 0444, uuid_show, NULL);
GFS2_ATTR(freeze, 0644, freeze_show, freeze_store);
GFS2_ATTR(withdraw, 0644, withdraw_show, withdraw_store);
GFS2_ATTR(statfs_sync, 0200, NULL, statfs_sync_store);
GFS2_ATTR(quota_sync, 0200, NULL, quota_sync_store);
GFS2_ATTR(quota_refresh_user, 0200, NULL, quota_refresh_user_store);
GFS2_ATTR(quota_refresh_group, 0200, NULL, quota_refresh_group_store);
GFS2_ATTR(demote_rq, 0200, NULL, demote_rq_store);
static struct attribute *gfs2_attrs[] = {
&gfs2_attr_id.attr,
&gfs2_attr_fsname.attr,
&gfs2_attr_uuid.attr,
&gfs2_attr_freeze.attr,
&gfs2_attr_withdraw.attr,
&gfs2_attr_statfs_sync.attr,
&gfs2_attr_quota_sync.attr,
&gfs2_attr_quota_refresh_user.attr,
&gfs2_attr_quota_refresh_group.attr,
&gfs2_attr_demote_rq.attr,
NULL,
};
static struct kobj_type gfs2_ktype = {
.default_attrs = gfs2_attrs,
.sysfs_ops = &gfs2_attr_ops,
};
/*
* lock_module. Originally from lock_dlm
*/
static ssize_t proto_name_show(struct gfs2_sbd *sdp, char *buf)
{
const struct lm_lockops *ops = sdp->sd_lockstruct.ls_ops;
return sprintf(buf, "%s\n", ops->lm_proto_name);
}
static ssize_t block_show(struct gfs2_sbd *sdp, char *buf)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
ssize_t ret;
int val = 0;
if (test_bit(DFL_BLOCK_LOCKS, &ls->ls_flags))
val = 1;
ret = sprintf(buf, "%d\n", val);
return ret;
}
static ssize_t block_store(struct gfs2_sbd *sdp, const char *buf, size_t len)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
ssize_t ret = len;
int val;
val = simple_strtol(buf, NULL, 0);
if (val == 1)
set_bit(DFL_BLOCK_LOCKS, &ls->ls_flags);
else if (val == 0) {
clear_bit(DFL_BLOCK_LOCKS, &ls->ls_flags);
smp_mb__after_clear_bit();
gfs2_glock_thaw(sdp);
} else {
ret = -EINVAL;
}
return ret;
}
static ssize_t lkfirst_show(struct gfs2_sbd *sdp, char *buf)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sprintf(buf, "%d\n", ls->ls_first);
}
static ssize_t lkfirst_store(struct gfs2_sbd *sdp, const char *buf, size_t len)
{
unsigned first;
int rv;
rv = sscanf(buf, "%u", &first);
if (rv != 1 || first > 1)
return -EINVAL;
rv = wait_for_completion_killable(&sdp->sd_locking_init);
if (rv)
return rv;
spin_lock(&sdp->sd_jindex_spin);
rv = -EBUSY;
if (test_bit(SDF_NOJOURNALID, &sdp->sd_flags) == 0)
goto out;
rv = -EINVAL;
if (sdp->sd_args.ar_spectator)
goto out;
if (sdp->sd_lockstruct.ls_ops->lm_mount == NULL)
goto out;
sdp->sd_lockstruct.ls_first = first;
rv = 0;
out:
spin_unlock(&sdp->sd_jindex_spin);
return rv ? rv : len;
}
static ssize_t first_done_show(struct gfs2_sbd *sdp, char *buf)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sprintf(buf, "%d\n", ls->ls_first_done);
}
static ssize_t recover_store(struct gfs2_sbd *sdp, const char *buf, size_t len)
{
unsigned jid;
struct gfs2_jdesc *jd;
int rv;
rv = sscanf(buf, "%u", &jid);
if (rv != 1)
return -EINVAL;
rv = -ESHUTDOWN;
spin_lock(&sdp->sd_jindex_spin);
if (test_bit(SDF_NORECOVERY, &sdp->sd_flags))
goto out;
rv = -EBUSY;
if (sdp->sd_jdesc->jd_jid == jid)
goto out;
rv = -ENOENT;
list_for_each_entry(jd, &sdp->sd_jindex_list, jd_list) {
if (jd->jd_jid != jid)
continue;
rv = gfs2_recover_journal(jd, false);
break;
}
out:
spin_unlock(&sdp->sd_jindex_spin);
return rv ? rv : len;
}
static ssize_t recover_done_show(struct gfs2_sbd *sdp, char *buf)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sprintf(buf, "%d\n", ls->ls_recover_jid_done);
}
static ssize_t recover_status_show(struct gfs2_sbd *sdp, char *buf)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sprintf(buf, "%d\n", ls->ls_recover_jid_status);
}
static ssize_t jid_show(struct gfs2_sbd *sdp, char *buf)
{
return sprintf(buf, "%d\n", sdp->sd_lockstruct.ls_jid);
}
static ssize_t jid_store(struct gfs2_sbd *sdp, const char *buf, size_t len)
{
int jid;
int rv;
rv = sscanf(buf, "%d", &jid);
if (rv != 1)
return -EINVAL;
rv = wait_for_completion_killable(&sdp->sd_locking_init);
if (rv)
return rv;
spin_lock(&sdp->sd_jindex_spin);
rv = -EINVAL;
if (sdp->sd_lockstruct.ls_ops->lm_mount == NULL)
goto out;
rv = -EBUSY;
if (test_bit(SDF_NOJOURNALID, &sdp->sd_flags) == 0)
goto out;
rv = 0;
if (sdp->sd_args.ar_spectator && jid > 0)
rv = jid = -EINVAL;
sdp->sd_lockstruct.ls_jid = jid;
clear_bit(SDF_NOJOURNALID, &sdp->sd_flags);
smp_mb__after_clear_bit();
wake_up_bit(&sdp->sd_flags, SDF_NOJOURNALID);
out:
spin_unlock(&sdp->sd_jindex_spin);
return rv ? rv : len;
}
#define GDLM_ATTR(_name,_mode,_show,_store) \
static struct gfs2_attr gdlm_attr_##_name = __ATTR(_name,_mode,_show,_store)
GDLM_ATTR(proto_name, 0444, proto_name_show, NULL);
GDLM_ATTR(block, 0644, block_show, block_store);
GDLM_ATTR(withdraw, 0644, withdraw_show, withdraw_store);
GDLM_ATTR(jid, 0644, jid_show, jid_store);
GDLM_ATTR(first, 0644, lkfirst_show, lkfirst_store);
GDLM_ATTR(first_done, 0444, first_done_show, NULL);
GDLM_ATTR(recover, 0600, NULL, recover_store);
GDLM_ATTR(recover_done, 0444, recover_done_show, NULL);
GDLM_ATTR(recover_status, 0444, recover_status_show, NULL);
static struct attribute *lock_module_attrs[] = {
&gdlm_attr_proto_name.attr,
&gdlm_attr_block.attr,
&gdlm_attr_withdraw.attr,
&gdlm_attr_jid.attr,
&gdlm_attr_first.attr,
&gdlm_attr_first_done.attr,
&gdlm_attr_recover.attr,
&gdlm_attr_recover_done.attr,
&gdlm_attr_recover_status.attr,
NULL,
};
/*
* get and set struct gfs2_tune fields
*/
static ssize_t quota_scale_show(struct gfs2_sbd *sdp, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%u %u\n",
sdp->sd_tune.gt_quota_scale_num,
sdp->sd_tune.gt_quota_scale_den);
}
static ssize_t quota_scale_store(struct gfs2_sbd *sdp, const char *buf,
size_t len)
{
struct gfs2_tune *gt = &sdp->sd_tune;
unsigned int x, y;
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
if (sscanf(buf, "%u %u", &x, &y) != 2 || !y)
return -EINVAL;
spin_lock(>->gt_spin);
gt->gt_quota_scale_num = x;
gt->gt_quota_scale_den = y;
spin_unlock(>->gt_spin);
return len;
}
static ssize_t tune_set(struct gfs2_sbd *sdp, unsigned int *field,
int check_zero, const char *buf, size_t len)
{
struct gfs2_tune *gt = &sdp->sd_tune;
unsigned int x;
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
x = simple_strtoul(buf, NULL, 0);
if (check_zero && !x)
return -EINVAL;
spin_lock(>->gt_spin);
*field = x;
spin_unlock(>->gt_spin);
return len;
}
#define TUNE_ATTR_3(name, show, store) \
static struct gfs2_attr tune_attr_##name = __ATTR(name, 0644, show, store)
#define TUNE_ATTR_2(name, store) \
static ssize_t name##_show(struct gfs2_sbd *sdp, char *buf) \
{ \
return snprintf(buf, PAGE_SIZE, "%u\n", sdp->sd_tune.gt_##name); \
} \
TUNE_ATTR_3(name, name##_show, store)
#define TUNE_ATTR(name, check_zero) \
static ssize_t name##_store(struct gfs2_sbd *sdp, const char *buf, size_t len)\
{ \
return tune_set(sdp, &sdp->sd_tune.gt_##name, check_zero, buf, len); \
} \
TUNE_ATTR_2(name, name##_store)
TUNE_ATTR(quota_warn_period, 0);
TUNE_ATTR(quota_quantum, 0);
TUNE_ATTR(max_readahead, 0);
TUNE_ATTR(complain_secs, 0);
TUNE_ATTR(statfs_slow, 0);
TUNE_ATTR(new_files_jdata, 0);
TUNE_ATTR(quota_simul_sync, 1);
TUNE_ATTR(statfs_quantum, 1);
TUNE_ATTR_3(quota_scale, quota_scale_show, quota_scale_store);
static struct attribute *tune_attrs[] = {
&tune_attr_quota_warn_period.attr,
&tune_attr_quota_quantum.attr,
&tune_attr_max_readahead.attr,
&tune_attr_complain_secs.attr,
&tune_attr_statfs_slow.attr,
&tune_attr_quota_simul_sync.attr,
&tune_attr_statfs_quantum.attr,
&tune_attr_quota_scale.attr,
&tune_attr_new_files_jdata.attr,
NULL,
};
static struct attribute_group tune_group = {
.name = "tune",
.attrs = tune_attrs,
};
static struct attribute_group lock_module_group = {
.name = "lock_module",
.attrs = lock_module_attrs,
};
int gfs2_sys_fs_add(struct gfs2_sbd *sdp)
{
struct super_block *sb = sdp->sd_vfs;
int error;
char ro[20];
char spectator[20];
char *envp[] = { ro, spectator, NULL };
sprintf(ro, "RDONLY=%d", (sb->s_flags & MS_RDONLY) ? 1 : 0);
sprintf(spectator, "SPECTATOR=%d", sdp->sd_args.ar_spectator ? 1 : 0);
sdp->sd_kobj.kset = gfs2_kset;
error = kobject_init_and_add(&sdp->sd_kobj, &gfs2_ktype, NULL,
"%s", sdp->sd_table_name);
if (error)
goto fail;
error = sysfs_create_group(&sdp->sd_kobj, &tune_group);
if (error)
goto fail_reg;
error = sysfs_create_group(&sdp->sd_kobj, &lock_module_group);
if (error)
goto fail_tune;
error = sysfs_create_link(&sdp->sd_kobj,
&disk_to_dev(sb->s_bdev->bd_disk)->kobj,
"device");
if (error)
goto fail_lock_module;
kobject_uevent_env(&sdp->sd_kobj, KOBJ_ADD, envp);
return 0;
fail_lock_module:
sysfs_remove_group(&sdp->sd_kobj, &lock_module_group);
fail_tune:
sysfs_remove_group(&sdp->sd_kobj, &tune_group);
fail_reg:
kobject_put(&sdp->sd_kobj);
fail:
fs_err(sdp, "error %d adding sysfs files", error);
return error;
}
void gfs2_sys_fs_del(struct gfs2_sbd *sdp)
{
sysfs_remove_link(&sdp->sd_kobj, "device");
sysfs_remove_group(&sdp->sd_kobj, &tune_group);
sysfs_remove_group(&sdp->sd_kobj, &lock_module_group);
kobject_put(&sdp->sd_kobj);
}
static int gfs2_uevent(struct kset *kset, struct kobject *kobj,
struct kobj_uevent_env *env)
{
struct gfs2_sbd *sdp = container_of(kobj, struct gfs2_sbd, sd_kobj);
struct super_block *s = sdp->sd_vfs;
const u8 *uuid = s->s_uuid;
add_uevent_var(env, "LOCKTABLE=%s", sdp->sd_table_name);
add_uevent_var(env, "LOCKPROTO=%s", sdp->sd_proto_name);
if (!test_bit(SDF_NOJOURNALID, &sdp->sd_flags))
add_uevent_var(env, "JOURNALID=%d", sdp->sd_lockstruct.ls_jid);
if (gfs2_uuid_valid(uuid))
add_uevent_var(env, "UUID=%pUB", uuid);
return 0;
}
static const struct kset_uevent_ops gfs2_uevent_ops = {
.uevent = gfs2_uevent,
};
int gfs2_sys_init(void)
{
gfs2_kset = kset_create_and_add("gfs2", &gfs2_uevent_ops, fs_kobj);
if (!gfs2_kset)
return -ENOMEM;
return 0;
}
void gfs2_sys_uninit(void)
{
kset_unregister(gfs2_kset);
}
| gpl-2.0 |
TeamWin/android_kernel_huawei_mt2l03 | kernel/irq/pm.c | 3451 | 3119 | /*
* linux/kernel/irq/pm.c
*
* Copyright (C) 2009 Rafael J. Wysocki <rjw@sisk.pl>, Novell Inc.
*
* This file contains power management functions related to interrupts.
*/
#include <linux/irq.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/syscore_ops.h>
#include "internals.h"
/**
* suspend_device_irqs - disable all currently enabled interrupt lines
*
* During system-wide suspend or hibernation device drivers need to be prevented
* from receiving interrupts and this function is provided for this purpose.
* It marks all interrupt lines in use, except for the timer ones, as disabled
* and sets the IRQS_SUSPENDED flag for each of them.
*/
void suspend_device_irqs(void)
{
struct irq_desc *desc;
int irq;
for_each_irq_desc(irq, desc) {
unsigned long flags;
raw_spin_lock_irqsave(&desc->lock, flags);
__disable_irq(desc, irq, true);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
for_each_irq_desc(irq, desc)
if (desc->istate & IRQS_SUSPENDED)
synchronize_irq(irq);
}
EXPORT_SYMBOL_GPL(suspend_device_irqs);
static void resume_irqs(bool want_early)
{
struct irq_desc *desc;
int irq;
for_each_irq_desc_reverse(irq, desc) {
unsigned long flags;
bool is_early = desc->action &&
desc->action->flags & IRQF_EARLY_RESUME;
if (is_early != want_early)
continue;
raw_spin_lock_irqsave(&desc->lock, flags);
__enable_irq(desc, irq, true);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
}
/**
* irq_pm_syscore_ops - enable interrupt lines early
*
* Enable all interrupt lines with %IRQF_EARLY_RESUME set.
*/
static void irq_pm_syscore_resume(void)
{
resume_irqs(true);
}
static struct syscore_ops irq_pm_syscore_ops = {
.resume = irq_pm_syscore_resume,
};
static int __init irq_pm_init_ops(void)
{
register_syscore_ops(&irq_pm_syscore_ops);
return 0;
}
device_initcall(irq_pm_init_ops);
/**
* resume_device_irqs - enable interrupt lines disabled by suspend_device_irqs()
*
* Enable all non-%IRQF_EARLY_RESUME interrupt lines previously
* disabled by suspend_device_irqs() that have the IRQS_SUSPENDED flag
* set as well as those with %IRQF_FORCE_RESUME.
*/
void resume_device_irqs(void)
{
resume_irqs(false);
}
EXPORT_SYMBOL_GPL(resume_device_irqs);
/**
* check_wakeup_irqs - check if any wake-up interrupts are pending
*/
int check_wakeup_irqs(void)
{
struct irq_desc *desc;
int irq;
for_each_irq_desc(irq, desc) {
if (irqd_is_wakeup_set(&desc->irq_data)) {
if (desc->istate & IRQS_PENDING) {
pr_info("Wakeup IRQ %d %s pending, suspend aborted\n",
irq,
desc->action && desc->action->name ?
desc->action->name : "");
return -EBUSY;
}
continue;
}
/*
* Check the non wakeup interrupts whether they need
* to be masked before finally going into suspend
* state. That's for hardware which has no wakeup
* source configuration facility. The chip
* implementation indicates that with
* IRQCHIP_MASK_ON_SUSPEND.
*/
if (desc->istate & IRQS_SUSPENDED &&
irq_desc_get_chip(desc)->flags & IRQCHIP_MASK_ON_SUSPEND)
mask_irq(desc);
}
return 0;
}
| gpl-2.0 |
syhost/android_kernel_kitkat | drivers/video/omap2/omapfb/omapfb-main.c | 3963 | 56899 | /*
* linux/drivers/video/omap2/omapfb-main.c
*
* Copyright (C) 2008 Nokia Corporation
* Author: Tomi Valkeinen <tomi.valkeinen@nokia.com>
*
* Some code and ideas taken from drivers/video/omap/ driver
* by Imre Deak.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/fb.h>
#include <linux/dma-mapping.h>
#include <linux/vmalloc.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/omapfb.h>
#include <video/omapdss.h>
#include <plat/vram.h>
#include <plat/vrfb.h>
#include "omapfb.h"
#define MODULE_NAME "omapfb"
#define OMAPFB_PLANE_XRES_MIN 8
#define OMAPFB_PLANE_YRES_MIN 8
static char *def_mode;
static char *def_vram;
static bool def_vrfb;
static int def_rotate;
static bool def_mirror;
static bool auto_update;
static unsigned int auto_update_freq;
module_param(auto_update, bool, 0);
module_param(auto_update_freq, uint, 0644);
#ifdef DEBUG
bool omapfb_debug;
module_param_named(debug, omapfb_debug, bool, 0644);
static bool omapfb_test_pattern;
module_param_named(test, omapfb_test_pattern, bool, 0644);
#endif
static int omapfb_fb_init(struct omapfb2_device *fbdev, struct fb_info *fbi);
static int omapfb_get_recommended_bpp(struct omapfb2_device *fbdev,
struct omap_dss_device *dssdev);
#ifdef DEBUG
static void draw_pixel(struct fb_info *fbi, int x, int y, unsigned color)
{
struct fb_var_screeninfo *var = &fbi->var;
struct fb_fix_screeninfo *fix = &fbi->fix;
void __iomem *addr = fbi->screen_base;
const unsigned bytespp = var->bits_per_pixel >> 3;
const unsigned line_len = fix->line_length / bytespp;
int r = (color >> 16) & 0xff;
int g = (color >> 8) & 0xff;
int b = (color >> 0) & 0xff;
if (var->bits_per_pixel == 16) {
u16 __iomem *p = (u16 __iomem *)addr;
p += y * line_len + x;
r = r * 32 / 256;
g = g * 64 / 256;
b = b * 32 / 256;
__raw_writew((r << 11) | (g << 5) | (b << 0), p);
} else if (var->bits_per_pixel == 24) {
u8 __iomem *p = (u8 __iomem *)addr;
p += (y * line_len + x) * 3;
__raw_writeb(b, p + 0);
__raw_writeb(g, p + 1);
__raw_writeb(r, p + 2);
} else if (var->bits_per_pixel == 32) {
u32 __iomem *p = (u32 __iomem *)addr;
p += y * line_len + x;
__raw_writel(color, p);
}
}
static void fill_fb(struct fb_info *fbi)
{
struct fb_var_screeninfo *var = &fbi->var;
const short w = var->xres_virtual;
const short h = var->yres_virtual;
void __iomem *addr = fbi->screen_base;
int y, x;
if (!addr)
return;
DBG("fill_fb %dx%d, line_len %d bytes\n", w, h, fbi->fix.line_length);
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++) {
if (x < 20 && y < 20)
draw_pixel(fbi, x, y, 0xffffff);
else if (x < 20 && (y > 20 && y < h - 20))
draw_pixel(fbi, x, y, 0xff);
else if (y < 20 && (x > 20 && x < w - 20))
draw_pixel(fbi, x, y, 0xff00);
else if (x > w - 20 && (y > 20 && y < h - 20))
draw_pixel(fbi, x, y, 0xff0000);
else if (y > h - 20 && (x > 20 && x < w - 20))
draw_pixel(fbi, x, y, 0xffff00);
else if (x == 20 || x == w - 20 ||
y == 20 || y == h - 20)
draw_pixel(fbi, x, y, 0xffffff);
else if (x == y || w - x == h - y)
draw_pixel(fbi, x, y, 0xff00ff);
else if (w - x == y || x == h - y)
draw_pixel(fbi, x, y, 0x00ffff);
else if (x > 20 && y > 20 && x < w - 20 && y < h - 20) {
int t = x * 3 / w;
unsigned r = 0, g = 0, b = 0;
unsigned c;
if (var->bits_per_pixel == 16) {
if (t == 0)
b = (y % 32) * 256 / 32;
else if (t == 1)
g = (y % 64) * 256 / 64;
else if (t == 2)
r = (y % 32) * 256 / 32;
} else {
if (t == 0)
b = (y % 256);
else if (t == 1)
g = (y % 256);
else if (t == 2)
r = (y % 256);
}
c = (r << 16) | (g << 8) | (b << 0);
draw_pixel(fbi, x, y, c);
} else {
draw_pixel(fbi, x, y, 0);
}
}
}
}
#endif
static unsigned omapfb_get_vrfb_offset(const struct omapfb_info *ofbi, int rot)
{
const struct vrfb *vrfb = &ofbi->region->vrfb;
unsigned offset;
switch (rot) {
case FB_ROTATE_UR:
offset = 0;
break;
case FB_ROTATE_CW:
offset = vrfb->yoffset;
break;
case FB_ROTATE_UD:
offset = vrfb->yoffset * OMAP_VRFB_LINE_LEN + vrfb->xoffset;
break;
case FB_ROTATE_CCW:
offset = vrfb->xoffset * OMAP_VRFB_LINE_LEN;
break;
default:
BUG();
}
offset *= vrfb->bytespp;
return offset;
}
static u32 omapfb_get_region_rot_paddr(const struct omapfb_info *ofbi, int rot)
{
if (ofbi->rotation_type == OMAP_DSS_ROT_VRFB) {
return ofbi->region->vrfb.paddr[rot]
+ omapfb_get_vrfb_offset(ofbi, rot);
} else {
return ofbi->region->paddr;
}
}
static u32 omapfb_get_region_paddr(const struct omapfb_info *ofbi)
{
if (ofbi->rotation_type == OMAP_DSS_ROT_VRFB)
return ofbi->region->vrfb.paddr[0];
else
return ofbi->region->paddr;
}
static void __iomem *omapfb_get_region_vaddr(const struct omapfb_info *ofbi)
{
if (ofbi->rotation_type == OMAP_DSS_ROT_VRFB)
return ofbi->region->vrfb.vaddr[0];
else
return ofbi->region->vaddr;
}
static struct omapfb_colormode omapfb_colormodes[] = {
{
.dssmode = OMAP_DSS_COLOR_UYVY,
.bits_per_pixel = 16,
.nonstd = OMAPFB_COLOR_YUV422,
}, {
.dssmode = OMAP_DSS_COLOR_YUV2,
.bits_per_pixel = 16,
.nonstd = OMAPFB_COLOR_YUY422,
}, {
.dssmode = OMAP_DSS_COLOR_ARGB16,
.bits_per_pixel = 16,
.red = { .length = 4, .offset = 8, .msb_right = 0 },
.green = { .length = 4, .offset = 4, .msb_right = 0 },
.blue = { .length = 4, .offset = 0, .msb_right = 0 },
.transp = { .length = 4, .offset = 12, .msb_right = 0 },
}, {
.dssmode = OMAP_DSS_COLOR_RGB16,
.bits_per_pixel = 16,
.red = { .length = 5, .offset = 11, .msb_right = 0 },
.green = { .length = 6, .offset = 5, .msb_right = 0 },
.blue = { .length = 5, .offset = 0, .msb_right = 0 },
.transp = { .length = 0, .offset = 0, .msb_right = 0 },
}, {
.dssmode = OMAP_DSS_COLOR_RGB24P,
.bits_per_pixel = 24,
.red = { .length = 8, .offset = 16, .msb_right = 0 },
.green = { .length = 8, .offset = 8, .msb_right = 0 },
.blue = { .length = 8, .offset = 0, .msb_right = 0 },
.transp = { .length = 0, .offset = 0, .msb_right = 0 },
}, {
.dssmode = OMAP_DSS_COLOR_RGB24U,
.bits_per_pixel = 32,
.red = { .length = 8, .offset = 16, .msb_right = 0 },
.green = { .length = 8, .offset = 8, .msb_right = 0 },
.blue = { .length = 8, .offset = 0, .msb_right = 0 },
.transp = { .length = 0, .offset = 0, .msb_right = 0 },
}, {
.dssmode = OMAP_DSS_COLOR_ARGB32,
.bits_per_pixel = 32,
.red = { .length = 8, .offset = 16, .msb_right = 0 },
.green = { .length = 8, .offset = 8, .msb_right = 0 },
.blue = { .length = 8, .offset = 0, .msb_right = 0 },
.transp = { .length = 8, .offset = 24, .msb_right = 0 },
}, {
.dssmode = OMAP_DSS_COLOR_RGBA32,
.bits_per_pixel = 32,
.red = { .length = 8, .offset = 24, .msb_right = 0 },
.green = { .length = 8, .offset = 16, .msb_right = 0 },
.blue = { .length = 8, .offset = 8, .msb_right = 0 },
.transp = { .length = 8, .offset = 0, .msb_right = 0 },
}, {
.dssmode = OMAP_DSS_COLOR_RGBX32,
.bits_per_pixel = 32,
.red = { .length = 8, .offset = 24, .msb_right = 0 },
.green = { .length = 8, .offset = 16, .msb_right = 0 },
.blue = { .length = 8, .offset = 8, .msb_right = 0 },
.transp = { .length = 0, .offset = 0, .msb_right = 0 },
},
};
static bool cmp_var_to_colormode(struct fb_var_screeninfo *var,
struct omapfb_colormode *color)
{
bool cmp_component(struct fb_bitfield *f1, struct fb_bitfield *f2)
{
return f1->length == f2->length &&
f1->offset == f2->offset &&
f1->msb_right == f2->msb_right;
}
if (var->bits_per_pixel == 0 ||
var->red.length == 0 ||
var->blue.length == 0 ||
var->green.length == 0)
return 0;
return var->bits_per_pixel == color->bits_per_pixel &&
cmp_component(&var->red, &color->red) &&
cmp_component(&var->green, &color->green) &&
cmp_component(&var->blue, &color->blue) &&
cmp_component(&var->transp, &color->transp);
}
static void assign_colormode_to_var(struct fb_var_screeninfo *var,
struct omapfb_colormode *color)
{
var->bits_per_pixel = color->bits_per_pixel;
var->nonstd = color->nonstd;
var->red = color->red;
var->green = color->green;
var->blue = color->blue;
var->transp = color->transp;
}
static int fb_mode_to_dss_mode(struct fb_var_screeninfo *var,
enum omap_color_mode *mode)
{
enum omap_color_mode dssmode;
int i;
/* first match with nonstd field */
if (var->nonstd) {
for (i = 0; i < ARRAY_SIZE(omapfb_colormodes); ++i) {
struct omapfb_colormode *m = &omapfb_colormodes[i];
if (var->nonstd == m->nonstd) {
assign_colormode_to_var(var, m);
*mode = m->dssmode;
return 0;
}
}
return -EINVAL;
}
/* then try exact match of bpp and colors */
for (i = 0; i < ARRAY_SIZE(omapfb_colormodes); ++i) {
struct omapfb_colormode *m = &omapfb_colormodes[i];
if (cmp_var_to_colormode(var, m)) {
assign_colormode_to_var(var, m);
*mode = m->dssmode;
return 0;
}
}
/* match with bpp if user has not filled color fields
* properly */
switch (var->bits_per_pixel) {
case 1:
dssmode = OMAP_DSS_COLOR_CLUT1;
break;
case 2:
dssmode = OMAP_DSS_COLOR_CLUT2;
break;
case 4:
dssmode = OMAP_DSS_COLOR_CLUT4;
break;
case 8:
dssmode = OMAP_DSS_COLOR_CLUT8;
break;
case 12:
dssmode = OMAP_DSS_COLOR_RGB12U;
break;
case 16:
dssmode = OMAP_DSS_COLOR_RGB16;
break;
case 24:
dssmode = OMAP_DSS_COLOR_RGB24P;
break;
case 32:
dssmode = OMAP_DSS_COLOR_RGB24U;
break;
default:
return -EINVAL;
}
for (i = 0; i < ARRAY_SIZE(omapfb_colormodes); ++i) {
struct omapfb_colormode *m = &omapfb_colormodes[i];
if (dssmode == m->dssmode) {
assign_colormode_to_var(var, m);
*mode = m->dssmode;
return 0;
}
}
return -EINVAL;
}
static int check_fb_res_bounds(struct fb_var_screeninfo *var)
{
int xres_min = OMAPFB_PLANE_XRES_MIN;
int xres_max = 2048;
int yres_min = OMAPFB_PLANE_YRES_MIN;
int yres_max = 2048;
/* XXX: some applications seem to set virtual res to 0. */
if (var->xres_virtual == 0)
var->xres_virtual = var->xres;
if (var->yres_virtual == 0)
var->yres_virtual = var->yres;
if (var->xres_virtual < xres_min || var->yres_virtual < yres_min)
return -EINVAL;
if (var->xres < xres_min)
var->xres = xres_min;
if (var->yres < yres_min)
var->yres = yres_min;
if (var->xres > xres_max)
var->xres = xres_max;
if (var->yres > yres_max)
var->yres = yres_max;
if (var->xres > var->xres_virtual)
var->xres = var->xres_virtual;
if (var->yres > var->yres_virtual)
var->yres = var->yres_virtual;
return 0;
}
static void shrink_height(unsigned long max_frame_size,
struct fb_var_screeninfo *var)
{
DBG("can't fit FB into memory, reducing y\n");
var->yres_virtual = max_frame_size /
(var->xres_virtual * var->bits_per_pixel >> 3);
if (var->yres_virtual < OMAPFB_PLANE_YRES_MIN)
var->yres_virtual = OMAPFB_PLANE_YRES_MIN;
if (var->yres > var->yres_virtual)
var->yres = var->yres_virtual;
}
static void shrink_width(unsigned long max_frame_size,
struct fb_var_screeninfo *var)
{
DBG("can't fit FB into memory, reducing x\n");
var->xres_virtual = max_frame_size / var->yres_virtual /
(var->bits_per_pixel >> 3);
if (var->xres_virtual < OMAPFB_PLANE_XRES_MIN)
var->xres_virtual = OMAPFB_PLANE_XRES_MIN;
if (var->xres > var->xres_virtual)
var->xres = var->xres_virtual;
}
static int check_vrfb_fb_size(unsigned long region_size,
const struct fb_var_screeninfo *var)
{
unsigned long min_phys_size = omap_vrfb_min_phys_size(var->xres_virtual,
var->yres_virtual, var->bits_per_pixel >> 3);
return min_phys_size > region_size ? -EINVAL : 0;
}
static int check_fb_size(const struct omapfb_info *ofbi,
struct fb_var_screeninfo *var)
{
unsigned long max_frame_size = ofbi->region->size;
int bytespp = var->bits_per_pixel >> 3;
unsigned long line_size = var->xres_virtual * bytespp;
if (ofbi->rotation_type == OMAP_DSS_ROT_VRFB) {
/* One needs to check for both VRFB and OMAPFB limitations. */
if (check_vrfb_fb_size(max_frame_size, var))
shrink_height(omap_vrfb_max_height(
max_frame_size, var->xres_virtual, bytespp) *
line_size, var);
if (check_vrfb_fb_size(max_frame_size, var)) {
DBG("cannot fit FB to memory\n");
return -EINVAL;
}
return 0;
}
DBG("max frame size %lu, line size %lu\n", max_frame_size, line_size);
if (line_size * var->yres_virtual > max_frame_size)
shrink_height(max_frame_size, var);
if (line_size * var->yres_virtual > max_frame_size) {
shrink_width(max_frame_size, var);
line_size = var->xres_virtual * bytespp;
}
if (line_size * var->yres_virtual > max_frame_size) {
DBG("cannot fit FB to memory\n");
return -EINVAL;
}
return 0;
}
/*
* Consider if VRFB assisted rotation is in use and if the virtual space for
* the zero degree view needs to be mapped. The need for mapping also acts as
* the trigger for setting up the hardware on the context in question. This
* ensures that one does not attempt to access the virtual view before the
* hardware is serving the address translations.
*/
static int setup_vrfb_rotation(struct fb_info *fbi)
{
struct omapfb_info *ofbi = FB2OFB(fbi);
struct omapfb2_mem_region *rg = ofbi->region;
struct vrfb *vrfb = &rg->vrfb;
struct fb_var_screeninfo *var = &fbi->var;
struct fb_fix_screeninfo *fix = &fbi->fix;
unsigned bytespp;
bool yuv_mode;
enum omap_color_mode mode;
int r;
bool reconf;
if (!rg->size || ofbi->rotation_type != OMAP_DSS_ROT_VRFB)
return 0;
DBG("setup_vrfb_rotation\n");
r = fb_mode_to_dss_mode(var, &mode);
if (r)
return r;
bytespp = var->bits_per_pixel >> 3;
yuv_mode = mode == OMAP_DSS_COLOR_YUV2 || mode == OMAP_DSS_COLOR_UYVY;
/* We need to reconfigure VRFB if the resolution changes, if yuv mode
* is enabled/disabled, or if bytes per pixel changes */
/* XXX we shouldn't allow this when framebuffer is mmapped */
reconf = false;
if (yuv_mode != vrfb->yuv_mode)
reconf = true;
else if (bytespp != vrfb->bytespp)
reconf = true;
else if (vrfb->xres != var->xres_virtual ||
vrfb->yres != var->yres_virtual)
reconf = true;
if (vrfb->vaddr[0] && reconf) {
fbi->screen_base = NULL;
fix->smem_start = 0;
fix->smem_len = 0;
iounmap(vrfb->vaddr[0]);
vrfb->vaddr[0] = NULL;
DBG("setup_vrfb_rotation: reset fb\n");
}
if (vrfb->vaddr[0])
return 0;
omap_vrfb_setup(&rg->vrfb, rg->paddr,
var->xres_virtual,
var->yres_virtual,
bytespp, yuv_mode);
/* Now one can ioremap the 0 angle view */
r = omap_vrfb_map_angle(vrfb, var->yres_virtual, 0);
if (r)
return r;
/* used by open/write in fbmem.c */
fbi->screen_base = ofbi->region->vrfb.vaddr[0];
fix->smem_start = ofbi->region->vrfb.paddr[0];
switch (var->nonstd) {
case OMAPFB_COLOR_YUV422:
case OMAPFB_COLOR_YUY422:
fix->line_length =
(OMAP_VRFB_LINE_LEN * var->bits_per_pixel) >> 2;
break;
default:
fix->line_length =
(OMAP_VRFB_LINE_LEN * var->bits_per_pixel) >> 3;
break;
}
fix->smem_len = var->yres_virtual * fix->line_length;
return 0;
}
int dss_mode_to_fb_mode(enum omap_color_mode dssmode,
struct fb_var_screeninfo *var)
{
int i;
for (i = 0; i < ARRAY_SIZE(omapfb_colormodes); ++i) {
struct omapfb_colormode *mode = &omapfb_colormodes[i];
if (dssmode == mode->dssmode) {
assign_colormode_to_var(var, mode);
return 0;
}
}
return -ENOENT;
}
void set_fb_fix(struct fb_info *fbi)
{
struct fb_fix_screeninfo *fix = &fbi->fix;
struct fb_var_screeninfo *var = &fbi->var;
struct omapfb_info *ofbi = FB2OFB(fbi);
struct omapfb2_mem_region *rg = ofbi->region;
DBG("set_fb_fix\n");
/* used by open/write in fbmem.c */
fbi->screen_base = (char __iomem *)omapfb_get_region_vaddr(ofbi);
/* used by mmap in fbmem.c */
if (ofbi->rotation_type == OMAP_DSS_ROT_VRFB) {
switch (var->nonstd) {
case OMAPFB_COLOR_YUV422:
case OMAPFB_COLOR_YUY422:
fix->line_length =
(OMAP_VRFB_LINE_LEN * var->bits_per_pixel) >> 2;
break;
default:
fix->line_length =
(OMAP_VRFB_LINE_LEN * var->bits_per_pixel) >> 3;
break;
}
fix->smem_len = var->yres_virtual * fix->line_length;
} else {
fix->line_length =
(var->xres_virtual * var->bits_per_pixel) >> 3;
fix->smem_len = rg->size;
}
fix->smem_start = omapfb_get_region_paddr(ofbi);
fix->type = FB_TYPE_PACKED_PIXELS;
if (var->nonstd)
fix->visual = FB_VISUAL_PSEUDOCOLOR;
else {
switch (var->bits_per_pixel) {
case 32:
case 24:
case 16:
case 12:
fix->visual = FB_VISUAL_TRUECOLOR;
/* 12bpp is stored in 16 bits */
break;
case 1:
case 2:
case 4:
case 8:
fix->visual = FB_VISUAL_PSEUDOCOLOR;
break;
}
}
fix->accel = FB_ACCEL_NONE;
fix->xpanstep = 1;
fix->ypanstep = 1;
}
/* check new var and possibly modify it to be ok */
int check_fb_var(struct fb_info *fbi, struct fb_var_screeninfo *var)
{
struct omapfb_info *ofbi = FB2OFB(fbi);
struct omap_dss_device *display = fb2display(fbi);
enum omap_color_mode mode = 0;
int i;
int r;
DBG("check_fb_var %d\n", ofbi->id);
WARN_ON(!atomic_read(&ofbi->region->lock_count));
r = fb_mode_to_dss_mode(var, &mode);
if (r) {
DBG("cannot convert var to omap dss mode\n");
return r;
}
for (i = 0; i < ofbi->num_overlays; ++i) {
if ((ofbi->overlays[i]->supported_modes & mode) == 0) {
DBG("invalid mode\n");
return -EINVAL;
}
}
if (var->rotate > 3)
return -EINVAL;
if (check_fb_res_bounds(var))
return -EINVAL;
/* When no memory is allocated ignore the size check */
if (ofbi->region->size != 0 && check_fb_size(ofbi, var))
return -EINVAL;
if (var->xres + var->xoffset > var->xres_virtual)
var->xoffset = var->xres_virtual - var->xres;
if (var->yres + var->yoffset > var->yres_virtual)
var->yoffset = var->yres_virtual - var->yres;
DBG("xres = %d, yres = %d, vxres = %d, vyres = %d\n",
var->xres, var->yres,
var->xres_virtual, var->yres_virtual);
if (display && display->driver->get_dimensions) {
u32 w, h;
display->driver->get_dimensions(display, &w, &h);
var->width = DIV_ROUND_CLOSEST(w, 1000);
var->height = DIV_ROUND_CLOSEST(h, 1000);
} else {
var->height = -1;
var->width = -1;
}
var->grayscale = 0;
if (display && display->driver->get_timings) {
struct omap_video_timings timings;
display->driver->get_timings(display, &timings);
/* pixclock in ps, the rest in pixclock */
var->pixclock = timings.pixel_clock != 0 ?
KHZ2PICOS(timings.pixel_clock) :
0;
var->left_margin = timings.hbp;
var->right_margin = timings.hfp;
var->upper_margin = timings.vbp;
var->lower_margin = timings.vfp;
var->hsync_len = timings.hsw;
var->vsync_len = timings.vsw;
} else {
var->pixclock = 0;
var->left_margin = 0;
var->right_margin = 0;
var->upper_margin = 0;
var->lower_margin = 0;
var->hsync_len = 0;
var->vsync_len = 0;
}
/* TODO: get these from panel->config */
var->vmode = FB_VMODE_NONINTERLACED;
var->sync = 0;
return 0;
}
/*
* ---------------------------------------------------------------------------
* fbdev framework callbacks
* ---------------------------------------------------------------------------
*/
static int omapfb_open(struct fb_info *fbi, int user)
{
return 0;
}
static int omapfb_release(struct fb_info *fbi, int user)
{
return 0;
}
static unsigned calc_rotation_offset_dma(const struct fb_var_screeninfo *var,
const struct fb_fix_screeninfo *fix, int rotation)
{
unsigned offset;
offset = var->yoffset * fix->line_length +
var->xoffset * (var->bits_per_pixel >> 3);
return offset;
}
static unsigned calc_rotation_offset_vrfb(const struct fb_var_screeninfo *var,
const struct fb_fix_screeninfo *fix, int rotation)
{
unsigned offset;
if (rotation == FB_ROTATE_UD)
offset = (var->yres_virtual - var->yres) *
fix->line_length;
else if (rotation == FB_ROTATE_CW)
offset = (var->yres_virtual - var->yres) *
(var->bits_per_pixel >> 3);
else
offset = 0;
if (rotation == FB_ROTATE_UR)
offset += var->yoffset * fix->line_length +
var->xoffset * (var->bits_per_pixel >> 3);
else if (rotation == FB_ROTATE_UD)
offset -= var->yoffset * fix->line_length +
var->xoffset * (var->bits_per_pixel >> 3);
else if (rotation == FB_ROTATE_CW)
offset -= var->xoffset * fix->line_length +
var->yoffset * (var->bits_per_pixel >> 3);
else if (rotation == FB_ROTATE_CCW)
offset += var->xoffset * fix->line_length +
var->yoffset * (var->bits_per_pixel >> 3);
return offset;
}
static void omapfb_calc_addr(const struct omapfb_info *ofbi,
const struct fb_var_screeninfo *var,
const struct fb_fix_screeninfo *fix,
int rotation, u32 *paddr)
{
u32 data_start_p;
int offset;
if (ofbi->rotation_type == OMAP_DSS_ROT_VRFB)
data_start_p = omapfb_get_region_rot_paddr(ofbi, rotation);
else
data_start_p = omapfb_get_region_paddr(ofbi);
if (ofbi->rotation_type == OMAP_DSS_ROT_VRFB)
offset = calc_rotation_offset_vrfb(var, fix, rotation);
else
offset = calc_rotation_offset_dma(var, fix, rotation);
data_start_p += offset;
if (offset)
DBG("offset %d, %d = %d\n",
var->xoffset, var->yoffset, offset);
DBG("paddr %x\n", data_start_p);
*paddr = data_start_p;
}
/* setup overlay according to the fb */
int omapfb_setup_overlay(struct fb_info *fbi, struct omap_overlay *ovl,
u16 posx, u16 posy, u16 outw, u16 outh)
{
int r = 0;
struct omapfb_info *ofbi = FB2OFB(fbi);
struct fb_var_screeninfo *var = &fbi->var;
struct fb_fix_screeninfo *fix = &fbi->fix;
enum omap_color_mode mode = 0;
u32 data_start_p = 0;
struct omap_overlay_info info;
int xres, yres;
int screen_width;
int mirror;
int rotation = var->rotate;
int i;
WARN_ON(!atomic_read(&ofbi->region->lock_count));
for (i = 0; i < ofbi->num_overlays; i++) {
if (ovl != ofbi->overlays[i])
continue;
rotation = (rotation + ofbi->rotation[i]) % 4;
break;
}
DBG("setup_overlay %d, posx %d, posy %d, outw %d, outh %d\n", ofbi->id,
posx, posy, outw, outh);
if (rotation == FB_ROTATE_CW || rotation == FB_ROTATE_CCW) {
xres = var->yres;
yres = var->xres;
} else {
xres = var->xres;
yres = var->yres;
}
if (ofbi->region->size)
omapfb_calc_addr(ofbi, var, fix, rotation, &data_start_p);
r = fb_mode_to_dss_mode(var, &mode);
if (r) {
DBG("fb_mode_to_dss_mode failed");
goto err;
}
switch (var->nonstd) {
case OMAPFB_COLOR_YUV422:
case OMAPFB_COLOR_YUY422:
if (ofbi->rotation_type == OMAP_DSS_ROT_VRFB) {
screen_width = fix->line_length
/ (var->bits_per_pixel >> 2);
break;
}
default:
screen_width = fix->line_length / (var->bits_per_pixel >> 3);
break;
}
ovl->get_overlay_info(ovl, &info);
if (ofbi->rotation_type == OMAP_DSS_ROT_VRFB)
mirror = 0;
else
mirror = ofbi->mirror;
info.paddr = data_start_p;
info.screen_width = screen_width;
info.width = xres;
info.height = yres;
info.color_mode = mode;
info.rotation_type = ofbi->rotation_type;
info.rotation = rotation;
info.mirror = mirror;
info.pos_x = posx;
info.pos_y = posy;
info.out_width = outw;
info.out_height = outh;
r = ovl->set_overlay_info(ovl, &info);
if (r) {
DBG("ovl->setup_overlay_info failed\n");
goto err;
}
return 0;
err:
DBG("setup_overlay failed\n");
return r;
}
/* apply var to the overlay */
int omapfb_apply_changes(struct fb_info *fbi, int init)
{
int r = 0;
struct omapfb_info *ofbi = FB2OFB(fbi);
struct fb_var_screeninfo *var = &fbi->var;
struct omap_overlay *ovl;
u16 posx, posy;
u16 outw, outh;
int i;
#ifdef DEBUG
if (omapfb_test_pattern)
fill_fb(fbi);
#endif
WARN_ON(!atomic_read(&ofbi->region->lock_count));
for (i = 0; i < ofbi->num_overlays; i++) {
ovl = ofbi->overlays[i];
DBG("apply_changes, fb %d, ovl %d\n", ofbi->id, ovl->id);
if (ofbi->region->size == 0) {
/* the fb is not available. disable the overlay */
omapfb_overlay_enable(ovl, 0);
if (!init && ovl->manager)
ovl->manager->apply(ovl->manager);
continue;
}
if (init || (ovl->caps & OMAP_DSS_OVL_CAP_SCALE) == 0) {
int rotation = (var->rotate + ofbi->rotation[i]) % 4;
if (rotation == FB_ROTATE_CW ||
rotation == FB_ROTATE_CCW) {
outw = var->yres;
outh = var->xres;
} else {
outw = var->xres;
outh = var->yres;
}
} else {
struct omap_overlay_info info;
ovl->get_overlay_info(ovl, &info);
outw = info.out_width;
outh = info.out_height;
}
if (init) {
posx = 0;
posy = 0;
} else {
struct omap_overlay_info info;
ovl->get_overlay_info(ovl, &info);
posx = info.pos_x;
posy = info.pos_y;
}
r = omapfb_setup_overlay(fbi, ovl, posx, posy, outw, outh);
if (r)
goto err;
if (!init && ovl->manager)
ovl->manager->apply(ovl->manager);
}
return 0;
err:
DBG("apply_changes failed\n");
return r;
}
/* checks var and eventually tweaks it to something supported,
* DO NOT MODIFY PAR */
static int omapfb_check_var(struct fb_var_screeninfo *var, struct fb_info *fbi)
{
struct omapfb_info *ofbi = FB2OFB(fbi);
int r;
DBG("check_var(%d)\n", FB2OFB(fbi)->id);
omapfb_get_mem_region(ofbi->region);
r = check_fb_var(fbi, var);
omapfb_put_mem_region(ofbi->region);
return r;
}
/* set the video mode according to info->var */
static int omapfb_set_par(struct fb_info *fbi)
{
struct omapfb_info *ofbi = FB2OFB(fbi);
int r;
DBG("set_par(%d)\n", FB2OFB(fbi)->id);
omapfb_get_mem_region(ofbi->region);
set_fb_fix(fbi);
r = setup_vrfb_rotation(fbi);
if (r)
goto out;
r = omapfb_apply_changes(fbi, 0);
out:
omapfb_put_mem_region(ofbi->region);
return r;
}
static int omapfb_pan_display(struct fb_var_screeninfo *var,
struct fb_info *fbi)
{
struct omapfb_info *ofbi = FB2OFB(fbi);
struct fb_var_screeninfo new_var;
int r;
DBG("pan_display(%d)\n", FB2OFB(fbi)->id);
if (var->xoffset == fbi->var.xoffset &&
var->yoffset == fbi->var.yoffset)
return 0;
new_var = fbi->var;
new_var.xoffset = var->xoffset;
new_var.yoffset = var->yoffset;
fbi->var = new_var;
omapfb_get_mem_region(ofbi->region);
r = omapfb_apply_changes(fbi, 0);
omapfb_put_mem_region(ofbi->region);
return r;
}
static void mmap_user_open(struct vm_area_struct *vma)
{
struct omapfb2_mem_region *rg = vma->vm_private_data;
omapfb_get_mem_region(rg);
atomic_inc(&rg->map_count);
omapfb_put_mem_region(rg);
}
static void mmap_user_close(struct vm_area_struct *vma)
{
struct omapfb2_mem_region *rg = vma->vm_private_data;
omapfb_get_mem_region(rg);
atomic_dec(&rg->map_count);
omapfb_put_mem_region(rg);
}
static struct vm_operations_struct mmap_user_ops = {
.open = mmap_user_open,
.close = mmap_user_close,
};
static int omapfb_mmap(struct fb_info *fbi, struct vm_area_struct *vma)
{
struct omapfb_info *ofbi = FB2OFB(fbi);
struct fb_fix_screeninfo *fix = &fbi->fix;
struct omapfb2_mem_region *rg;
unsigned long off;
unsigned long start;
u32 len;
int r = -EINVAL;
if (vma->vm_end - vma->vm_start == 0)
return 0;
if (vma->vm_pgoff > (~0UL >> PAGE_SHIFT))
return -EINVAL;
off = vma->vm_pgoff << PAGE_SHIFT;
rg = omapfb_get_mem_region(ofbi->region);
start = omapfb_get_region_paddr(ofbi);
len = fix->smem_len;
if (off >= len)
goto error;
if ((vma->vm_end - vma->vm_start + off) > len)
goto error;
off += start;
DBG("user mmap region start %lx, len %d, off %lx\n", start, len, off);
vma->vm_pgoff = off >> PAGE_SHIFT;
vma->vm_flags |= VM_IO | VM_RESERVED;
vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot);
vma->vm_ops = &mmap_user_ops;
vma->vm_private_data = rg;
if (io_remap_pfn_range(vma, vma->vm_start, off >> PAGE_SHIFT,
vma->vm_end - vma->vm_start,
vma->vm_page_prot)) {
r = -EAGAIN;
goto error;
}
/* vm_ops.open won't be called for mmap itself. */
atomic_inc(&rg->map_count);
omapfb_put_mem_region(rg);
return 0;
error:
omapfb_put_mem_region(ofbi->region);
return r;
}
/* Store a single color palette entry into a pseudo palette or the hardware
* palette if one is available. For now we support only 16bpp and thus store
* the entry only to the pseudo palette.
*/
static int _setcolreg(struct fb_info *fbi, u_int regno, u_int red, u_int green,
u_int blue, u_int transp, int update_hw_pal)
{
/*struct omapfb_info *ofbi = FB2OFB(fbi);*/
/*struct omapfb2_device *fbdev = ofbi->fbdev;*/
struct fb_var_screeninfo *var = &fbi->var;
int r = 0;
enum omapfb_color_format mode = OMAPFB_COLOR_RGB24U; /* XXX */
/*switch (plane->color_mode) {*/
switch (mode) {
case OMAPFB_COLOR_YUV422:
case OMAPFB_COLOR_YUV420:
case OMAPFB_COLOR_YUY422:
r = -EINVAL;
break;
case OMAPFB_COLOR_CLUT_8BPP:
case OMAPFB_COLOR_CLUT_4BPP:
case OMAPFB_COLOR_CLUT_2BPP:
case OMAPFB_COLOR_CLUT_1BPP:
/*
if (fbdev->ctrl->setcolreg)
r = fbdev->ctrl->setcolreg(regno, red, green, blue,
transp, update_hw_pal);
*/
/* Fallthrough */
r = -EINVAL;
break;
case OMAPFB_COLOR_RGB565:
case OMAPFB_COLOR_RGB444:
case OMAPFB_COLOR_RGB24P:
case OMAPFB_COLOR_RGB24U:
if (r != 0)
break;
if (regno < 16) {
u16 pal;
pal = ((red >> (16 - var->red.length)) <<
var->red.offset) |
((green >> (16 - var->green.length)) <<
var->green.offset) |
(blue >> (16 - var->blue.length));
((u32 *)(fbi->pseudo_palette))[regno] = pal;
}
break;
default:
BUG();
}
return r;
}
static int omapfb_setcolreg(u_int regno, u_int red, u_int green, u_int blue,
u_int transp, struct fb_info *info)
{
DBG("setcolreg\n");
return _setcolreg(info, regno, red, green, blue, transp, 1);
}
static int omapfb_setcmap(struct fb_cmap *cmap, struct fb_info *info)
{
int count, index, r;
u16 *red, *green, *blue, *transp;
u16 trans = 0xffff;
DBG("setcmap\n");
red = cmap->red;
green = cmap->green;
blue = cmap->blue;
transp = cmap->transp;
index = cmap->start;
for (count = 0; count < cmap->len; count++) {
if (transp)
trans = *transp++;
r = _setcolreg(info, index++, *red++, *green++, *blue++, trans,
count == cmap->len - 1);
if (r != 0)
return r;
}
return 0;
}
static int omapfb_blank(int blank, struct fb_info *fbi)
{
struct omapfb_info *ofbi = FB2OFB(fbi);
struct omapfb2_device *fbdev = ofbi->fbdev;
struct omap_dss_device *display = fb2display(fbi);
struct omapfb_display_data *d;
int r = 0;
if (!display)
return -EINVAL;
omapfb_lock(fbdev);
d = get_display_data(fbdev, display);
switch (blank) {
case FB_BLANK_UNBLANK:
if (display->state != OMAP_DSS_DISPLAY_SUSPENDED)
goto exit;
if (display->driver->resume)
r = display->driver->resume(display);
if ((display->caps & OMAP_DSS_DISPLAY_CAP_MANUAL_UPDATE) &&
d->update_mode == OMAPFB_AUTO_UPDATE &&
!d->auto_update_work_enabled)
omapfb_start_auto_update(fbdev, display);
break;
case FB_BLANK_NORMAL:
/* FB_BLANK_NORMAL could be implemented.
* Needs DSS additions. */
case FB_BLANK_VSYNC_SUSPEND:
case FB_BLANK_HSYNC_SUSPEND:
case FB_BLANK_POWERDOWN:
if (display->state != OMAP_DSS_DISPLAY_ACTIVE)
goto exit;
if (d->auto_update_work_enabled)
omapfb_stop_auto_update(fbdev, display);
if (display->driver->suspend)
r = display->driver->suspend(display);
break;
default:
r = -EINVAL;
}
exit:
omapfb_unlock(fbdev);
return r;
}
#if 0
/* XXX fb_read and fb_write are needed for VRFB */
ssize_t omapfb_write(struct fb_info *info, const char __user *buf,
size_t count, loff_t *ppos)
{
DBG("omapfb_write %d, %lu\n", count, (unsigned long)*ppos);
/* XXX needed for VRFB */
return count;
}
#endif
static struct fb_ops omapfb_ops = {
.owner = THIS_MODULE,
.fb_open = omapfb_open,
.fb_release = omapfb_release,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
.fb_blank = omapfb_blank,
.fb_ioctl = omapfb_ioctl,
.fb_check_var = omapfb_check_var,
.fb_set_par = omapfb_set_par,
.fb_pan_display = omapfb_pan_display,
.fb_mmap = omapfb_mmap,
.fb_setcolreg = omapfb_setcolreg,
.fb_setcmap = omapfb_setcmap,
/*.fb_write = omapfb_write,*/
};
static void omapfb_free_fbmem(struct fb_info *fbi)
{
struct omapfb_info *ofbi = FB2OFB(fbi);
struct omapfb2_device *fbdev = ofbi->fbdev;
struct omapfb2_mem_region *rg;
rg = ofbi->region;
WARN_ON(atomic_read(&rg->map_count));
if (rg->paddr)
if (omap_vram_free(rg->paddr, rg->size))
dev_err(fbdev->dev, "VRAM FREE failed\n");
if (rg->vaddr)
iounmap(rg->vaddr);
if (ofbi->rotation_type == OMAP_DSS_ROT_VRFB) {
/* unmap the 0 angle rotation */
if (rg->vrfb.vaddr[0]) {
iounmap(rg->vrfb.vaddr[0]);
omap_vrfb_release_ctx(&rg->vrfb);
rg->vrfb.vaddr[0] = NULL;
}
}
rg->vaddr = NULL;
rg->paddr = 0;
rg->alloc = 0;
rg->size = 0;
}
static void clear_fb_info(struct fb_info *fbi)
{
memset(&fbi->var, 0, sizeof(fbi->var));
memset(&fbi->fix, 0, sizeof(fbi->fix));
strlcpy(fbi->fix.id, MODULE_NAME, sizeof(fbi->fix.id));
}
static int omapfb_free_all_fbmem(struct omapfb2_device *fbdev)
{
int i;
DBG("free all fbmem\n");
for (i = 0; i < fbdev->num_fbs; i++) {
struct fb_info *fbi = fbdev->fbs[i];
omapfb_free_fbmem(fbi);
clear_fb_info(fbi);
}
return 0;
}
static int omapfb_alloc_fbmem(struct fb_info *fbi, unsigned long size,
unsigned long paddr)
{
struct omapfb_info *ofbi = FB2OFB(fbi);
struct omapfb2_device *fbdev = ofbi->fbdev;
struct omapfb2_mem_region *rg;
void __iomem *vaddr;
int r;
rg = ofbi->region;
rg->paddr = 0;
rg->vaddr = NULL;
memset(&rg->vrfb, 0, sizeof rg->vrfb);
rg->size = 0;
rg->type = 0;
rg->alloc = false;
rg->map = false;
size = PAGE_ALIGN(size);
if (!paddr) {
DBG("allocating %lu bytes for fb %d\n", size, ofbi->id);
r = omap_vram_alloc(size, &paddr);
} else {
DBG("reserving %lu bytes at %lx for fb %d\n", size, paddr,
ofbi->id);
r = omap_vram_reserve(paddr, size);
}
if (r) {
dev_err(fbdev->dev, "failed to allocate framebuffer\n");
return -ENOMEM;
}
if (ofbi->rotation_type != OMAP_DSS_ROT_VRFB) {
vaddr = ioremap_wc(paddr, size);
if (!vaddr) {
dev_err(fbdev->dev, "failed to ioremap framebuffer\n");
omap_vram_free(paddr, size);
return -ENOMEM;
}
DBG("allocated VRAM paddr %lx, vaddr %p\n", paddr, vaddr);
} else {
r = omap_vrfb_request_ctx(&rg->vrfb);
if (r) {
dev_err(fbdev->dev, "vrfb create ctx failed\n");
return r;
}
vaddr = NULL;
}
rg->paddr = paddr;
rg->vaddr = vaddr;
rg->size = size;
rg->alloc = 1;
return 0;
}
/* allocate fbmem using display resolution as reference */
static int omapfb_alloc_fbmem_display(struct fb_info *fbi, unsigned long size,
unsigned long paddr)
{
struct omapfb_info *ofbi = FB2OFB(fbi);
struct omapfb2_device *fbdev = ofbi->fbdev;
struct omap_dss_device *display;
int bytespp;
display = fb2display(fbi);
if (!display)
return 0;
switch (omapfb_get_recommended_bpp(fbdev, display)) {
case 16:
bytespp = 2;
break;
case 24:
bytespp = 4;
break;
default:
bytespp = 4;
break;
}
if (!size) {
u16 w, h;
display->driver->get_resolution(display, &w, &h);
if (ofbi->rotation_type == OMAP_DSS_ROT_VRFB) {
size = max(omap_vrfb_min_phys_size(w, h, bytespp),
omap_vrfb_min_phys_size(h, w, bytespp));
DBG("adjusting fb mem size for VRFB, %u -> %lu\n",
w * h * bytespp, size);
} else {
size = w * h * bytespp;
}
}
if (!size)
return 0;
return omapfb_alloc_fbmem(fbi, size, paddr);
}
static int omapfb_parse_vram_param(const char *param, int max_entries,
unsigned long *sizes, unsigned long *paddrs)
{
int fbnum;
unsigned long size;
unsigned long paddr = 0;
char *p, *start;
start = (char *)param;
while (1) {
p = start;
fbnum = simple_strtoul(p, &p, 10);
if (p == param)
return -EINVAL;
if (*p != ':')
return -EINVAL;
if (fbnum >= max_entries)
return -EINVAL;
size = memparse(p + 1, &p);
if (!size)
return -EINVAL;
paddr = 0;
if (*p == '@') {
paddr = simple_strtoul(p + 1, &p, 16);
if (!paddr)
return -EINVAL;
}
paddrs[fbnum] = paddr;
sizes[fbnum] = size;
if (*p == 0)
break;
if (*p != ',')
return -EINVAL;
++p;
start = p;
}
return 0;
}
static int omapfb_allocate_all_fbs(struct omapfb2_device *fbdev)
{
int i, r;
unsigned long vram_sizes[10];
unsigned long vram_paddrs[10];
memset(&vram_sizes, 0, sizeof(vram_sizes));
memset(&vram_paddrs, 0, sizeof(vram_paddrs));
if (def_vram && omapfb_parse_vram_param(def_vram, 10,
vram_sizes, vram_paddrs)) {
dev_err(fbdev->dev, "failed to parse vram parameter\n");
memset(&vram_sizes, 0, sizeof(vram_sizes));
memset(&vram_paddrs, 0, sizeof(vram_paddrs));
}
for (i = 0; i < fbdev->num_fbs; i++) {
/* allocate memory automatically only for fb0, or if
* excplicitly defined with vram or plat data option */
if (i == 0 || vram_sizes[i] != 0) {
r = omapfb_alloc_fbmem_display(fbdev->fbs[i],
vram_sizes[i], vram_paddrs[i]);
if (r)
return r;
}
}
for (i = 0; i < fbdev->num_fbs; i++) {
struct omapfb_info *ofbi = FB2OFB(fbdev->fbs[i]);
struct omapfb2_mem_region *rg;
rg = ofbi->region;
DBG("region%d phys %08x virt %p size=%lu\n",
i,
rg->paddr,
rg->vaddr,
rg->size);
}
return 0;
}
int omapfb_realloc_fbmem(struct fb_info *fbi, unsigned long size, int type)
{
struct omapfb_info *ofbi = FB2OFB(fbi);
struct omapfb2_device *fbdev = ofbi->fbdev;
struct omap_dss_device *display = fb2display(fbi);
struct omapfb2_mem_region *rg = ofbi->region;
unsigned long old_size = rg->size;
unsigned long old_paddr = rg->paddr;
int old_type = rg->type;
int r;
if (type != OMAPFB_MEMTYPE_SDRAM)
return -EINVAL;
size = PAGE_ALIGN(size);
if (old_size == size && old_type == type)
return 0;
if (display && display->driver->sync)
display->driver->sync(display);
omapfb_free_fbmem(fbi);
if (size == 0) {
clear_fb_info(fbi);
return 0;
}
r = omapfb_alloc_fbmem(fbi, size, 0);
if (r) {
if (old_size)
omapfb_alloc_fbmem(fbi, old_size, old_paddr);
if (rg->size == 0)
clear_fb_info(fbi);
return r;
}
if (old_size == size)
return 0;
if (old_size == 0) {
DBG("initializing fb %d\n", ofbi->id);
r = omapfb_fb_init(fbdev, fbi);
if (r) {
DBG("omapfb_fb_init failed\n");
goto err;
}
r = omapfb_apply_changes(fbi, 1);
if (r) {
DBG("omapfb_apply_changes failed\n");
goto err;
}
} else {
struct fb_var_screeninfo new_var;
memcpy(&new_var, &fbi->var, sizeof(new_var));
r = check_fb_var(fbi, &new_var);
if (r)
goto err;
memcpy(&fbi->var, &new_var, sizeof(fbi->var));
set_fb_fix(fbi);
r = setup_vrfb_rotation(fbi);
if (r)
goto err;
}
return 0;
err:
omapfb_free_fbmem(fbi);
clear_fb_info(fbi);
return r;
}
static void omapfb_auto_update_work(struct work_struct *work)
{
struct omap_dss_device *dssdev;
struct omap_dss_driver *dssdrv;
struct omapfb_display_data *d;
u16 w, h;
unsigned int freq;
struct omapfb2_device *fbdev;
d = container_of(work, struct omapfb_display_data,
auto_update_work.work);
dssdev = d->dssdev;
dssdrv = dssdev->driver;
fbdev = d->fbdev;
if (!dssdrv || !dssdrv->update)
return;
if (dssdrv->sync)
dssdrv->sync(dssdev);
dssdrv->get_resolution(dssdev, &w, &h);
dssdrv->update(dssdev, 0, 0, w, h);
freq = auto_update_freq;
if (freq == 0)
freq = 20;
queue_delayed_work(fbdev->auto_update_wq,
&d->auto_update_work, HZ / freq);
}
void omapfb_start_auto_update(struct omapfb2_device *fbdev,
struct omap_dss_device *display)
{
struct omapfb_display_data *d;
if (fbdev->auto_update_wq == NULL) {
struct workqueue_struct *wq;
wq = create_singlethread_workqueue("omapfb_auto_update");
if (wq == NULL) {
dev_err(fbdev->dev, "Failed to create workqueue for "
"auto-update\n");
return;
}
fbdev->auto_update_wq = wq;
}
d = get_display_data(fbdev, display);
INIT_DELAYED_WORK(&d->auto_update_work, omapfb_auto_update_work);
d->auto_update_work_enabled = true;
omapfb_auto_update_work(&d->auto_update_work.work);
}
void omapfb_stop_auto_update(struct omapfb2_device *fbdev,
struct omap_dss_device *display)
{
struct omapfb_display_data *d;
d = get_display_data(fbdev, display);
cancel_delayed_work_sync(&d->auto_update_work);
d->auto_update_work_enabled = false;
}
/* initialize fb_info, var, fix to something sane based on the display */
static int omapfb_fb_init(struct omapfb2_device *fbdev, struct fb_info *fbi)
{
struct fb_var_screeninfo *var = &fbi->var;
struct omap_dss_device *display = fb2display(fbi);
struct omapfb_info *ofbi = FB2OFB(fbi);
int r = 0;
fbi->fbops = &omapfb_ops;
fbi->flags = FBINFO_FLAG_DEFAULT;
fbi->pseudo_palette = fbdev->pseudo_palette;
if (ofbi->region->size == 0) {
clear_fb_info(fbi);
return 0;
}
var->nonstd = 0;
var->bits_per_pixel = 0;
var->rotate = def_rotate;
if (display) {
u16 w, h;
int rotation = (var->rotate + ofbi->rotation[0]) % 4;
display->driver->get_resolution(display, &w, &h);
if (rotation == FB_ROTATE_CW ||
rotation == FB_ROTATE_CCW) {
var->xres = h;
var->yres = w;
} else {
var->xres = w;
var->yres = h;
}
var->xres_virtual = var->xres;
var->yres_virtual = var->yres;
if (!var->bits_per_pixel) {
switch (omapfb_get_recommended_bpp(fbdev, display)) {
case 16:
var->bits_per_pixel = 16;
break;
case 24:
var->bits_per_pixel = 32;
break;
default:
dev_err(fbdev->dev, "illegal display "
"bpp\n");
return -EINVAL;
}
}
} else {
/* if there's no display, let's just guess some basic values */
var->xres = 320;
var->yres = 240;
var->xres_virtual = var->xres;
var->yres_virtual = var->yres;
if (!var->bits_per_pixel)
var->bits_per_pixel = 16;
}
r = check_fb_var(fbi, var);
if (r)
goto err;
set_fb_fix(fbi);
r = setup_vrfb_rotation(fbi);
if (r)
goto err;
r = fb_alloc_cmap(&fbi->cmap, 256, 0);
if (r)
dev_err(fbdev->dev, "unable to allocate color map memory\n");
err:
return r;
}
static void fbinfo_cleanup(struct omapfb2_device *fbdev, struct fb_info *fbi)
{
fb_dealloc_cmap(&fbi->cmap);
}
static void omapfb_free_resources(struct omapfb2_device *fbdev)
{
int i;
DBG("free_resources\n");
if (fbdev == NULL)
return;
for (i = 0; i < fbdev->num_fbs; i++)
unregister_framebuffer(fbdev->fbs[i]);
/* free the reserved fbmem */
omapfb_free_all_fbmem(fbdev);
for (i = 0; i < fbdev->num_fbs; i++) {
fbinfo_cleanup(fbdev, fbdev->fbs[i]);
framebuffer_release(fbdev->fbs[i]);
}
for (i = 0; i < fbdev->num_displays; i++) {
struct omap_dss_device *dssdev = fbdev->displays[i].dssdev;
if (fbdev->displays[i].auto_update_work_enabled)
omapfb_stop_auto_update(fbdev, dssdev);
if (dssdev->state != OMAP_DSS_DISPLAY_DISABLED)
dssdev->driver->disable(dssdev);
omap_dss_put_device(dssdev);
}
if (fbdev->auto_update_wq != NULL) {
flush_workqueue(fbdev->auto_update_wq);
destroy_workqueue(fbdev->auto_update_wq);
fbdev->auto_update_wq = NULL;
}
dev_set_drvdata(fbdev->dev, NULL);
kfree(fbdev);
}
static int omapfb_create_framebuffers(struct omapfb2_device *fbdev)
{
int r, i;
fbdev->num_fbs = 0;
DBG("create %d framebuffers\n", CONFIG_FB_OMAP2_NUM_FBS);
/* allocate fb_infos */
for (i = 0; i < CONFIG_FB_OMAP2_NUM_FBS; i++) {
struct fb_info *fbi;
struct omapfb_info *ofbi;
fbi = framebuffer_alloc(sizeof(struct omapfb_info),
fbdev->dev);
if (fbi == NULL) {
dev_err(fbdev->dev,
"unable to allocate memory for plane info\n");
return -ENOMEM;
}
clear_fb_info(fbi);
fbdev->fbs[i] = fbi;
ofbi = FB2OFB(fbi);
ofbi->fbdev = fbdev;
ofbi->id = i;
ofbi->region = &fbdev->regions[i];
ofbi->region->id = i;
init_rwsem(&ofbi->region->lock);
/* assign these early, so that fb alloc can use them */
ofbi->rotation_type = def_vrfb ? OMAP_DSS_ROT_VRFB :
OMAP_DSS_ROT_DMA;
ofbi->mirror = def_mirror;
fbdev->num_fbs++;
}
DBG("fb_infos allocated\n");
/* assign overlays for the fbs */
for (i = 0; i < min(fbdev->num_fbs, fbdev->num_overlays); i++) {
struct omapfb_info *ofbi = FB2OFB(fbdev->fbs[i]);
ofbi->overlays[0] = fbdev->overlays[i];
ofbi->num_overlays = 1;
}
/* allocate fb memories */
r = omapfb_allocate_all_fbs(fbdev);
if (r) {
dev_err(fbdev->dev, "failed to allocate fbmem\n");
return r;
}
DBG("fbmems allocated\n");
/* setup fb_infos */
for (i = 0; i < fbdev->num_fbs; i++) {
struct fb_info *fbi = fbdev->fbs[i];
struct omapfb_info *ofbi = FB2OFB(fbi);
omapfb_get_mem_region(ofbi->region);
r = omapfb_fb_init(fbdev, fbi);
omapfb_put_mem_region(ofbi->region);
if (r) {
dev_err(fbdev->dev, "failed to setup fb_info\n");
return r;
}
}
DBG("fb_infos initialized\n");
for (i = 0; i < fbdev->num_fbs; i++) {
r = register_framebuffer(fbdev->fbs[i]);
if (r != 0) {
dev_err(fbdev->dev,
"registering framebuffer %d failed\n", i);
return r;
}
}
DBG("framebuffers registered\n");
for (i = 0; i < fbdev->num_fbs; i++) {
struct fb_info *fbi = fbdev->fbs[i];
struct omapfb_info *ofbi = FB2OFB(fbi);
omapfb_get_mem_region(ofbi->region);
r = omapfb_apply_changes(fbi, 1);
omapfb_put_mem_region(ofbi->region);
if (r) {
dev_err(fbdev->dev, "failed to change mode\n");
return r;
}
}
/* Enable fb0 */
if (fbdev->num_fbs > 0) {
struct omapfb_info *ofbi = FB2OFB(fbdev->fbs[0]);
if (ofbi->num_overlays > 0) {
struct omap_overlay *ovl = ofbi->overlays[0];
ovl->manager->apply(ovl->manager);
r = omapfb_overlay_enable(ovl, 1);
if (r) {
dev_err(fbdev->dev,
"failed to enable overlay\n");
return r;
}
}
}
DBG("create_framebuffers done\n");
return 0;
}
static int omapfb_mode_to_timings(const char *mode_str,
struct omap_video_timings *timings, u8 *bpp)
{
struct fb_info *fbi;
struct fb_var_screeninfo *var;
struct fb_ops *fbops;
int r;
#ifdef CONFIG_OMAP2_DSS_VENC
if (strcmp(mode_str, "pal") == 0) {
*timings = omap_dss_pal_timings;
*bpp = 24;
return 0;
} else if (strcmp(mode_str, "ntsc") == 0) {
*timings = omap_dss_ntsc_timings;
*bpp = 24;
return 0;
}
#endif
/* this is quite a hack, but I wanted to use the modedb and for
* that we need fb_info and var, so we create dummy ones */
*bpp = 0;
fbi = NULL;
var = NULL;
fbops = NULL;
fbi = kzalloc(sizeof(*fbi), GFP_KERNEL);
if (fbi == NULL) {
r = -ENOMEM;
goto err;
}
var = kzalloc(sizeof(*var), GFP_KERNEL);
if (var == NULL) {
r = -ENOMEM;
goto err;
}
fbops = kzalloc(sizeof(*fbops), GFP_KERNEL);
if (fbops == NULL) {
r = -ENOMEM;
goto err;
}
fbi->fbops = fbops;
r = fb_find_mode(var, fbi, mode_str, NULL, 0, NULL, 24);
if (r == 0) {
r = -EINVAL;
goto err;
}
timings->pixel_clock = PICOS2KHZ(var->pixclock);
timings->hbp = var->left_margin;
timings->hfp = var->right_margin;
timings->vbp = var->upper_margin;
timings->vfp = var->lower_margin;
timings->hsw = var->hsync_len;
timings->vsw = var->vsync_len;
timings->x_res = var->xres;
timings->y_res = var->yres;
switch (var->bits_per_pixel) {
case 16:
*bpp = 16;
break;
case 24:
case 32:
default:
*bpp = 24;
break;
}
r = 0;
err:
kfree(fbi);
kfree(var);
kfree(fbops);
return r;
}
static int omapfb_set_def_mode(struct omapfb2_device *fbdev,
struct omap_dss_device *display, char *mode_str)
{
int r;
u8 bpp;
struct omap_video_timings timings, temp_timings;
struct omapfb_display_data *d;
r = omapfb_mode_to_timings(mode_str, &timings, &bpp);
if (r)
return r;
d = get_display_data(fbdev, display);
d->bpp_override = bpp;
if (display->driver->check_timings) {
r = display->driver->check_timings(display, &timings);
if (r)
return r;
} else {
/* If check_timings is not present compare xres and yres */
if (display->driver->get_timings) {
display->driver->get_timings(display, &temp_timings);
if (temp_timings.x_res != timings.x_res ||
temp_timings.y_res != timings.y_res)
return -EINVAL;
}
}
if (display->driver->set_timings)
display->driver->set_timings(display, &timings);
return 0;
}
static int omapfb_get_recommended_bpp(struct omapfb2_device *fbdev,
struct omap_dss_device *dssdev)
{
struct omapfb_display_data *d;
BUG_ON(dssdev->driver->get_recommended_bpp == NULL);
d = get_display_data(fbdev, dssdev);
if (d->bpp_override != 0)
return d->bpp_override;
return dssdev->driver->get_recommended_bpp(dssdev);
}
static int omapfb_parse_def_modes(struct omapfb2_device *fbdev)
{
char *str, *options, *this_opt;
int r = 0;
str = kstrdup(def_mode, GFP_KERNEL);
if (!str)
return -ENOMEM;
options = str;
while (!r && (this_opt = strsep(&options, ",")) != NULL) {
char *p, *display_str, *mode_str;
struct omap_dss_device *display;
int i;
p = strchr(this_opt, ':');
if (!p) {
r = -EINVAL;
break;
}
*p = 0;
display_str = this_opt;
mode_str = p + 1;
display = NULL;
for (i = 0; i < fbdev->num_displays; ++i) {
if (strcmp(fbdev->displays[i].dssdev->name,
display_str) == 0) {
display = fbdev->displays[i].dssdev;
break;
}
}
if (!display) {
r = -EINVAL;
break;
}
r = omapfb_set_def_mode(fbdev, display, mode_str);
if (r)
break;
}
kfree(str);
return r;
}
static void fb_videomode_to_omap_timings(struct fb_videomode *m,
struct omap_video_timings *t)
{
t->x_res = m->xres;
t->y_res = m->yres;
t->pixel_clock = PICOS2KHZ(m->pixclock);
t->hsw = m->hsync_len;
t->hfp = m->right_margin;
t->hbp = m->left_margin;
t->vsw = m->vsync_len;
t->vfp = m->lower_margin;
t->vbp = m->upper_margin;
}
static int omapfb_find_best_mode(struct omap_dss_device *display,
struct omap_video_timings *timings)
{
struct fb_monspecs *specs;
u8 *edid;
int r, i, best_xres, best_idx, len;
if (!display->driver->read_edid)
return -ENODEV;
len = 0x80 * 2;
edid = kmalloc(len, GFP_KERNEL);
r = display->driver->read_edid(display, edid, len);
if (r < 0)
goto err1;
specs = kzalloc(sizeof(*specs), GFP_KERNEL);
fb_edid_to_monspecs(edid, specs);
if (edid[126] > 0)
fb_edid_add_monspecs(edid + 0x80, specs);
best_xres = 0;
best_idx = -1;
for (i = 0; i < specs->modedb_len; ++i) {
struct fb_videomode *m;
struct omap_video_timings t;
m = &specs->modedb[i];
if (m->pixclock == 0)
continue;
/* skip repeated pixel modes */
if (m->xres == 2880 || m->xres == 1440)
continue;
fb_videomode_to_omap_timings(m, &t);
r = display->driver->check_timings(display, &t);
if (r == 0 && best_xres < m->xres) {
best_xres = m->xres;
best_idx = i;
}
}
if (best_xres == 0) {
r = -ENOENT;
goto err2;
}
fb_videomode_to_omap_timings(&specs->modedb[best_idx], timings);
r = 0;
err2:
fb_destroy_modedb(specs->modedb);
kfree(specs);
err1:
kfree(edid);
return r;
}
static int omapfb_init_display(struct omapfb2_device *fbdev,
struct omap_dss_device *dssdev)
{
struct omap_dss_driver *dssdrv = dssdev->driver;
struct omapfb_display_data *d;
int r;
r = dssdrv->enable(dssdev);
if (r) {
dev_warn(fbdev->dev, "Failed to enable display '%s'\n",
dssdev->name);
return r;
}
d = get_display_data(fbdev, dssdev);
d->fbdev = fbdev;
if (dssdev->caps & OMAP_DSS_DISPLAY_CAP_MANUAL_UPDATE) {
u16 w, h;
if (auto_update) {
omapfb_start_auto_update(fbdev, dssdev);
d->update_mode = OMAPFB_AUTO_UPDATE;
} else {
d->update_mode = OMAPFB_MANUAL_UPDATE;
}
if (dssdrv->enable_te) {
r = dssdrv->enable_te(dssdev, 1);
if (r) {
dev_err(fbdev->dev, "Failed to set TE\n");
return r;
}
}
dssdrv->get_resolution(dssdev, &w, &h);
r = dssdrv->update(dssdev, 0, 0, w, h);
if (r) {
dev_err(fbdev->dev,
"Failed to update display\n");
return r;
}
} else {
d->update_mode = OMAPFB_AUTO_UPDATE;
}
return 0;
}
static int omapfb_probe(struct platform_device *pdev)
{
struct omapfb2_device *fbdev = NULL;
int r = 0;
int i;
struct omap_overlay *ovl;
struct omap_dss_device *def_display;
struct omap_dss_device *dssdev;
DBG("omapfb_probe\n");
if (pdev->num_resources != 0) {
dev_err(&pdev->dev, "probed for an unknown device\n");
r = -ENODEV;
goto err0;
}
fbdev = kzalloc(sizeof(struct omapfb2_device), GFP_KERNEL);
if (fbdev == NULL) {
r = -ENOMEM;
goto err0;
}
/* TODO : Replace cpu check with omap_has_vrfb once HAS_FEATURE
* available for OMAP2 and OMAP3
*/
if (def_vrfb && !cpu_is_omap24xx() && !cpu_is_omap34xx()) {
def_vrfb = 0;
dev_warn(&pdev->dev, "VRFB is not supported on this hardware, "
"ignoring the module parameter vrfb=y\n");
}
mutex_init(&fbdev->mtx);
fbdev->dev = &pdev->dev;
platform_set_drvdata(pdev, fbdev);
r = 0;
fbdev->num_displays = 0;
dssdev = NULL;
for_each_dss_dev(dssdev) {
struct omapfb_display_data *d;
omap_dss_get_device(dssdev);
if (!dssdev->driver) {
dev_warn(&pdev->dev, "no driver for display: %s\n",
dssdev->name);
omap_dss_put_device(dssdev);
continue;
}
d = &fbdev->displays[fbdev->num_displays++];
d->dssdev = dssdev;
if (dssdev->caps & OMAP_DSS_DISPLAY_CAP_MANUAL_UPDATE)
d->update_mode = OMAPFB_MANUAL_UPDATE;
else
d->update_mode = OMAPFB_AUTO_UPDATE;
}
if (r)
goto cleanup;
if (fbdev->num_displays == 0) {
dev_err(&pdev->dev, "no displays\n");
r = -EINVAL;
goto cleanup;
}
fbdev->num_overlays = omap_dss_get_num_overlays();
for (i = 0; i < fbdev->num_overlays; i++)
fbdev->overlays[i] = omap_dss_get_overlay(i);
fbdev->num_managers = omap_dss_get_num_overlay_managers();
for (i = 0; i < fbdev->num_managers; i++)
fbdev->managers[i] = omap_dss_get_overlay_manager(i);
/* gfx overlay should be the default one. find a display
* connected to that, and use it as default display */
ovl = omap_dss_get_overlay(0);
if (ovl->manager && ovl->manager->device) {
def_display = ovl->manager->device;
} else {
dev_warn(&pdev->dev, "cannot find default display\n");
def_display = NULL;
}
if (def_mode && strlen(def_mode) > 0) {
if (omapfb_parse_def_modes(fbdev))
dev_warn(&pdev->dev, "cannot parse default modes\n");
} else if (def_display && def_display->driver->set_timings &&
def_display->driver->check_timings) {
struct omap_video_timings t;
r = omapfb_find_best_mode(def_display, &t);
if (r == 0)
def_display->driver->set_timings(def_display, &t);
}
r = omapfb_create_framebuffers(fbdev);
if (r)
goto cleanup;
for (i = 0; i < fbdev->num_managers; i++) {
struct omap_overlay_manager *mgr;
mgr = fbdev->managers[i];
r = mgr->apply(mgr);
if (r)
dev_warn(fbdev->dev, "failed to apply dispc config\n");
}
DBG("mgr->apply'ed\n");
if (def_display) {
r = omapfb_init_display(fbdev, def_display);
if (r) {
dev_err(fbdev->dev,
"failed to initialize default "
"display\n");
goto cleanup;
}
}
DBG("create sysfs for fbs\n");
r = omapfb_create_sysfs(fbdev);
if (r) {
dev_err(fbdev->dev, "failed to create sysfs entries\n");
goto cleanup;
}
return 0;
cleanup:
omapfb_free_resources(fbdev);
err0:
dev_err(&pdev->dev, "failed to setup omapfb\n");
return r;
}
static int omapfb_remove(struct platform_device *pdev)
{
struct omapfb2_device *fbdev = platform_get_drvdata(pdev);
/* FIXME: wait till completion of pending events */
omapfb_remove_sysfs(fbdev);
omapfb_free_resources(fbdev);
return 0;
}
static struct platform_driver omapfb_driver = {
.probe = omapfb_probe,
.remove = omapfb_remove,
.driver = {
.name = "omapfb",
.owner = THIS_MODULE,
},
};
static int __init omapfb_init(void)
{
DBG("omapfb_init\n");
if (platform_driver_register(&omapfb_driver)) {
printk(KERN_ERR "failed to register omapfb driver\n");
return -ENODEV;
}
return 0;
}
static void __exit omapfb_exit(void)
{
DBG("omapfb_exit\n");
platform_driver_unregister(&omapfb_driver);
}
module_param_named(mode, def_mode, charp, 0);
module_param_named(vram, def_vram, charp, 0);
module_param_named(rotate, def_rotate, int, 0);
module_param_named(vrfb, def_vrfb, bool, 0);
module_param_named(mirror, def_mirror, bool, 0);
/* late_initcall to let panel/ctrl drivers loaded first.
* I guess better option would be a more dynamic approach,
* so that omapfb reacts to new panels when they are loaded */
late_initcall(omapfb_init);
/*module_init(omapfb_init);*/
module_exit(omapfb_exit);
MODULE_AUTHOR("Tomi Valkeinen <tomi.valkeinen@nokia.com>");
MODULE_DESCRIPTION("OMAP2/3 Framebuffer");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
peter-65/rpi-linux | drivers/scsi/aic94xx/aic94xx_seq.c | 4475 | 47421 | /*
* Aic94xx SAS/SATA driver sequencer interface.
*
* Copyright (C) 2005 Adaptec, Inc. All rights reserved.
* Copyright (C) 2005 Luben Tuikov <luben_tuikov@adaptec.com>
*
* Parts of this code adapted from David Chaw's adp94xx_seq.c.
*
* This file is licensed under GPLv2.
*
* This file is part of the aic94xx driver.
*
* The aic94xx driver 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.
*
* The aic94xx driver 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 the aic94xx driver; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <linux/delay.h>
#include <linux/gfp.h>
#include <linux/pci.h>
#include <linux/module.h>
#include <linux/firmware.h>
#include "aic94xx_reg.h"
#include "aic94xx_hwi.h"
#include "aic94xx_seq.h"
#include "aic94xx_dump.h"
/* It takes no more than 0.05 us for an instruction
* to complete. So waiting for 1 us should be more than
* plenty.
*/
#define PAUSE_DELAY 1
#define PAUSE_TRIES 1000
static const struct firmware *sequencer_fw;
static u16 cseq_vecs[CSEQ_NUM_VECS], lseq_vecs[LSEQ_NUM_VECS], mode2_task,
cseq_idle_loop, lseq_idle_loop;
static const u8 *cseq_code, *lseq_code;
static u32 cseq_code_size, lseq_code_size;
static u16 first_scb_site_no = 0xFFFF;
static u16 last_scb_site_no;
/* ---------- Pause/Unpause CSEQ/LSEQ ---------- */
/**
* asd_pause_cseq - pause the central sequencer
* @asd_ha: pointer to host adapter structure
*
* Return 0 on success, negative on failure.
*/
static int asd_pause_cseq(struct asd_ha_struct *asd_ha)
{
int count = PAUSE_TRIES;
u32 arp2ctl;
arp2ctl = asd_read_reg_dword(asd_ha, CARP2CTL);
if (arp2ctl & PAUSED)
return 0;
asd_write_reg_dword(asd_ha, CARP2CTL, arp2ctl | EPAUSE);
do {
arp2ctl = asd_read_reg_dword(asd_ha, CARP2CTL);
if (arp2ctl & PAUSED)
return 0;
udelay(PAUSE_DELAY);
} while (--count > 0);
ASD_DPRINTK("couldn't pause CSEQ\n");
return -1;
}
/**
* asd_unpause_cseq - unpause the central sequencer.
* @asd_ha: pointer to host adapter structure.
*
* Return 0 on success, negative on error.
*/
static int asd_unpause_cseq(struct asd_ha_struct *asd_ha)
{
u32 arp2ctl;
int count = PAUSE_TRIES;
arp2ctl = asd_read_reg_dword(asd_ha, CARP2CTL);
if (!(arp2ctl & PAUSED))
return 0;
asd_write_reg_dword(asd_ha, CARP2CTL, arp2ctl & ~EPAUSE);
do {
arp2ctl = asd_read_reg_dword(asd_ha, CARP2CTL);
if (!(arp2ctl & PAUSED))
return 0;
udelay(PAUSE_DELAY);
} while (--count > 0);
ASD_DPRINTK("couldn't unpause the CSEQ\n");
return -1;
}
/**
* asd_seq_pause_lseq - pause a link sequencer
* @asd_ha: pointer to a host adapter structure
* @lseq: link sequencer of interest
*
* Return 0 on success, negative on error.
*/
static int asd_seq_pause_lseq(struct asd_ha_struct *asd_ha, int lseq)
{
u32 arp2ctl;
int count = PAUSE_TRIES;
arp2ctl = asd_read_reg_dword(asd_ha, LmARP2CTL(lseq));
if (arp2ctl & PAUSED)
return 0;
asd_write_reg_dword(asd_ha, LmARP2CTL(lseq), arp2ctl | EPAUSE);
do {
arp2ctl = asd_read_reg_dword(asd_ha, LmARP2CTL(lseq));
if (arp2ctl & PAUSED)
return 0;
udelay(PAUSE_DELAY);
} while (--count > 0);
ASD_DPRINTK("couldn't pause LSEQ %d\n", lseq);
return -1;
}
/**
* asd_pause_lseq - pause the link sequencer(s)
* @asd_ha: pointer to host adapter structure
* @lseq_mask: mask of link sequencers of interest
*
* Return 0 on success, negative on failure.
*/
static int asd_pause_lseq(struct asd_ha_struct *asd_ha, u8 lseq_mask)
{
int lseq;
int err = 0;
for_each_sequencer(lseq_mask, lseq_mask, lseq) {
err = asd_seq_pause_lseq(asd_ha, lseq);
if (err)
return err;
}
return err;
}
/**
* asd_seq_unpause_lseq - unpause a link sequencer
* @asd_ha: pointer to host adapter structure
* @lseq: link sequencer of interest
*
* Return 0 on success, negative on error.
*/
static int asd_seq_unpause_lseq(struct asd_ha_struct *asd_ha, int lseq)
{
u32 arp2ctl;
int count = PAUSE_TRIES;
arp2ctl = asd_read_reg_dword(asd_ha, LmARP2CTL(lseq));
if (!(arp2ctl & PAUSED))
return 0;
asd_write_reg_dword(asd_ha, LmARP2CTL(lseq), arp2ctl & ~EPAUSE);
do {
arp2ctl = asd_read_reg_dword(asd_ha, LmARP2CTL(lseq));
if (!(arp2ctl & PAUSED))
return 0;
udelay(PAUSE_DELAY);
} while (--count > 0);
ASD_DPRINTK("couldn't unpause LSEQ %d\n", lseq);
return 0;
}
/* ---------- Downloading CSEQ/LSEQ microcode ---------- */
static int asd_verify_cseq(struct asd_ha_struct *asd_ha, const u8 *_prog,
u32 size)
{
u32 addr = CSEQ_RAM_REG_BASE_ADR;
const u32 *prog = (u32 *) _prog;
u32 i;
for (i = 0; i < size; i += 4, prog++, addr += 4) {
u32 val = asd_read_reg_dword(asd_ha, addr);
if (le32_to_cpu(*prog) != val) {
asd_printk("%s: cseq verify failed at %u "
"read:0x%x, wanted:0x%x\n",
pci_name(asd_ha->pcidev),
i, val, le32_to_cpu(*prog));
return -1;
}
}
ASD_DPRINTK("verified %d bytes, passed\n", size);
return 0;
}
/**
* asd_verify_lseq - verify the microcode of a link sequencer
* @asd_ha: pointer to host adapter structure
* @_prog: pointer to the microcode
* @size: size of the microcode in bytes
* @lseq: link sequencer of interest
*
* The link sequencer code is accessed in 4 KB pages, which are selected
* by setting LmRAMPAGE (bits 8 and 9) of the LmBISTCTL1 register.
* The 10 KB LSEQm instruction code is mapped, page at a time, at
* LmSEQRAM address.
*/
static int asd_verify_lseq(struct asd_ha_struct *asd_ha, const u8 *_prog,
u32 size, int lseq)
{
#define LSEQ_CODEPAGE_SIZE 4096
int pages = (size + LSEQ_CODEPAGE_SIZE - 1) / LSEQ_CODEPAGE_SIZE;
u32 page;
const u32 *prog = (u32 *) _prog;
for (page = 0; page < pages; page++) {
u32 i;
asd_write_reg_dword(asd_ha, LmBISTCTL1(lseq),
page << LmRAMPAGE_LSHIFT);
for (i = 0; size > 0 && i < LSEQ_CODEPAGE_SIZE;
i += 4, prog++, size-=4) {
u32 val = asd_read_reg_dword(asd_ha, LmSEQRAM(lseq)+i);
if (le32_to_cpu(*prog) != val) {
asd_printk("%s: LSEQ%d verify failed "
"page:%d, offs:%d\n",
pci_name(asd_ha->pcidev),
lseq, page, i);
return -1;
}
}
}
ASD_DPRINTK("LSEQ%d verified %d bytes, passed\n", lseq,
(int)((u8 *)prog-_prog));
return 0;
}
/**
* asd_verify_seq -- verify CSEQ/LSEQ microcode
* @asd_ha: pointer to host adapter structure
* @prog: pointer to microcode
* @size: size of the microcode
* @lseq_mask: if 0, verify CSEQ microcode, else mask of LSEQs of interest
*
* Return 0 if microcode is correct, negative on mismatch.
*/
static int asd_verify_seq(struct asd_ha_struct *asd_ha, const u8 *prog,
u32 size, u8 lseq_mask)
{
if (lseq_mask == 0)
return asd_verify_cseq(asd_ha, prog, size);
else {
int lseq, err;
for_each_sequencer(lseq_mask, lseq_mask, lseq) {
err = asd_verify_lseq(asd_ha, prog, size, lseq);
if (err)
return err;
}
}
return 0;
}
#define ASD_DMA_MODE_DOWNLOAD
#ifdef ASD_DMA_MODE_DOWNLOAD
/* This is the size of the CSEQ Mapped instruction page */
#define MAX_DMA_OVLY_COUNT ((1U << 14)-1)
static int asd_download_seq(struct asd_ha_struct *asd_ha,
const u8 * const prog, u32 size, u8 lseq_mask)
{
u32 comstaten;
u32 reg;
int page;
const int pages = (size + MAX_DMA_OVLY_COUNT - 1) / MAX_DMA_OVLY_COUNT;
struct asd_dma_tok *token;
int err = 0;
if (size % 4) {
asd_printk("sequencer program not multiple of 4\n");
return -1;
}
asd_pause_cseq(asd_ha);
asd_pause_lseq(asd_ha, 0xFF);
/* save, disable and clear interrupts */
comstaten = asd_read_reg_dword(asd_ha, COMSTATEN);
asd_write_reg_dword(asd_ha, COMSTATEN, 0);
asd_write_reg_dword(asd_ha, COMSTAT, COMSTAT_MASK);
asd_write_reg_dword(asd_ha, CHIMINTEN, RST_CHIMINTEN);
asd_write_reg_dword(asd_ha, CHIMINT, CHIMINT_MASK);
token = asd_alloc_coherent(asd_ha, MAX_DMA_OVLY_COUNT, GFP_KERNEL);
if (!token) {
asd_printk("out of memory for dma SEQ download\n");
err = -ENOMEM;
goto out;
}
ASD_DPRINTK("dma-ing %d bytes\n", size);
for (page = 0; page < pages; page++) {
int i;
u32 left = min(size-page*MAX_DMA_OVLY_COUNT,
(u32)MAX_DMA_OVLY_COUNT);
memcpy(token->vaddr, prog + page*MAX_DMA_OVLY_COUNT, left);
asd_write_reg_addr(asd_ha, OVLYDMAADR, token->dma_handle);
asd_write_reg_dword(asd_ha, OVLYDMACNT, left);
reg = !page ? RESETOVLYDMA : 0;
reg |= (STARTOVLYDMA | OVLYHALTERR);
reg |= (lseq_mask ? (((u32)lseq_mask) << 8) : OVLYCSEQ);
/* Start DMA. */
asd_write_reg_dword(asd_ha, OVLYDMACTL, reg);
for (i = PAUSE_TRIES*100; i > 0; i--) {
u32 dmadone = asd_read_reg_dword(asd_ha, OVLYDMACTL);
if (!(dmadone & OVLYDMAACT))
break;
udelay(PAUSE_DELAY);
}
}
reg = asd_read_reg_dword(asd_ha, COMSTAT);
if (!(reg & OVLYDMADONE) || (reg & OVLYERR)
|| (asd_read_reg_dword(asd_ha, CHIMINT) & DEVEXCEPT_MASK)){
asd_printk("%s: error DMA-ing sequencer code\n",
pci_name(asd_ha->pcidev));
err = -ENODEV;
}
asd_free_coherent(asd_ha, token);
out:
asd_write_reg_dword(asd_ha, COMSTATEN, comstaten);
return err ? : asd_verify_seq(asd_ha, prog, size, lseq_mask);
}
#else /* ASD_DMA_MODE_DOWNLOAD */
static int asd_download_seq(struct asd_ha_struct *asd_ha, const u8 *_prog,
u32 size, u8 lseq_mask)
{
int i;
u32 reg = 0;
const u32 *prog = (u32 *) _prog;
if (size % 4) {
asd_printk("sequencer program not multiple of 4\n");
return -1;
}
asd_pause_cseq(asd_ha);
asd_pause_lseq(asd_ha, 0xFF);
reg |= (lseq_mask ? (((u32)lseq_mask) << 8) : OVLYCSEQ);
reg |= PIOCMODE;
asd_write_reg_dword(asd_ha, OVLYDMACNT, size);
asd_write_reg_dword(asd_ha, OVLYDMACTL, reg);
ASD_DPRINTK("downloading %s sequencer%s in PIO mode...\n",
lseq_mask ? "LSEQ" : "CSEQ", lseq_mask ? "s" : "");
for (i = 0; i < size; i += 4, prog++)
asd_write_reg_dword(asd_ha, SPIODATA, *prog);
reg = (reg & ~PIOCMODE) | OVLYHALTERR;
asd_write_reg_dword(asd_ha, OVLYDMACTL, reg);
return asd_verify_seq(asd_ha, _prog, size, lseq_mask);
}
#endif /* ASD_DMA_MODE_DOWNLOAD */
/**
* asd_seq_download_seqs - download the sequencer microcode
* @asd_ha: pointer to host adapter structure
*
* Download the central and link sequencer microcode.
*/
static int asd_seq_download_seqs(struct asd_ha_struct *asd_ha)
{
int err;
if (!asd_ha->hw_prof.enabled_phys) {
asd_printk("%s: no enabled phys!\n", pci_name(asd_ha->pcidev));
return -ENODEV;
}
/* Download the CSEQ */
ASD_DPRINTK("downloading CSEQ...\n");
err = asd_download_seq(asd_ha, cseq_code, cseq_code_size, 0);
if (err) {
asd_printk("CSEQ download failed:%d\n", err);
return err;
}
/* Download the Link Sequencers code. All of the Link Sequencers
* microcode can be downloaded at the same time.
*/
ASD_DPRINTK("downloading LSEQs...\n");
err = asd_download_seq(asd_ha, lseq_code, lseq_code_size,
asd_ha->hw_prof.enabled_phys);
if (err) {
/* Try it one at a time */
u8 lseq;
u8 lseq_mask = asd_ha->hw_prof.enabled_phys;
for_each_sequencer(lseq_mask, lseq_mask, lseq) {
err = asd_download_seq(asd_ha, lseq_code,
lseq_code_size, 1<<lseq);
if (err)
break;
}
}
if (err)
asd_printk("LSEQs download failed:%d\n", err);
return err;
}
/* ---------- Initializing the chip, chip memory, etc. ---------- */
/**
* asd_init_cseq_mip - initialize CSEQ mode independent pages 4-7
* @asd_ha: pointer to host adapter structure
*/
static void asd_init_cseq_mip(struct asd_ha_struct *asd_ha)
{
/* CSEQ Mode Independent, page 4 setup. */
asd_write_reg_word(asd_ha, CSEQ_Q_EXE_HEAD, 0xFFFF);
asd_write_reg_word(asd_ha, CSEQ_Q_EXE_TAIL, 0xFFFF);
asd_write_reg_word(asd_ha, CSEQ_Q_DONE_HEAD, 0xFFFF);
asd_write_reg_word(asd_ha, CSEQ_Q_DONE_TAIL, 0xFFFF);
asd_write_reg_word(asd_ha, CSEQ_Q_SEND_HEAD, 0xFFFF);
asd_write_reg_word(asd_ha, CSEQ_Q_SEND_TAIL, 0xFFFF);
asd_write_reg_word(asd_ha, CSEQ_Q_DMA2CHIM_HEAD, 0xFFFF);
asd_write_reg_word(asd_ha, CSEQ_Q_DMA2CHIM_TAIL, 0xFFFF);
asd_write_reg_word(asd_ha, CSEQ_Q_COPY_HEAD, 0xFFFF);
asd_write_reg_word(asd_ha, CSEQ_Q_COPY_TAIL, 0xFFFF);
asd_write_reg_word(asd_ha, CSEQ_REG0, 0);
asd_write_reg_word(asd_ha, CSEQ_REG1, 0);
asd_write_reg_dword(asd_ha, CSEQ_REG2, 0);
asd_write_reg_byte(asd_ha, CSEQ_LINK_CTL_Q_MAP, 0);
{
u8 con = asd_read_reg_byte(asd_ha, CCONEXIST);
u8 val = hweight8(con);
asd_write_reg_byte(asd_ha, CSEQ_MAX_CSEQ_MODE, (val<<4)|val);
}
asd_write_reg_word(asd_ha, CSEQ_FREE_LIST_HACK_COUNT, 0);
/* CSEQ Mode independent, page 5 setup. */
asd_write_reg_dword(asd_ha, CSEQ_EST_NEXUS_REQ_QUEUE, 0);
asd_write_reg_dword(asd_ha, CSEQ_EST_NEXUS_REQ_QUEUE+4, 0);
asd_write_reg_dword(asd_ha, CSEQ_EST_NEXUS_REQ_COUNT, 0);
asd_write_reg_dword(asd_ha, CSEQ_EST_NEXUS_REQ_COUNT+4, 0);
asd_write_reg_word(asd_ha, CSEQ_Q_EST_NEXUS_HEAD, 0xFFFF);
asd_write_reg_word(asd_ha, CSEQ_Q_EST_NEXUS_TAIL, 0xFFFF);
asd_write_reg_word(asd_ha, CSEQ_NEED_EST_NEXUS_SCB, 0);
asd_write_reg_byte(asd_ha, CSEQ_EST_NEXUS_REQ_HEAD, 0);
asd_write_reg_byte(asd_ha, CSEQ_EST_NEXUS_REQ_TAIL, 0);
asd_write_reg_byte(asd_ha, CSEQ_EST_NEXUS_SCB_OFFSET, 0);
/* CSEQ Mode independent, page 6 setup. */
asd_write_reg_word(asd_ha, CSEQ_INT_ROUT_RET_ADDR0, 0);
asd_write_reg_word(asd_ha, CSEQ_INT_ROUT_RET_ADDR1, 0);
asd_write_reg_word(asd_ha, CSEQ_INT_ROUT_SCBPTR, 0);
asd_write_reg_byte(asd_ha, CSEQ_INT_ROUT_MODE, 0);
asd_write_reg_byte(asd_ha, CSEQ_ISR_SCRATCH_FLAGS, 0);
asd_write_reg_word(asd_ha, CSEQ_ISR_SAVE_SINDEX, 0);
asd_write_reg_word(asd_ha, CSEQ_ISR_SAVE_DINDEX, 0);
asd_write_reg_word(asd_ha, CSEQ_Q_MONIRTT_HEAD, 0xFFFF);
asd_write_reg_word(asd_ha, CSEQ_Q_MONIRTT_TAIL, 0xFFFF);
/* Calculate the free scb mask. */
{
u16 cmdctx = asd_get_cmdctx_size(asd_ha);
cmdctx = (~((cmdctx/128)-1)) >> 8;
asd_write_reg_byte(asd_ha, CSEQ_FREE_SCB_MASK, (u8)cmdctx);
}
asd_write_reg_word(asd_ha, CSEQ_BUILTIN_FREE_SCB_HEAD,
first_scb_site_no);
asd_write_reg_word(asd_ha, CSEQ_BUILTIN_FREE_SCB_TAIL,
last_scb_site_no);
asd_write_reg_word(asd_ha, CSEQ_EXTENDED_FREE_SCB_HEAD, 0xFFFF);
asd_write_reg_word(asd_ha, CSEQ_EXTENDED_FREE_SCB_TAIL, 0xFFFF);
/* CSEQ Mode independent, page 7 setup. */
asd_write_reg_dword(asd_ha, CSEQ_EMPTY_REQ_QUEUE, 0);
asd_write_reg_dword(asd_ha, CSEQ_EMPTY_REQ_QUEUE+4, 0);
asd_write_reg_dword(asd_ha, CSEQ_EMPTY_REQ_COUNT, 0);
asd_write_reg_dword(asd_ha, CSEQ_EMPTY_REQ_COUNT+4, 0);
asd_write_reg_word(asd_ha, CSEQ_Q_EMPTY_HEAD, 0xFFFF);
asd_write_reg_word(asd_ha, CSEQ_Q_EMPTY_TAIL, 0xFFFF);
asd_write_reg_word(asd_ha, CSEQ_NEED_EMPTY_SCB, 0);
asd_write_reg_byte(asd_ha, CSEQ_EMPTY_REQ_HEAD, 0);
asd_write_reg_byte(asd_ha, CSEQ_EMPTY_REQ_TAIL, 0);
asd_write_reg_byte(asd_ha, CSEQ_EMPTY_SCB_OFFSET, 0);
asd_write_reg_word(asd_ha, CSEQ_PRIMITIVE_DATA, 0);
asd_write_reg_dword(asd_ha, CSEQ_TIMEOUT_CONST, 0);
}
/**
* asd_init_cseq_mdp - initialize CSEQ Mode dependent pages
* @asd_ha: pointer to host adapter structure
*/
static void asd_init_cseq_mdp(struct asd_ha_struct *asd_ha)
{
int i;
int moffs;
moffs = CSEQ_PAGE_SIZE * 2;
/* CSEQ Mode dependent, modes 0-7, page 0 setup. */
for (i = 0; i < 8; i++) {
asd_write_reg_word(asd_ha, i*moffs+CSEQ_LRM_SAVE_SINDEX, 0);
asd_write_reg_word(asd_ha, i*moffs+CSEQ_LRM_SAVE_SCBPTR, 0);
asd_write_reg_word(asd_ha, i*moffs+CSEQ_Q_LINK_HEAD, 0xFFFF);
asd_write_reg_word(asd_ha, i*moffs+CSEQ_Q_LINK_TAIL, 0xFFFF);
asd_write_reg_byte(asd_ha, i*moffs+CSEQ_LRM_SAVE_SCRPAGE, 0);
}
/* CSEQ Mode dependent, mode 0-7, page 1 and 2 shall be ignored. */
/* CSEQ Mode dependent, mode 8, page 0 setup. */
asd_write_reg_word(asd_ha, CSEQ_RET_ADDR, 0xFFFF);
asd_write_reg_word(asd_ha, CSEQ_RET_SCBPTR, 0);
asd_write_reg_word(asd_ha, CSEQ_SAVE_SCBPTR, 0);
asd_write_reg_word(asd_ha, CSEQ_EMPTY_TRANS_CTX, 0);
asd_write_reg_word(asd_ha, CSEQ_RESP_LEN, 0);
asd_write_reg_word(asd_ha, CSEQ_TMF_SCBPTR, 0);
asd_write_reg_word(asd_ha, CSEQ_GLOBAL_PREV_SCB, 0);
asd_write_reg_word(asd_ha, CSEQ_GLOBAL_HEAD, 0);
asd_write_reg_word(asd_ha, CSEQ_CLEAR_LU_HEAD, 0);
asd_write_reg_byte(asd_ha, CSEQ_TMF_OPCODE, 0);
asd_write_reg_byte(asd_ha, CSEQ_SCRATCH_FLAGS, 0);
asd_write_reg_word(asd_ha, CSEQ_HSB_SITE, 0);
asd_write_reg_word(asd_ha, CSEQ_FIRST_INV_SCB_SITE,
(u16)last_scb_site_no+1);
asd_write_reg_word(asd_ha, CSEQ_FIRST_INV_DDB_SITE,
(u16)asd_ha->hw_prof.max_ddbs);
/* CSEQ Mode dependent, mode 8, page 1 setup. */
asd_write_reg_dword(asd_ha, CSEQ_LUN_TO_CLEAR, 0);
asd_write_reg_dword(asd_ha, CSEQ_LUN_TO_CLEAR + 4, 0);
asd_write_reg_dword(asd_ha, CSEQ_LUN_TO_CHECK, 0);
asd_write_reg_dword(asd_ha, CSEQ_LUN_TO_CHECK + 4, 0);
/* CSEQ Mode dependent, mode 8, page 2 setup. */
/* Tell the sequencer the bus address of the first SCB. */
asd_write_reg_addr(asd_ha, CSEQ_HQ_NEW_POINTER,
asd_ha->seq.next_scb.dma_handle);
ASD_DPRINTK("First SCB dma_handle: 0x%llx\n",
(unsigned long long)asd_ha->seq.next_scb.dma_handle);
/* Tell the sequencer the first Done List entry address. */
asd_write_reg_addr(asd_ha, CSEQ_HQ_DONE_BASE,
asd_ha->seq.actual_dl->dma_handle);
/* Initialize the Q_DONE_POINTER with the least significant
* 4 bytes of the first Done List address. */
asd_write_reg_dword(asd_ha, CSEQ_HQ_DONE_POINTER,
ASD_BUSADDR_LO(asd_ha->seq.actual_dl->dma_handle));
asd_write_reg_byte(asd_ha, CSEQ_HQ_DONE_PASS, ASD_DEF_DL_TOGGLE);
/* CSEQ Mode dependent, mode 8, page 3 shall be ignored. */
}
/**
* asd_init_cseq_scratch -- setup and init CSEQ
* @asd_ha: pointer to host adapter structure
*
* Setup and initialize Central sequencers. Initialize the mode
* independent and dependent scratch page to the default settings.
*/
static void asd_init_cseq_scratch(struct asd_ha_struct *asd_ha)
{
asd_init_cseq_mip(asd_ha);
asd_init_cseq_mdp(asd_ha);
}
/**
* asd_init_lseq_mip -- initialize LSEQ Mode independent pages 0-3
* @asd_ha: pointer to host adapter structure
*/
static void asd_init_lseq_mip(struct asd_ha_struct *asd_ha, u8 lseq)
{
int i;
/* LSEQ Mode independent page 0 setup. */
asd_write_reg_word(asd_ha, LmSEQ_Q_TGTXFR_HEAD(lseq), 0xFFFF);
asd_write_reg_word(asd_ha, LmSEQ_Q_TGTXFR_TAIL(lseq), 0xFFFF);
asd_write_reg_byte(asd_ha, LmSEQ_LINK_NUMBER(lseq), lseq);
asd_write_reg_byte(asd_ha, LmSEQ_SCRATCH_FLAGS(lseq),
ASD_NOTIFY_ENABLE_SPINUP);
asd_write_reg_dword(asd_ha, LmSEQ_CONNECTION_STATE(lseq),0x08000000);
asd_write_reg_word(asd_ha, LmSEQ_CONCTL(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_CONSTAT(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_CONNECTION_MODES(lseq), 0);
asd_write_reg_word(asd_ha, LmSEQ_REG1_ISR(lseq), 0);
asd_write_reg_word(asd_ha, LmSEQ_REG2_ISR(lseq), 0);
asd_write_reg_word(asd_ha, LmSEQ_REG3_ISR(lseq), 0);
asd_write_reg_dword(asd_ha, LmSEQ_REG0_ISR(lseq), 0);
asd_write_reg_dword(asd_ha, LmSEQ_REG0_ISR(lseq)+4, 0);
/* LSEQ Mode independent page 1 setup. */
asd_write_reg_word(asd_ha, LmSEQ_EST_NEXUS_SCBPTR0(lseq), 0xFFFF);
asd_write_reg_word(asd_ha, LmSEQ_EST_NEXUS_SCBPTR1(lseq), 0xFFFF);
asd_write_reg_word(asd_ha, LmSEQ_EST_NEXUS_SCBPTR2(lseq), 0xFFFF);
asd_write_reg_word(asd_ha, LmSEQ_EST_NEXUS_SCBPTR3(lseq), 0xFFFF);
asd_write_reg_byte(asd_ha, LmSEQ_EST_NEXUS_SCB_OPCODE0(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_EST_NEXUS_SCB_OPCODE1(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_EST_NEXUS_SCB_OPCODE2(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_EST_NEXUS_SCB_OPCODE3(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_EST_NEXUS_SCB_HEAD(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_EST_NEXUS_SCB_TAIL(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_EST_NEXUS_BUF_AVAIL(lseq), 0);
asd_write_reg_dword(asd_ha, LmSEQ_TIMEOUT_CONST(lseq), 0);
asd_write_reg_word(asd_ha, LmSEQ_ISR_SAVE_SINDEX(lseq), 0);
asd_write_reg_word(asd_ha, LmSEQ_ISR_SAVE_DINDEX(lseq), 0);
/* LSEQ Mode Independent page 2 setup. */
asd_write_reg_word(asd_ha, LmSEQ_EMPTY_SCB_PTR0(lseq), 0xFFFF);
asd_write_reg_word(asd_ha, LmSEQ_EMPTY_SCB_PTR1(lseq), 0xFFFF);
asd_write_reg_word(asd_ha, LmSEQ_EMPTY_SCB_PTR2(lseq), 0xFFFF);
asd_write_reg_word(asd_ha, LmSEQ_EMPTY_SCB_PTR3(lseq), 0xFFFF);
asd_write_reg_byte(asd_ha, LmSEQ_EMPTY_SCB_OPCD0(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_EMPTY_SCB_OPCD1(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_EMPTY_SCB_OPCD2(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_EMPTY_SCB_OPCD3(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_EMPTY_SCB_HEAD(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_EMPTY_SCB_TAIL(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_EMPTY_BUFS_AVAIL(lseq), 0);
for (i = 0; i < 12; i += 4)
asd_write_reg_dword(asd_ha, LmSEQ_ATA_SCR_REGS(lseq) + i, 0);
/* LSEQ Mode Independent page 3 setup. */
/* Device present timer timeout */
asd_write_reg_dword(asd_ha, LmSEQ_DEV_PRES_TMR_TOUT_CONST(lseq),
ASD_DEV_PRESENT_TIMEOUT);
/* SATA interlock timer disabled */
asd_write_reg_dword(asd_ha, LmSEQ_SATA_INTERLOCK_TIMEOUT(lseq),
ASD_SATA_INTERLOCK_TIMEOUT);
/* STP shutdown timer timeout constant, IGNORED by the sequencer,
* always 0. */
asd_write_reg_dword(asd_ha, LmSEQ_STP_SHUTDOWN_TIMEOUT(lseq),
ASD_STP_SHUTDOWN_TIMEOUT);
asd_write_reg_dword(asd_ha, LmSEQ_SRST_ASSERT_TIMEOUT(lseq),
ASD_SRST_ASSERT_TIMEOUT);
asd_write_reg_dword(asd_ha, LmSEQ_RCV_FIS_TIMEOUT(lseq),
ASD_RCV_FIS_TIMEOUT);
asd_write_reg_dword(asd_ha, LmSEQ_ONE_MILLISEC_TIMEOUT(lseq),
ASD_ONE_MILLISEC_TIMEOUT);
/* COM_INIT timer */
asd_write_reg_dword(asd_ha, LmSEQ_TEN_MS_COMINIT_TIMEOUT(lseq),
ASD_TEN_MILLISEC_TIMEOUT);
asd_write_reg_dword(asd_ha, LmSEQ_SMP_RCV_TIMEOUT(lseq),
ASD_SMP_RCV_TIMEOUT);
}
/**
* asd_init_lseq_mdp -- initialize LSEQ mode dependent pages.
* @asd_ha: pointer to host adapter structure
*/
static void asd_init_lseq_mdp(struct asd_ha_struct *asd_ha, int lseq)
{
int i;
u32 moffs;
u16 ret_addr[] = {
0xFFFF, /* mode 0 */
0xFFFF, /* mode 1 */
mode2_task, /* mode 2 */
0,
0xFFFF, /* mode 4/5 */
0xFFFF, /* mode 4/5 */
};
/*
* Mode 0,1,2 and 4/5 have common field on page 0 for the first
* 14 bytes.
*/
for (i = 0; i < 3; i++) {
moffs = i * LSEQ_MODE_SCRATCH_SIZE;
asd_write_reg_word(asd_ha, LmSEQ_RET_ADDR(lseq)+moffs,
ret_addr[i]);
asd_write_reg_word(asd_ha, LmSEQ_REG0_MODE(lseq)+moffs, 0);
asd_write_reg_word(asd_ha, LmSEQ_MODE_FLAGS(lseq)+moffs, 0);
asd_write_reg_word(asd_ha, LmSEQ_RET_ADDR2(lseq)+moffs,0xFFFF);
asd_write_reg_word(asd_ha, LmSEQ_RET_ADDR1(lseq)+moffs,0xFFFF);
asd_write_reg_byte(asd_ha, LmSEQ_OPCODE_TO_CSEQ(lseq)+moffs,0);
asd_write_reg_word(asd_ha, LmSEQ_DATA_TO_CSEQ(lseq)+moffs,0);
}
/*
* Mode 5 page 0 overlaps the same scratch page with Mode 0 page 3.
*/
asd_write_reg_word(asd_ha,
LmSEQ_RET_ADDR(lseq)+LSEQ_MODE5_PAGE0_OFFSET,
ret_addr[5]);
asd_write_reg_word(asd_ha,
LmSEQ_REG0_MODE(lseq)+LSEQ_MODE5_PAGE0_OFFSET,0);
asd_write_reg_word(asd_ha,
LmSEQ_MODE_FLAGS(lseq)+LSEQ_MODE5_PAGE0_OFFSET, 0);
asd_write_reg_word(asd_ha,
LmSEQ_RET_ADDR2(lseq)+LSEQ_MODE5_PAGE0_OFFSET,0xFFFF);
asd_write_reg_word(asd_ha,
LmSEQ_RET_ADDR1(lseq)+LSEQ_MODE5_PAGE0_OFFSET,0xFFFF);
asd_write_reg_byte(asd_ha,
LmSEQ_OPCODE_TO_CSEQ(lseq)+LSEQ_MODE5_PAGE0_OFFSET,0);
asd_write_reg_word(asd_ha,
LmSEQ_DATA_TO_CSEQ(lseq)+LSEQ_MODE5_PAGE0_OFFSET, 0);
/* LSEQ Mode dependent 0, page 0 setup. */
asd_write_reg_word(asd_ha, LmSEQ_FIRST_INV_DDB_SITE(lseq),
(u16)asd_ha->hw_prof.max_ddbs);
asd_write_reg_word(asd_ha, LmSEQ_EMPTY_TRANS_CTX(lseq), 0);
asd_write_reg_word(asd_ha, LmSEQ_RESP_LEN(lseq), 0);
asd_write_reg_word(asd_ha, LmSEQ_FIRST_INV_SCB_SITE(lseq),
(u16)last_scb_site_no+1);
asd_write_reg_word(asd_ha, LmSEQ_INTEN_SAVE(lseq),
(u16) ((LmM0INTEN_MASK & 0xFFFF0000) >> 16));
asd_write_reg_word(asd_ha, LmSEQ_INTEN_SAVE(lseq) + 2,
(u16) LmM0INTEN_MASK & 0xFFFF);
asd_write_reg_byte(asd_ha, LmSEQ_LINK_RST_FRM_LEN(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_LINK_RST_PROTOCOL(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_RESP_STATUS(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_LAST_LOADED_SGE(lseq), 0);
asd_write_reg_word(asd_ha, LmSEQ_SAVE_SCBPTR(lseq), 0);
/* LSEQ mode dependent, mode 1, page 0 setup. */
asd_write_reg_word(asd_ha, LmSEQ_Q_XMIT_HEAD(lseq), 0xFFFF);
asd_write_reg_word(asd_ha, LmSEQ_M1_EMPTY_TRANS_CTX(lseq), 0);
asd_write_reg_word(asd_ha, LmSEQ_INI_CONN_TAG(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_FAILED_OPEN_STATUS(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_XMIT_REQUEST_TYPE(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_M1_RESP_STATUS(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_M1_LAST_LOADED_SGE(lseq), 0);
asd_write_reg_word(asd_ha, LmSEQ_M1_SAVE_SCBPTR(lseq), 0);
/* LSEQ Mode dependent mode 2, page 0 setup */
asd_write_reg_word(asd_ha, LmSEQ_PORT_COUNTER(lseq), 0);
asd_write_reg_word(asd_ha, LmSEQ_PM_TABLE_PTR(lseq), 0);
asd_write_reg_word(asd_ha, LmSEQ_SATA_INTERLOCK_TMR_SAVE(lseq), 0);
asd_write_reg_word(asd_ha, LmSEQ_IP_BITL(lseq), 0);
asd_write_reg_word(asd_ha, LmSEQ_COPY_SMP_CONN_TAG(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_P0M2_OFFS1AH(lseq), 0);
/* LSEQ Mode dependent, mode 4/5, page 0 setup. */
asd_write_reg_byte(asd_ha, LmSEQ_SAVED_OOB_STATUS(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_SAVED_OOB_MODE(lseq), 0);
asd_write_reg_word(asd_ha, LmSEQ_Q_LINK_HEAD(lseq), 0xFFFF);
asd_write_reg_byte(asd_ha, LmSEQ_LINK_RST_ERR(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_SAVED_OOB_SIGNALS(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_SAS_RESET_MODE(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_LINK_RESET_RETRY_COUNT(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_NUM_LINK_RESET_RETRIES(lseq), 0);
asd_write_reg_word(asd_ha, LmSEQ_OOB_INT_ENABLES(lseq), 0);
/*
* Set the desired interval between transmissions of the NOTIFY
* (ENABLE SPINUP) primitive. Must be initialized to val - 1.
*/
asd_write_reg_word(asd_ha, LmSEQ_NOTIFY_TIMER_TIMEOUT(lseq),
ASD_NOTIFY_TIMEOUT - 1);
/* No delay for the first NOTIFY to be sent to the attached target. */
asd_write_reg_word(asd_ha, LmSEQ_NOTIFY_TIMER_DOWN_COUNT(lseq),
ASD_NOTIFY_DOWN_COUNT);
asd_write_reg_word(asd_ha, LmSEQ_NOTIFY_TIMER_INITIAL_COUNT(lseq),
ASD_NOTIFY_DOWN_COUNT);
/* LSEQ Mode dependent, mode 0 and 1, page 1 setup. */
for (i = 0; i < 2; i++) {
int j;
/* Start from Page 1 of Mode 0 and 1. */
moffs = LSEQ_PAGE_SIZE + i*LSEQ_MODE_SCRATCH_SIZE;
/* All the fields of page 1 can be initialized to 0. */
for (j = 0; j < LSEQ_PAGE_SIZE; j += 4)
asd_write_reg_dword(asd_ha, LmSCRATCH(lseq)+moffs+j,0);
}
/* LSEQ Mode dependent, mode 2, page 1 setup. */
asd_write_reg_dword(asd_ha, LmSEQ_INVALID_DWORD_COUNT(lseq), 0);
asd_write_reg_dword(asd_ha, LmSEQ_DISPARITY_ERROR_COUNT(lseq), 0);
asd_write_reg_dword(asd_ha, LmSEQ_LOSS_OF_SYNC_COUNT(lseq), 0);
/* LSEQ Mode dependent, mode 4/5, page 1. */
for (i = 0; i < LSEQ_PAGE_SIZE; i+=4)
asd_write_reg_dword(asd_ha, LmSEQ_FRAME_TYPE_MASK(lseq)+i, 0);
asd_write_reg_byte(asd_ha, LmSEQ_FRAME_TYPE_MASK(lseq), 0xFF);
asd_write_reg_byte(asd_ha, LmSEQ_HASHED_DEST_ADDR_MASK(lseq), 0xFF);
asd_write_reg_byte(asd_ha, LmSEQ_HASHED_DEST_ADDR_MASK(lseq)+1,0xFF);
asd_write_reg_byte(asd_ha, LmSEQ_HASHED_DEST_ADDR_MASK(lseq)+2,0xFF);
asd_write_reg_byte(asd_ha, LmSEQ_HASHED_SRC_ADDR_MASK(lseq), 0xFF);
asd_write_reg_byte(asd_ha, LmSEQ_HASHED_SRC_ADDR_MASK(lseq)+1, 0xFF);
asd_write_reg_byte(asd_ha, LmSEQ_HASHED_SRC_ADDR_MASK(lseq)+2, 0xFF);
asd_write_reg_dword(asd_ha, LmSEQ_DATA_OFFSET(lseq), 0xFFFFFFFF);
/* LSEQ Mode dependent, mode 0, page 2 setup. */
asd_write_reg_dword(asd_ha, LmSEQ_SMP_RCV_TIMER_TERM_TS(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_DEVICE_BITS(lseq), 0);
asd_write_reg_word(asd_ha, LmSEQ_SDB_DDB(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_SDB_NUM_TAGS(lseq), 0);
asd_write_reg_byte(asd_ha, LmSEQ_SDB_CURR_TAG(lseq), 0);
/* LSEQ Mode Dependent 1, page 2 setup. */
asd_write_reg_dword(asd_ha, LmSEQ_TX_ID_ADDR_FRAME(lseq), 0);
asd_write_reg_dword(asd_ha, LmSEQ_TX_ID_ADDR_FRAME(lseq)+4, 0);
asd_write_reg_dword(asd_ha, LmSEQ_OPEN_TIMER_TERM_TS(lseq), 0);
asd_write_reg_dword(asd_ha, LmSEQ_SRST_AS_TIMER_TERM_TS(lseq), 0);
asd_write_reg_dword(asd_ha, LmSEQ_LAST_LOADED_SG_EL(lseq), 0);
/* LSEQ Mode Dependent 2, page 2 setup. */
/* The LmSEQ_STP_SHUTDOWN_TIMER_TERM_TS is IGNORED by the sequencer,
* i.e. always 0. */
asd_write_reg_dword(asd_ha, LmSEQ_STP_SHUTDOWN_TIMER_TERM_TS(lseq),0);
asd_write_reg_dword(asd_ha, LmSEQ_CLOSE_TIMER_TERM_TS(lseq), 0);
asd_write_reg_dword(asd_ha, LmSEQ_BREAK_TIMER_TERM_TS(lseq), 0);
asd_write_reg_dword(asd_ha, LmSEQ_DWS_RESET_TIMER_TERM_TS(lseq), 0);
asd_write_reg_dword(asd_ha,LmSEQ_SATA_INTERLOCK_TIMER_TERM_TS(lseq),0);
asd_write_reg_dword(asd_ha, LmSEQ_MCTL_TIMER_TERM_TS(lseq), 0);
/* LSEQ Mode Dependent 4/5, page 2 setup. */
asd_write_reg_dword(asd_ha, LmSEQ_COMINIT_TIMER_TERM_TS(lseq), 0);
asd_write_reg_dword(asd_ha, LmSEQ_RCV_ID_TIMER_TERM_TS(lseq), 0);
asd_write_reg_dword(asd_ha, LmSEQ_RCV_FIS_TIMER_TERM_TS(lseq), 0);
asd_write_reg_dword(asd_ha, LmSEQ_DEV_PRES_TIMER_TERM_TS(lseq), 0);
}
/**
* asd_init_lseq_scratch -- setup and init link sequencers
* @asd_ha: pointer to host adapter struct
*/
static void asd_init_lseq_scratch(struct asd_ha_struct *asd_ha)
{
u8 lseq;
u8 lseq_mask;
lseq_mask = asd_ha->hw_prof.enabled_phys;
for_each_sequencer(lseq_mask, lseq_mask, lseq) {
asd_init_lseq_mip(asd_ha, lseq);
asd_init_lseq_mdp(asd_ha, lseq);
}
}
/**
* asd_init_scb_sites -- initialize sequencer SCB sites (memory).
* @asd_ha: pointer to host adapter structure
*
* This should be done before initializing common CSEQ and LSEQ
* scratch since those areas depend on some computed values here,
* last_scb_site_no, etc.
*/
static void asd_init_scb_sites(struct asd_ha_struct *asd_ha)
{
u16 site_no;
u16 max_scbs = 0;
for (site_no = asd_ha->hw_prof.max_scbs-1;
site_no != (u16) -1;
site_no--) {
u16 i;
/* Initialize all fields in the SCB site to 0. */
for (i = 0; i < ASD_SCB_SIZE; i += 4)
asd_scbsite_write_dword(asd_ha, site_no, i, 0);
/* Initialize SCB Site Opcode field to invalid. */
asd_scbsite_write_byte(asd_ha, site_no,
offsetof(struct scb_header, opcode),
0xFF);
/* Initialize SCB Site Flags field to mean a response
* frame has been received. This means inadvertent
* frames received to be dropped. */
asd_scbsite_write_byte(asd_ha, site_no, 0x49, 0x01);
/* Workaround needed by SEQ to fix a SATA issue is to exclude
* certain SCB sites from the free list. */
if (!SCB_SITE_VALID(site_no))
continue;
if (last_scb_site_no == 0)
last_scb_site_no = site_no;
/* For every SCB site, we need to initialize the
* following fields: Q_NEXT, SCB_OPCODE, SCB_FLAGS,
* and SG Element Flag. */
/* Q_NEXT field of the last SCB is invalidated. */
asd_scbsite_write_word(asd_ha, site_no, 0, first_scb_site_no);
first_scb_site_no = site_no;
max_scbs++;
}
asd_ha->hw_prof.max_scbs = max_scbs;
ASD_DPRINTK("max_scbs:%d\n", asd_ha->hw_prof.max_scbs);
ASD_DPRINTK("first_scb_site_no:0x%x\n", first_scb_site_no);
ASD_DPRINTK("last_scb_site_no:0x%x\n", last_scb_site_no);
}
/**
* asd_init_cseq_cio - initialize CSEQ CIO registers
* @asd_ha: pointer to host adapter structure
*/
static void asd_init_cseq_cio(struct asd_ha_struct *asd_ha)
{
int i;
asd_write_reg_byte(asd_ha, CSEQCOMINTEN, 0);
asd_write_reg_byte(asd_ha, CSEQDLCTL, ASD_DL_SIZE_BITS);
asd_write_reg_byte(asd_ha, CSEQDLOFFS, 0);
asd_write_reg_byte(asd_ha, CSEQDLOFFS+1, 0);
asd_ha->seq.scbpro = 0;
asd_write_reg_dword(asd_ha, SCBPRO, 0);
asd_write_reg_dword(asd_ha, CSEQCON, 0);
/* Initialize CSEQ Mode 11 Interrupt Vectors.
* The addresses are 16 bit wide and in dword units.
* The values of their macros are in byte units.
* Thus we have to divide by 4. */
asd_write_reg_word(asd_ha, CM11INTVEC0, cseq_vecs[0]);
asd_write_reg_word(asd_ha, CM11INTVEC1, cseq_vecs[1]);
asd_write_reg_word(asd_ha, CM11INTVEC2, cseq_vecs[2]);
/* Enable ARP2HALTC (ARP2 Halted from Halt Code Write). */
asd_write_reg_byte(asd_ha, CARP2INTEN, EN_ARP2HALTC);
/* Initialize CSEQ Scratch Page to 0x04. */
asd_write_reg_byte(asd_ha, CSCRATCHPAGE, 0x04);
/* Initialize CSEQ Mode[0-8] Dependent registers. */
/* Initialize Scratch Page to 0. */
for (i = 0; i < 9; i++)
asd_write_reg_byte(asd_ha, CMnSCRATCHPAGE(i), 0);
/* Reset the ARP2 Program Count. */
asd_write_reg_word(asd_ha, CPRGMCNT, cseq_idle_loop);
for (i = 0; i < 8; i++) {
/* Initialize Mode n Link m Interrupt Enable. */
asd_write_reg_dword(asd_ha, CMnINTEN(i), EN_CMnRSPMBXF);
/* Initialize Mode n Request Mailbox. */
asd_write_reg_dword(asd_ha, CMnREQMBX(i), 0);
}
}
/**
* asd_init_lseq_cio -- initialize LmSEQ CIO registers
* @asd_ha: pointer to host adapter structure
*/
static void asd_init_lseq_cio(struct asd_ha_struct *asd_ha, int lseq)
{
u8 *sas_addr;
int i;
/* Enable ARP2HALTC (ARP2 Halted from Halt Code Write). */
asd_write_reg_dword(asd_ha, LmARP2INTEN(lseq), EN_ARP2HALTC);
asd_write_reg_byte(asd_ha, LmSCRATCHPAGE(lseq), 0);
/* Initialize Mode 0,1, and 2 SCRATCHPAGE to 0. */
for (i = 0; i < 3; i++)
asd_write_reg_byte(asd_ha, LmMnSCRATCHPAGE(lseq, i), 0);
/* Initialize Mode 5 SCRATCHPAGE to 0. */
asd_write_reg_byte(asd_ha, LmMnSCRATCHPAGE(lseq, 5), 0);
asd_write_reg_dword(asd_ha, LmRSPMBX(lseq), 0);
/* Initialize Mode 0,1,2 and 5 Interrupt Enable and
* Interrupt registers. */
asd_write_reg_dword(asd_ha, LmMnINTEN(lseq, 0), LmM0INTEN_MASK);
asd_write_reg_dword(asd_ha, LmMnINT(lseq, 0), 0xFFFFFFFF);
/* Mode 1 */
asd_write_reg_dword(asd_ha, LmMnINTEN(lseq, 1), LmM1INTEN_MASK);
asd_write_reg_dword(asd_ha, LmMnINT(lseq, 1), 0xFFFFFFFF);
/* Mode 2 */
asd_write_reg_dword(asd_ha, LmMnINTEN(lseq, 2), LmM2INTEN_MASK);
asd_write_reg_dword(asd_ha, LmMnINT(lseq, 2), 0xFFFFFFFF);
/* Mode 5 */
asd_write_reg_dword(asd_ha, LmMnINTEN(lseq, 5), LmM5INTEN_MASK);
asd_write_reg_dword(asd_ha, LmMnINT(lseq, 5), 0xFFFFFFFF);
/* Enable HW Timer status. */
asd_write_reg_byte(asd_ha, LmHWTSTATEN(lseq), LmHWTSTATEN_MASK);
/* Enable Primitive Status 0 and 1. */
asd_write_reg_dword(asd_ha, LmPRIMSTAT0EN(lseq), LmPRIMSTAT0EN_MASK);
asd_write_reg_dword(asd_ha, LmPRIMSTAT1EN(lseq), LmPRIMSTAT1EN_MASK);
/* Enable Frame Error. */
asd_write_reg_dword(asd_ha, LmFRMERREN(lseq), LmFRMERREN_MASK);
asd_write_reg_byte(asd_ha, LmMnHOLDLVL(lseq, 0), 0x50);
/* Initialize Mode 0 Transfer Level to 512. */
asd_write_reg_byte(asd_ha, LmMnXFRLVL(lseq, 0), LmMnXFRLVL_512);
/* Initialize Mode 1 Transfer Level to 256. */
asd_write_reg_byte(asd_ha, LmMnXFRLVL(lseq, 1), LmMnXFRLVL_256);
/* Initialize Program Count. */
asd_write_reg_word(asd_ha, LmPRGMCNT(lseq), lseq_idle_loop);
/* Enable Blind SG Move. */
asd_write_reg_dword(asd_ha, LmMODECTL(lseq), LmBLIND48);
asd_write_reg_word(asd_ha, LmM3SATATIMER(lseq),
ASD_SATA_INTERLOCK_TIMEOUT);
(void) asd_read_reg_dword(asd_ha, LmREQMBX(lseq));
/* Clear Primitive Status 0 and 1. */
asd_write_reg_dword(asd_ha, LmPRMSTAT0(lseq), 0xFFFFFFFF);
asd_write_reg_dword(asd_ha, LmPRMSTAT1(lseq), 0xFFFFFFFF);
/* Clear HW Timer status. */
asd_write_reg_byte(asd_ha, LmHWTSTAT(lseq), 0xFF);
/* Clear DMA Errors for Mode 0 and 1. */
asd_write_reg_byte(asd_ha, LmMnDMAERRS(lseq, 0), 0xFF);
asd_write_reg_byte(asd_ha, LmMnDMAERRS(lseq, 1), 0xFF);
/* Clear SG DMA Errors for Mode 0 and 1. */
asd_write_reg_byte(asd_ha, LmMnSGDMAERRS(lseq, 0), 0xFF);
asd_write_reg_byte(asd_ha, LmMnSGDMAERRS(lseq, 1), 0xFF);
/* Clear Mode 0 Buffer Parity Error. */
asd_write_reg_byte(asd_ha, LmMnBUFSTAT(lseq, 0), LmMnBUFPERR);
/* Clear Mode 0 Frame Error register. */
asd_write_reg_dword(asd_ha, LmMnFRMERR(lseq, 0), 0xFFFFFFFF);
/* Reset LSEQ external interrupt arbiter. */
asd_write_reg_byte(asd_ha, LmARP2INTCTL(lseq), RSTINTCTL);
/* Set the Phy SAS for the LmSEQ WWN. */
sas_addr = asd_ha->phys[lseq].phy_desc->sas_addr;
for (i = 0; i < SAS_ADDR_SIZE; i++)
asd_write_reg_byte(asd_ha, LmWWN(lseq) + i, sas_addr[i]);
/* Set the Transmit Size to 1024 bytes, 0 = 256 Dwords. */
asd_write_reg_byte(asd_ha, LmMnXMTSIZE(lseq, 1), 0);
/* Set the Bus Inactivity Time Limit Timer. */
asd_write_reg_word(asd_ha, LmBITL_TIMER(lseq), 9);
/* Enable SATA Port Multiplier. */
asd_write_reg_byte(asd_ha, LmMnSATAFS(lseq, 1), 0x80);
/* Initialize Interrupt Vector[0-10] address in Mode 3.
* See the comment on CSEQ_INT_* */
asd_write_reg_word(asd_ha, LmM3INTVEC0(lseq), lseq_vecs[0]);
asd_write_reg_word(asd_ha, LmM3INTVEC1(lseq), lseq_vecs[1]);
asd_write_reg_word(asd_ha, LmM3INTVEC2(lseq), lseq_vecs[2]);
asd_write_reg_word(asd_ha, LmM3INTVEC3(lseq), lseq_vecs[3]);
asd_write_reg_word(asd_ha, LmM3INTVEC4(lseq), lseq_vecs[4]);
asd_write_reg_word(asd_ha, LmM3INTVEC5(lseq), lseq_vecs[5]);
asd_write_reg_word(asd_ha, LmM3INTVEC6(lseq), lseq_vecs[6]);
asd_write_reg_word(asd_ha, LmM3INTVEC7(lseq), lseq_vecs[7]);
asd_write_reg_word(asd_ha, LmM3INTVEC8(lseq), lseq_vecs[8]);
asd_write_reg_word(asd_ha, LmM3INTVEC9(lseq), lseq_vecs[9]);
asd_write_reg_word(asd_ha, LmM3INTVEC10(lseq), lseq_vecs[10]);
/*
* Program the Link LED control, applicable only for
* Chip Rev. B or later.
*/
asd_write_reg_dword(asd_ha, LmCONTROL(lseq),
(LEDTIMER | LEDMODE_TXRX | LEDTIMERS_100ms));
/* Set the Align Rate for SAS and STP mode. */
asd_write_reg_byte(asd_ha, LmM1SASALIGN(lseq), SAS_ALIGN_DEFAULT);
asd_write_reg_byte(asd_ha, LmM1STPALIGN(lseq), STP_ALIGN_DEFAULT);
}
/**
* asd_post_init_cseq -- clear CSEQ Mode n Int. status and Response mailbox
* @asd_ha: pointer to host adapter struct
*/
static void asd_post_init_cseq(struct asd_ha_struct *asd_ha)
{
int i;
for (i = 0; i < 8; i++)
asd_write_reg_dword(asd_ha, CMnINT(i), 0xFFFFFFFF);
for (i = 0; i < 8; i++)
asd_read_reg_dword(asd_ha, CMnRSPMBX(i));
/* Reset the external interrupt arbiter. */
asd_write_reg_byte(asd_ha, CARP2INTCTL, RSTINTCTL);
}
/**
* asd_init_ddb_0 -- initialize DDB 0
* @asd_ha: pointer to host adapter structure
*
* Initialize DDB site 0 which is used internally by the sequencer.
*/
static void asd_init_ddb_0(struct asd_ha_struct *asd_ha)
{
int i;
/* Zero out the DDB explicitly */
for (i = 0; i < sizeof(struct asd_ddb_seq_shared); i+=4)
asd_ddbsite_write_dword(asd_ha, 0, i, 0);
asd_ddbsite_write_word(asd_ha, 0,
offsetof(struct asd_ddb_seq_shared, q_free_ddb_head), 0);
asd_ddbsite_write_word(asd_ha, 0,
offsetof(struct asd_ddb_seq_shared, q_free_ddb_tail),
asd_ha->hw_prof.max_ddbs-1);
asd_ddbsite_write_word(asd_ha, 0,
offsetof(struct asd_ddb_seq_shared, q_free_ddb_cnt), 0);
asd_ddbsite_write_word(asd_ha, 0,
offsetof(struct asd_ddb_seq_shared, q_used_ddb_head), 0xFFFF);
asd_ddbsite_write_word(asd_ha, 0,
offsetof(struct asd_ddb_seq_shared, q_used_ddb_tail), 0xFFFF);
asd_ddbsite_write_word(asd_ha, 0,
offsetof(struct asd_ddb_seq_shared, shared_mem_lock), 0);
asd_ddbsite_write_word(asd_ha, 0,
offsetof(struct asd_ddb_seq_shared, smp_conn_tag), 0);
asd_ddbsite_write_word(asd_ha, 0,
offsetof(struct asd_ddb_seq_shared, est_nexus_buf_cnt), 0);
asd_ddbsite_write_word(asd_ha, 0,
offsetof(struct asd_ddb_seq_shared, est_nexus_buf_thresh),
asd_ha->hw_prof.num_phys * 2);
asd_ddbsite_write_byte(asd_ha, 0,
offsetof(struct asd_ddb_seq_shared, settable_max_contexts),0);
asd_ddbsite_write_byte(asd_ha, 0,
offsetof(struct asd_ddb_seq_shared, conn_not_active), 0xFF);
asd_ddbsite_write_byte(asd_ha, 0,
offsetof(struct asd_ddb_seq_shared, phy_is_up), 0x00);
/* DDB 0 is reserved */
set_bit(0, asd_ha->hw_prof.ddb_bitmap);
}
static void asd_seq_init_ddb_sites(struct asd_ha_struct *asd_ha)
{
unsigned int i;
unsigned int ddb_site;
for (ddb_site = 0 ; ddb_site < ASD_MAX_DDBS; ddb_site++)
for (i = 0; i < sizeof(struct asd_ddb_ssp_smp_target_port); i+= 4)
asd_ddbsite_write_dword(asd_ha, ddb_site, i, 0);
}
/**
* asd_seq_setup_seqs -- setup and initialize central and link sequencers
* @asd_ha: pointer to host adapter structure
*/
static void asd_seq_setup_seqs(struct asd_ha_struct *asd_ha)
{
int lseq;
u8 lseq_mask;
/* Initialize DDB sites */
asd_seq_init_ddb_sites(asd_ha);
/* Initialize SCB sites. Done first to compute some values which
* the rest of the init code depends on. */
asd_init_scb_sites(asd_ha);
/* Initialize CSEQ Scratch RAM registers. */
asd_init_cseq_scratch(asd_ha);
/* Initialize LmSEQ Scratch RAM registers. */
asd_init_lseq_scratch(asd_ha);
/* Initialize CSEQ CIO registers. */
asd_init_cseq_cio(asd_ha);
asd_init_ddb_0(asd_ha);
/* Initialize LmSEQ CIO registers. */
lseq_mask = asd_ha->hw_prof.enabled_phys;
for_each_sequencer(lseq_mask, lseq_mask, lseq)
asd_init_lseq_cio(asd_ha, lseq);
asd_post_init_cseq(asd_ha);
}
/**
* asd_seq_start_cseq -- start the central sequencer, CSEQ
* @asd_ha: pointer to host adapter structure
*/
static int asd_seq_start_cseq(struct asd_ha_struct *asd_ha)
{
/* Reset the ARP2 instruction to location zero. */
asd_write_reg_word(asd_ha, CPRGMCNT, cseq_idle_loop);
/* Unpause the CSEQ */
return asd_unpause_cseq(asd_ha);
}
/**
* asd_seq_start_lseq -- start a link sequencer
* @asd_ha: pointer to host adapter structure
* @lseq: the link sequencer of interest
*/
static int asd_seq_start_lseq(struct asd_ha_struct *asd_ha, int lseq)
{
/* Reset the ARP2 instruction to location zero. */
asd_write_reg_word(asd_ha, LmPRGMCNT(lseq), lseq_idle_loop);
/* Unpause the LmSEQ */
return asd_seq_unpause_lseq(asd_ha, lseq);
}
int asd_release_firmware(void)
{
release_firmware(sequencer_fw);
return 0;
}
static int asd_request_firmware(struct asd_ha_struct *asd_ha)
{
int err, i;
struct sequencer_file_header header;
const struct sequencer_file_header *hdr_ptr;
u32 csum = 0;
u16 *ptr_cseq_vecs, *ptr_lseq_vecs;
if (sequencer_fw)
/* already loaded */
return 0;
err = request_firmware(&sequencer_fw,
SAS_RAZOR_SEQUENCER_FW_FILE,
&asd_ha->pcidev->dev);
if (err)
return err;
hdr_ptr = (const struct sequencer_file_header *)sequencer_fw->data;
header.csum = le32_to_cpu(hdr_ptr->csum);
header.major = le32_to_cpu(hdr_ptr->major);
header.minor = le32_to_cpu(hdr_ptr->minor);
header.cseq_table_offset = le32_to_cpu(hdr_ptr->cseq_table_offset);
header.cseq_table_size = le32_to_cpu(hdr_ptr->cseq_table_size);
header.lseq_table_offset = le32_to_cpu(hdr_ptr->lseq_table_offset);
header.lseq_table_size = le32_to_cpu(hdr_ptr->lseq_table_size);
header.cseq_code_offset = le32_to_cpu(hdr_ptr->cseq_code_offset);
header.cseq_code_size = le32_to_cpu(hdr_ptr->cseq_code_size);
header.lseq_code_offset = le32_to_cpu(hdr_ptr->lseq_code_offset);
header.lseq_code_size = le32_to_cpu(hdr_ptr->lseq_code_size);
header.mode2_task = le16_to_cpu(hdr_ptr->mode2_task);
header.cseq_idle_loop = le16_to_cpu(hdr_ptr->cseq_idle_loop);
header.lseq_idle_loop = le16_to_cpu(hdr_ptr->lseq_idle_loop);
for (i = sizeof(header.csum); i < sequencer_fw->size; i++)
csum += sequencer_fw->data[i];
if (csum != header.csum) {
asd_printk("Firmware file checksum mismatch\n");
return -EINVAL;
}
if (header.cseq_table_size != CSEQ_NUM_VECS ||
header.lseq_table_size != LSEQ_NUM_VECS) {
asd_printk("Firmware file table size mismatch\n");
return -EINVAL;
}
asd_printk("Found sequencer Firmware version %d.%d (%s)\n",
header.major, header.minor, hdr_ptr->version);
if (header.major != SAS_RAZOR_SEQUENCER_FW_MAJOR) {
asd_printk("Firmware Major Version Mismatch;"
"driver requires version %d.X",
SAS_RAZOR_SEQUENCER_FW_MAJOR);
return -EINVAL;
}
ptr_cseq_vecs = (u16 *)&sequencer_fw->data[header.cseq_table_offset];
ptr_lseq_vecs = (u16 *)&sequencer_fw->data[header.lseq_table_offset];
mode2_task = header.mode2_task;
cseq_idle_loop = header.cseq_idle_loop;
lseq_idle_loop = header.lseq_idle_loop;
for (i = 0; i < CSEQ_NUM_VECS; i++)
cseq_vecs[i] = le16_to_cpu(ptr_cseq_vecs[i]);
for (i = 0; i < LSEQ_NUM_VECS; i++)
lseq_vecs[i] = le16_to_cpu(ptr_lseq_vecs[i]);
cseq_code = &sequencer_fw->data[header.cseq_code_offset];
cseq_code_size = header.cseq_code_size;
lseq_code = &sequencer_fw->data[header.lseq_code_offset];
lseq_code_size = header.lseq_code_size;
return 0;
}
int asd_init_seqs(struct asd_ha_struct *asd_ha)
{
int err;
err = asd_request_firmware(asd_ha);
if (err) {
asd_printk("Failed to load sequencer firmware file %s, error %d\n",
SAS_RAZOR_SEQUENCER_FW_FILE, err);
return err;
}
err = asd_seq_download_seqs(asd_ha);
if (err) {
asd_printk("couldn't download sequencers for %s\n",
pci_name(asd_ha->pcidev));
return err;
}
asd_seq_setup_seqs(asd_ha);
return 0;
}
int asd_start_seqs(struct asd_ha_struct *asd_ha)
{
int err;
u8 lseq_mask;
int lseq;
err = asd_seq_start_cseq(asd_ha);
if (err) {
asd_printk("couldn't start CSEQ for %s\n",
pci_name(asd_ha->pcidev));
return err;
}
lseq_mask = asd_ha->hw_prof.enabled_phys;
for_each_sequencer(lseq_mask, lseq_mask, lseq) {
err = asd_seq_start_lseq(asd_ha, lseq);
if (err) {
asd_printk("coudln't start LSEQ %d for %s\n", lseq,
pci_name(asd_ha->pcidev));
return err;
}
}
return 0;
}
/**
* asd_update_port_links -- update port_map_by_links and phy_is_up
* @sas_phy: pointer to the phy which has been added to a port
*
* 1) When a link reset has completed and we got BYTES DMAED with a
* valid frame we call this function for that phy, to indicate that
* the phy is up, i.e. we update the phy_is_up in DDB 0. The
* sequencer checks phy_is_up when pending SCBs are to be sent, and
* when an open address frame has been received.
*
* 2) When we know of ports, we call this function to update the map
* of phys participaing in that port, i.e. we update the
* port_map_by_links in DDB 0. When a HARD_RESET primitive has been
* received, the sequencer disables all phys in that port.
* port_map_by_links is also used as the conn_mask byte in the
* initiator/target port DDB.
*/
void asd_update_port_links(struct asd_ha_struct *asd_ha, struct asd_phy *phy)
{
const u8 phy_mask = (u8) phy->asd_port->phy_mask;
u8 phy_is_up;
u8 mask;
int i, err;
unsigned long flags;
spin_lock_irqsave(&asd_ha->hw_prof.ddb_lock, flags);
for_each_phy(phy_mask, mask, i)
asd_ddbsite_write_byte(asd_ha, 0,
offsetof(struct asd_ddb_seq_shared,
port_map_by_links)+i,phy_mask);
for (i = 0; i < 12; i++) {
phy_is_up = asd_ddbsite_read_byte(asd_ha, 0,
offsetof(struct asd_ddb_seq_shared, phy_is_up));
err = asd_ddbsite_update_byte(asd_ha, 0,
offsetof(struct asd_ddb_seq_shared, phy_is_up),
phy_is_up,
phy_is_up | phy_mask);
if (!err)
break;
else if (err == -EFAULT) {
asd_printk("phy_is_up: parity error in DDB 0\n");
break;
}
}
spin_unlock_irqrestore(&asd_ha->hw_prof.ddb_lock, flags);
if (err)
asd_printk("couldn't update DDB 0:error:%d\n", err);
}
MODULE_FIRMWARE(SAS_RAZOR_SEQUENCER_FW_FILE);
| gpl-2.0 |
nitrogen-devs/android_kernel_lge_geeb | arch/arm/mach-sa1100/simpad.c | 4731 | 8588 | /*
* linux/arch/arm/mach-sa1100/simpad.c
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/tty.h>
#include <linux/proc_fs.h>
#include <linux/string.h>
#include <linux/pm.h>
#include <linux/platform_device.h>
#include <linux/mfd/ucb1x00.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <mach/hardware.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/flash.h>
#include <asm/mach/map.h>
#include <asm/mach/serial_sa1100.h>
#include <mach/mcp.h>
#include <mach/simpad.h>
#include <mach/irqs.h>
#include <linux/serial_core.h>
#include <linux/ioport.h>
#include <linux/input.h>
#include <linux/gpio_keys.h>
#include <linux/leds.h>
#include <linux/i2c-gpio.h>
#include "generic.h"
/*
* CS3 support
*/
static long cs3_shadow;
static spinlock_t cs3_lock;
static struct gpio_chip cs3_gpio;
long simpad_get_cs3_ro(void)
{
return readl(CS3_BASE);
}
EXPORT_SYMBOL(simpad_get_cs3_ro);
long simpad_get_cs3_shadow(void)
{
return cs3_shadow;
}
EXPORT_SYMBOL(simpad_get_cs3_shadow);
static void __simpad_write_cs3(void)
{
writel(cs3_shadow, CS3_BASE);
}
void simpad_set_cs3_bit(int value)
{
unsigned long flags;
spin_lock_irqsave(&cs3_lock, flags);
cs3_shadow |= value;
__simpad_write_cs3();
spin_unlock_irqrestore(&cs3_lock, flags);
}
EXPORT_SYMBOL(simpad_set_cs3_bit);
void simpad_clear_cs3_bit(int value)
{
unsigned long flags;
spin_lock_irqsave(&cs3_lock, flags);
cs3_shadow &= ~value;
__simpad_write_cs3();
spin_unlock_irqrestore(&cs3_lock, flags);
}
EXPORT_SYMBOL(simpad_clear_cs3_bit);
static void cs3_gpio_set(struct gpio_chip *chip, unsigned offset, int value)
{
if (offset > 15)
return;
if (value)
simpad_set_cs3_bit(1 << offset);
else
simpad_clear_cs3_bit(1 << offset);
};
static int cs3_gpio_get(struct gpio_chip *chip, unsigned offset)
{
if (offset > 15)
return simpad_get_cs3_ro() & (1 << (offset - 16));
return simpad_get_cs3_shadow() & (1 << offset);
};
static int cs3_gpio_direction_input(struct gpio_chip *chip, unsigned offset)
{
if (offset > 15)
return 0;
return -EINVAL;
};
static int cs3_gpio_direction_output(struct gpio_chip *chip, unsigned offset,
int value)
{
if (offset > 15)
return -EINVAL;
cs3_gpio_set(chip, offset, value);
return 0;
};
static struct map_desc simpad_io_desc[] __initdata = {
{ /* MQ200 */
.virtual = 0xf2800000,
.pfn = __phys_to_pfn(0x4b800000),
.length = 0x00800000,
.type = MT_DEVICE
}, { /* Simpad CS3 */
.virtual = CS3_BASE,
.pfn = __phys_to_pfn(SA1100_CS3_PHYS),
.length = 0x00100000,
.type = MT_DEVICE
},
};
static void simpad_uart_pm(struct uart_port *port, u_int state, u_int oldstate)
{
if (port->mapbase == (u_int)&Ser1UTCR0) {
if (state)
{
simpad_clear_cs3_bit(RS232_ON);
simpad_clear_cs3_bit(DECT_POWER_ON);
}else
{
simpad_set_cs3_bit(RS232_ON);
simpad_set_cs3_bit(DECT_POWER_ON);
}
}
}
static struct sa1100_port_fns simpad_port_fns __initdata = {
.pm = simpad_uart_pm,
};
static struct mtd_partition simpad_partitions[] = {
{
.name = "SIMpad boot firmware",
.size = 0x00080000,
.offset = 0,
.mask_flags = MTD_WRITEABLE,
}, {
.name = "SIMpad kernel",
.size = 0x0010000,
.offset = MTDPART_OFS_APPEND,
}, {
.name = "SIMpad root jffs2",
.size = MTDPART_SIZ_FULL,
.offset = MTDPART_OFS_APPEND,
}
};
static struct flash_platform_data simpad_flash_data = {
.map_name = "cfi_probe",
.parts = simpad_partitions,
.nr_parts = ARRAY_SIZE(simpad_partitions),
};
static struct resource simpad_flash_resources [] = {
DEFINE_RES_MEM(SA1100_CS0_PHYS, SZ_16M),
DEFINE_RES_MEM(SA1100_CS1_PHYS, SZ_16M),
};
static struct ucb1x00_plat_data simpad_ucb1x00_data = {
.gpio_base = SIMPAD_UCB1X00_GPIO_BASE,
};
static struct mcp_plat_data simpad_mcp_data = {
.mccr0 = MCCR0_ADM,
.sclk_rate = 11981000,
.codec_pdata = &simpad_ucb1x00_data,
};
static void __init simpad_map_io(void)
{
sa1100_map_io();
iotable_init(simpad_io_desc, ARRAY_SIZE(simpad_io_desc));
/* Initialize CS3 */
cs3_shadow = (EN1 | EN0 | LED2_ON | DISPLAY_ON |
RS232_ON | ENABLE_5V | RESET_SIMCARD | DECT_POWER_ON);
__simpad_write_cs3(); /* Spinlocks not yet initialized */
sa1100_register_uart_fns(&simpad_port_fns);
sa1100_register_uart(0, 3); /* serial interface */
sa1100_register_uart(1, 1); /* DECT */
// Reassign UART 1 pins
GAFR |= GPIO_UART_TXD | GPIO_UART_RXD;
GPDR |= GPIO_UART_TXD | GPIO_LDD13 | GPIO_LDD15;
GPDR &= ~GPIO_UART_RXD;
PPAR |= PPAR_UPR;
/*
* Set up registers for sleep mode.
*/
PWER = PWER_GPIO0| PWER_RTC;
PGSR = 0x818;
PCFR = 0;
PSDR = 0;
}
static void simpad_power_off(void)
{
local_irq_disable();
cs3_shadow = SD_MEDIAQ;
__simpad_write_cs3(); /* Bypass spinlock here */
/* disable internal oscillator, float CS lines */
PCFR = (PCFR_OPDE | PCFR_FP | PCFR_FS);
/* enable wake-up on GPIO0 */
PWER = GFER = GRER = PWER_GPIO0;
/*
* set scratchpad to zero, just in case it is used as a
* restart address by the bootloader.
*/
PSPR = 0;
PGSR = 0;
/* enter sleep mode */
PMCR = PMCR_SF;
while(1);
local_irq_enable(); /* we won't ever call it */
}
/*
* gpio_keys
*/
static struct gpio_keys_button simpad_button_table[] = {
{ KEY_POWER, IRQ_GPIO_POWER_BUTTON, 1, "power button" },
};
static struct gpio_keys_platform_data simpad_keys_data = {
.buttons = simpad_button_table,
.nbuttons = ARRAY_SIZE(simpad_button_table),
};
static struct platform_device simpad_keys = {
.name = "gpio-keys",
.dev = {
.platform_data = &simpad_keys_data,
},
};
static struct gpio_keys_button simpad_polled_button_table[] = {
{ KEY_PROG1, SIMPAD_UCB1X00_GPIO_PROG1, 1, "prog1 button" },
{ KEY_PROG2, SIMPAD_UCB1X00_GPIO_PROG2, 1, "prog2 button" },
{ KEY_UP, SIMPAD_UCB1X00_GPIO_UP, 1, "up button" },
{ KEY_DOWN, SIMPAD_UCB1X00_GPIO_DOWN, 1, "down button" },
{ KEY_LEFT, SIMPAD_UCB1X00_GPIO_LEFT, 1, "left button" },
{ KEY_RIGHT, SIMPAD_UCB1X00_GPIO_RIGHT, 1, "right button" },
};
static struct gpio_keys_platform_data simpad_polled_keys_data = {
.buttons = simpad_polled_button_table,
.nbuttons = ARRAY_SIZE(simpad_polled_button_table),
.poll_interval = 50,
};
static struct platform_device simpad_polled_keys = {
.name = "gpio-keys-polled",
.dev = {
.platform_data = &simpad_polled_keys_data,
},
};
/*
* GPIO LEDs
*/
static struct gpio_led simpad_leds[] = {
{
.name = "simpad:power",
.gpio = SIMPAD_CS3_LED2_ON,
.active_low = 0,
.default_trigger = "default-on",
},
};
static struct gpio_led_platform_data simpad_led_data = {
.num_leds = ARRAY_SIZE(simpad_leds),
.leds = simpad_leds,
};
static struct platform_device simpad_gpio_leds = {
.name = "leds-gpio",
.id = 0,
.dev = {
.platform_data = &simpad_led_data,
},
};
/*
* i2c
*/
static struct i2c_gpio_platform_data simpad_i2c_data = {
.sda_pin = GPIO_GPIO21,
.scl_pin = GPIO_GPIO25,
.udelay = 10,
.timeout = HZ,
};
static struct platform_device simpad_i2c = {
.name = "i2c-gpio",
.id = 0,
.dev = {
.platform_data = &simpad_i2c_data,
},
};
/*
* MediaQ Video Device
*/
static struct platform_device simpad_mq200fb = {
.name = "simpad-mq200",
.id = 0,
};
static struct platform_device *devices[] __initdata = {
&simpad_keys,
&simpad_polled_keys,
&simpad_mq200fb,
&simpad_gpio_leds,
&simpad_i2c,
};
static int __init simpad_init(void)
{
int ret;
spin_lock_init(&cs3_lock);
cs3_gpio.label = "simpad_cs3";
cs3_gpio.base = SIMPAD_CS3_GPIO_BASE;
cs3_gpio.ngpio = 24;
cs3_gpio.set = cs3_gpio_set;
cs3_gpio.get = cs3_gpio_get;
cs3_gpio.direction_input = cs3_gpio_direction_input;
cs3_gpio.direction_output = cs3_gpio_direction_output;
ret = gpiochip_add(&cs3_gpio);
if (ret)
printk(KERN_WARNING "simpad: Unable to register cs3 GPIO device");
pm_power_off = simpad_power_off;
sa11x0_ppc_configure_mcp();
sa11x0_register_mtd(&simpad_flash_data, simpad_flash_resources,
ARRAY_SIZE(simpad_flash_resources));
sa11x0_register_mcp(&simpad_mcp_data);
ret = platform_add_devices(devices, ARRAY_SIZE(devices));
if(ret)
printk(KERN_WARNING "simpad: Unable to register mq200 framebuffer device");
return 0;
}
arch_initcall(simpad_init);
MACHINE_START(SIMPAD, "Simpad")
/* Maintainer: Holger Freyther */
.atag_offset = 0x100,
.map_io = simpad_map_io,
.nr_irqs = SA1100_NR_IRQS,
.init_irq = sa1100_init_irq,
.timer = &sa1100_timer,
.restart = sa11x0_restart,
MACHINE_END
| gpl-2.0 |
lovemrdeng/android_kernel_msm8960 | sound/soc/tegra/tegra_i2s.c | 4731 | 11309 | /*
* tegra_i2s.c - Tegra I2S driver
*
* Author: Stephen Warren <swarren@nvidia.com>
* Copyright (C) 2010 - NVIDIA, Inc.
*
* Based on code copyright/by:
*
* Copyright (c) 2009-2010, NVIDIA Corporation.
* Scott Peterson <speterson@nvidia.com>
*
* Copyright (C) 2010 Google, Inc.
* Iliyan Malchev <malchev@google.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <linux/clk.h>
#include <linux/module.h>
#include <linux/debugfs.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/io.h>
#include <linux/of.h>
#include <mach/iomap.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include "tegra_i2s.h"
#define DRV_NAME "tegra-i2s"
static inline void tegra_i2s_write(struct tegra_i2s *i2s, u32 reg, u32 val)
{
__raw_writel(val, i2s->regs + reg);
}
static inline u32 tegra_i2s_read(struct tegra_i2s *i2s, u32 reg)
{
return __raw_readl(i2s->regs + reg);
}
#ifdef CONFIG_DEBUG_FS
static int tegra_i2s_show(struct seq_file *s, void *unused)
{
#define REG(r) { r, #r }
static const struct {
int offset;
const char *name;
} regs[] = {
REG(TEGRA_I2S_CTRL),
REG(TEGRA_I2S_STATUS),
REG(TEGRA_I2S_TIMING),
REG(TEGRA_I2S_FIFO_SCR),
REG(TEGRA_I2S_PCM_CTRL),
REG(TEGRA_I2S_NW_CTRL),
REG(TEGRA_I2S_TDM_CTRL),
REG(TEGRA_I2S_TDM_TX_RX_CTRL),
};
#undef REG
struct tegra_i2s *i2s = s->private;
int i;
clk_enable(i2s->clk_i2s);
for (i = 0; i < ARRAY_SIZE(regs); i++) {
u32 val = tegra_i2s_read(i2s, regs[i].offset);
seq_printf(s, "%s = %08x\n", regs[i].name, val);
}
clk_disable(i2s->clk_i2s);
return 0;
}
static int tegra_i2s_debug_open(struct inode *inode, struct file *file)
{
return single_open(file, tegra_i2s_show, inode->i_private);
}
static const struct file_operations tegra_i2s_debug_fops = {
.open = tegra_i2s_debug_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static void tegra_i2s_debug_add(struct tegra_i2s *i2s)
{
i2s->debug = debugfs_create_file(i2s->dai.name, S_IRUGO,
snd_soc_debugfs_root, i2s,
&tegra_i2s_debug_fops);
}
static void tegra_i2s_debug_remove(struct tegra_i2s *i2s)
{
if (i2s->debug)
debugfs_remove(i2s->debug);
}
#else
static inline void tegra_i2s_debug_add(struct tegra_i2s *i2s)
{
}
static inline void tegra_i2s_debug_remove(struct tegra_i2s *i2s)
{
}
#endif
static int tegra_i2s_set_fmt(struct snd_soc_dai *dai,
unsigned int fmt)
{
struct tegra_i2s *i2s = snd_soc_dai_get_drvdata(dai);
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
default:
return -EINVAL;
}
i2s->reg_ctrl &= ~TEGRA_I2S_CTRL_MASTER_ENABLE;
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBS_CFS:
i2s->reg_ctrl |= TEGRA_I2S_CTRL_MASTER_ENABLE;
break;
case SND_SOC_DAIFMT_CBM_CFM:
break;
default:
return -EINVAL;
}
i2s->reg_ctrl &= ~(TEGRA_I2S_CTRL_BIT_FORMAT_MASK |
TEGRA_I2S_CTRL_LRCK_MASK);
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_DSP_A:
i2s->reg_ctrl |= TEGRA_I2S_CTRL_BIT_FORMAT_DSP;
i2s->reg_ctrl |= TEGRA_I2S_CTRL_LRCK_L_LOW;
break;
case SND_SOC_DAIFMT_DSP_B:
i2s->reg_ctrl |= TEGRA_I2S_CTRL_BIT_FORMAT_DSP;
i2s->reg_ctrl |= TEGRA_I2S_CTRL_LRCK_R_LOW;
break;
case SND_SOC_DAIFMT_I2S:
i2s->reg_ctrl |= TEGRA_I2S_CTRL_BIT_FORMAT_I2S;
i2s->reg_ctrl |= TEGRA_I2S_CTRL_LRCK_L_LOW;
break;
case SND_SOC_DAIFMT_RIGHT_J:
i2s->reg_ctrl |= TEGRA_I2S_CTRL_BIT_FORMAT_RJM;
i2s->reg_ctrl |= TEGRA_I2S_CTRL_LRCK_L_LOW;
break;
case SND_SOC_DAIFMT_LEFT_J:
i2s->reg_ctrl |= TEGRA_I2S_CTRL_BIT_FORMAT_LJM;
i2s->reg_ctrl |= TEGRA_I2S_CTRL_LRCK_L_LOW;
break;
default:
return -EINVAL;
}
return 0;
}
static int tegra_i2s_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct device *dev = substream->pcm->card->dev;
struct tegra_i2s *i2s = snd_soc_dai_get_drvdata(dai);
u32 reg;
int ret, sample_size, srate, i2sclock, bitcnt;
i2s->reg_ctrl &= ~TEGRA_I2S_CTRL_BIT_SIZE_MASK;
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
i2s->reg_ctrl |= TEGRA_I2S_CTRL_BIT_SIZE_16;
sample_size = 16;
break;
case SNDRV_PCM_FORMAT_S24_LE:
i2s->reg_ctrl |= TEGRA_I2S_CTRL_BIT_SIZE_24;
sample_size = 24;
break;
case SNDRV_PCM_FORMAT_S32_LE:
i2s->reg_ctrl |= TEGRA_I2S_CTRL_BIT_SIZE_32;
sample_size = 32;
break;
default:
return -EINVAL;
}
srate = params_rate(params);
/* Final "* 2" required by Tegra hardware */
i2sclock = srate * params_channels(params) * sample_size * 2;
ret = clk_set_rate(i2s->clk_i2s, i2sclock);
if (ret) {
dev_err(dev, "Can't set I2S clock rate: %d\n", ret);
return ret;
}
bitcnt = (i2sclock / (2 * srate)) - 1;
if (bitcnt < 0 || bitcnt > TEGRA_I2S_TIMING_CHANNEL_BIT_COUNT_MASK_US)
return -EINVAL;
reg = bitcnt << TEGRA_I2S_TIMING_CHANNEL_BIT_COUNT_SHIFT;
if (i2sclock % (2 * srate))
reg |= TEGRA_I2S_TIMING_NON_SYM_ENABLE;
if (!i2s->clk_refs)
clk_enable(i2s->clk_i2s);
tegra_i2s_write(i2s, TEGRA_I2S_TIMING, reg);
tegra_i2s_write(i2s, TEGRA_I2S_FIFO_SCR,
TEGRA_I2S_FIFO_SCR_FIFO2_ATN_LVL_FOUR_SLOTS |
TEGRA_I2S_FIFO_SCR_FIFO1_ATN_LVL_FOUR_SLOTS);
if (!i2s->clk_refs)
clk_disable(i2s->clk_i2s);
return 0;
}
static void tegra_i2s_start_playback(struct tegra_i2s *i2s)
{
i2s->reg_ctrl |= TEGRA_I2S_CTRL_FIFO1_ENABLE;
tegra_i2s_write(i2s, TEGRA_I2S_CTRL, i2s->reg_ctrl);
}
static void tegra_i2s_stop_playback(struct tegra_i2s *i2s)
{
i2s->reg_ctrl &= ~TEGRA_I2S_CTRL_FIFO1_ENABLE;
tegra_i2s_write(i2s, TEGRA_I2S_CTRL, i2s->reg_ctrl);
}
static void tegra_i2s_start_capture(struct tegra_i2s *i2s)
{
i2s->reg_ctrl |= TEGRA_I2S_CTRL_FIFO2_ENABLE;
tegra_i2s_write(i2s, TEGRA_I2S_CTRL, i2s->reg_ctrl);
}
static void tegra_i2s_stop_capture(struct tegra_i2s *i2s)
{
i2s->reg_ctrl &= ~TEGRA_I2S_CTRL_FIFO2_ENABLE;
tegra_i2s_write(i2s, TEGRA_I2S_CTRL, i2s->reg_ctrl);
}
static int tegra_i2s_trigger(struct snd_pcm_substream *substream, int cmd,
struct snd_soc_dai *dai)
{
struct tegra_i2s *i2s = snd_soc_dai_get_drvdata(dai);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_RESUME:
if (!i2s->clk_refs)
clk_enable(i2s->clk_i2s);
i2s->clk_refs++;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
tegra_i2s_start_playback(i2s);
else
tegra_i2s_start_capture(i2s);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_SUSPEND:
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
tegra_i2s_stop_playback(i2s);
else
tegra_i2s_stop_capture(i2s);
i2s->clk_refs--;
if (!i2s->clk_refs)
clk_disable(i2s->clk_i2s);
break;
default:
return -EINVAL;
}
return 0;
}
static int tegra_i2s_probe(struct snd_soc_dai *dai)
{
struct tegra_i2s * i2s = snd_soc_dai_get_drvdata(dai);
dai->capture_dma_data = &i2s->capture_dma_data;
dai->playback_dma_data = &i2s->playback_dma_data;
return 0;
}
static const struct snd_soc_dai_ops tegra_i2s_dai_ops = {
.set_fmt = tegra_i2s_set_fmt,
.hw_params = tegra_i2s_hw_params,
.trigger = tegra_i2s_trigger,
};
static const struct snd_soc_dai_driver tegra_i2s_dai_template = {
.probe = tegra_i2s_probe,
.playback = {
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_96000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
},
.capture = {
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_96000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
},
.ops = &tegra_i2s_dai_ops,
.symmetric_rates = 1,
};
static __devinit int tegra_i2s_platform_probe(struct platform_device *pdev)
{
struct tegra_i2s * i2s;
struct resource *mem, *memregion, *dmareq;
u32 of_dma[2];
u32 dma_ch;
int ret;
i2s = devm_kzalloc(&pdev->dev, sizeof(struct tegra_i2s), GFP_KERNEL);
if (!i2s) {
dev_err(&pdev->dev, "Can't allocate tegra_i2s\n");
ret = -ENOMEM;
goto err;
}
dev_set_drvdata(&pdev->dev, i2s);
i2s->dai = tegra_i2s_dai_template;
i2s->dai.name = dev_name(&pdev->dev);
i2s->clk_i2s = clk_get(&pdev->dev, NULL);
if (IS_ERR(i2s->clk_i2s)) {
dev_err(&pdev->dev, "Can't retrieve i2s clock\n");
ret = PTR_ERR(i2s->clk_i2s);
goto err;
}
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!mem) {
dev_err(&pdev->dev, "No memory resource\n");
ret = -ENODEV;
goto err_clk_put;
}
dmareq = platform_get_resource(pdev, IORESOURCE_DMA, 0);
if (!dmareq) {
if (of_property_read_u32_array(pdev->dev.of_node,
"nvidia,dma-request-selector",
of_dma, 2) < 0) {
dev_err(&pdev->dev, "No DMA resource\n");
ret = -ENODEV;
goto err_clk_put;
}
dma_ch = of_dma[1];
} else {
dma_ch = dmareq->start;
}
memregion = devm_request_mem_region(&pdev->dev, mem->start,
resource_size(mem), DRV_NAME);
if (!memregion) {
dev_err(&pdev->dev, "Memory region already claimed\n");
ret = -EBUSY;
goto err_clk_put;
}
i2s->regs = devm_ioremap(&pdev->dev, mem->start, resource_size(mem));
if (!i2s->regs) {
dev_err(&pdev->dev, "ioremap failed\n");
ret = -ENOMEM;
goto err_clk_put;
}
i2s->capture_dma_data.addr = mem->start + TEGRA_I2S_FIFO2;
i2s->capture_dma_data.wrap = 4;
i2s->capture_dma_data.width = 32;
i2s->capture_dma_data.req_sel = dma_ch;
i2s->playback_dma_data.addr = mem->start + TEGRA_I2S_FIFO1;
i2s->playback_dma_data.wrap = 4;
i2s->playback_dma_data.width = 32;
i2s->playback_dma_data.req_sel = dma_ch;
i2s->reg_ctrl = TEGRA_I2S_CTRL_FIFO_FORMAT_PACKED;
ret = snd_soc_register_dai(&pdev->dev, &i2s->dai);
if (ret) {
dev_err(&pdev->dev, "Could not register DAI: %d\n", ret);
ret = -ENOMEM;
goto err_clk_put;
}
tegra_i2s_debug_add(i2s);
return 0;
err_clk_put:
clk_put(i2s->clk_i2s);
err:
return ret;
}
static int __devexit tegra_i2s_platform_remove(struct platform_device *pdev)
{
struct tegra_i2s *i2s = dev_get_drvdata(&pdev->dev);
snd_soc_unregister_dai(&pdev->dev);
tegra_i2s_debug_remove(i2s);
clk_put(i2s->clk_i2s);
return 0;
}
static const struct of_device_id tegra_i2s_of_match[] __devinitconst = {
{ .compatible = "nvidia,tegra20-i2s", },
{},
};
static struct platform_driver tegra_i2s_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
.of_match_table = tegra_i2s_of_match,
},
.probe = tegra_i2s_platform_probe,
.remove = __devexit_p(tegra_i2s_platform_remove),
};
module_platform_driver(tegra_i2s_driver);
MODULE_AUTHOR("Stephen Warren <swarren@nvidia.com>");
MODULE_DESCRIPTION("Tegra I2S ASoC driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" DRV_NAME);
MODULE_DEVICE_TABLE(of, tegra_i2s_of_match);
| gpl-2.0 |
bryan2894/D851_Kernel | arch/arm/mach-sa1100/simpad.c | 4731 | 8588 | /*
* linux/arch/arm/mach-sa1100/simpad.c
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/tty.h>
#include <linux/proc_fs.h>
#include <linux/string.h>
#include <linux/pm.h>
#include <linux/platform_device.h>
#include <linux/mfd/ucb1x00.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <mach/hardware.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/flash.h>
#include <asm/mach/map.h>
#include <asm/mach/serial_sa1100.h>
#include <mach/mcp.h>
#include <mach/simpad.h>
#include <mach/irqs.h>
#include <linux/serial_core.h>
#include <linux/ioport.h>
#include <linux/input.h>
#include <linux/gpio_keys.h>
#include <linux/leds.h>
#include <linux/i2c-gpio.h>
#include "generic.h"
/*
* CS3 support
*/
static long cs3_shadow;
static spinlock_t cs3_lock;
static struct gpio_chip cs3_gpio;
long simpad_get_cs3_ro(void)
{
return readl(CS3_BASE);
}
EXPORT_SYMBOL(simpad_get_cs3_ro);
long simpad_get_cs3_shadow(void)
{
return cs3_shadow;
}
EXPORT_SYMBOL(simpad_get_cs3_shadow);
static void __simpad_write_cs3(void)
{
writel(cs3_shadow, CS3_BASE);
}
void simpad_set_cs3_bit(int value)
{
unsigned long flags;
spin_lock_irqsave(&cs3_lock, flags);
cs3_shadow |= value;
__simpad_write_cs3();
spin_unlock_irqrestore(&cs3_lock, flags);
}
EXPORT_SYMBOL(simpad_set_cs3_bit);
void simpad_clear_cs3_bit(int value)
{
unsigned long flags;
spin_lock_irqsave(&cs3_lock, flags);
cs3_shadow &= ~value;
__simpad_write_cs3();
spin_unlock_irqrestore(&cs3_lock, flags);
}
EXPORT_SYMBOL(simpad_clear_cs3_bit);
static void cs3_gpio_set(struct gpio_chip *chip, unsigned offset, int value)
{
if (offset > 15)
return;
if (value)
simpad_set_cs3_bit(1 << offset);
else
simpad_clear_cs3_bit(1 << offset);
};
static int cs3_gpio_get(struct gpio_chip *chip, unsigned offset)
{
if (offset > 15)
return simpad_get_cs3_ro() & (1 << (offset - 16));
return simpad_get_cs3_shadow() & (1 << offset);
};
static int cs3_gpio_direction_input(struct gpio_chip *chip, unsigned offset)
{
if (offset > 15)
return 0;
return -EINVAL;
};
static int cs3_gpio_direction_output(struct gpio_chip *chip, unsigned offset,
int value)
{
if (offset > 15)
return -EINVAL;
cs3_gpio_set(chip, offset, value);
return 0;
};
static struct map_desc simpad_io_desc[] __initdata = {
{ /* MQ200 */
.virtual = 0xf2800000,
.pfn = __phys_to_pfn(0x4b800000),
.length = 0x00800000,
.type = MT_DEVICE
}, { /* Simpad CS3 */
.virtual = CS3_BASE,
.pfn = __phys_to_pfn(SA1100_CS3_PHYS),
.length = 0x00100000,
.type = MT_DEVICE
},
};
static void simpad_uart_pm(struct uart_port *port, u_int state, u_int oldstate)
{
if (port->mapbase == (u_int)&Ser1UTCR0) {
if (state)
{
simpad_clear_cs3_bit(RS232_ON);
simpad_clear_cs3_bit(DECT_POWER_ON);
}else
{
simpad_set_cs3_bit(RS232_ON);
simpad_set_cs3_bit(DECT_POWER_ON);
}
}
}
static struct sa1100_port_fns simpad_port_fns __initdata = {
.pm = simpad_uart_pm,
};
static struct mtd_partition simpad_partitions[] = {
{
.name = "SIMpad boot firmware",
.size = 0x00080000,
.offset = 0,
.mask_flags = MTD_WRITEABLE,
}, {
.name = "SIMpad kernel",
.size = 0x0010000,
.offset = MTDPART_OFS_APPEND,
}, {
.name = "SIMpad root jffs2",
.size = MTDPART_SIZ_FULL,
.offset = MTDPART_OFS_APPEND,
}
};
static struct flash_platform_data simpad_flash_data = {
.map_name = "cfi_probe",
.parts = simpad_partitions,
.nr_parts = ARRAY_SIZE(simpad_partitions),
};
static struct resource simpad_flash_resources [] = {
DEFINE_RES_MEM(SA1100_CS0_PHYS, SZ_16M),
DEFINE_RES_MEM(SA1100_CS1_PHYS, SZ_16M),
};
static struct ucb1x00_plat_data simpad_ucb1x00_data = {
.gpio_base = SIMPAD_UCB1X00_GPIO_BASE,
};
static struct mcp_plat_data simpad_mcp_data = {
.mccr0 = MCCR0_ADM,
.sclk_rate = 11981000,
.codec_pdata = &simpad_ucb1x00_data,
};
static void __init simpad_map_io(void)
{
sa1100_map_io();
iotable_init(simpad_io_desc, ARRAY_SIZE(simpad_io_desc));
/* Initialize CS3 */
cs3_shadow = (EN1 | EN0 | LED2_ON | DISPLAY_ON |
RS232_ON | ENABLE_5V | RESET_SIMCARD | DECT_POWER_ON);
__simpad_write_cs3(); /* Spinlocks not yet initialized */
sa1100_register_uart_fns(&simpad_port_fns);
sa1100_register_uart(0, 3); /* serial interface */
sa1100_register_uart(1, 1); /* DECT */
// Reassign UART 1 pins
GAFR |= GPIO_UART_TXD | GPIO_UART_RXD;
GPDR |= GPIO_UART_TXD | GPIO_LDD13 | GPIO_LDD15;
GPDR &= ~GPIO_UART_RXD;
PPAR |= PPAR_UPR;
/*
* Set up registers for sleep mode.
*/
PWER = PWER_GPIO0| PWER_RTC;
PGSR = 0x818;
PCFR = 0;
PSDR = 0;
}
static void simpad_power_off(void)
{
local_irq_disable();
cs3_shadow = SD_MEDIAQ;
__simpad_write_cs3(); /* Bypass spinlock here */
/* disable internal oscillator, float CS lines */
PCFR = (PCFR_OPDE | PCFR_FP | PCFR_FS);
/* enable wake-up on GPIO0 */
PWER = GFER = GRER = PWER_GPIO0;
/*
* set scratchpad to zero, just in case it is used as a
* restart address by the bootloader.
*/
PSPR = 0;
PGSR = 0;
/* enter sleep mode */
PMCR = PMCR_SF;
while(1);
local_irq_enable(); /* we won't ever call it */
}
/*
* gpio_keys
*/
static struct gpio_keys_button simpad_button_table[] = {
{ KEY_POWER, IRQ_GPIO_POWER_BUTTON, 1, "power button" },
};
static struct gpio_keys_platform_data simpad_keys_data = {
.buttons = simpad_button_table,
.nbuttons = ARRAY_SIZE(simpad_button_table),
};
static struct platform_device simpad_keys = {
.name = "gpio-keys",
.dev = {
.platform_data = &simpad_keys_data,
},
};
static struct gpio_keys_button simpad_polled_button_table[] = {
{ KEY_PROG1, SIMPAD_UCB1X00_GPIO_PROG1, 1, "prog1 button" },
{ KEY_PROG2, SIMPAD_UCB1X00_GPIO_PROG2, 1, "prog2 button" },
{ KEY_UP, SIMPAD_UCB1X00_GPIO_UP, 1, "up button" },
{ KEY_DOWN, SIMPAD_UCB1X00_GPIO_DOWN, 1, "down button" },
{ KEY_LEFT, SIMPAD_UCB1X00_GPIO_LEFT, 1, "left button" },
{ KEY_RIGHT, SIMPAD_UCB1X00_GPIO_RIGHT, 1, "right button" },
};
static struct gpio_keys_platform_data simpad_polled_keys_data = {
.buttons = simpad_polled_button_table,
.nbuttons = ARRAY_SIZE(simpad_polled_button_table),
.poll_interval = 50,
};
static struct platform_device simpad_polled_keys = {
.name = "gpio-keys-polled",
.dev = {
.platform_data = &simpad_polled_keys_data,
},
};
/*
* GPIO LEDs
*/
static struct gpio_led simpad_leds[] = {
{
.name = "simpad:power",
.gpio = SIMPAD_CS3_LED2_ON,
.active_low = 0,
.default_trigger = "default-on",
},
};
static struct gpio_led_platform_data simpad_led_data = {
.num_leds = ARRAY_SIZE(simpad_leds),
.leds = simpad_leds,
};
static struct platform_device simpad_gpio_leds = {
.name = "leds-gpio",
.id = 0,
.dev = {
.platform_data = &simpad_led_data,
},
};
/*
* i2c
*/
static struct i2c_gpio_platform_data simpad_i2c_data = {
.sda_pin = GPIO_GPIO21,
.scl_pin = GPIO_GPIO25,
.udelay = 10,
.timeout = HZ,
};
static struct platform_device simpad_i2c = {
.name = "i2c-gpio",
.id = 0,
.dev = {
.platform_data = &simpad_i2c_data,
},
};
/*
* MediaQ Video Device
*/
static struct platform_device simpad_mq200fb = {
.name = "simpad-mq200",
.id = 0,
};
static struct platform_device *devices[] __initdata = {
&simpad_keys,
&simpad_polled_keys,
&simpad_mq200fb,
&simpad_gpio_leds,
&simpad_i2c,
};
static int __init simpad_init(void)
{
int ret;
spin_lock_init(&cs3_lock);
cs3_gpio.label = "simpad_cs3";
cs3_gpio.base = SIMPAD_CS3_GPIO_BASE;
cs3_gpio.ngpio = 24;
cs3_gpio.set = cs3_gpio_set;
cs3_gpio.get = cs3_gpio_get;
cs3_gpio.direction_input = cs3_gpio_direction_input;
cs3_gpio.direction_output = cs3_gpio_direction_output;
ret = gpiochip_add(&cs3_gpio);
if (ret)
printk(KERN_WARNING "simpad: Unable to register cs3 GPIO device");
pm_power_off = simpad_power_off;
sa11x0_ppc_configure_mcp();
sa11x0_register_mtd(&simpad_flash_data, simpad_flash_resources,
ARRAY_SIZE(simpad_flash_resources));
sa11x0_register_mcp(&simpad_mcp_data);
ret = platform_add_devices(devices, ARRAY_SIZE(devices));
if(ret)
printk(KERN_WARNING "simpad: Unable to register mq200 framebuffer device");
return 0;
}
arch_initcall(simpad_init);
MACHINE_START(SIMPAD, "Simpad")
/* Maintainer: Holger Freyther */
.atag_offset = 0x100,
.map_io = simpad_map_io,
.nr_irqs = SA1100_NR_IRQS,
.init_irq = sa1100_init_irq,
.timer = &sa1100_timer,
.restart = sa11x0_restart,
MACHINE_END
| gpl-2.0 |
coolshou/htc_m7u_kernel-3.4.10 | fs/ufs/inode.c | 4731 | 25705 | /*
* linux/fs/ufs/inode.c
*
* Copyright (C) 1998
* Daniel Pirkl <daniel.pirkl@email.cz>
* Charles University, Faculty of Mathematics and Physics
*
* from
*
* linux/fs/ext2/inode.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/inode.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Goal-directed block allocation by Stephen Tweedie (sct@dcs.ed.ac.uk), 1993
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller (davem@caip.rutgers.edu), 1995
*/
#include <asm/uaccess.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/time.h>
#include <linux/stat.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/buffer_head.h>
#include <linux/writeback.h>
#include "ufs_fs.h"
#include "ufs.h"
#include "swab.h"
#include "util.h"
static u64 ufs_frag_map(struct inode *inode, sector_t frag, bool needs_lock);
static int ufs_block_to_path(struct inode *inode, sector_t i_block, sector_t offsets[4])
{
struct ufs_sb_private_info *uspi = UFS_SB(inode->i_sb)->s_uspi;
int ptrs = uspi->s_apb;
int ptrs_bits = uspi->s_apbshift;
const long direct_blocks = UFS_NDADDR,
indirect_blocks = ptrs,
double_blocks = (1 << (ptrs_bits * 2));
int n = 0;
UFSD("ptrs=uspi->s_apb = %d,double_blocks=%ld \n",ptrs,double_blocks);
if (i_block < direct_blocks) {
offsets[n++] = i_block;
} else if ((i_block -= direct_blocks) < indirect_blocks) {
offsets[n++] = UFS_IND_BLOCK;
offsets[n++] = i_block;
} else if ((i_block -= indirect_blocks) < double_blocks) {
offsets[n++] = UFS_DIND_BLOCK;
offsets[n++] = i_block >> ptrs_bits;
offsets[n++] = i_block & (ptrs - 1);
} else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
offsets[n++] = UFS_TIND_BLOCK;
offsets[n++] = i_block >> (ptrs_bits * 2);
offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
offsets[n++] = i_block & (ptrs - 1);
} else {
ufs_warning(inode->i_sb, "ufs_block_to_path", "block > big");
}
return n;
}
/*
* Returns the location of the fragment from
* the beginning of the filesystem.
*/
static u64 ufs_frag_map(struct inode *inode, sector_t frag, bool needs_lock)
{
struct ufs_inode_info *ufsi = UFS_I(inode);
struct super_block *sb = inode->i_sb;
struct ufs_sb_private_info *uspi = UFS_SB(sb)->s_uspi;
u64 mask = (u64) uspi->s_apbmask>>uspi->s_fpbshift;
int shift = uspi->s_apbshift-uspi->s_fpbshift;
sector_t offsets[4], *p;
int depth = ufs_block_to_path(inode, frag >> uspi->s_fpbshift, offsets);
u64 ret = 0L;
__fs32 block;
__fs64 u2_block = 0L;
unsigned flags = UFS_SB(sb)->s_flags;
u64 temp = 0L;
UFSD(": frag = %llu depth = %d\n", (unsigned long long)frag, depth);
UFSD(": uspi->s_fpbshift = %d ,uspi->s_apbmask = %x, mask=%llx\n",
uspi->s_fpbshift, uspi->s_apbmask,
(unsigned long long)mask);
if (depth == 0)
return 0;
p = offsets;
if (needs_lock)
lock_ufs(sb);
if ((flags & UFS_TYPE_MASK) == UFS_TYPE_UFS2)
goto ufs2;
block = ufsi->i_u1.i_data[*p++];
if (!block)
goto out;
while (--depth) {
struct buffer_head *bh;
sector_t n = *p++;
bh = sb_bread(sb, uspi->s_sbbase + fs32_to_cpu(sb, block)+(n>>shift));
if (!bh)
goto out;
block = ((__fs32 *) bh->b_data)[n & mask];
brelse (bh);
if (!block)
goto out;
}
ret = (u64) (uspi->s_sbbase + fs32_to_cpu(sb, block) + (frag & uspi->s_fpbmask));
goto out;
ufs2:
u2_block = ufsi->i_u1.u2_i_data[*p++];
if (!u2_block)
goto out;
while (--depth) {
struct buffer_head *bh;
sector_t n = *p++;
temp = (u64)(uspi->s_sbbase) + fs64_to_cpu(sb, u2_block);
bh = sb_bread(sb, temp +(u64) (n>>shift));
if (!bh)
goto out;
u2_block = ((__fs64 *)bh->b_data)[n & mask];
brelse(bh);
if (!u2_block)
goto out;
}
temp = (u64)uspi->s_sbbase + fs64_to_cpu(sb, u2_block);
ret = temp + (u64) (frag & uspi->s_fpbmask);
out:
if (needs_lock)
unlock_ufs(sb);
return ret;
}
/**
* ufs_inode_getfrag() - allocate new fragment(s)
* @inode - pointer to inode
* @fragment - number of `fragment' which hold pointer
* to new allocated fragment(s)
* @new_fragment - number of new allocated fragment(s)
* @required - how many fragment(s) we require
* @err - we set it if something wrong
* @phys - pointer to where we save physical number of new allocated fragments,
* NULL if we allocate not data(indirect blocks for example).
* @new - we set it if we allocate new block
* @locked_page - for ufs_new_fragments()
*/
static struct buffer_head *
ufs_inode_getfrag(struct inode *inode, u64 fragment,
sector_t new_fragment, unsigned int required, int *err,
long *phys, int *new, struct page *locked_page)
{
struct ufs_inode_info *ufsi = UFS_I(inode);
struct super_block *sb = inode->i_sb;
struct ufs_sb_private_info *uspi = UFS_SB(sb)->s_uspi;
struct buffer_head * result;
unsigned blockoff, lastblockoff;
u64 tmp, goal, lastfrag, block, lastblock;
void *p, *p2;
UFSD("ENTER, ino %lu, fragment %llu, new_fragment %llu, required %u, "
"metadata %d\n", inode->i_ino, (unsigned long long)fragment,
(unsigned long long)new_fragment, required, !phys);
/* TODO : to be done for write support
if ( (flags & UFS_TYPE_MASK) == UFS_TYPE_UFS2)
goto ufs2;
*/
block = ufs_fragstoblks (fragment);
blockoff = ufs_fragnum (fragment);
p = ufs_get_direct_data_ptr(uspi, ufsi, block);
goal = 0;
repeat:
tmp = ufs_data_ptr_to_cpu(sb, p);
lastfrag = ufsi->i_lastfrag;
if (tmp && fragment < lastfrag) {
if (!phys) {
result = sb_getblk(sb, uspi->s_sbbase + tmp + blockoff);
if (tmp == ufs_data_ptr_to_cpu(sb, p)) {
UFSD("EXIT, result %llu\n",
(unsigned long long)tmp + blockoff);
return result;
}
brelse (result);
goto repeat;
} else {
*phys = uspi->s_sbbase + tmp + blockoff;
return NULL;
}
}
lastblock = ufs_fragstoblks (lastfrag);
lastblockoff = ufs_fragnum (lastfrag);
/*
* We will extend file into new block beyond last allocated block
*/
if (lastblock < block) {
/*
* We must reallocate last allocated block
*/
if (lastblockoff) {
p2 = ufs_get_direct_data_ptr(uspi, ufsi, lastblock);
tmp = ufs_new_fragments(inode, p2, lastfrag,
ufs_data_ptr_to_cpu(sb, p2),
uspi->s_fpb - lastblockoff,
err, locked_page);
if (!tmp) {
if (lastfrag != ufsi->i_lastfrag)
goto repeat;
else
return NULL;
}
lastfrag = ufsi->i_lastfrag;
}
tmp = ufs_data_ptr_to_cpu(sb,
ufs_get_direct_data_ptr(uspi, ufsi,
lastblock));
if (tmp)
goal = tmp + uspi->s_fpb;
tmp = ufs_new_fragments (inode, p, fragment - blockoff,
goal, required + blockoff,
err,
phys != NULL ? locked_page : NULL);
} else if (lastblock == block) {
/*
* We will extend last allocated block
*/
tmp = ufs_new_fragments(inode, p, fragment -
(blockoff - lastblockoff),
ufs_data_ptr_to_cpu(sb, p),
required + (blockoff - lastblockoff),
err, phys != NULL ? locked_page : NULL);
} else /* (lastblock > block) */ {
/*
* We will allocate new block before last allocated block
*/
if (block) {
tmp = ufs_data_ptr_to_cpu(sb,
ufs_get_direct_data_ptr(uspi, ufsi, block - 1));
if (tmp)
goal = tmp + uspi->s_fpb;
}
tmp = ufs_new_fragments(inode, p, fragment - blockoff,
goal, uspi->s_fpb, err,
phys != NULL ? locked_page : NULL);
}
if (!tmp) {
if ((!blockoff && ufs_data_ptr_to_cpu(sb, p)) ||
(blockoff && lastfrag != ufsi->i_lastfrag))
goto repeat;
*err = -ENOSPC;
return NULL;
}
if (!phys) {
result = sb_getblk(sb, uspi->s_sbbase + tmp + blockoff);
} else {
*phys = uspi->s_sbbase + tmp + blockoff;
result = NULL;
*err = 0;
*new = 1;
}
inode->i_ctime = CURRENT_TIME_SEC;
if (IS_SYNC(inode))
ufs_sync_inode (inode);
mark_inode_dirty(inode);
UFSD("EXIT, result %llu\n", (unsigned long long)tmp + blockoff);
return result;
/* This part : To be implemented ....
Required only for writing, not required for READ-ONLY.
ufs2:
u2_block = ufs_fragstoblks(fragment);
u2_blockoff = ufs_fragnum(fragment);
p = ufsi->i_u1.u2_i_data + block;
goal = 0;
repeat2:
tmp = fs32_to_cpu(sb, *p);
lastfrag = ufsi->i_lastfrag;
*/
}
/**
* ufs_inode_getblock() - allocate new block
* @inode - pointer to inode
* @bh - pointer to block which hold "pointer" to new allocated block
* @fragment - number of `fragment' which hold pointer
* to new allocated block
* @new_fragment - number of new allocated fragment
* (block will hold this fragment and also uspi->s_fpb-1)
* @err - see ufs_inode_getfrag()
* @phys - see ufs_inode_getfrag()
* @new - see ufs_inode_getfrag()
* @locked_page - see ufs_inode_getfrag()
*/
static struct buffer_head *
ufs_inode_getblock(struct inode *inode, struct buffer_head *bh,
u64 fragment, sector_t new_fragment, int *err,
long *phys, int *new, struct page *locked_page)
{
struct super_block *sb = inode->i_sb;
struct ufs_sb_private_info *uspi = UFS_SB(sb)->s_uspi;
struct buffer_head * result;
unsigned blockoff;
u64 tmp, goal, block;
void *p;
block = ufs_fragstoblks (fragment);
blockoff = ufs_fragnum (fragment);
UFSD("ENTER, ino %lu, fragment %llu, new_fragment %llu, metadata %d\n",
inode->i_ino, (unsigned long long)fragment,
(unsigned long long)new_fragment, !phys);
result = NULL;
if (!bh)
goto out;
if (!buffer_uptodate(bh)) {
ll_rw_block (READ, 1, &bh);
wait_on_buffer (bh);
if (!buffer_uptodate(bh))
goto out;
}
if (uspi->fs_magic == UFS2_MAGIC)
p = (__fs64 *)bh->b_data + block;
else
p = (__fs32 *)bh->b_data + block;
repeat:
tmp = ufs_data_ptr_to_cpu(sb, p);
if (tmp) {
if (!phys) {
result = sb_getblk(sb, uspi->s_sbbase + tmp + blockoff);
if (tmp == ufs_data_ptr_to_cpu(sb, p))
goto out;
brelse (result);
goto repeat;
} else {
*phys = uspi->s_sbbase + tmp + blockoff;
goto out;
}
}
if (block && (uspi->fs_magic == UFS2_MAGIC ?
(tmp = fs64_to_cpu(sb, ((__fs64 *)bh->b_data)[block-1])) :
(tmp = fs32_to_cpu(sb, ((__fs32 *)bh->b_data)[block-1]))))
goal = tmp + uspi->s_fpb;
else
goal = bh->b_blocknr + uspi->s_fpb;
tmp = ufs_new_fragments(inode, p, ufs_blknum(new_fragment), goal,
uspi->s_fpb, err, locked_page);
if (!tmp) {
if (ufs_data_ptr_to_cpu(sb, p))
goto repeat;
goto out;
}
if (!phys) {
result = sb_getblk(sb, uspi->s_sbbase + tmp + blockoff);
} else {
*phys = uspi->s_sbbase + tmp + blockoff;
*new = 1;
}
mark_buffer_dirty(bh);
if (IS_SYNC(inode))
sync_dirty_buffer(bh);
inode->i_ctime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
UFSD("result %llu\n", (unsigned long long)tmp + blockoff);
out:
brelse (bh);
UFSD("EXIT\n");
return result;
}
/**
* ufs_getfrag_block() - `get_block_t' function, interface between UFS and
* readpage, writepage and so on
*/
int ufs_getfrag_block(struct inode *inode, sector_t fragment, struct buffer_head *bh_result, int create)
{
struct super_block * sb = inode->i_sb;
struct ufs_sb_info * sbi = UFS_SB(sb);
struct ufs_sb_private_info * uspi = sbi->s_uspi;
struct buffer_head * bh;
int ret, err, new;
unsigned long ptr,phys;
u64 phys64 = 0;
bool needs_lock = (sbi->mutex_owner != current);
if (!create) {
phys64 = ufs_frag_map(inode, fragment, needs_lock);
UFSD("phys64 = %llu\n", (unsigned long long)phys64);
if (phys64)
map_bh(bh_result, sb, phys64);
return 0;
}
/* This code entered only while writing ....? */
err = -EIO;
new = 0;
ret = 0;
bh = NULL;
if (needs_lock)
lock_ufs(sb);
UFSD("ENTER, ino %lu, fragment %llu\n", inode->i_ino, (unsigned long long)fragment);
if (fragment >
((UFS_NDADDR + uspi->s_apb + uspi->s_2apb + uspi->s_3apb)
<< uspi->s_fpbshift))
goto abort_too_big;
err = 0;
ptr = fragment;
/*
* ok, these macros clean the logic up a bit and make
* it much more readable:
*/
#define GET_INODE_DATABLOCK(x) \
ufs_inode_getfrag(inode, x, fragment, 1, &err, &phys, &new,\
bh_result->b_page)
#define GET_INODE_PTR(x) \
ufs_inode_getfrag(inode, x, fragment, uspi->s_fpb, &err, NULL, NULL,\
bh_result->b_page)
#define GET_INDIRECT_DATABLOCK(x) \
ufs_inode_getblock(inode, bh, x, fragment, \
&err, &phys, &new, bh_result->b_page)
#define GET_INDIRECT_PTR(x) \
ufs_inode_getblock(inode, bh, x, fragment, \
&err, NULL, NULL, NULL)
if (ptr < UFS_NDIR_FRAGMENT) {
bh = GET_INODE_DATABLOCK(ptr);
goto out;
}
ptr -= UFS_NDIR_FRAGMENT;
if (ptr < (1 << (uspi->s_apbshift + uspi->s_fpbshift))) {
bh = GET_INODE_PTR(UFS_IND_FRAGMENT + (ptr >> uspi->s_apbshift));
goto get_indirect;
}
ptr -= 1 << (uspi->s_apbshift + uspi->s_fpbshift);
if (ptr < (1 << (uspi->s_2apbshift + uspi->s_fpbshift))) {
bh = GET_INODE_PTR(UFS_DIND_FRAGMENT + (ptr >> uspi->s_2apbshift));
goto get_double;
}
ptr -= 1 << (uspi->s_2apbshift + uspi->s_fpbshift);
bh = GET_INODE_PTR(UFS_TIND_FRAGMENT + (ptr >> uspi->s_3apbshift));
bh = GET_INDIRECT_PTR((ptr >> uspi->s_2apbshift) & uspi->s_apbmask);
get_double:
bh = GET_INDIRECT_PTR((ptr >> uspi->s_apbshift) & uspi->s_apbmask);
get_indirect:
bh = GET_INDIRECT_DATABLOCK(ptr & uspi->s_apbmask);
#undef GET_INODE_DATABLOCK
#undef GET_INODE_PTR
#undef GET_INDIRECT_DATABLOCK
#undef GET_INDIRECT_PTR
out:
if (err)
goto abort;
if (new)
set_buffer_new(bh_result);
map_bh(bh_result, sb, phys);
abort:
if (needs_lock)
unlock_ufs(sb);
return err;
abort_too_big:
ufs_warning(sb, "ufs_get_block", "block > big");
goto abort;
}
static int ufs_writepage(struct page *page, struct writeback_control *wbc)
{
return block_write_full_page(page,ufs_getfrag_block,wbc);
}
static int ufs_readpage(struct file *file, struct page *page)
{
return block_read_full_page(page,ufs_getfrag_block);
}
int ufs_prepare_chunk(struct page *page, loff_t pos, unsigned len)
{
return __block_write_begin(page, pos, len, ufs_getfrag_block);
}
static int ufs_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
int ret;
ret = block_write_begin(mapping, pos, len, flags, pagep,
ufs_getfrag_block);
if (unlikely(ret)) {
loff_t isize = mapping->host->i_size;
if (pos + len > isize)
vmtruncate(mapping->host, isize);
}
return ret;
}
static sector_t ufs_bmap(struct address_space *mapping, sector_t block)
{
return generic_block_bmap(mapping,block,ufs_getfrag_block);
}
const struct address_space_operations ufs_aops = {
.readpage = ufs_readpage,
.writepage = ufs_writepage,
.write_begin = ufs_write_begin,
.write_end = generic_write_end,
.bmap = ufs_bmap
};
static void ufs_set_inode_ops(struct inode *inode)
{
if (S_ISREG(inode->i_mode)) {
inode->i_op = &ufs_file_inode_operations;
inode->i_fop = &ufs_file_operations;
inode->i_mapping->a_ops = &ufs_aops;
} else if (S_ISDIR(inode->i_mode)) {
inode->i_op = &ufs_dir_inode_operations;
inode->i_fop = &ufs_dir_operations;
inode->i_mapping->a_ops = &ufs_aops;
} else if (S_ISLNK(inode->i_mode)) {
if (!inode->i_blocks)
inode->i_op = &ufs_fast_symlink_inode_operations;
else {
inode->i_op = &ufs_symlink_inode_operations;
inode->i_mapping->a_ops = &ufs_aops;
}
} else
init_special_inode(inode, inode->i_mode,
ufs_get_inode_dev(inode->i_sb, UFS_I(inode)));
}
static int ufs1_read_inode(struct inode *inode, struct ufs_inode *ufs_inode)
{
struct ufs_inode_info *ufsi = UFS_I(inode);
struct super_block *sb = inode->i_sb;
umode_t mode;
/*
* Copy data to the in-core inode.
*/
inode->i_mode = mode = fs16_to_cpu(sb, ufs_inode->ui_mode);
set_nlink(inode, fs16_to_cpu(sb, ufs_inode->ui_nlink));
if (inode->i_nlink == 0) {
ufs_error (sb, "ufs_read_inode", "inode %lu has zero nlink\n", inode->i_ino);
return -1;
}
/*
* Linux now has 32-bit uid and gid, so we can support EFT.
*/
inode->i_uid = ufs_get_inode_uid(sb, ufs_inode);
inode->i_gid = ufs_get_inode_gid(sb, ufs_inode);
inode->i_size = fs64_to_cpu(sb, ufs_inode->ui_size);
inode->i_atime.tv_sec = fs32_to_cpu(sb, ufs_inode->ui_atime.tv_sec);
inode->i_ctime.tv_sec = fs32_to_cpu(sb, ufs_inode->ui_ctime.tv_sec);
inode->i_mtime.tv_sec = fs32_to_cpu(sb, ufs_inode->ui_mtime.tv_sec);
inode->i_mtime.tv_nsec = 0;
inode->i_atime.tv_nsec = 0;
inode->i_ctime.tv_nsec = 0;
inode->i_blocks = fs32_to_cpu(sb, ufs_inode->ui_blocks);
inode->i_generation = fs32_to_cpu(sb, ufs_inode->ui_gen);
ufsi->i_flags = fs32_to_cpu(sb, ufs_inode->ui_flags);
ufsi->i_shadow = fs32_to_cpu(sb, ufs_inode->ui_u3.ui_sun.ui_shadow);
ufsi->i_oeftflag = fs32_to_cpu(sb, ufs_inode->ui_u3.ui_sun.ui_oeftflag);
if (S_ISCHR(mode) || S_ISBLK(mode) || inode->i_blocks) {
memcpy(ufsi->i_u1.i_data, &ufs_inode->ui_u2.ui_addr,
sizeof(ufs_inode->ui_u2.ui_addr));
} else {
memcpy(ufsi->i_u1.i_symlink, ufs_inode->ui_u2.ui_symlink,
sizeof(ufs_inode->ui_u2.ui_symlink) - 1);
ufsi->i_u1.i_symlink[sizeof(ufs_inode->ui_u2.ui_symlink) - 1] = 0;
}
return 0;
}
static int ufs2_read_inode(struct inode *inode, struct ufs2_inode *ufs2_inode)
{
struct ufs_inode_info *ufsi = UFS_I(inode);
struct super_block *sb = inode->i_sb;
umode_t mode;
UFSD("Reading ufs2 inode, ino %lu\n", inode->i_ino);
/*
* Copy data to the in-core inode.
*/
inode->i_mode = mode = fs16_to_cpu(sb, ufs2_inode->ui_mode);
set_nlink(inode, fs16_to_cpu(sb, ufs2_inode->ui_nlink));
if (inode->i_nlink == 0) {
ufs_error (sb, "ufs_read_inode", "inode %lu has zero nlink\n", inode->i_ino);
return -1;
}
/*
* Linux now has 32-bit uid and gid, so we can support EFT.
*/
inode->i_uid = fs32_to_cpu(sb, ufs2_inode->ui_uid);
inode->i_gid = fs32_to_cpu(sb, ufs2_inode->ui_gid);
inode->i_size = fs64_to_cpu(sb, ufs2_inode->ui_size);
inode->i_atime.tv_sec = fs64_to_cpu(sb, ufs2_inode->ui_atime);
inode->i_ctime.tv_sec = fs64_to_cpu(sb, ufs2_inode->ui_ctime);
inode->i_mtime.tv_sec = fs64_to_cpu(sb, ufs2_inode->ui_mtime);
inode->i_atime.tv_nsec = fs32_to_cpu(sb, ufs2_inode->ui_atimensec);
inode->i_ctime.tv_nsec = fs32_to_cpu(sb, ufs2_inode->ui_ctimensec);
inode->i_mtime.tv_nsec = fs32_to_cpu(sb, ufs2_inode->ui_mtimensec);
inode->i_blocks = fs64_to_cpu(sb, ufs2_inode->ui_blocks);
inode->i_generation = fs32_to_cpu(sb, ufs2_inode->ui_gen);
ufsi->i_flags = fs32_to_cpu(sb, ufs2_inode->ui_flags);
/*
ufsi->i_shadow = fs32_to_cpu(sb, ufs_inode->ui_u3.ui_sun.ui_shadow);
ufsi->i_oeftflag = fs32_to_cpu(sb, ufs_inode->ui_u3.ui_sun.ui_oeftflag);
*/
if (S_ISCHR(mode) || S_ISBLK(mode) || inode->i_blocks) {
memcpy(ufsi->i_u1.u2_i_data, &ufs2_inode->ui_u2.ui_addr,
sizeof(ufs2_inode->ui_u2.ui_addr));
} else {
memcpy(ufsi->i_u1.i_symlink, ufs2_inode->ui_u2.ui_symlink,
sizeof(ufs2_inode->ui_u2.ui_symlink) - 1);
ufsi->i_u1.i_symlink[sizeof(ufs2_inode->ui_u2.ui_symlink) - 1] = 0;
}
return 0;
}
struct inode *ufs_iget(struct super_block *sb, unsigned long ino)
{
struct ufs_inode_info *ufsi;
struct ufs_sb_private_info *uspi = UFS_SB(sb)->s_uspi;
struct buffer_head * bh;
struct inode *inode;
int err;
UFSD("ENTER, ino %lu\n", ino);
if (ino < UFS_ROOTINO || ino > (uspi->s_ncg * uspi->s_ipg)) {
ufs_warning(sb, "ufs_read_inode", "bad inode number (%lu)\n",
ino);
return ERR_PTR(-EIO);
}
inode = iget_locked(sb, ino);
if (!inode)
return ERR_PTR(-ENOMEM);
if (!(inode->i_state & I_NEW))
return inode;
ufsi = UFS_I(inode);
bh = sb_bread(sb, uspi->s_sbbase + ufs_inotofsba(inode->i_ino));
if (!bh) {
ufs_warning(sb, "ufs_read_inode", "unable to read inode %lu\n",
inode->i_ino);
goto bad_inode;
}
if ((UFS_SB(sb)->s_flags & UFS_TYPE_MASK) == UFS_TYPE_UFS2) {
struct ufs2_inode *ufs2_inode = (struct ufs2_inode *)bh->b_data;
err = ufs2_read_inode(inode,
ufs2_inode + ufs_inotofsbo(inode->i_ino));
} else {
struct ufs_inode *ufs_inode = (struct ufs_inode *)bh->b_data;
err = ufs1_read_inode(inode,
ufs_inode + ufs_inotofsbo(inode->i_ino));
}
if (err)
goto bad_inode;
inode->i_version++;
ufsi->i_lastfrag =
(inode->i_size + uspi->s_fsize - 1) >> uspi->s_fshift;
ufsi->i_dir_start_lookup = 0;
ufsi->i_osync = 0;
ufs_set_inode_ops(inode);
brelse(bh);
UFSD("EXIT\n");
unlock_new_inode(inode);
return inode;
bad_inode:
iget_failed(inode);
return ERR_PTR(-EIO);
}
static void ufs1_update_inode(struct inode *inode, struct ufs_inode *ufs_inode)
{
struct super_block *sb = inode->i_sb;
struct ufs_inode_info *ufsi = UFS_I(inode);
ufs_inode->ui_mode = cpu_to_fs16(sb, inode->i_mode);
ufs_inode->ui_nlink = cpu_to_fs16(sb, inode->i_nlink);
ufs_set_inode_uid(sb, ufs_inode, inode->i_uid);
ufs_set_inode_gid(sb, ufs_inode, inode->i_gid);
ufs_inode->ui_size = cpu_to_fs64(sb, inode->i_size);
ufs_inode->ui_atime.tv_sec = cpu_to_fs32(sb, inode->i_atime.tv_sec);
ufs_inode->ui_atime.tv_usec = 0;
ufs_inode->ui_ctime.tv_sec = cpu_to_fs32(sb, inode->i_ctime.tv_sec);
ufs_inode->ui_ctime.tv_usec = 0;
ufs_inode->ui_mtime.tv_sec = cpu_to_fs32(sb, inode->i_mtime.tv_sec);
ufs_inode->ui_mtime.tv_usec = 0;
ufs_inode->ui_blocks = cpu_to_fs32(sb, inode->i_blocks);
ufs_inode->ui_flags = cpu_to_fs32(sb, ufsi->i_flags);
ufs_inode->ui_gen = cpu_to_fs32(sb, inode->i_generation);
if ((UFS_SB(sb)->s_flags & UFS_UID_MASK) == UFS_UID_EFT) {
ufs_inode->ui_u3.ui_sun.ui_shadow = cpu_to_fs32(sb, ufsi->i_shadow);
ufs_inode->ui_u3.ui_sun.ui_oeftflag = cpu_to_fs32(sb, ufsi->i_oeftflag);
}
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
/* ufs_inode->ui_u2.ui_addr.ui_db[0] = cpu_to_fs32(sb, inode->i_rdev); */
ufs_inode->ui_u2.ui_addr.ui_db[0] = ufsi->i_u1.i_data[0];
} else if (inode->i_blocks) {
memcpy(&ufs_inode->ui_u2.ui_addr, ufsi->i_u1.i_data,
sizeof(ufs_inode->ui_u2.ui_addr));
}
else {
memcpy(&ufs_inode->ui_u2.ui_symlink, ufsi->i_u1.i_symlink,
sizeof(ufs_inode->ui_u2.ui_symlink));
}
if (!inode->i_nlink)
memset (ufs_inode, 0, sizeof(struct ufs_inode));
}
static void ufs2_update_inode(struct inode *inode, struct ufs2_inode *ufs_inode)
{
struct super_block *sb = inode->i_sb;
struct ufs_inode_info *ufsi = UFS_I(inode);
UFSD("ENTER\n");
ufs_inode->ui_mode = cpu_to_fs16(sb, inode->i_mode);
ufs_inode->ui_nlink = cpu_to_fs16(sb, inode->i_nlink);
ufs_inode->ui_uid = cpu_to_fs32(sb, inode->i_uid);
ufs_inode->ui_gid = cpu_to_fs32(sb, inode->i_gid);
ufs_inode->ui_size = cpu_to_fs64(sb, inode->i_size);
ufs_inode->ui_atime = cpu_to_fs64(sb, inode->i_atime.tv_sec);
ufs_inode->ui_atimensec = cpu_to_fs32(sb, inode->i_atime.tv_nsec);
ufs_inode->ui_ctime = cpu_to_fs64(sb, inode->i_ctime.tv_sec);
ufs_inode->ui_ctimensec = cpu_to_fs32(sb, inode->i_ctime.tv_nsec);
ufs_inode->ui_mtime = cpu_to_fs64(sb, inode->i_mtime.tv_sec);
ufs_inode->ui_mtimensec = cpu_to_fs32(sb, inode->i_mtime.tv_nsec);
ufs_inode->ui_blocks = cpu_to_fs64(sb, inode->i_blocks);
ufs_inode->ui_flags = cpu_to_fs32(sb, ufsi->i_flags);
ufs_inode->ui_gen = cpu_to_fs32(sb, inode->i_generation);
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
/* ufs_inode->ui_u2.ui_addr.ui_db[0] = cpu_to_fs32(sb, inode->i_rdev); */
ufs_inode->ui_u2.ui_addr.ui_db[0] = ufsi->i_u1.u2_i_data[0];
} else if (inode->i_blocks) {
memcpy(&ufs_inode->ui_u2.ui_addr, ufsi->i_u1.u2_i_data,
sizeof(ufs_inode->ui_u2.ui_addr));
} else {
memcpy(&ufs_inode->ui_u2.ui_symlink, ufsi->i_u1.i_symlink,
sizeof(ufs_inode->ui_u2.ui_symlink));
}
if (!inode->i_nlink)
memset (ufs_inode, 0, sizeof(struct ufs2_inode));
UFSD("EXIT\n");
}
static int ufs_update_inode(struct inode * inode, int do_sync)
{
struct super_block *sb = inode->i_sb;
struct ufs_sb_private_info *uspi = UFS_SB(sb)->s_uspi;
struct buffer_head * bh;
UFSD("ENTER, ino %lu\n", inode->i_ino);
if (inode->i_ino < UFS_ROOTINO ||
inode->i_ino > (uspi->s_ncg * uspi->s_ipg)) {
ufs_warning (sb, "ufs_read_inode", "bad inode number (%lu)\n", inode->i_ino);
return -1;
}
bh = sb_bread(sb, ufs_inotofsba(inode->i_ino));
if (!bh) {
ufs_warning (sb, "ufs_read_inode", "unable to read inode %lu\n", inode->i_ino);
return -1;
}
if (uspi->fs_magic == UFS2_MAGIC) {
struct ufs2_inode *ufs2_inode = (struct ufs2_inode *)bh->b_data;
ufs2_update_inode(inode,
ufs2_inode + ufs_inotofsbo(inode->i_ino));
} else {
struct ufs_inode *ufs_inode = (struct ufs_inode *) bh->b_data;
ufs1_update_inode(inode, ufs_inode + ufs_inotofsbo(inode->i_ino));
}
mark_buffer_dirty(bh);
if (do_sync)
sync_dirty_buffer(bh);
brelse (bh);
UFSD("EXIT\n");
return 0;
}
int ufs_write_inode(struct inode *inode, struct writeback_control *wbc)
{
int ret;
lock_ufs(inode->i_sb);
ret = ufs_update_inode(inode, wbc->sync_mode == WB_SYNC_ALL);
unlock_ufs(inode->i_sb);
return ret;
}
int ufs_sync_inode (struct inode *inode)
{
return ufs_update_inode (inode, 1);
}
void ufs_evict_inode(struct inode * inode)
{
int want_delete = 0;
if (!inode->i_nlink && !is_bad_inode(inode))
want_delete = 1;
truncate_inode_pages(&inode->i_data, 0);
if (want_delete) {
loff_t old_i_size;
/*UFS_I(inode)->i_dtime = CURRENT_TIME;*/
lock_ufs(inode->i_sb);
mark_inode_dirty(inode);
ufs_update_inode(inode, IS_SYNC(inode));
old_i_size = inode->i_size;
inode->i_size = 0;
if (inode->i_blocks && ufs_truncate(inode, old_i_size))
ufs_warning(inode->i_sb, __func__, "ufs_truncate failed\n");
unlock_ufs(inode->i_sb);
}
invalidate_inode_buffers(inode);
end_writeback(inode);
if (want_delete) {
lock_ufs(inode->i_sb);
ufs_free_inode (inode);
unlock_ufs(inode->i_sb);
}
}
| gpl-2.0 |
CyanogenMod/android_kernel_samsung_klte | arch/mips/jz4740/pm.c | 4987 | 1256 | /*
* Copyright (C) 2010, Lars-Peter Clausen <lars@metafoo.de>
* JZ4740 SoC power management 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.
*
* 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/pm.h>
#include <linux/delay.h>
#include <linux/suspend.h>
#include <asm/mach-jz4740/clock.h>
#include "clock.h"
static int jz4740_pm_enter(suspend_state_t state)
{
jz4740_clock_suspend();
jz4740_clock_set_wait_mode(JZ4740_WAIT_MODE_SLEEP);
__asm__(".set\tmips3\n\t"
"wait\n\t"
".set\tmips0");
jz4740_clock_set_wait_mode(JZ4740_WAIT_MODE_IDLE);
jz4740_clock_resume();
return 0;
}
static const struct platform_suspend_ops jz4740_pm_ops = {
.valid = suspend_valid_only_mem,
.enter = jz4740_pm_enter,
};
static int __init jz4740_pm_init(void)
{
suspend_set_ops(&jz4740_pm_ops);
return 0;
}
late_initcall(jz4740_pm_init);
| gpl-2.0 |
KronicKernel/bullhead | drivers/isdn/hisax/st5481_init.c | 4987 | 5409 | /*
* Driver for ST5481 USB ISDN modem
*
* Author Frode Isaksen
* Copyright 2001 by Frode Isaksen <fisaksen@bewan.com>
* 2001 by Kai Germaschewski <kai.germaschewski@gmx.de>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
/*
* TODO:
*
* b layer1 delay?
* hotplug / unregister issues
* mod_inc/dec_use_count
* unify parts of d/b channel usb handling
* file header
* avoid copy to isoc buffer?
* improve usb delay?
* merge l1 state machines?
* clean up debug
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/usb.h>
#include <linux/slab.h>
#include "st5481.h"
MODULE_DESCRIPTION("ISDN4Linux: driver for ST5481 USB ISDN adapter");
MODULE_AUTHOR("Frode Isaksen");
MODULE_LICENSE("GPL");
static int protocol = 2; /* EURO-ISDN Default */
module_param(protocol, int, 0);
static int number_of_leds = 2; /* 2 LEDs on the adpater default */
module_param(number_of_leds, int, 0);
#ifdef CONFIG_HISAX_DEBUG
static int debug = 0;
module_param(debug, int, 0);
#endif
int st5481_debug;
/* ======================================================================
* registration/deregistration with the USB layer
*/
/*
* This function will be called when the adapter is plugged
* into the USB bus.
*/
static int probe_st5481(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_device *dev = interface_to_usbdev(intf);
struct st5481_adapter *adapter;
struct hisax_b_if *b_if[2];
int retval, i;
printk(KERN_INFO "st541: found adapter VendorId %04x, ProductId %04x, LEDs %d\n",
le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct),
number_of_leds);
adapter = kzalloc(sizeof(struct st5481_adapter), GFP_KERNEL);
if (!adapter)
return -ENOMEM;
adapter->number_of_leds = number_of_leds;
adapter->usb_dev = dev;
adapter->hisax_d_if.owner = THIS_MODULE;
adapter->hisax_d_if.ifc.priv = adapter;
adapter->hisax_d_if.ifc.l2l1 = st5481_d_l2l1;
for (i = 0; i < 2; i++) {
adapter->bcs[i].adapter = adapter;
adapter->bcs[i].channel = i;
adapter->bcs[i].b_if.ifc.priv = &adapter->bcs[i];
adapter->bcs[i].b_if.ifc.l2l1 = st5481_b_l2l1;
}
retval = st5481_setup_usb(adapter);
if (retval < 0)
goto err;
retval = st5481_setup_d(adapter);
if (retval < 0)
goto err_usb;
retval = st5481_setup_b(&adapter->bcs[0]);
if (retval < 0)
goto err_d;
retval = st5481_setup_b(&adapter->bcs[1]);
if (retval < 0)
goto err_b;
for (i = 0; i < 2; i++)
b_if[i] = &adapter->bcs[i].b_if;
if (hisax_register(&adapter->hisax_d_if, b_if, "st5481_usb",
protocol) != 0)
goto err_b1;
st5481_start(adapter);
usb_set_intfdata(intf, adapter);
return 0;
err_b1:
st5481_release_b(&adapter->bcs[1]);
err_b:
st5481_release_b(&adapter->bcs[0]);
err_d:
st5481_release_d(adapter);
err_usb:
st5481_release_usb(adapter);
err:
kfree(adapter);
return -EIO;
}
/*
* This function will be called when the adapter is removed
* from the USB bus.
*/
static void disconnect_st5481(struct usb_interface *intf)
{
struct st5481_adapter *adapter = usb_get_intfdata(intf);
DBG(1, "");
usb_set_intfdata(intf, NULL);
if (!adapter)
return;
st5481_stop(adapter);
st5481_release_b(&adapter->bcs[1]);
st5481_release_b(&adapter->bcs[0]);
st5481_release_d(adapter);
// we would actually better wait for completion of outstanding urbs
mdelay(2);
st5481_release_usb(adapter);
hisax_unregister(&adapter->hisax_d_if);
kfree(adapter);
}
/*
* The last 4 bits in the Product Id is set with 4 pins on the chip.
*/
static struct usb_device_id st5481_ids[] = {
{ USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID + 0x0) },
{ USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID + 0x1) },
{ USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID + 0x2) },
{ USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID + 0x3) },
{ USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID + 0x4) },
{ USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID + 0x5) },
{ USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID + 0x6) },
{ USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID + 0x7) },
{ USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID + 0x8) },
{ USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID + 0x9) },
{ USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID + 0xA) },
{ USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID + 0xB) },
{ USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID + 0xC) },
{ USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID + 0xD) },
{ USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID + 0xE) },
{ USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID + 0xF) },
{ }
};
MODULE_DEVICE_TABLE(usb, st5481_ids);
static struct usb_driver st5481_usb_driver = {
.name = "st5481_usb",
.probe = probe_st5481,
.disconnect = disconnect_st5481,
.id_table = st5481_ids,
.disable_hub_initiated_lpm = 1,
};
static int __init st5481_usb_init(void)
{
int retval;
#ifdef CONFIG_HISAX_DEBUG
st5481_debug = debug;
#endif
printk(KERN_INFO "hisax_st5481: ST5481 USB ISDN driver $Revision: 2.4.2.3 $\n");
retval = st5481_d_init();
if (retval < 0)
goto out;
retval = usb_register(&st5481_usb_driver);
if (retval < 0)
goto out_d_exit;
return 0;
out_d_exit:
st5481_d_exit();
out:
return retval;
}
static void __exit st5481_usb_exit(void)
{
usb_deregister(&st5481_usb_driver);
st5481_d_exit();
}
module_init(st5481_usb_init);
module_exit(st5481_usb_exit);
| gpl-2.0 |
TeamWin/android_kernel_oneplus_msm8974 | drivers/pinctrl/pinctrl-mmp2.c | 4987 | 39622 | /*
* linux/drivers/pinctrl/pinmux-mmp2.c
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* publishhed by the Free Software Foundation.
*
* Copyright (C) 2011, Marvell Technology Group Ltd.
*
* Author: Haojian Zhuang <haojian.zhuang@marvell.com>
*
*/
#include <linux/device.h>
#include <linux/module.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include "pinctrl-pxa3xx.h"
#define MMP2_DS_MASK 0x1800
#define MMP2_DS_SHIFT 11
#define MMP2_SLEEP_MASK 0x38
#define MMP2_SLEEP_SELECT (1 << 9)
#define MMP2_SLEEP_DATA (1 << 8)
#define MMP2_SLEEP_DIR (1 << 7)
#define MFPR_MMP2(a, r, f0, f1, f2, f3, f4, f5, f6, f7) \
{ \
.name = #a, \
.pin = a, \
.mfpr = r, \
.func = { \
MMP2_MUX_##f0, \
MMP2_MUX_##f1, \
MMP2_MUX_##f2, \
MMP2_MUX_##f3, \
MMP2_MUX_##f4, \
MMP2_MUX_##f5, \
MMP2_MUX_##f6, \
MMP2_MUX_##f7, \
}, \
}
#define GRP_MMP2(a, m, p) \
{ .name = a, .mux = MMP2_MUX_##m, .pins = p, .npins = ARRAY_SIZE(p), }
/* 174 pins */
enum mmp2_pin_list {
/* 0~168: GPIO0~GPIO168 */
TWSI4_SCL = 169,
TWSI4_SDA, /* 170 */
G_CLKREQ,
VCXO_REQ,
VCXO_OUT,
};
enum mmp2_mux {
/* PXA3xx_MUX_GPIO = 0 (predefined in pinctrl-pxa3xx.h) */
MMP2_MUX_GPIO = 0,
MMP2_MUX_G_CLKREQ,
MMP2_MUX_VCXO_REQ,
MMP2_MUX_VCXO_OUT,
MMP2_MUX_KP_MK,
MMP2_MUX_KP_DK,
MMP2_MUX_CCIC1,
MMP2_MUX_CCIC2,
MMP2_MUX_SPI,
MMP2_MUX_SSPA2,
MMP2_MUX_ROT,
MMP2_MUX_I2S,
MMP2_MUX_TB,
MMP2_MUX_CAM2,
MMP2_MUX_HDMI,
MMP2_MUX_TWSI2,
MMP2_MUX_TWSI3,
MMP2_MUX_TWSI4,
MMP2_MUX_TWSI5,
MMP2_MUX_TWSI6,
MMP2_MUX_UART1,
MMP2_MUX_UART2,
MMP2_MUX_UART3,
MMP2_MUX_UART4,
MMP2_MUX_SSP1_RX,
MMP2_MUX_SSP1_FRM,
MMP2_MUX_SSP1_TXRX,
MMP2_MUX_SSP2_RX,
MMP2_MUX_SSP2_FRM,
MMP2_MUX_SSP1,
MMP2_MUX_SSP2,
MMP2_MUX_SSP3,
MMP2_MUX_SSP4,
MMP2_MUX_MMC1,
MMP2_MUX_MMC2,
MMP2_MUX_MMC3,
MMP2_MUX_MMC4,
MMP2_MUX_ULPI,
MMP2_MUX_AC,
MMP2_MUX_CA,
MMP2_MUX_PWM,
MMP2_MUX_USIM,
MMP2_MUX_TIPU,
MMP2_MUX_PLL,
MMP2_MUX_NAND,
MMP2_MUX_FSIC,
MMP2_MUX_SLEEP_IND,
MMP2_MUX_EXT_DMA,
MMP2_MUX_ONE_WIRE,
MMP2_MUX_LCD,
MMP2_MUX_SMC,
MMP2_MUX_SMC_INT,
MMP2_MUX_MSP,
MMP2_MUX_G_CLKOUT,
MMP2_MUX_32K_CLKOUT,
MMP2_MUX_PRI_JTAG,
MMP2_MUX_AAS_JTAG,
MMP2_MUX_AAS_GPIO,
MMP2_MUX_AAS_SPI,
MMP2_MUX_AAS_TWSI,
MMP2_MUX_AAS_DEU_EX,
MMP2_MUX_NONE = 0xffff,
};
static struct pinctrl_pin_desc mmp2_pads[] = {
/*
* The name indicates function 0 of this pin.
* After reset, function 0 is the default function of pin.
*/
PINCTRL_PIN(GPIO0, "GPIO0"),
PINCTRL_PIN(GPIO1, "GPIO1"),
PINCTRL_PIN(GPIO2, "GPIO2"),
PINCTRL_PIN(GPIO3, "GPIO3"),
PINCTRL_PIN(GPIO4, "GPIO4"),
PINCTRL_PIN(GPIO5, "GPIO5"),
PINCTRL_PIN(GPIO6, "GPIO6"),
PINCTRL_PIN(GPIO7, "GPIO7"),
PINCTRL_PIN(GPIO8, "GPIO8"),
PINCTRL_PIN(GPIO9, "GPIO9"),
PINCTRL_PIN(GPIO10, "GPIO10"),
PINCTRL_PIN(GPIO11, "GPIO11"),
PINCTRL_PIN(GPIO12, "GPIO12"),
PINCTRL_PIN(GPIO13, "GPIO13"),
PINCTRL_PIN(GPIO14, "GPIO14"),
PINCTRL_PIN(GPIO15, "GPIO15"),
PINCTRL_PIN(GPIO16, "GPIO16"),
PINCTRL_PIN(GPIO17, "GPIO17"),
PINCTRL_PIN(GPIO18, "GPIO18"),
PINCTRL_PIN(GPIO19, "GPIO19"),
PINCTRL_PIN(GPIO20, "GPIO20"),
PINCTRL_PIN(GPIO21, "GPIO21"),
PINCTRL_PIN(GPIO22, "GPIO22"),
PINCTRL_PIN(GPIO23, "GPIO23"),
PINCTRL_PIN(GPIO24, "GPIO24"),
PINCTRL_PIN(GPIO25, "GPIO25"),
PINCTRL_PIN(GPIO26, "GPIO26"),
PINCTRL_PIN(GPIO27, "GPIO27"),
PINCTRL_PIN(GPIO28, "GPIO28"),
PINCTRL_PIN(GPIO29, "GPIO29"),
PINCTRL_PIN(GPIO30, "GPIO30"),
PINCTRL_PIN(GPIO31, "GPIO31"),
PINCTRL_PIN(GPIO32, "GPIO32"),
PINCTRL_PIN(GPIO33, "GPIO33"),
PINCTRL_PIN(GPIO34, "GPIO34"),
PINCTRL_PIN(GPIO35, "GPIO35"),
PINCTRL_PIN(GPIO36, "GPIO36"),
PINCTRL_PIN(GPIO37, "GPIO37"),
PINCTRL_PIN(GPIO38, "GPIO38"),
PINCTRL_PIN(GPIO39, "GPIO39"),
PINCTRL_PIN(GPIO40, "GPIO40"),
PINCTRL_PIN(GPIO41, "GPIO41"),
PINCTRL_PIN(GPIO42, "GPIO42"),
PINCTRL_PIN(GPIO43, "GPIO43"),
PINCTRL_PIN(GPIO44, "GPIO44"),
PINCTRL_PIN(GPIO45, "GPIO45"),
PINCTRL_PIN(GPIO46, "GPIO46"),
PINCTRL_PIN(GPIO47, "GPIO47"),
PINCTRL_PIN(GPIO48, "GPIO48"),
PINCTRL_PIN(GPIO49, "GPIO49"),
PINCTRL_PIN(GPIO50, "GPIO50"),
PINCTRL_PIN(GPIO51, "GPIO51"),
PINCTRL_PIN(GPIO52, "GPIO52"),
PINCTRL_PIN(GPIO53, "GPIO53"),
PINCTRL_PIN(GPIO54, "GPIO54"),
PINCTRL_PIN(GPIO55, "GPIO55"),
PINCTRL_PIN(GPIO56, "GPIO56"),
PINCTRL_PIN(GPIO57, "GPIO57"),
PINCTRL_PIN(GPIO58, "GPIO58"),
PINCTRL_PIN(GPIO59, "GPIO59"),
PINCTRL_PIN(GPIO60, "GPIO60"),
PINCTRL_PIN(GPIO61, "GPIO61"),
PINCTRL_PIN(GPIO62, "GPIO62"),
PINCTRL_PIN(GPIO63, "GPIO63"),
PINCTRL_PIN(GPIO64, "GPIO64"),
PINCTRL_PIN(GPIO65, "GPIO65"),
PINCTRL_PIN(GPIO66, "GPIO66"),
PINCTRL_PIN(GPIO67, "GPIO67"),
PINCTRL_PIN(GPIO68, "GPIO68"),
PINCTRL_PIN(GPIO69, "GPIO69"),
PINCTRL_PIN(GPIO70, "GPIO70"),
PINCTRL_PIN(GPIO71, "GPIO71"),
PINCTRL_PIN(GPIO72, "GPIO72"),
PINCTRL_PIN(GPIO73, "GPIO73"),
PINCTRL_PIN(GPIO74, "GPIO74"),
PINCTRL_PIN(GPIO75, "GPIO75"),
PINCTRL_PIN(GPIO76, "GPIO76"),
PINCTRL_PIN(GPIO77, "GPIO77"),
PINCTRL_PIN(GPIO78, "GPIO78"),
PINCTRL_PIN(GPIO79, "GPIO79"),
PINCTRL_PIN(GPIO80, "GPIO80"),
PINCTRL_PIN(GPIO81, "GPIO81"),
PINCTRL_PIN(GPIO82, "GPIO82"),
PINCTRL_PIN(GPIO83, "GPIO83"),
PINCTRL_PIN(GPIO84, "GPIO84"),
PINCTRL_PIN(GPIO85, "GPIO85"),
PINCTRL_PIN(GPIO86, "GPIO86"),
PINCTRL_PIN(GPIO87, "GPIO87"),
PINCTRL_PIN(GPIO88, "GPIO88"),
PINCTRL_PIN(GPIO89, "GPIO89"),
PINCTRL_PIN(GPIO90, "GPIO90"),
PINCTRL_PIN(GPIO91, "GPIO91"),
PINCTRL_PIN(GPIO92, "GPIO92"),
PINCTRL_PIN(GPIO93, "GPIO93"),
PINCTRL_PIN(GPIO94, "GPIO94"),
PINCTRL_PIN(GPIO95, "GPIO95"),
PINCTRL_PIN(GPIO96, "GPIO96"),
PINCTRL_PIN(GPIO97, "GPIO97"),
PINCTRL_PIN(GPIO98, "GPIO98"),
PINCTRL_PIN(GPIO99, "GPIO99"),
PINCTRL_PIN(GPIO100, "GPIO100"),
PINCTRL_PIN(GPIO101, "GPIO101"),
PINCTRL_PIN(GPIO102, "GPIO102"),
PINCTRL_PIN(GPIO103, "GPIO103"),
PINCTRL_PIN(GPIO104, "GPIO104"),
PINCTRL_PIN(GPIO105, "GPIO105"),
PINCTRL_PIN(GPIO106, "GPIO106"),
PINCTRL_PIN(GPIO107, "GPIO107"),
PINCTRL_PIN(GPIO108, "GPIO108"),
PINCTRL_PIN(GPIO109, "GPIO109"),
PINCTRL_PIN(GPIO110, "GPIO110"),
PINCTRL_PIN(GPIO111, "GPIO111"),
PINCTRL_PIN(GPIO112, "GPIO112"),
PINCTRL_PIN(GPIO113, "GPIO113"),
PINCTRL_PIN(GPIO114, "GPIO114"),
PINCTRL_PIN(GPIO115, "GPIO115"),
PINCTRL_PIN(GPIO116, "GPIO116"),
PINCTRL_PIN(GPIO117, "GPIO117"),
PINCTRL_PIN(GPIO118, "GPIO118"),
PINCTRL_PIN(GPIO119, "GPIO119"),
PINCTRL_PIN(GPIO120, "GPIO120"),
PINCTRL_PIN(GPIO121, "GPIO121"),
PINCTRL_PIN(GPIO122, "GPIO122"),
PINCTRL_PIN(GPIO123, "GPIO123"),
PINCTRL_PIN(GPIO124, "GPIO124"),
PINCTRL_PIN(GPIO125, "GPIO125"),
PINCTRL_PIN(GPIO126, "GPIO126"),
PINCTRL_PIN(GPIO127, "GPIO127"),
PINCTRL_PIN(GPIO128, "GPIO128"),
PINCTRL_PIN(GPIO129, "GPIO129"),
PINCTRL_PIN(GPIO130, "GPIO130"),
PINCTRL_PIN(GPIO131, "GPIO131"),
PINCTRL_PIN(GPIO132, "GPIO132"),
PINCTRL_PIN(GPIO133, "GPIO133"),
PINCTRL_PIN(GPIO134, "GPIO134"),
PINCTRL_PIN(GPIO135, "GPIO135"),
PINCTRL_PIN(GPIO136, "GPIO136"),
PINCTRL_PIN(GPIO137, "GPIO137"),
PINCTRL_PIN(GPIO138, "GPIO138"),
PINCTRL_PIN(GPIO139, "GPIO139"),
PINCTRL_PIN(GPIO140, "GPIO140"),
PINCTRL_PIN(GPIO141, "GPIO141"),
PINCTRL_PIN(GPIO142, "GPIO142"),
PINCTRL_PIN(GPIO143, "GPIO143"),
PINCTRL_PIN(GPIO144, "GPIO144"),
PINCTRL_PIN(GPIO145, "GPIO145"),
PINCTRL_PIN(GPIO146, "GPIO146"),
PINCTRL_PIN(GPIO147, "GPIO147"),
PINCTRL_PIN(GPIO148, "GPIO148"),
PINCTRL_PIN(GPIO149, "GPIO149"),
PINCTRL_PIN(GPIO150, "GPIO150"),
PINCTRL_PIN(GPIO151, "GPIO151"),
PINCTRL_PIN(GPIO152, "GPIO152"),
PINCTRL_PIN(GPIO153, "GPIO153"),
PINCTRL_PIN(GPIO154, "GPIO154"),
PINCTRL_PIN(GPIO155, "GPIO155"),
PINCTRL_PIN(GPIO156, "GPIO156"),
PINCTRL_PIN(GPIO157, "GPIO157"),
PINCTRL_PIN(GPIO158, "GPIO158"),
PINCTRL_PIN(GPIO159, "GPIO159"),
PINCTRL_PIN(GPIO160, "GPIO160"),
PINCTRL_PIN(GPIO161, "GPIO161"),
PINCTRL_PIN(GPIO162, "GPIO162"),
PINCTRL_PIN(GPIO163, "GPIO163"),
PINCTRL_PIN(GPIO164, "GPIO164"),
PINCTRL_PIN(GPIO165, "GPIO165"),
PINCTRL_PIN(GPIO166, "GPIO166"),
PINCTRL_PIN(GPIO167, "GPIO167"),
PINCTRL_PIN(GPIO168, "GPIO168"),
PINCTRL_PIN(TWSI4_SCL, "TWSI4_SCL"),
PINCTRL_PIN(TWSI4_SDA, "TWSI4_SDA"),
PINCTRL_PIN(G_CLKREQ, "G_CLKREQ"),
PINCTRL_PIN(VCXO_REQ, "VCXO_REQ"),
PINCTRL_PIN(VCXO_OUT, "VCXO_OUT"),
};
struct pxa3xx_mfp_pin mmp2_mfp[] = {
/* pin offs f0 f1 f2 f3 f4 f5 f6 f7 */
MFPR_MMP2(GPIO0, 0x054, GPIO, KP_MK, NONE, SPI, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO1, 0x058, GPIO, KP_MK, NONE, SPI, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO2, 0x05C, GPIO, KP_MK, NONE, SPI, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO3, 0x060, GPIO, KP_MK, NONE, SPI, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO4, 0x064, GPIO, KP_MK, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO5, 0x068, GPIO, KP_MK, NONE, SPI, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO6, 0x06C, GPIO, KP_MK, NONE, SPI, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO7, 0x070, GPIO, KP_MK, NONE, SPI, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO8, 0x074, GPIO, KP_MK, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO9, 0x078, GPIO, KP_MK, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO10, 0x07C, GPIO, KP_MK, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO11, 0x080, GPIO, KP_MK, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO12, 0x084, GPIO, KP_MK, NONE, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO13, 0x088, GPIO, KP_MK, NONE, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO14, 0x08C, GPIO, KP_MK, NONE, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO15, 0x090, GPIO, KP_MK, KP_DK, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO16, 0x094, GPIO, KP_DK, ROT, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO17, 0x098, GPIO, KP_DK, ROT, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO18, 0x09C, GPIO, KP_DK, ROT, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO19, 0x0A0, GPIO, KP_DK, ROT, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO20, 0x0A4, GPIO, KP_DK, TB, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO21, 0x0A8, GPIO, KP_DK, TB, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO22, 0x0AC, GPIO, KP_DK, TB, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO23, 0x0B0, GPIO, KP_DK, TB, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO24, 0x0B4, GPIO, I2S, VCXO_OUT, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO25, 0x0B8, GPIO, I2S, HDMI, SSPA2, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO26, 0x0BC, GPIO, I2S, HDMI, SSPA2, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO27, 0x0C0, GPIO, I2S, HDMI, SSPA2, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO28, 0x0C4, GPIO, I2S, NONE, SSPA2, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO29, 0x0C8, GPIO, UART1, KP_MK, NONE, NONE, NONE, AAS_SPI, NONE),
MFPR_MMP2(GPIO30, 0x0CC, GPIO, UART1, KP_MK, NONE, NONE, NONE, AAS_SPI, NONE),
MFPR_MMP2(GPIO31, 0x0D0, GPIO, UART1, KP_MK, NONE, NONE, NONE, AAS_SPI, NONE),
MFPR_MMP2(GPIO32, 0x0D4, GPIO, UART1, KP_MK, NONE, NONE, NONE, AAS_SPI, NONE),
MFPR_MMP2(GPIO33, 0x0D8, GPIO, SSPA2, I2S, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO34, 0x0DC, GPIO, SSPA2, I2S, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO35, 0x0E0, GPIO, SSPA2, I2S, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO36, 0x0E4, GPIO, SSPA2, I2S, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO37, 0x0E8, GPIO, MMC2, SSP1, TWSI2, UART2, UART3, AAS_SPI, AAS_TWSI),
MFPR_MMP2(GPIO38, 0x0EC, GPIO, MMC2, SSP1, TWSI2, UART2, UART3, AAS_SPI, AAS_TWSI),
MFPR_MMP2(GPIO39, 0x0F0, GPIO, MMC2, SSP1, TWSI2, UART2, UART3, AAS_SPI, AAS_TWSI),
MFPR_MMP2(GPIO40, 0x0F4, GPIO, MMC2, SSP1, TWSI2, UART2, UART3, AAS_SPI, AAS_TWSI),
MFPR_MMP2(GPIO41, 0x0F8, GPIO, MMC2, TWSI5, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO42, 0x0FC, GPIO, MMC2, TWSI5, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO43, 0x100, GPIO, TWSI2, UART4, SSP1, UART2, UART3, NONE, AAS_TWSI),
MFPR_MMP2(GPIO44, 0x104, GPIO, TWSI2, UART4, SSP1, UART2, UART3, NONE, AAS_TWSI),
MFPR_MMP2(GPIO45, 0x108, GPIO, UART1, UART4, SSP1, UART2, UART3, NONE, NONE),
MFPR_MMP2(GPIO46, 0x10C, GPIO, UART1, UART4, SSP1, UART2, UART3, NONE, NONE),
MFPR_MMP2(GPIO47, 0x110, GPIO, UART2, SSP2, TWSI6, CAM2, AAS_SPI, AAS_GPIO, NONE),
MFPR_MMP2(GPIO48, 0x114, GPIO, UART2, SSP2, TWSI6, CAM2, AAS_SPI, AAS_GPIO, NONE),
MFPR_MMP2(GPIO49, 0x118, GPIO, UART2, SSP2, PWM, CCIC2, AAS_SPI, NONE, NONE),
MFPR_MMP2(GPIO50, 0x11C, GPIO, UART2, SSP2, PWM, CCIC2, AAS_SPI, NONE, NONE),
MFPR_MMP2(GPIO51, 0x120, GPIO, UART3, ROT, AAS_GPIO, PWM, NONE, NONE, NONE),
MFPR_MMP2(GPIO52, 0x124, GPIO, UART3, ROT, AAS_GPIO, PWM, NONE, NONE, NONE),
MFPR_MMP2(GPIO53, 0x128, GPIO, UART3, TWSI2, VCXO_REQ, NONE, PWM, NONE, AAS_TWSI),
MFPR_MMP2(GPIO54, 0x12C, GPIO, UART3, TWSI2, VCXO_OUT, HDMI, PWM, NONE, AAS_TWSI),
MFPR_MMP2(GPIO55, 0x130, GPIO, SSP2, SSP1, UART2, ROT, TWSI2, SSP3, AAS_TWSI),
MFPR_MMP2(GPIO56, 0x134, GPIO, SSP2, SSP1, UART2, ROT, TWSI2, KP_DK, AAS_TWSI),
MFPR_MMP2(GPIO57, 0x138, GPIO, SSP2_RX, SSP1_TXRX, SSP2_FRM, SSP1_RX, VCXO_REQ, KP_DK, NONE),
MFPR_MMP2(GPIO58, 0x13C, GPIO, SSP2, SSP1_RX, SSP1_FRM, SSP1_TXRX, VCXO_REQ, KP_DK, NONE),
MFPR_MMP2(GPIO59, 0x280, GPIO, CCIC1, ULPI, MMC3, CCIC2, UART3, UART4, NONE),
MFPR_MMP2(GPIO60, 0x284, GPIO, CCIC1, ULPI, MMC3, CCIC2, UART3, UART4, NONE),
MFPR_MMP2(GPIO61, 0x288, GPIO, CCIC1, ULPI, MMC3, CCIC2, UART3, HDMI, NONE),
MFPR_MMP2(GPIO62, 0x28C, GPIO, CCIC1, ULPI, MMC3, CCIC2, UART3, NONE, NONE),
MFPR_MMP2(GPIO63, 0x290, GPIO, CCIC1, ULPI, MMC3, CCIC2, MSP, UART4, NONE),
MFPR_MMP2(GPIO64, 0x294, GPIO, CCIC1, ULPI, MMC3, CCIC2, MSP, UART4, NONE),
MFPR_MMP2(GPIO65, 0x298, GPIO, CCIC1, ULPI, MMC3, CCIC2, MSP, UART4, NONE),
MFPR_MMP2(GPIO66, 0x29C, GPIO, CCIC1, ULPI, MMC3, CCIC2, MSP, UART4, NONE),
MFPR_MMP2(GPIO67, 0x2A0, GPIO, CCIC1, ULPI, MMC3, CCIC2, MSP, NONE, NONE),
MFPR_MMP2(GPIO68, 0x2A4, GPIO, CCIC1, ULPI, MMC3, CCIC2, MSP, LCD, NONE),
MFPR_MMP2(GPIO69, 0x2A8, GPIO, CCIC1, ULPI, MMC3, CCIC2, NONE, LCD, NONE),
MFPR_MMP2(GPIO70, 0x2AC, GPIO, CCIC1, ULPI, MMC3, CCIC2, MSP, LCD, NONE),
MFPR_MMP2(GPIO71, 0x2B0, GPIO, TWSI3, NONE, PWM, NONE, NONE, LCD, AAS_TWSI),
MFPR_MMP2(GPIO72, 0x2B4, GPIO, TWSI3, HDMI, PWM, NONE, NONE, LCD, AAS_TWSI),
MFPR_MMP2(GPIO73, 0x2B8, GPIO, VCXO_REQ, 32K_CLKOUT, PWM, VCXO_OUT, NONE, LCD, NONE),
MFPR_MMP2(GPIO74, 0x170, GPIO, LCD, SMC, MMC4, SSP3, UART2, UART4, TIPU),
MFPR_MMP2(GPIO75, 0x174, GPIO, LCD, SMC, MMC4, SSP3, UART2, UART4, TIPU),
MFPR_MMP2(GPIO76, 0x178, GPIO, LCD, SMC, MMC4, SSP3, UART2, UART4, TIPU),
MFPR_MMP2(GPIO77, 0x17C, GPIO, LCD, SMC, MMC4, SSP3, UART2, UART4, TIPU),
MFPR_MMP2(GPIO78, 0x180, GPIO, LCD, HDMI, MMC4, NONE, SSP4, AAS_SPI, TIPU),
MFPR_MMP2(GPIO79, 0x184, GPIO, LCD, AAS_GPIO, MMC4, NONE, SSP4, AAS_SPI, TIPU),
MFPR_MMP2(GPIO80, 0x188, GPIO, LCD, AAS_GPIO, MMC4, NONE, SSP4, AAS_SPI, TIPU),
MFPR_MMP2(GPIO81, 0x18C, GPIO, LCD, AAS_GPIO, MMC4, NONE, SSP4, AAS_SPI, TIPU),
MFPR_MMP2(GPIO82, 0x190, GPIO, LCD, NONE, MMC4, NONE, NONE, CCIC2, TIPU),
MFPR_MMP2(GPIO83, 0x194, GPIO, LCD, NONE, MMC4, NONE, NONE, CCIC2, TIPU),
MFPR_MMP2(GPIO84, 0x198, GPIO, LCD, SMC, MMC2, NONE, TWSI5, AAS_TWSI, TIPU),
MFPR_MMP2(GPIO85, 0x19C, GPIO, LCD, SMC, MMC2, NONE, TWSI5, AAS_TWSI, TIPU),
MFPR_MMP2(GPIO86, 0x1A0, GPIO, LCD, SMC, MMC2, NONE, TWSI6, CCIC2, TIPU),
MFPR_MMP2(GPIO87, 0x1A4, GPIO, LCD, SMC, MMC2, NONE, TWSI6, CCIC2, TIPU),
MFPR_MMP2(GPIO88, 0x1A8, GPIO, LCD, AAS_GPIO, MMC2, NONE, NONE, CCIC2, TIPU),
MFPR_MMP2(GPIO89, 0x1AC, GPIO, LCD, AAS_GPIO, MMC2, NONE, NONE, CCIC2, TIPU),
MFPR_MMP2(GPIO90, 0x1B0, GPIO, LCD, AAS_GPIO, MMC2, NONE, NONE, CCIC2, TIPU),
MFPR_MMP2(GPIO91, 0x1B4, GPIO, LCD, AAS_GPIO, MMC2, NONE, NONE, CCIC2, TIPU),
MFPR_MMP2(GPIO92, 0x1B8, GPIO, LCD, AAS_GPIO, MMC2, NONE, NONE, CCIC2, TIPU),
MFPR_MMP2(GPIO93, 0x1BC, GPIO, LCD, AAS_GPIO, MMC2, NONE, NONE, CCIC2, TIPU),
MFPR_MMP2(GPIO94, 0x1C0, GPIO, LCD, AAS_GPIO, SPI, NONE, AAS_SPI, CCIC2, TIPU),
MFPR_MMP2(GPIO95, 0x1C4, GPIO, LCD, TWSI3, SPI, AAS_DEU_EX, AAS_SPI, CCIC2, TIPU),
MFPR_MMP2(GPIO96, 0x1C8, GPIO, LCD, TWSI3, SPI, AAS_DEU_EX, AAS_SPI, NONE, TIPU),
MFPR_MMP2(GPIO97, 0x1CC, GPIO, LCD, TWSI6, SPI, AAS_DEU_EX, AAS_SPI, NONE, TIPU),
MFPR_MMP2(GPIO98, 0x1D0, GPIO, LCD, TWSI6, SPI, ONE_WIRE, NONE, NONE, TIPU),
MFPR_MMP2(GPIO99, 0x1D4, GPIO, LCD, SMC, SPI, TWSI5, NONE, NONE, TIPU),
MFPR_MMP2(GPIO100, 0x1D8, GPIO, LCD, SMC, SPI, TWSI5, NONE, NONE, TIPU),
MFPR_MMP2(GPIO101, 0x1DC, GPIO, LCD, SMC, SPI, NONE, NONE, NONE, TIPU),
MFPR_MMP2(GPIO102, 0x000, USIM, GPIO, FSIC, KP_DK, LCD, NONE, NONE, NONE),
MFPR_MMP2(GPIO103, 0x004, USIM, GPIO, FSIC, KP_DK, LCD, NONE, NONE, NONE),
MFPR_MMP2(GPIO104, 0x1FC, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO105, 0x1F8, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO106, 0x1F4, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO107, 0x1F0, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO108, 0x21C, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO109, 0x218, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO110, 0x214, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO111, 0x200, NAND, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO112, 0x244, NAND, GPIO, MMC3, SMC, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO113, 0x25C, SMC, GPIO, EXT_DMA, MMC3, SMC, HDMI, NONE, NONE),
MFPR_MMP2(GPIO114, 0x164, G_CLKOUT, 32K_CLKOUT, HDMI, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO115, 0x260, GPIO, NONE, AC, UART4, UART3, SSP1, NONE, NONE),
MFPR_MMP2(GPIO116, 0x264, GPIO, NONE, AC, UART4, UART3, SSP1, NONE, NONE),
MFPR_MMP2(GPIO117, 0x268, GPIO, NONE, AC, UART4, UART3, SSP1, NONE, NONE),
MFPR_MMP2(GPIO118, 0x26C, GPIO, NONE, AC, UART4, UART3, SSP1, NONE, NONE),
MFPR_MMP2(GPIO119, 0x270, GPIO, NONE, CA, SSP3, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO120, 0x274, GPIO, NONE, CA, SSP3, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO121, 0x278, GPIO, NONE, CA, SSP3, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO122, 0x27C, GPIO, NONE, CA, SSP3, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO123, 0x148, GPIO, SLEEP_IND, ONE_WIRE, 32K_CLKOUT, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO124, 0x00C, GPIO, MMC1, LCD, MMC3, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO125, 0x010, GPIO, MMC1, LCD, MMC3, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO126, 0x014, GPIO, MMC1, LCD, MMC3, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO127, 0x018, GPIO, NONE, LCD, MMC3, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO128, 0x01C, GPIO, NONE, LCD, MMC3, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO129, 0x020, GPIO, MMC1, LCD, MMC3, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO130, 0x024, GPIO, MMC1, LCD, MMC3, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO131, 0x028, GPIO, MMC1, NONE, MSP, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO132, 0x02C, GPIO, MMC1, PRI_JTAG, MSP, SSP3, AAS_JTAG, NONE, NONE),
MFPR_MMP2(GPIO133, 0x030, GPIO, MMC1, PRI_JTAG, MSP, SSP3, AAS_JTAG, NONE, NONE),
MFPR_MMP2(GPIO134, 0x034, GPIO, MMC1, PRI_JTAG, MSP, SSP3, AAS_JTAG, NONE, NONE),
MFPR_MMP2(GPIO135, 0x038, GPIO, NONE, LCD, MMC3, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO136, 0x03C, GPIO, MMC1, PRI_JTAG, MSP, SSP3, AAS_JTAG, NONE, NONE),
MFPR_MMP2(GPIO137, 0x040, GPIO, HDMI, LCD, MSP, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO138, 0x044, GPIO, NONE, LCD, MMC3, SMC, NONE, NONE, NONE),
MFPR_MMP2(GPIO139, 0x048, GPIO, MMC1, PRI_JTAG, MSP, NONE, AAS_JTAG, NONE, NONE),
MFPR_MMP2(GPIO140, 0x04C, GPIO, MMC1, LCD, NONE, NONE, UART2, UART1, NONE),
MFPR_MMP2(GPIO141, 0x050, GPIO, MMC1, LCD, NONE, NONE, UART2, UART1, NONE),
MFPR_MMP2(GPIO142, 0x008, USIM, GPIO, FSIC, KP_DK, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO143, 0x220, NAND, GPIO, SMC, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO144, 0x224, NAND, GPIO, SMC_INT, SMC, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO145, 0x228, SMC, GPIO, NONE, NONE, SMC, NONE, NONE, NONE),
MFPR_MMP2(GPIO146, 0x22C, SMC, GPIO, NONE, NONE, SMC, NONE, NONE, NONE),
MFPR_MMP2(GPIO147, 0x230, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO148, 0x234, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO149, 0x238, NAND, GPIO, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO150, 0x23C, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO151, 0x240, SMC, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO152, 0x248, SMC, GPIO, NONE, NONE, SMC, NONE, NONE, NONE),
MFPR_MMP2(GPIO153, 0x24C, SMC, GPIO, NONE, NONE, SMC, NONE, NONE, NONE),
MFPR_MMP2(GPIO154, 0x254, SMC_INT, GPIO, SMC, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO155, 0x258, EXT_DMA, GPIO, SMC, NONE, EXT_DMA, NONE, NONE, NONE),
MFPR_MMP2(GPIO156, 0x14C, PRI_JTAG, GPIO, PWM, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO157, 0x150, PRI_JTAG, GPIO, PWM, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO158, 0x154, PRI_JTAG, GPIO, PWM, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO159, 0x158, PRI_JTAG, GPIO, PWM, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO160, 0x250, NAND, GPIO, SMC, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO161, 0x210, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO162, 0x20C, NAND, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO163, 0x208, NAND, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO164, 0x204, NAND, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO165, 0x1EC, NAND, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO166, 0x1E8, NAND, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO167, 0x1E4, NAND, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO168, 0x1E0, NAND, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(TWSI4_SCL, 0x2BC, TWSI4, LCD, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(TWSI4_SDA, 0x2C0, TWSI4, LCD, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(G_CLKREQ, 0x160, G_CLKREQ, ONE_WIRE, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(VCXO_REQ, 0x168, VCXO_REQ, ONE_WIRE, PLL, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(VCXO_OUT, 0x16C, VCXO_OUT, 32K_CLKOUT, NONE, NONE, NONE, NONE, NONE, NONE),
};
static const unsigned mmp2_uart1_pin1[] = {GPIO29, GPIO30, GPIO31, GPIO32};
static const unsigned mmp2_uart1_pin2[] = {GPIO45, GPIO46};
static const unsigned mmp2_uart1_pin3[] = {GPIO140, GPIO141};
static const unsigned mmp2_uart2_pin1[] = {GPIO37, GPIO38, GPIO39, GPIO40};
static const unsigned mmp2_uart2_pin2[] = {GPIO43, GPIO44, GPIO45, GPIO46};
static const unsigned mmp2_uart2_pin3[] = {GPIO47, GPIO48, GPIO49, GPIO50};
static const unsigned mmp2_uart2_pin4[] = {GPIO74, GPIO75, GPIO76, GPIO77};
static const unsigned mmp2_uart2_pin5[] = {GPIO55, GPIO56};
static const unsigned mmp2_uart2_pin6[] = {GPIO140, GPIO141};
static const unsigned mmp2_uart3_pin1[] = {GPIO37, GPIO38, GPIO39, GPIO40};
static const unsigned mmp2_uart3_pin2[] = {GPIO43, GPIO44, GPIO45, GPIO46};
static const unsigned mmp2_uart3_pin3[] = {GPIO51, GPIO52, GPIO53, GPIO54};
static const unsigned mmp2_uart3_pin4[] = {GPIO59, GPIO60, GPIO61, GPIO62};
static const unsigned mmp2_uart3_pin5[] = {GPIO115, GPIO116, GPIO117, GPIO118};
static const unsigned mmp2_uart3_pin6[] = {GPIO51, GPIO52};
static const unsigned mmp2_uart4_pin1[] = {GPIO43, GPIO44, GPIO45, GPIO46};
static const unsigned mmp2_uart4_pin2[] = {GPIO63, GPIO64, GPIO65, GPIO66};
static const unsigned mmp2_uart4_pin3[] = {GPIO74, GPIO75, GPIO76, GPIO77};
static const unsigned mmp2_uart4_pin4[] = {GPIO115, GPIO116, GPIO117, GPIO118};
static const unsigned mmp2_uart4_pin5[] = {GPIO59, GPIO60};
static const unsigned mmp2_kpdk_pin1[] = {GPIO16, GPIO17, GPIO18, GPIO19};
static const unsigned mmp2_kpdk_pin2[] = {GPIO16, GPIO17};
static const unsigned mmp2_twsi2_pin1[] = {GPIO37, GPIO38};
static const unsigned mmp2_twsi2_pin2[] = {GPIO39, GPIO40};
static const unsigned mmp2_twsi2_pin3[] = {GPIO43, GPIO44};
static const unsigned mmp2_twsi2_pin4[] = {GPIO53, GPIO54};
static const unsigned mmp2_twsi2_pin5[] = {GPIO55, GPIO56};
static const unsigned mmp2_twsi3_pin1[] = {GPIO71, GPIO72};
static const unsigned mmp2_twsi3_pin2[] = {GPIO95, GPIO96};
static const unsigned mmp2_twsi4_pin1[] = {TWSI4_SCL, TWSI4_SDA};
static const unsigned mmp2_twsi5_pin1[] = {GPIO41, GPIO42};
static const unsigned mmp2_twsi5_pin2[] = {GPIO84, GPIO85};
static const unsigned mmp2_twsi5_pin3[] = {GPIO99, GPIO100};
static const unsigned mmp2_twsi6_pin1[] = {GPIO47, GPIO48};
static const unsigned mmp2_twsi6_pin2[] = {GPIO86, GPIO87};
static const unsigned mmp2_twsi6_pin3[] = {GPIO97, GPIO98};
static const unsigned mmp2_ccic1_pin1[] = {GPIO12, GPIO13, GPIO14, GPIO15,
GPIO16, GPIO17, GPIO18, GPIO19, GPIO20, GPIO21, GPIO22, GPIO23};
static const unsigned mmp2_ccic1_pin2[] = {GPIO59, GPIO60, GPIO61, GPIO62,
GPIO63, GPIO64, GPIO65, GPIO66, GPIO67, GPIO68, GPIO69, GPIO70};
static const unsigned mmp2_ccic2_pin1[] = {GPIO59, GPIO60, GPIO61, GPIO62,
GPIO63, GPIO64, GPIO65, GPIO66, GPIO67, GPIO68, GPIO69, GPIO70};
static const unsigned mmp2_ccic2_pin2[] = {GPIO82, GPIO83, GPIO86, GPIO87,
GPIO88, GPIO89, GPIO90, GPIO91, GPIO92, GPIO93, GPIO94, GPIO95};
static const unsigned mmp2_ulpi_pin1[] = {GPIO59, GPIO60, GPIO61, GPIO62,
GPIO63, GPIO64, GPIO65, GPIO66, GPIO67, GPIO68, GPIO69, GPIO70};
static const unsigned mmp2_ro_pin1[] = {GPIO16, GPIO17};
static const unsigned mmp2_ro_pin2[] = {GPIO18, GPIO19};
static const unsigned mmp2_ro_pin3[] = {GPIO51, GPIO52};
static const unsigned mmp2_ro_pin4[] = {GPIO55, GPIO56};
static const unsigned mmp2_i2s_pin1[] = {GPIO24, GPIO25, GPIO26, GPIO27,
GPIO28};
static const unsigned mmp2_i2s_pin2[] = {GPIO33, GPIO34, GPIO35, GPIO36};
static const unsigned mmp2_ssp1_pin1[] = {GPIO37, GPIO38, GPIO39, GPIO40};
static const unsigned mmp2_ssp1_pin2[] = {GPIO43, GPIO44, GPIO45, GPIO46};
static const unsigned mmp2_ssp1_pin3[] = {GPIO115, GPIO116, GPIO117, GPIO118};
static const unsigned mmp2_ssp2_pin1[] = {GPIO47, GPIO48, GPIO49, GPIO50};
static const unsigned mmp2_ssp3_pin1[] = {GPIO119, GPIO120, GPIO121, GPIO122};
static const unsigned mmp2_ssp3_pin2[] = {GPIO132, GPIO133, GPIO133, GPIO136};
static const unsigned mmp2_sspa2_pin1[] = {GPIO25, GPIO26, GPIO27, GPIO28};
static const unsigned mmp2_sspa2_pin2[] = {GPIO33, GPIO34, GPIO35, GPIO36};
static const unsigned mmp2_mmc1_pin1[] = {GPIO131, GPIO132, GPIO133, GPIO134,
GPIO136, GPIO139, GPIO140, GPIO141};
static const unsigned mmp2_mmc2_pin1[] = {GPIO37, GPIO38, GPIO39, GPIO40,
GPIO41, GPIO42};
static const unsigned mmp2_mmc3_pin1[] = {GPIO111, GPIO112, GPIO151, GPIO162,
GPIO163, GPIO164, GPIO165, GPIO166, GPIO167, GPIO168};
static struct pxa3xx_pin_group mmp2_grps[] = {
GRP_MMP2("uart1 4p1", UART1, mmp2_uart1_pin1),
GRP_MMP2("uart1 2p2", UART1, mmp2_uart1_pin2),
GRP_MMP2("uart1 2p3", UART1, mmp2_uart1_pin3),
GRP_MMP2("uart2 4p1", UART2, mmp2_uart2_pin1),
GRP_MMP2("uart2 4p2", UART2, mmp2_uart2_pin2),
GRP_MMP2("uart2 4p3", UART2, mmp2_uart2_pin3),
GRP_MMP2("uart2 4p4", UART2, mmp2_uart2_pin4),
GRP_MMP2("uart2 2p5", UART2, mmp2_uart2_pin5),
GRP_MMP2("uart2 2p6", UART2, mmp2_uart2_pin6),
GRP_MMP2("uart3 4p1", UART3, mmp2_uart3_pin1),
GRP_MMP2("uart3 4p2", UART3, mmp2_uart3_pin2),
GRP_MMP2("uart3 4p3", UART3, mmp2_uart3_pin3),
GRP_MMP2("uart3 4p4", UART3, mmp2_uart3_pin4),
GRP_MMP2("uart3 4p5", UART3, mmp2_uart3_pin5),
GRP_MMP2("uart3 2p6", UART3, mmp2_uart3_pin6),
GRP_MMP2("uart4 4p1", UART4, mmp2_uart4_pin1),
GRP_MMP2("uart4 4p2", UART4, mmp2_uart4_pin2),
GRP_MMP2("uart4 4p3", UART4, mmp2_uart4_pin3),
GRP_MMP2("uart4 4p4", UART4, mmp2_uart4_pin4),
GRP_MMP2("uart4 2p5", UART4, mmp2_uart4_pin5),
GRP_MMP2("kpdk 4p1", KP_DK, mmp2_kpdk_pin1),
GRP_MMP2("kpdk 4p2", KP_DK, mmp2_kpdk_pin2),
GRP_MMP2("twsi2-1", TWSI2, mmp2_twsi2_pin1),
GRP_MMP2("twsi2-2", TWSI2, mmp2_twsi2_pin2),
GRP_MMP2("twsi2-3", TWSI2, mmp2_twsi2_pin3),
GRP_MMP2("twsi2-4", TWSI2, mmp2_twsi2_pin4),
GRP_MMP2("twsi2-5", TWSI2, mmp2_twsi2_pin5),
GRP_MMP2("twsi3-1", TWSI3, mmp2_twsi3_pin1),
GRP_MMP2("twsi3-2", TWSI3, mmp2_twsi3_pin2),
GRP_MMP2("twsi4", TWSI4, mmp2_twsi4_pin1),
GRP_MMP2("twsi5-1", TWSI5, mmp2_twsi5_pin1),
GRP_MMP2("twsi5-2", TWSI5, mmp2_twsi5_pin2),
GRP_MMP2("twsi5-3", TWSI5, mmp2_twsi5_pin3),
GRP_MMP2("twsi6-1", TWSI6, mmp2_twsi6_pin1),
GRP_MMP2("twsi6-2", TWSI6, mmp2_twsi6_pin2),
GRP_MMP2("twsi6-3", TWSI6, mmp2_twsi6_pin3),
GRP_MMP2("ccic1-1", CCIC1, mmp2_ccic1_pin1),
GRP_MMP2("ccic1-2", CCIC1, mmp2_ccic1_pin2),
GRP_MMP2("ccic2-1", CCIC2, mmp2_ccic2_pin1),
GRP_MMP2("ccic2-1", CCIC2, mmp2_ccic2_pin2),
GRP_MMP2("ulpi", ULPI, mmp2_ulpi_pin1),
GRP_MMP2("ro-1", ROT, mmp2_ro_pin1),
GRP_MMP2("ro-2", ROT, mmp2_ro_pin2),
GRP_MMP2("ro-3", ROT, mmp2_ro_pin3),
GRP_MMP2("ro-4", ROT, mmp2_ro_pin4),
GRP_MMP2("i2s 5p1", I2S, mmp2_i2s_pin1),
GRP_MMP2("i2s 4p2", I2S, mmp2_i2s_pin2),
GRP_MMP2("ssp1 4p1", SSP1, mmp2_ssp1_pin1),
GRP_MMP2("ssp1 4p2", SSP1, mmp2_ssp1_pin2),
GRP_MMP2("ssp1 4p3", SSP1, mmp2_ssp1_pin3),
GRP_MMP2("ssp2 4p1", SSP2, mmp2_ssp2_pin1),
GRP_MMP2("ssp3 4p1", SSP3, mmp2_ssp3_pin1),
GRP_MMP2("ssp3 4p2", SSP3, mmp2_ssp3_pin2),
GRP_MMP2("sspa2 4p1", SSPA2, mmp2_sspa2_pin1),
GRP_MMP2("sspa2 4p2", SSPA2, mmp2_sspa2_pin2),
GRP_MMP2("mmc1 8p1", MMC1, mmp2_mmc1_pin1),
GRP_MMP2("mmc2 6p1", MMC2, mmp2_mmc2_pin1),
GRP_MMP2("mmc3 10p1", MMC3, mmp2_mmc3_pin1),
};
static const char * const mmp2_uart1_grps[] = {"uart1 4p1", "uart1 2p2",
"uart1 2p3"};
static const char * const mmp2_uart2_grps[] = {"uart2 4p1", "uart2 4p2",
"uart2 4p3", "uart2 4p4", "uart2 4p5", "uart2 4p6"};
static const char * const mmp2_uart3_grps[] = {"uart3 4p1", "uart3 4p2",
"uart3 4p3", "uart3 4p4", "uart3 4p5", "uart3 2p6"};
static const char * const mmp2_uart4_grps[] = {"uart4 4p1", "uart4 4p2",
"uart4 4p3", "uart4 4p4", "uart4 2p5"};
static const char * const mmp2_kpdk_grps[] = {"kpdk 4p1", "kpdk 4p2"};
static const char * const mmp2_twsi2_grps[] = {"twsi2-1", "twsi2-2",
"twsi2-3", "twsi2-4", "twsi2-5"};
static const char * const mmp2_twsi3_grps[] = {"twsi3-1", "twsi3-2"};
static const char * const mmp2_twsi4_grps[] = {"twsi4"};
static const char * const mmp2_twsi5_grps[] = {"twsi5-1", "twsi5-2",
"twsi5-3"};
static const char * const mmp2_twsi6_grps[] = {"twsi6-1", "twsi6-2",
"twsi6-3"};
static const char * const mmp2_ccic1_grps[] = {"ccic1-1", "ccic1-2"};
static const char * const mmp2_ccic2_grps[] = {"ccic2-1", "ccic2-2"};
static const char * const mmp2_ulpi_grps[] = {"ulpi"};
static const char * const mmp2_ro_grps[] = {"ro-1", "ro-2", "ro-3", "ro-4"};
static const char * const mmp2_i2s_grps[] = {"i2s 5p1", "i2s 4p2"};
static const char * const mmp2_ssp1_grps[] = {"ssp1 4p1", "ssp1 4p2",
"ssp1 4p3"};
static const char * const mmp2_ssp2_grps[] = {"ssp2 4p1"};
static const char * const mmp2_ssp3_grps[] = {"ssp3 4p1", "ssp3 4p2"};
static const char * const mmp2_sspa2_grps[] = {"sspa2 4p1", "sspa2 4p2"};
static const char * const mmp2_mmc1_grps[] = {"mmc1 8p1"};
static const char * const mmp2_mmc2_grps[] = {"mmc2 6p1"};
static const char * const mmp2_mmc3_grps[] = {"mmc3 10p1"};
static struct pxa3xx_pmx_func mmp2_funcs[] = {
{"uart1", ARRAY_AND_SIZE(mmp2_uart1_grps)},
{"uart2", ARRAY_AND_SIZE(mmp2_uart2_grps)},
{"uart3", ARRAY_AND_SIZE(mmp2_uart3_grps)},
{"uart4", ARRAY_AND_SIZE(mmp2_uart4_grps)},
{"kpdk", ARRAY_AND_SIZE(mmp2_kpdk_grps)},
{"twsi2", ARRAY_AND_SIZE(mmp2_twsi2_grps)},
{"twsi3", ARRAY_AND_SIZE(mmp2_twsi3_grps)},
{"twsi4", ARRAY_AND_SIZE(mmp2_twsi4_grps)},
{"twsi5", ARRAY_AND_SIZE(mmp2_twsi5_grps)},
{"twsi6", ARRAY_AND_SIZE(mmp2_twsi6_grps)},
{"ccic1", ARRAY_AND_SIZE(mmp2_ccic1_grps)},
{"ccic2", ARRAY_AND_SIZE(mmp2_ccic2_grps)},
{"ulpi", ARRAY_AND_SIZE(mmp2_ulpi_grps)},
{"ro", ARRAY_AND_SIZE(mmp2_ro_grps)},
{"i2s", ARRAY_AND_SIZE(mmp2_i2s_grps)},
{"ssp1", ARRAY_AND_SIZE(mmp2_ssp1_grps)},
{"ssp2", ARRAY_AND_SIZE(mmp2_ssp2_grps)},
{"ssp3", ARRAY_AND_SIZE(mmp2_ssp3_grps)},
{"sspa2", ARRAY_AND_SIZE(mmp2_sspa2_grps)},
{"mmc1", ARRAY_AND_SIZE(mmp2_mmc1_grps)},
{"mmc2", ARRAY_AND_SIZE(mmp2_mmc2_grps)},
{"mmc3", ARRAY_AND_SIZE(mmp2_mmc3_grps)},
};
static struct pinctrl_desc mmp2_pctrl_desc = {
.name = "mmp2-pinctrl",
.owner = THIS_MODULE,
};
static struct pxa3xx_pinmux_info mmp2_info = {
.mfp = mmp2_mfp,
.num_mfp = ARRAY_SIZE(mmp2_mfp),
.grps = mmp2_grps,
.num_grps = ARRAY_SIZE(mmp2_grps),
.funcs = mmp2_funcs,
.num_funcs = ARRAY_SIZE(mmp2_funcs),
.num_gpio = 169,
.desc = &mmp2_pctrl_desc,
.pads = mmp2_pads,
.num_pads = ARRAY_SIZE(mmp2_pads),
.cputype = PINCTRL_MMP2,
.ds_mask = MMP2_DS_MASK,
.ds_shift = MMP2_DS_SHIFT,
};
static int __devinit mmp2_pinmux_probe(struct platform_device *pdev)
{
return pxa3xx_pinctrl_register(pdev, &mmp2_info);
}
static int __devexit mmp2_pinmux_remove(struct platform_device *pdev)
{
return pxa3xx_pinctrl_unregister(pdev);
}
static struct platform_driver mmp2_pinmux_driver = {
.driver = {
.name = "mmp2-pinmux",
.owner = THIS_MODULE,
},
.probe = mmp2_pinmux_probe,
.remove = __devexit_p(mmp2_pinmux_remove),
};
static int __init mmp2_pinmux_init(void)
{
return platform_driver_register(&mmp2_pinmux_driver);
}
core_initcall_sync(mmp2_pinmux_init);
static void __exit mmp2_pinmux_exit(void)
{
platform_driver_unregister(&mmp2_pinmux_driver);
}
module_exit(mmp2_pinmux_exit);
MODULE_AUTHOR("Haojian Zhuang <haojian.zhuang@marvell.com>");
MODULE_DESCRIPTION("PXA3xx pin control driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
chrisch1974/htc8960-3.4 | drivers/scsi/arm/acornscsi.c | 4987 | 87791 | /*
* linux/drivers/acorn/scsi/acornscsi.c
*
* Acorn SCSI 3 driver
* By R.M.King.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Abandoned using the Select and Transfer command since there were
* some nasty races between our software and the target devices that
* were not easy to solve, and the device errata had a lot of entries
* for this command, some of them quite nasty...
*
* Changelog:
* 26-Sep-1997 RMK Re-jigged to use the queue module.
* Re-coded state machine to be based on driver
* state not scsi state. Should be easier to debug.
* Added acornscsi_release to clean up properly.
* Updated proc/scsi reporting.
* 05-Oct-1997 RMK Implemented writing to SCSI devices.
* 06-Oct-1997 RMK Corrected small (non-serious) bug with the connect/
* reconnect race condition causing a warning message.
* 12-Oct-1997 RMK Added catch for re-entering interrupt routine.
* 15-Oct-1997 RMK Improved handling of commands.
* 27-Jun-1998 RMK Changed asm/delay.h to linux/delay.h.
* 13-Dec-1998 RMK Better abort code and command handling. Extra state
* transitions added to allow dodgy devices to work.
*/
#define DEBUG_NO_WRITE 1
#define DEBUG_QUEUES 2
#define DEBUG_DMA 4
#define DEBUG_ABORT 8
#define DEBUG_DISCON 16
#define DEBUG_CONNECT 32
#define DEBUG_PHASES 64
#define DEBUG_WRITE 128
#define DEBUG_LINK 256
#define DEBUG_MESSAGES 512
#define DEBUG_RESET 1024
#define DEBUG_ALL (DEBUG_RESET|DEBUG_MESSAGES|DEBUG_LINK|DEBUG_WRITE|\
DEBUG_PHASES|DEBUG_CONNECT|DEBUG_DISCON|DEBUG_ABORT|\
DEBUG_DMA|DEBUG_QUEUES)
/* DRIVER CONFIGURATION
*
* SCSI-II Tagged queue support.
*
* I don't have any SCSI devices that support it, so it is totally untested
* (except to make sure that it doesn't interfere with any non-tagging
* devices). It is not fully implemented either - what happens when a
* tagging device reconnects???
*
* You can tell if you have a device that supports tagged queueing my
* cating (eg) /proc/scsi/acornscsi/0 and see if the SCSI revision is reported
* as '2 TAG'.
*
* Also note that CONFIG_SCSI_ACORNSCSI_TAGGED_QUEUE is normally set in the config
* scripts, but disabled here. Once debugged, remove the #undef, otherwise to debug,
* comment out the undef.
*/
#undef CONFIG_SCSI_ACORNSCSI_TAGGED_QUEUE
/*
* SCSI-II Linked command support.
*
* The higher level code doesn't support linked commands yet, and so the option
* is undef'd here.
*/
#undef CONFIG_SCSI_ACORNSCSI_LINK
/*
* SCSI-II Synchronous transfer support.
*
* Tried and tested...
*
* SDTR_SIZE - maximum number of un-acknowledged bytes (0 = off, 12 = max)
* SDTR_PERIOD - period of REQ signal (min=125, max=1020)
* DEFAULT_PERIOD - default REQ period.
*/
#define SDTR_SIZE 12
#define SDTR_PERIOD 125
#define DEFAULT_PERIOD 500
/*
* Debugging information
*
* DEBUG - bit mask from list above
* DEBUG_TARGET - is defined to the target number if you want to debug
* a specific target. [only recon/write/dma].
*/
#define DEBUG (DEBUG_RESET|DEBUG_WRITE|DEBUG_NO_WRITE)
/* only allow writing to SCSI device 0 */
#define NO_WRITE 0xFE
/*#define DEBUG_TARGET 2*/
/*
* Select timeout time (in 10ms units)
*
* This is the timeout used between the start of selection and the WD33C93
* chip deciding that the device isn't responding.
*/
#define TIMEOUT_TIME 10
/*
* Define this if you want to have verbose explanation of SCSI
* status/messages.
*/
#undef CONFIG_ACORNSCSI_CONSTANTS
/*
* Define this if you want to use the on board DMAC [don't remove this option]
* If not set, then use PIO mode (not currently supported).
*/
#define USE_DMAC
/*
* ====================================================================================
*/
#ifdef DEBUG_TARGET
#define DBG(cmd,xxx...) \
if (cmd->device->id == DEBUG_TARGET) { \
xxx; \
}
#else
#define DBG(cmd,xxx...) xxx
#endif
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/proc_fs.h>
#include <linux/ioport.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/bitops.h>
#include <linux/stringify.h>
#include <linux/io.h>
#include <asm/ecard.h>
#include "../scsi.h"
#include <scsi/scsi_dbg.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_transport_spi.h>
#include "acornscsi.h"
#include "msgqueue.h"
#include "scsi.h"
#include <scsi/scsicam.h>
#define VER_MAJOR 2
#define VER_MINOR 0
#define VER_PATCH 6
#ifndef ABORT_TAG
#define ABORT_TAG 0xd
#else
#error "Yippee! ABORT TAG is now defined! Remove this error!"
#endif
#ifdef CONFIG_SCSI_ACORNSCSI_LINK
#error SCSI2 LINKed commands not supported (yet)!
#endif
#ifdef USE_DMAC
/*
* DMAC setup parameters
*/
#define INIT_DEVCON0 (DEVCON0_RQL|DEVCON0_EXW|DEVCON0_CMP)
#define INIT_DEVCON1 (DEVCON1_BHLD)
#define DMAC_READ (MODECON_READ)
#define DMAC_WRITE (MODECON_WRITE)
#define INIT_SBICDMA (CTRL_DMABURST)
#define scsi_xferred have_data_in
/*
* Size of on-board DMA buffer
*/
#define DMAC_BUFFER_SIZE 65536
#endif
#define STATUS_BUFFER_TO_PRINT 24
unsigned int sdtr_period = SDTR_PERIOD;
unsigned int sdtr_size = SDTR_SIZE;
static void acornscsi_done(AS_Host *host, struct scsi_cmnd **SCpntp,
unsigned int result);
static int acornscsi_reconnect_finish(AS_Host *host);
static void acornscsi_dma_cleanup(AS_Host *host);
static void acornscsi_abortcmd(AS_Host *host, unsigned char tag);
/* ====================================================================================
* Miscellaneous
*/
/* Offsets from MEMC base */
#define SBIC_REGIDX 0x2000
#define SBIC_REGVAL 0x2004
#define DMAC_OFFSET 0x3000
/* Offsets from FAST IOC base */
#define INT_REG 0x2000
#define PAGE_REG 0x3000
static inline void sbic_arm_write(AS_Host *host, unsigned int reg, unsigned int value)
{
writeb(reg, host->base + SBIC_REGIDX);
writeb(value, host->base + SBIC_REGVAL);
}
static inline int sbic_arm_read(AS_Host *host, unsigned int reg)
{
if(reg == SBIC_ASR)
return readl(host->base + SBIC_REGIDX) & 255;
writeb(reg, host->base + SBIC_REGIDX);
return readl(host->base + SBIC_REGVAL) & 255;
}
#define sbic_arm_writenext(host, val) writeb((val), (host)->base + SBIC_REGVAL)
#define sbic_arm_readnext(host) readb((host)->base + SBIC_REGVAL)
#ifdef USE_DMAC
#define dmac_read(host,reg) \
readb((host)->base + DMAC_OFFSET + ((reg) << 2))
#define dmac_write(host,reg,value) \
({ writeb((value), (host)->base + DMAC_OFFSET + ((reg) << 2)); })
#define dmac_clearintr(host) writeb(0, (host)->fast + INT_REG)
static inline unsigned int dmac_address(AS_Host *host)
{
return dmac_read(host, DMAC_TXADRHI) << 16 |
dmac_read(host, DMAC_TXADRMD) << 8 |
dmac_read(host, DMAC_TXADRLO);
}
static
void acornscsi_dumpdma(AS_Host *host, char *where)
{
unsigned int mode, addr, len;
mode = dmac_read(host, DMAC_MODECON);
addr = dmac_address(host);
len = dmac_read(host, DMAC_TXCNTHI) << 8 |
dmac_read(host, DMAC_TXCNTLO);
printk("scsi%d: %s: DMAC %02x @%06x+%04x msk %02x, ",
host->host->host_no, where,
mode, addr, (len + 1) & 0xffff,
dmac_read(host, DMAC_MASKREG));
printk("DMA @%06x, ", host->dma.start_addr);
printk("BH @%p +%04x, ", host->scsi.SCp.ptr,
host->scsi.SCp.this_residual);
printk("DT @+%04x ST @+%04x", host->dma.transferred,
host->scsi.SCp.scsi_xferred);
printk("\n");
}
#endif
static
unsigned long acornscsi_sbic_xfcount(AS_Host *host)
{
unsigned long length;
length = sbic_arm_read(host, SBIC_TRANSCNTH) << 16;
length |= sbic_arm_readnext(host) << 8;
length |= sbic_arm_readnext(host);
return length;
}
static int
acornscsi_sbic_wait(AS_Host *host, int stat_mask, int stat, int timeout, char *msg)
{
int asr;
do {
asr = sbic_arm_read(host, SBIC_ASR);
if ((asr & stat_mask) == stat)
return 0;
udelay(1);
} while (--timeout);
printk("scsi%d: timeout while %s\n", host->host->host_no, msg);
return -1;
}
static
int acornscsi_sbic_issuecmd(AS_Host *host, int command)
{
if (acornscsi_sbic_wait(host, ASR_CIP, 0, 1000, "issuing command"))
return -1;
sbic_arm_write(host, SBIC_CMND, command);
return 0;
}
static void
acornscsi_csdelay(unsigned int cs)
{
unsigned long target_jiffies, flags;
target_jiffies = jiffies + 1 + cs * HZ / 100;
local_save_flags(flags);
local_irq_enable();
while (time_before(jiffies, target_jiffies)) barrier();
local_irq_restore(flags);
}
static
void acornscsi_resetcard(AS_Host *host)
{
unsigned int i, timeout;
/* assert reset line */
host->card.page_reg = 0x80;
writeb(host->card.page_reg, host->fast + PAGE_REG);
/* wait 3 cs. SCSI standard says 25ms. */
acornscsi_csdelay(3);
host->card.page_reg = 0;
writeb(host->card.page_reg, host->fast + PAGE_REG);
/*
* Should get a reset from the card
*/
timeout = 1000;
do {
if (readb(host->fast + INT_REG) & 8)
break;
udelay(1);
} while (--timeout);
if (timeout == 0)
printk("scsi%d: timeout while resetting card\n",
host->host->host_no);
sbic_arm_read(host, SBIC_ASR);
sbic_arm_read(host, SBIC_SSR);
/* setup sbic - WD33C93A */
sbic_arm_write(host, SBIC_OWNID, OWNID_EAF | host->host->this_id);
sbic_arm_write(host, SBIC_CMND, CMND_RESET);
/*
* Command should cause a reset interrupt
*/
timeout = 1000;
do {
if (readb(host->fast + INT_REG) & 8)
break;
udelay(1);
} while (--timeout);
if (timeout == 0)
printk("scsi%d: timeout while resetting card\n",
host->host->host_no);
sbic_arm_read(host, SBIC_ASR);
if (sbic_arm_read(host, SBIC_SSR) != 0x01)
printk(KERN_CRIT "scsi%d: WD33C93A didn't give enhanced reset interrupt\n",
host->host->host_no);
sbic_arm_write(host, SBIC_CTRL, INIT_SBICDMA | CTRL_IDI);
sbic_arm_write(host, SBIC_TIMEOUT, TIMEOUT_TIME);
sbic_arm_write(host, SBIC_SYNCHTRANSFER, SYNCHTRANSFER_2DBA);
sbic_arm_write(host, SBIC_SOURCEID, SOURCEID_ER | SOURCEID_DSP);
host->card.page_reg = 0x40;
writeb(host->card.page_reg, host->fast + PAGE_REG);
/* setup dmac - uPC71071 */
dmac_write(host, DMAC_INIT, 0);
#ifdef USE_DMAC
dmac_write(host, DMAC_INIT, INIT_8BIT);
dmac_write(host, DMAC_CHANNEL, CHANNEL_0);
dmac_write(host, DMAC_DEVCON0, INIT_DEVCON0);
dmac_write(host, DMAC_DEVCON1, INIT_DEVCON1);
#endif
host->SCpnt = NULL;
host->scsi.phase = PHASE_IDLE;
host->scsi.disconnectable = 0;
memset(host->busyluns, 0, sizeof(host->busyluns));
for (i = 0; i < 8; i++) {
host->device[i].sync_state = SYNC_NEGOCIATE;
host->device[i].disconnect_ok = 1;
}
/* wait 25 cs. SCSI standard says 250ms. */
acornscsi_csdelay(25);
}
/*=============================================================================================
* Utility routines (eg. debug)
*/
#ifdef CONFIG_ACORNSCSI_CONSTANTS
static char *acornscsi_interrupttype[] = {
"rst", "suc", "p/a", "3",
"term", "5", "6", "7",
"serv", "9", "a", "b",
"c", "d", "e", "f"
};
static signed char acornscsi_map[] = {
0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 2, -1, -1, -1, -1, 3, -1, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, -1, -1, -1, -1, -1, 4, 5, 6, 7, 8, 9, 10, 11,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
15, 16, 17, 18, 19, -1, -1, 20, 4, 5, 6, 7, 8, 9, 10, 11,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
21, 22, -1, -1, -1, 23, -1, -1, 4, 5, 6, 7, 8, 9, 10, 11,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
static char *acornscsi_interruptcode[] = {
/* 0 */
"reset - normal mode", /* 00 */
"reset - advanced mode", /* 01 */
/* 2 */
"sel", /* 11 */
"sel+xfer", /* 16 */
"data-out", /* 18 */
"data-in", /* 19 */
"cmd", /* 1A */
"stat", /* 1B */
"??-out", /* 1C */
"??-in", /* 1D */
"msg-out", /* 1E */
"msg-in", /* 1F */
/* 12 */
"/ACK asserted", /* 20 */
"save-data-ptr", /* 21 */
"{re}sel", /* 22 */
/* 15 */
"inv cmd", /* 40 */
"unexpected disconnect", /* 41 */
"sel timeout", /* 42 */
"P err", /* 43 */
"P err+ATN", /* 44 */
"bad status byte", /* 47 */
/* 21 */
"resel, no id", /* 80 */
"resel", /* 81 */
"discon", /* 85 */
};
static
void print_scsi_status(unsigned int ssr)
{
if (acornscsi_map[ssr] != -1)
printk("%s:%s",
acornscsi_interrupttype[(ssr >> 4)],
acornscsi_interruptcode[acornscsi_map[ssr]]);
else
printk("%X:%X", ssr >> 4, ssr & 0x0f);
}
#endif
static
void print_sbic_status(int asr, int ssr, int cmdphase)
{
#ifdef CONFIG_ACORNSCSI_CONSTANTS
printk("sbic: %c%c%c%c%c%c ",
asr & ASR_INT ? 'I' : 'i',
asr & ASR_LCI ? 'L' : 'l',
asr & ASR_BSY ? 'B' : 'b',
asr & ASR_CIP ? 'C' : 'c',
asr & ASR_PE ? 'P' : 'p',
asr & ASR_DBR ? 'D' : 'd');
printk("scsi: ");
print_scsi_status(ssr);
printk(" ph %02X\n", cmdphase);
#else
printk("sbic: %02X scsi: %X:%X ph: %02X\n",
asr, (ssr & 0xf0)>>4, ssr & 0x0f, cmdphase);
#endif
}
static void
acornscsi_dumplogline(AS_Host *host, int target, int line)
{
unsigned long prev;
signed int ptr;
ptr = host->status_ptr[target] - STATUS_BUFFER_TO_PRINT;
if (ptr < 0)
ptr += STATUS_BUFFER_SIZE;
printk("%c: %3s:", target == 8 ? 'H' : '0' + target,
line == 0 ? "ph" : line == 1 ? "ssr" : "int");
prev = host->status[target][ptr].when;
for (; ptr != host->status_ptr[target]; ptr = (ptr + 1) & (STATUS_BUFFER_SIZE - 1)) {
unsigned long time_diff;
if (!host->status[target][ptr].when)
continue;
switch (line) {
case 0:
printk("%c%02X", host->status[target][ptr].irq ? '-' : ' ',
host->status[target][ptr].ph);
break;
case 1:
printk(" %02X", host->status[target][ptr].ssr);
break;
case 2:
time_diff = host->status[target][ptr].when - prev;
prev = host->status[target][ptr].when;
if (time_diff == 0)
printk("==^");
else if (time_diff >= 100)
printk(" ");
else
printk(" %02ld", time_diff);
break;
}
}
printk("\n");
}
static
void acornscsi_dumplog(AS_Host *host, int target)
{
do {
acornscsi_dumplogline(host, target, 0);
acornscsi_dumplogline(host, target, 1);
acornscsi_dumplogline(host, target, 2);
if (target == 8)
break;
target = 8;
} while (1);
}
static
char acornscsi_target(AS_Host *host)
{
if (host->SCpnt)
return '0' + host->SCpnt->device->id;
return 'H';
}
/*
* Prototype: cmdtype_t acornscsi_cmdtype(int command)
* Purpose : differentiate READ from WRITE from other commands
* Params : command - command to interpret
* Returns : CMD_READ - command reads data,
* CMD_WRITE - command writes data,
* CMD_MISC - everything else
*/
static inline
cmdtype_t acornscsi_cmdtype(int command)
{
switch (command) {
case WRITE_6: case WRITE_10: case WRITE_12:
return CMD_WRITE;
case READ_6: case READ_10: case READ_12:
return CMD_READ;
default:
return CMD_MISC;
}
}
/*
* Prototype: int acornscsi_datadirection(int command)
* Purpose : differentiate between commands that have a DATA IN phase
* and a DATA OUT phase
* Params : command - command to interpret
* Returns : DATADIR_OUT - data out phase expected
* DATADIR_IN - data in phase expected
*/
static
datadir_t acornscsi_datadirection(int command)
{
switch (command) {
case CHANGE_DEFINITION: case COMPARE: case COPY:
case COPY_VERIFY: case LOG_SELECT: case MODE_SELECT:
case MODE_SELECT_10: case SEND_DIAGNOSTIC: case WRITE_BUFFER:
case FORMAT_UNIT: case REASSIGN_BLOCKS: case RESERVE:
case SEARCH_EQUAL: case SEARCH_HIGH: case SEARCH_LOW:
case WRITE_6: case WRITE_10: case WRITE_VERIFY:
case UPDATE_BLOCK: case WRITE_LONG: case WRITE_SAME:
case SEARCH_HIGH_12: case SEARCH_EQUAL_12: case SEARCH_LOW_12:
case WRITE_12: case WRITE_VERIFY_12: case SET_WINDOW:
case MEDIUM_SCAN: case SEND_VOLUME_TAG: case 0xea:
return DATADIR_OUT;
default:
return DATADIR_IN;
}
}
/*
* Purpose : provide values for synchronous transfers with 33C93.
* Copyright: Copyright (c) 1996 John Shifflett, GeoLog Consulting
* Modified by Russell King for 8MHz WD33C93A
*/
static struct sync_xfer_tbl {
unsigned int period_ns;
unsigned char reg_value;
} sync_xfer_table[] = {
{ 1, 0x20 }, { 249, 0x20 }, { 374, 0x30 },
{ 499, 0x40 }, { 624, 0x50 }, { 749, 0x60 },
{ 874, 0x70 }, { 999, 0x00 }, { 0, 0 }
};
/*
* Prototype: int acornscsi_getperiod(unsigned char syncxfer)
* Purpose : period for the synchronous transfer setting
* Params : syncxfer SYNCXFER register value
* Returns : period in ns.
*/
static
int acornscsi_getperiod(unsigned char syncxfer)
{
int i;
syncxfer &= 0xf0;
if (syncxfer == 0x10)
syncxfer = 0;
for (i = 1; sync_xfer_table[i].period_ns; i++)
if (syncxfer == sync_xfer_table[i].reg_value)
return sync_xfer_table[i].period_ns;
return 0;
}
/*
* Prototype: int round_period(unsigned int period)
* Purpose : return index into above table for a required REQ period
* Params : period - time (ns) for REQ
* Returns : table index
* Copyright: Copyright (c) 1996 John Shifflett, GeoLog Consulting
*/
static inline
int round_period(unsigned int period)
{
int i;
for (i = 1; sync_xfer_table[i].period_ns; i++) {
if ((period <= sync_xfer_table[i].period_ns) &&
(period > sync_xfer_table[i - 1].period_ns))
return i;
}
return 7;
}
/*
* Prototype: unsigned char calc_sync_xfer(unsigned int period, unsigned int offset)
* Purpose : calculate value for 33c93s SYNC register
* Params : period - time (ns) for REQ
* offset - offset in bytes between REQ/ACK
* Returns : value for SYNC register
* Copyright: Copyright (c) 1996 John Shifflett, GeoLog Consulting
*/
static
unsigned char calc_sync_xfer(unsigned int period, unsigned int offset)
{
return sync_xfer_table[round_period(period)].reg_value |
((offset < SDTR_SIZE) ? offset : SDTR_SIZE);
}
/* ====================================================================================
* Command functions
*/
/*
* Function: acornscsi_kick(AS_Host *host)
* Purpose : kick next command to interface
* Params : host - host to send command to
* Returns : INTR_IDLE if idle, otherwise INTR_PROCESSING
* Notes : interrupts are always disabled!
*/
static
intr_ret_t acornscsi_kick(AS_Host *host)
{
int from_queue = 0;
struct scsi_cmnd *SCpnt;
/* first check to see if a command is waiting to be executed */
SCpnt = host->origSCpnt;
host->origSCpnt = NULL;
/* retrieve next command */
if (!SCpnt) {
SCpnt = queue_remove_exclude(&host->queues.issue, host->busyluns);
if (!SCpnt)
return INTR_IDLE;
from_queue = 1;
}
if (host->scsi.disconnectable && host->SCpnt) {
queue_add_cmd_tail(&host->queues.disconnected, host->SCpnt);
host->scsi.disconnectable = 0;
#if (DEBUG & (DEBUG_QUEUES|DEBUG_DISCON))
DBG(host->SCpnt, printk("scsi%d.%c: moved command to disconnected queue\n",
host->host->host_no, acornscsi_target(host)));
#endif
host->SCpnt = NULL;
}
/*
* If we have an interrupt pending, then we may have been reselected.
* In this case, we don't want to write to the registers
*/
if (!(sbic_arm_read(host, SBIC_ASR) & (ASR_INT|ASR_BSY|ASR_CIP))) {
sbic_arm_write(host, SBIC_DESTID, SCpnt->device->id);
sbic_arm_write(host, SBIC_CMND, CMND_SELWITHATN);
}
/*
* claim host busy - all of these must happen atomically wrt
* our interrupt routine. Failure means command loss.
*/
host->scsi.phase = PHASE_CONNECTING;
host->SCpnt = SCpnt;
host->scsi.SCp = SCpnt->SCp;
host->dma.xfer_setup = 0;
host->dma.xfer_required = 0;
host->dma.xfer_done = 0;
#if (DEBUG & (DEBUG_ABORT|DEBUG_CONNECT))
DBG(SCpnt,printk("scsi%d.%c: starting cmd %02X\n",
host->host->host_no, '0' + SCpnt->device->id,
SCpnt->cmnd[0]));
#endif
if (from_queue) {
#ifdef CONFIG_SCSI_ACORNSCSI_TAGGED_QUEUE
/*
* tagged queueing - allocate a new tag to this command
*/
if (SCpnt->device->simple_tags) {
SCpnt->device->current_tag += 1;
if (SCpnt->device->current_tag == 0)
SCpnt->device->current_tag = 1;
SCpnt->tag = SCpnt->device->current_tag;
} else
#endif
set_bit(SCpnt->device->id * 8 + SCpnt->device->lun, host->busyluns);
host->stats.removes += 1;
switch (acornscsi_cmdtype(SCpnt->cmnd[0])) {
case CMD_WRITE:
host->stats.writes += 1;
break;
case CMD_READ:
host->stats.reads += 1;
break;
case CMD_MISC:
host->stats.miscs += 1;
break;
}
}
return INTR_PROCESSING;
}
/*
* Function: void acornscsi_done(AS_Host *host, struct scsi_cmnd **SCpntp, unsigned int result)
* Purpose : complete processing for command
* Params : host - interface that completed
* result - driver byte of result
*/
static void acornscsi_done(AS_Host *host, struct scsi_cmnd **SCpntp,
unsigned int result)
{
struct scsi_cmnd *SCpnt = *SCpntp;
/* clean up */
sbic_arm_write(host, SBIC_SOURCEID, SOURCEID_ER | SOURCEID_DSP);
host->stats.fins += 1;
if (SCpnt) {
*SCpntp = NULL;
acornscsi_dma_cleanup(host);
SCpnt->result = result << 16 | host->scsi.SCp.Message << 8 | host->scsi.SCp.Status;
/*
* In theory, this should not happen. In practice, it seems to.
* Only trigger an error if the device attempts to report all happy
* but with untransferred buffers... If we don't do something, then
* data loss will occur. Should we check SCpnt->underflow here?
* It doesn't appear to be set to something meaningful by the higher
* levels all the time.
*/
if (result == DID_OK) {
int xfer_warn = 0;
if (SCpnt->underflow == 0) {
if (host->scsi.SCp.ptr &&
acornscsi_cmdtype(SCpnt->cmnd[0]) != CMD_MISC)
xfer_warn = 1;
} else {
if (host->scsi.SCp.scsi_xferred < SCpnt->underflow ||
host->scsi.SCp.scsi_xferred != host->dma.transferred)
xfer_warn = 1;
}
/* ANSI standard says: (SCSI-2 Rev 10c Sect 5.6.6)
* Targets which break data transfers into multiple
* connections shall end each successful connection
* (except possibly the last) with a SAVE DATA
* POINTER - DISCONNECT message sequence.
*
* This makes it difficult to ensure that a transfer has
* completed. If we reach the end of a transfer during
* the command, then we can only have finished the transfer.
* therefore, if we seem to have some data remaining, this
* is not a problem.
*/
if (host->dma.xfer_done)
xfer_warn = 0;
if (xfer_warn) {
switch (status_byte(SCpnt->result)) {
case CHECK_CONDITION:
case COMMAND_TERMINATED:
case BUSY:
case QUEUE_FULL:
case RESERVATION_CONFLICT:
break;
default:
printk(KERN_ERR "scsi%d.H: incomplete data transfer detected: result=%08X command=",
host->host->host_no, SCpnt->result);
__scsi_print_command(SCpnt->cmnd);
acornscsi_dumpdma(host, "done");
acornscsi_dumplog(host, SCpnt->device->id);
SCpnt->result &= 0xffff;
SCpnt->result |= DID_ERROR << 16;
}
}
}
if (!SCpnt->scsi_done)
panic("scsi%d.H: null scsi_done function in acornscsi_done", host->host->host_no);
clear_bit(SCpnt->device->id * 8 + SCpnt->device->lun, host->busyluns);
SCpnt->scsi_done(SCpnt);
} else
printk("scsi%d: null command in acornscsi_done", host->host->host_no);
host->scsi.phase = PHASE_IDLE;
}
/* ====================================================================================
* DMA routines
*/
/*
* Purpose : update SCSI Data Pointer
* Notes : this will only be one SG entry or less
*/
static
void acornscsi_data_updateptr(AS_Host *host, struct scsi_pointer *SCp, unsigned int length)
{
SCp->ptr += length;
SCp->this_residual -= length;
if (SCp->this_residual == 0 && next_SCp(SCp) == 0)
host->dma.xfer_done = 1;
}
/*
* Prototype: void acornscsi_data_read(AS_Host *host, char *ptr,
* unsigned int start_addr, unsigned int length)
* Purpose : read data from DMA RAM
* Params : host - host to transfer from
* ptr - DRAM address
* start_addr - host mem address
* length - number of bytes to transfer
* Notes : this will only be one SG entry or less
*/
static
void acornscsi_data_read(AS_Host *host, char *ptr,
unsigned int start_addr, unsigned int length)
{
extern void __acornscsi_in(void __iomem *, char *buf, int len);
unsigned int page, offset, len = length;
page = (start_addr >> 12);
offset = start_addr & ((1 << 12) - 1);
writeb((page & 0x3f) | host->card.page_reg, host->fast + PAGE_REG);
while (len > 0) {
unsigned int this_len;
if (len + offset > (1 << 12))
this_len = (1 << 12) - offset;
else
this_len = len;
__acornscsi_in(host->base + (offset << 1), ptr, this_len);
offset += this_len;
ptr += this_len;
len -= this_len;
if (offset == (1 << 12)) {
offset = 0;
page ++;
writeb((page & 0x3f) | host->card.page_reg, host->fast + PAGE_REG);
}
}
writeb(host->card.page_reg, host->fast + PAGE_REG);
}
/*
* Prototype: void acornscsi_data_write(AS_Host *host, char *ptr,
* unsigned int start_addr, unsigned int length)
* Purpose : write data to DMA RAM
* Params : host - host to transfer from
* ptr - DRAM address
* start_addr - host mem address
* length - number of bytes to transfer
* Notes : this will only be one SG entry or less
*/
static
void acornscsi_data_write(AS_Host *host, char *ptr,
unsigned int start_addr, unsigned int length)
{
extern void __acornscsi_out(void __iomem *, char *buf, int len);
unsigned int page, offset, len = length;
page = (start_addr >> 12);
offset = start_addr & ((1 << 12) - 1);
writeb((page & 0x3f) | host->card.page_reg, host->fast + PAGE_REG);
while (len > 0) {
unsigned int this_len;
if (len + offset > (1 << 12))
this_len = (1 << 12) - offset;
else
this_len = len;
__acornscsi_out(host->base + (offset << 1), ptr, this_len);
offset += this_len;
ptr += this_len;
len -= this_len;
if (offset == (1 << 12)) {
offset = 0;
page ++;
writeb((page & 0x3f) | host->card.page_reg, host->fast + PAGE_REG);
}
}
writeb(host->card.page_reg, host->fast + PAGE_REG);
}
/* =========================================================================================
* On-board DMA routines
*/
#ifdef USE_DMAC
/*
* Prototype: void acornscsi_dmastop(AS_Host *host)
* Purpose : stop all DMA
* Params : host - host on which to stop DMA
* Notes : This is called when leaving DATA IN/OUT phase,
* or when interface is RESET
*/
static inline
void acornscsi_dma_stop(AS_Host *host)
{
dmac_write(host, DMAC_MASKREG, MASK_ON);
dmac_clearintr(host);
#if (DEBUG & DEBUG_DMA)
DBG(host->SCpnt, acornscsi_dumpdma(host, "stop"));
#endif
}
/*
* Function: void acornscsi_dma_setup(AS_Host *host, dmadir_t direction)
* Purpose : setup DMA controller for data transfer
* Params : host - host to setup
* direction - data transfer direction
* Notes : This is called when entering DATA I/O phase, not
* while we're in a DATA I/O phase
*/
static
void acornscsi_dma_setup(AS_Host *host, dmadir_t direction)
{
unsigned int address, length, mode;
host->dma.direction = direction;
dmac_write(host, DMAC_MASKREG, MASK_ON);
if (direction == DMA_OUT) {
#if (DEBUG & DEBUG_NO_WRITE)
if (NO_WRITE & (1 << host->SCpnt->device->id)) {
printk(KERN_CRIT "scsi%d.%c: I can't handle DMA_OUT!\n",
host->host->host_no, acornscsi_target(host));
return;
}
#endif
mode = DMAC_WRITE;
} else
mode = DMAC_READ;
/*
* Allocate some buffer space, limited to half the buffer size
*/
length = min_t(unsigned int, host->scsi.SCp.this_residual, DMAC_BUFFER_SIZE / 2);
if (length) {
host->dma.start_addr = address = host->dma.free_addr;
host->dma.free_addr = (host->dma.free_addr + length) &
(DMAC_BUFFER_SIZE - 1);
/*
* Transfer data to DMA memory
*/
if (direction == DMA_OUT)
acornscsi_data_write(host, host->scsi.SCp.ptr, host->dma.start_addr,
length);
length -= 1;
dmac_write(host, DMAC_TXCNTLO, length);
dmac_write(host, DMAC_TXCNTHI, length >> 8);
dmac_write(host, DMAC_TXADRLO, address);
dmac_write(host, DMAC_TXADRMD, address >> 8);
dmac_write(host, DMAC_TXADRHI, 0);
dmac_write(host, DMAC_MODECON, mode);
dmac_write(host, DMAC_MASKREG, MASK_OFF);
#if (DEBUG & DEBUG_DMA)
DBG(host->SCpnt, acornscsi_dumpdma(host, "strt"));
#endif
host->dma.xfer_setup = 1;
}
}
/*
* Function: void acornscsi_dma_cleanup(AS_Host *host)
* Purpose : ensure that all DMA transfers are up-to-date & host->scsi.SCp is correct
* Params : host - host to finish
* Notes : This is called when a command is:
* terminating, RESTORE_POINTERS, SAVE_POINTERS, DISCONECT
* : This must not return until all transfers are completed.
*/
static
void acornscsi_dma_cleanup(AS_Host *host)
{
dmac_write(host, DMAC_MASKREG, MASK_ON);
dmac_clearintr(host);
/*
* Check for a pending transfer
*/
if (host->dma.xfer_required) {
host->dma.xfer_required = 0;
if (host->dma.direction == DMA_IN)
acornscsi_data_read(host, host->dma.xfer_ptr,
host->dma.xfer_start, host->dma.xfer_length);
}
/*
* Has a transfer been setup?
*/
if (host->dma.xfer_setup) {
unsigned int transferred;
host->dma.xfer_setup = 0;
#if (DEBUG & DEBUG_DMA)
DBG(host->SCpnt, acornscsi_dumpdma(host, "cupi"));
#endif
/*
* Calculate number of bytes transferred from DMA.
*/
transferred = dmac_address(host) - host->dma.start_addr;
host->dma.transferred += transferred;
if (host->dma.direction == DMA_IN)
acornscsi_data_read(host, host->scsi.SCp.ptr,
host->dma.start_addr, transferred);
/*
* Update SCSI pointers
*/
acornscsi_data_updateptr(host, &host->scsi.SCp, transferred);
#if (DEBUG & DEBUG_DMA)
DBG(host->SCpnt, acornscsi_dumpdma(host, "cupo"));
#endif
}
}
/*
* Function: void acornscsi_dmacintr(AS_Host *host)
* Purpose : handle interrupts from DMAC device
* Params : host - host to process
* Notes : If reading, we schedule the read to main memory &
* allow the transfer to continue.
* : If writing, we fill the onboard DMA memory from main
* memory.
* : Called whenever DMAC finished it's current transfer.
*/
static
void acornscsi_dma_intr(AS_Host *host)
{
unsigned int address, length, transferred;
#if (DEBUG & DEBUG_DMA)
DBG(host->SCpnt, acornscsi_dumpdma(host, "inti"));
#endif
dmac_write(host, DMAC_MASKREG, MASK_ON);
dmac_clearintr(host);
/*
* Calculate amount transferred via DMA
*/
transferred = dmac_address(host) - host->dma.start_addr;
host->dma.transferred += transferred;
/*
* Schedule DMA transfer off board
*/
if (host->dma.direction == DMA_IN) {
host->dma.xfer_start = host->dma.start_addr;
host->dma.xfer_length = transferred;
host->dma.xfer_ptr = host->scsi.SCp.ptr;
host->dma.xfer_required = 1;
}
acornscsi_data_updateptr(host, &host->scsi.SCp, transferred);
/*
* Allocate some buffer space, limited to half the on-board RAM size
*/
length = min_t(unsigned int, host->scsi.SCp.this_residual, DMAC_BUFFER_SIZE / 2);
if (length) {
host->dma.start_addr = address = host->dma.free_addr;
host->dma.free_addr = (host->dma.free_addr + length) &
(DMAC_BUFFER_SIZE - 1);
/*
* Transfer data to DMA memory
*/
if (host->dma.direction == DMA_OUT)
acornscsi_data_write(host, host->scsi.SCp.ptr, host->dma.start_addr,
length);
length -= 1;
dmac_write(host, DMAC_TXCNTLO, length);
dmac_write(host, DMAC_TXCNTHI, length >> 8);
dmac_write(host, DMAC_TXADRLO, address);
dmac_write(host, DMAC_TXADRMD, address >> 8);
dmac_write(host, DMAC_TXADRHI, 0);
dmac_write(host, DMAC_MASKREG, MASK_OFF);
#if (DEBUG & DEBUG_DMA)
DBG(host->SCpnt, acornscsi_dumpdma(host, "into"));
#endif
} else {
host->dma.xfer_setup = 0;
#if 0
/*
* If the interface still wants more, then this is an error.
* We give it another byte, but we also attempt to raise an
* attention condition. We continue giving one byte until
* the device recognises the attention.
*/
if (dmac_read(host, DMAC_STATUS) & STATUS_RQ0) {
acornscsi_abortcmd(host, host->SCpnt->tag);
dmac_write(host, DMAC_TXCNTLO, 0);
dmac_write(host, DMAC_TXCNTHI, 0);
dmac_write(host, DMAC_TXADRLO, 0);
dmac_write(host, DMAC_TXADRMD, 0);
dmac_write(host, DMAC_TXADRHI, 0);
dmac_write(host, DMAC_MASKREG, MASK_OFF);
}
#endif
}
}
/*
* Function: void acornscsi_dma_xfer(AS_Host *host)
* Purpose : transfer data between AcornSCSI and memory
* Params : host - host to process
*/
static
void acornscsi_dma_xfer(AS_Host *host)
{
host->dma.xfer_required = 0;
if (host->dma.direction == DMA_IN)
acornscsi_data_read(host, host->dma.xfer_ptr,
host->dma.xfer_start, host->dma.xfer_length);
}
/*
* Function: void acornscsi_dma_adjust(AS_Host *host)
* Purpose : adjust DMA pointers & count for bytes transferred to
* SBIC but not SCSI bus.
* Params : host - host to adjust DMA count for
*/
static
void acornscsi_dma_adjust(AS_Host *host)
{
if (host->dma.xfer_setup) {
signed long transferred;
#if (DEBUG & (DEBUG_DMA|DEBUG_WRITE))
DBG(host->SCpnt, acornscsi_dumpdma(host, "adji"));
#endif
/*
* Calculate correct DMA address - DMA is ahead of SCSI bus while
* writing.
* host->scsi.SCp.scsi_xferred is the number of bytes
* actually transferred to/from the SCSI bus.
* host->dma.transferred is the number of bytes transferred
* over DMA since host->dma.start_addr was last set.
*
* real_dma_addr = host->dma.start_addr + host->scsi.SCp.scsi_xferred
* - host->dma.transferred
*/
transferred = host->scsi.SCp.scsi_xferred - host->dma.transferred;
if (transferred < 0)
printk("scsi%d.%c: Ack! DMA write correction %ld < 0!\n",
host->host->host_no, acornscsi_target(host), transferred);
else if (transferred == 0)
host->dma.xfer_setup = 0;
else {
transferred += host->dma.start_addr;
dmac_write(host, DMAC_TXADRLO, transferred);
dmac_write(host, DMAC_TXADRMD, transferred >> 8);
dmac_write(host, DMAC_TXADRHI, transferred >> 16);
#if (DEBUG & (DEBUG_DMA|DEBUG_WRITE))
DBG(host->SCpnt, acornscsi_dumpdma(host, "adjo"));
#endif
}
}
}
#endif
/* =========================================================================================
* Data I/O
*/
static int
acornscsi_write_pio(AS_Host *host, char *bytes, int *ptr, int len, unsigned int max_timeout)
{
unsigned int asr, timeout = max_timeout;
int my_ptr = *ptr;
while (my_ptr < len) {
asr = sbic_arm_read(host, SBIC_ASR);
if (asr & ASR_DBR) {
timeout = max_timeout;
sbic_arm_write(host, SBIC_DATA, bytes[my_ptr++]);
} else if (asr & ASR_INT)
break;
else if (--timeout == 0)
break;
udelay(1);
}
*ptr = my_ptr;
return (timeout == 0) ? -1 : 0;
}
/*
* Function: void acornscsi_sendcommand(AS_Host *host)
* Purpose : send a command to a target
* Params : host - host which is connected to target
*/
static void
acornscsi_sendcommand(AS_Host *host)
{
struct scsi_cmnd *SCpnt = host->SCpnt;
sbic_arm_write(host, SBIC_TRANSCNTH, 0);
sbic_arm_writenext(host, 0);
sbic_arm_writenext(host, SCpnt->cmd_len - host->scsi.SCp.sent_command);
acornscsi_sbic_issuecmd(host, CMND_XFERINFO);
if (acornscsi_write_pio(host, SCpnt->cmnd,
(int *)&host->scsi.SCp.sent_command, SCpnt->cmd_len, 1000000))
printk("scsi%d: timeout while sending command\n", host->host->host_no);
host->scsi.phase = PHASE_COMMAND;
}
static
void acornscsi_sendmessage(AS_Host *host)
{
unsigned int message_length = msgqueue_msglength(&host->scsi.msgs);
unsigned int msgnr;
struct message *msg;
#if (DEBUG & DEBUG_MESSAGES)
printk("scsi%d.%c: sending message ",
host->host->host_no, acornscsi_target(host));
#endif
switch (message_length) {
case 0:
acornscsi_sbic_issuecmd(host, CMND_XFERINFO | CMND_SBT);
acornscsi_sbic_wait(host, ASR_DBR, ASR_DBR, 1000, "sending message 1");
sbic_arm_write(host, SBIC_DATA, NOP);
host->scsi.last_message = NOP;
#if (DEBUG & DEBUG_MESSAGES)
printk("NOP");
#endif
break;
case 1:
acornscsi_sbic_issuecmd(host, CMND_XFERINFO | CMND_SBT);
msg = msgqueue_getmsg(&host->scsi.msgs, 0);
acornscsi_sbic_wait(host, ASR_DBR, ASR_DBR, 1000, "sending message 2");
sbic_arm_write(host, SBIC_DATA, msg->msg[0]);
host->scsi.last_message = msg->msg[0];
#if (DEBUG & DEBUG_MESSAGES)
spi_print_msg(msg->msg);
#endif
break;
default:
/*
* ANSI standard says: (SCSI-2 Rev 10c Sect 5.6.14)
* 'When a target sends this (MESSAGE_REJECT) message, it
* shall change to MESSAGE IN phase and send this message
* prior to requesting additional message bytes from the
* initiator. This provides an interlock so that the
* initiator can determine which message byte is rejected.
*/
sbic_arm_write(host, SBIC_TRANSCNTH, 0);
sbic_arm_writenext(host, 0);
sbic_arm_writenext(host, message_length);
acornscsi_sbic_issuecmd(host, CMND_XFERINFO);
msgnr = 0;
while ((msg = msgqueue_getmsg(&host->scsi.msgs, msgnr++)) != NULL) {
unsigned int i;
#if (DEBUG & DEBUG_MESSAGES)
spi_print_msg(msg);
#endif
i = 0;
if (acornscsi_write_pio(host, msg->msg, &i, msg->length, 1000000))
printk("scsi%d: timeout while sending message\n", host->host->host_no);
host->scsi.last_message = msg->msg[0];
if (msg->msg[0] == EXTENDED_MESSAGE)
host->scsi.last_message |= msg->msg[2] << 8;
if (i != msg->length)
break;
}
break;
}
#if (DEBUG & DEBUG_MESSAGES)
printk("\n");
#endif
}
/*
* Function: void acornscsi_readstatusbyte(AS_Host *host)
* Purpose : Read status byte from connected target
* Params : host - host connected to target
*/
static
void acornscsi_readstatusbyte(AS_Host *host)
{
acornscsi_sbic_issuecmd(host, CMND_XFERINFO|CMND_SBT);
acornscsi_sbic_wait(host, ASR_DBR, ASR_DBR, 1000, "reading status byte");
host->scsi.SCp.Status = sbic_arm_read(host, SBIC_DATA);
}
/*
* Function: unsigned char acornscsi_readmessagebyte(AS_Host *host)
* Purpose : Read one message byte from connected target
* Params : host - host connected to target
*/
static
unsigned char acornscsi_readmessagebyte(AS_Host *host)
{
unsigned char message;
acornscsi_sbic_issuecmd(host, CMND_XFERINFO | CMND_SBT);
acornscsi_sbic_wait(host, ASR_DBR, ASR_DBR, 1000, "for message byte");
message = sbic_arm_read(host, SBIC_DATA);
/* wait for MSGIN-XFER-PAUSED */
acornscsi_sbic_wait(host, ASR_INT, ASR_INT, 1000, "for interrupt after message byte");
sbic_arm_read(host, SBIC_SSR);
return message;
}
/*
* Function: void acornscsi_message(AS_Host *host)
* Purpose : Read complete message from connected target & action message
* Params : host - host connected to target
*/
static
void acornscsi_message(AS_Host *host)
{
unsigned char message[16];
unsigned int msgidx = 0, msglen = 1;
do {
message[msgidx] = acornscsi_readmessagebyte(host);
switch (msgidx) {
case 0:
if (message[0] == EXTENDED_MESSAGE ||
(message[0] >= 0x20 && message[0] <= 0x2f))
msglen = 2;
break;
case 1:
if (message[0] == EXTENDED_MESSAGE)
msglen += message[msgidx];
break;
}
msgidx += 1;
if (msgidx < msglen) {
acornscsi_sbic_issuecmd(host, CMND_NEGATEACK);
/* wait for next msg-in */
acornscsi_sbic_wait(host, ASR_INT, ASR_INT, 1000, "for interrupt after negate ack");
sbic_arm_read(host, SBIC_SSR);
}
} while (msgidx < msglen);
#if (DEBUG & DEBUG_MESSAGES)
printk("scsi%d.%c: message in: ",
host->host->host_no, acornscsi_target(host));
spi_print_msg(message);
printk("\n");
#endif
if (host->scsi.phase == PHASE_RECONNECTED) {
/*
* ANSI standard says: (Section SCSI-2 Rev. 10c Sect 5.6.17)
* 'Whenever a target reconnects to an initiator to continue
* a tagged I/O process, the SIMPLE QUEUE TAG message shall
* be sent immediately following the IDENTIFY message...'
*/
if (message[0] == SIMPLE_QUEUE_TAG)
host->scsi.reconnected.tag = message[1];
if (acornscsi_reconnect_finish(host))
host->scsi.phase = PHASE_MSGIN;
}
switch (message[0]) {
case ABORT:
case ABORT_TAG:
case COMMAND_COMPLETE:
if (host->scsi.phase != PHASE_STATUSIN) {
printk(KERN_ERR "scsi%d.%c: command complete following non-status in phase?\n",
host->host->host_no, acornscsi_target(host));
acornscsi_dumplog(host, host->SCpnt->device->id);
}
host->scsi.phase = PHASE_DONE;
host->scsi.SCp.Message = message[0];
break;
case SAVE_POINTERS:
/*
* ANSI standard says: (Section SCSI-2 Rev. 10c Sect 5.6.20)
* 'The SAVE DATA POINTER message is sent from a target to
* direct the initiator to copy the active data pointer to
* the saved data pointer for the current I/O process.
*/
acornscsi_dma_cleanup(host);
host->SCpnt->SCp = host->scsi.SCp;
host->SCpnt->SCp.sent_command = 0;
host->scsi.phase = PHASE_MSGIN;
break;
case RESTORE_POINTERS:
/*
* ANSI standard says: (Section SCSI-2 Rev. 10c Sect 5.6.19)
* 'The RESTORE POINTERS message is sent from a target to
* direct the initiator to copy the most recently saved
* command, data, and status pointers for the I/O process
* to the corresponding active pointers. The command and
* status pointers shall be restored to the beginning of
* the present command and status areas.'
*/
acornscsi_dma_cleanup(host);
host->scsi.SCp = host->SCpnt->SCp;
host->scsi.phase = PHASE_MSGIN;
break;
case DISCONNECT:
/*
* ANSI standard says: (Section SCSI-2 Rev. 10c Sect 6.4.2)
* 'On those occasions when an error or exception condition occurs
* and the target elects to repeat the information transfer, the
* target may repeat the transfer either issuing a RESTORE POINTERS
* message or by disconnecting without issuing a SAVE POINTERS
* message. When reconnection is completed, the most recent
* saved pointer values are restored.'
*/
acornscsi_dma_cleanup(host);
host->scsi.phase = PHASE_DISCONNECT;
break;
case MESSAGE_REJECT:
#if 0 /* this isn't needed any more */
/*
* If we were negociating sync transfer, we don't yet know if
* this REJECT is for the sync transfer or for the tagged queue/wide
* transfer. Re-initiate sync transfer negotiation now, and if
* we got a REJECT in response to SDTR, then it'll be set to DONE.
*/
if (host->device[host->SCpnt->device->id].sync_state == SYNC_SENT_REQUEST)
host->device[host->SCpnt->device->id].sync_state = SYNC_NEGOCIATE;
#endif
/*
* If we have any messages waiting to go out, then assert ATN now
*/
if (msgqueue_msglength(&host->scsi.msgs))
acornscsi_sbic_issuecmd(host, CMND_ASSERTATN);
switch (host->scsi.last_message) {
#ifdef CONFIG_SCSI_ACORNSCSI_TAGGED_QUEUE
case HEAD_OF_QUEUE_TAG:
case ORDERED_QUEUE_TAG:
case SIMPLE_QUEUE_TAG:
/*
* ANSI standard says: (Section SCSI-2 Rev. 10c Sect 5.6.17)
* If a target does not implement tagged queuing and a queue tag
* message is received, it shall respond with a MESSAGE REJECT
* message and accept the I/O process as if it were untagged.
*/
printk(KERN_NOTICE "scsi%d.%c: disabling tagged queueing\n",
host->host->host_no, acornscsi_target(host));
host->SCpnt->device->simple_tags = 0;
set_bit(host->SCpnt->device->id * 8 + host->SCpnt->device->lun, host->busyluns);
break;
#endif
case EXTENDED_MESSAGE | (EXTENDED_SDTR << 8):
/*
* Target can't handle synchronous transfers
*/
printk(KERN_NOTICE "scsi%d.%c: Using asynchronous transfer\n",
host->host->host_no, acornscsi_target(host));
host->device[host->SCpnt->device->id].sync_xfer = SYNCHTRANSFER_2DBA;
host->device[host->SCpnt->device->id].sync_state = SYNC_ASYNCHRONOUS;
sbic_arm_write(host, SBIC_SYNCHTRANSFER, host->device[host->SCpnt->device->id].sync_xfer);
break;
default:
break;
}
break;
case QUEUE_FULL:
/* TODO: target queue is full */
break;
case SIMPLE_QUEUE_TAG:
/* tag queue reconnect... message[1] = queue tag. Print something to indicate something happened! */
printk("scsi%d.%c: reconnect queue tag %02X\n",
host->host->host_no, acornscsi_target(host),
message[1]);
break;
case EXTENDED_MESSAGE:
switch (message[2]) {
#ifdef CONFIG_SCSI_ACORNSCSI_SYNC
case EXTENDED_SDTR:
if (host->device[host->SCpnt->device->id].sync_state == SYNC_SENT_REQUEST) {
/*
* We requested synchronous transfers. This isn't quite right...
* We can only say if this succeeded if we proceed on to execute the
* command from this message. If we get a MESSAGE PARITY ERROR,
* and the target retries fail, then we fallback to asynchronous mode
*/
host->device[host->SCpnt->device->id].sync_state = SYNC_COMPLETED;
printk(KERN_NOTICE "scsi%d.%c: Using synchronous transfer, offset %d, %d ns\n",
host->host->host_no, acornscsi_target(host),
message[4], message[3] * 4);
host->device[host->SCpnt->device->id].sync_xfer =
calc_sync_xfer(message[3] * 4, message[4]);
} else {
unsigned char period, length;
/*
* Target requested synchronous transfers. The agreement is only
* to be in operation AFTER the target leaves message out phase.
*/
acornscsi_sbic_issuecmd(host, CMND_ASSERTATN);
period = max_t(unsigned int, message[3], sdtr_period / 4);
length = min_t(unsigned int, message[4], sdtr_size);
msgqueue_addmsg(&host->scsi.msgs, 5, EXTENDED_MESSAGE, 3,
EXTENDED_SDTR, period, length);
host->device[host->SCpnt->device->id].sync_xfer =
calc_sync_xfer(period * 4, length);
}
sbic_arm_write(host, SBIC_SYNCHTRANSFER, host->device[host->SCpnt->device->id].sync_xfer);
break;
#else
/* We do not accept synchronous transfers. Respond with a
* MESSAGE_REJECT.
*/
#endif
case EXTENDED_WDTR:
/* The WD33C93A is only 8-bit. We respond with a MESSAGE_REJECT
* to a wide data transfer request.
*/
default:
acornscsi_sbic_issuecmd(host, CMND_ASSERTATN);
msgqueue_flush(&host->scsi.msgs);
msgqueue_addmsg(&host->scsi.msgs, 1, MESSAGE_REJECT);
break;
}
break;
#ifdef CONFIG_SCSI_ACORNSCSI_LINK
case LINKED_CMD_COMPLETE:
case LINKED_FLG_CMD_COMPLETE:
/*
* We don't support linked commands yet
*/
if (0) {
#if (DEBUG & DEBUG_LINK)
printk("scsi%d.%c: lun %d tag %d linked command complete\n",
host->host->host_no, acornscsi_target(host), host->SCpnt->tag);
#endif
/*
* A linked command should only terminate with one of these messages
* if there are more linked commands available.
*/
if (!host->SCpnt->next_link) {
printk(KERN_WARNING "scsi%d.%c: lun %d tag %d linked command complete, but no next_link\n",
instance->host_no, acornscsi_target(host), host->SCpnt->tag);
acornscsi_sbic_issuecmd(host, CMND_ASSERTATN);
msgqueue_addmsg(&host->scsi.msgs, 1, ABORT);
} else {
struct scsi_cmnd *SCpnt = host->SCpnt;
acornscsi_dma_cleanup(host);
host->SCpnt = host->SCpnt->next_link;
host->SCpnt->tag = SCpnt->tag;
SCpnt->result = DID_OK | host->scsi.SCp.Message << 8 | host->Scsi.SCp.Status;
SCpnt->done(SCpnt);
/* initialise host->SCpnt->SCp */
}
break;
}
#endif
default: /* reject message */
printk(KERN_ERR "scsi%d.%c: unrecognised message %02X, rejecting\n",
host->host->host_no, acornscsi_target(host),
message[0]);
acornscsi_sbic_issuecmd(host, CMND_ASSERTATN);
msgqueue_flush(&host->scsi.msgs);
msgqueue_addmsg(&host->scsi.msgs, 1, MESSAGE_REJECT);
host->scsi.phase = PHASE_MSGIN;
break;
}
acornscsi_sbic_issuecmd(host, CMND_NEGATEACK);
}
/*
* Function: int acornscsi_buildmessages(AS_Host *host)
* Purpose : build the connection messages for a host
* Params : host - host to add messages to
*/
static
void acornscsi_buildmessages(AS_Host *host)
{
#if 0
/* does the device need resetting? */
if (cmd_reset) {
msgqueue_addmsg(&host->scsi.msgs, 1, BUS_DEVICE_RESET);
return;
}
#endif
msgqueue_addmsg(&host->scsi.msgs, 1,
IDENTIFY(host->device[host->SCpnt->device->id].disconnect_ok,
host->SCpnt->device->lun));
#if 0
/* does the device need the current command aborted */
if (cmd_aborted) {
acornscsi_abortcmd(host->SCpnt->tag);
return;
}
#endif
#ifdef CONFIG_SCSI_ACORNSCSI_TAGGED_QUEUE
if (host->SCpnt->tag) {
unsigned int tag_type;
if (host->SCpnt->cmnd[0] == REQUEST_SENSE ||
host->SCpnt->cmnd[0] == TEST_UNIT_READY ||
host->SCpnt->cmnd[0] == INQUIRY)
tag_type = HEAD_OF_QUEUE_TAG;
else
tag_type = SIMPLE_QUEUE_TAG;
msgqueue_addmsg(&host->scsi.msgs, 2, tag_type, host->SCpnt->tag);
}
#endif
#ifdef CONFIG_SCSI_ACORNSCSI_SYNC
if (host->device[host->SCpnt->device->id].sync_state == SYNC_NEGOCIATE) {
host->device[host->SCpnt->device->id].sync_state = SYNC_SENT_REQUEST;
msgqueue_addmsg(&host->scsi.msgs, 5,
EXTENDED_MESSAGE, 3, EXTENDED_SDTR,
sdtr_period / 4, sdtr_size);
}
#endif
}
/*
* Function: int acornscsi_starttransfer(AS_Host *host)
* Purpose : transfer data to/from connected target
* Params : host - host to which target is connected
* Returns : 0 if failure
*/
static
int acornscsi_starttransfer(AS_Host *host)
{
int residual;
if (!host->scsi.SCp.ptr /*&& host->scsi.SCp.this_residual*/) {
printk(KERN_ERR "scsi%d.%c: null buffer passed to acornscsi_starttransfer\n",
host->host->host_no, acornscsi_target(host));
return 0;
}
residual = scsi_bufflen(host->SCpnt) - host->scsi.SCp.scsi_xferred;
sbic_arm_write(host, SBIC_SYNCHTRANSFER, host->device[host->SCpnt->device->id].sync_xfer);
sbic_arm_writenext(host, residual >> 16);
sbic_arm_writenext(host, residual >> 8);
sbic_arm_writenext(host, residual);
acornscsi_sbic_issuecmd(host, CMND_XFERINFO);
return 1;
}
/* =========================================================================================
* Connection & Disconnection
*/
/*
* Function : acornscsi_reconnect(AS_Host *host)
* Purpose : reconnect a previously disconnected command
* Params : host - host specific data
* Remarks : SCSI spec says:
* 'The set of active pointers is restored from the set
* of saved pointers upon reconnection of the I/O process'
*/
static
int acornscsi_reconnect(AS_Host *host)
{
unsigned int target, lun, ok = 0;
target = sbic_arm_read(host, SBIC_SOURCEID);
if (!(target & 8))
printk(KERN_ERR "scsi%d: invalid source id after reselection "
"- device fault?\n",
host->host->host_no);
target &= 7;
if (host->SCpnt && !host->scsi.disconnectable) {
printk(KERN_ERR "scsi%d.%d: reconnected while command in "
"progress to target %d?\n",
host->host->host_no, target, host->SCpnt->device->id);
host->SCpnt = NULL;
}
lun = sbic_arm_read(host, SBIC_DATA) & 7;
host->scsi.reconnected.target = target;
host->scsi.reconnected.lun = lun;
host->scsi.reconnected.tag = 0;
if (host->scsi.disconnectable && host->SCpnt &&
host->SCpnt->device->id == target && host->SCpnt->device->lun == lun)
ok = 1;
if (!ok && queue_probetgtlun(&host->queues.disconnected, target, lun))
ok = 1;
ADD_STATUS(target, 0x81, host->scsi.phase, 0);
if (ok) {
host->scsi.phase = PHASE_RECONNECTED;
} else {
/* this doesn't seem to work */
printk(KERN_ERR "scsi%d.%c: reselected with no command "
"to reconnect with\n",
host->host->host_no, '0' + target);
acornscsi_dumplog(host, target);
acornscsi_abortcmd(host, 0);
if (host->SCpnt) {
queue_add_cmd_tail(&host->queues.disconnected, host->SCpnt);
host->SCpnt = NULL;
}
}
acornscsi_sbic_issuecmd(host, CMND_NEGATEACK);
return !ok;
}
/*
* Function: int acornscsi_reconect_finish(AS_Host *host)
* Purpose : finish reconnecting a command
* Params : host - host to complete
* Returns : 0 if failed
*/
static
int acornscsi_reconnect_finish(AS_Host *host)
{
if (host->scsi.disconnectable && host->SCpnt) {
host->scsi.disconnectable = 0;
if (host->SCpnt->device->id == host->scsi.reconnected.target &&
host->SCpnt->device->lun == host->scsi.reconnected.lun &&
host->SCpnt->tag == host->scsi.reconnected.tag) {
#if (DEBUG & (DEBUG_QUEUES|DEBUG_DISCON))
DBG(host->SCpnt, printk("scsi%d.%c: reconnected",
host->host->host_no, acornscsi_target(host)));
#endif
} else {
queue_add_cmd_tail(&host->queues.disconnected, host->SCpnt);
#if (DEBUG & (DEBUG_QUEUES|DEBUG_DISCON))
DBG(host->SCpnt, printk("scsi%d.%c: had to move command "
"to disconnected queue\n",
host->host->host_no, acornscsi_target(host)));
#endif
host->SCpnt = NULL;
}
}
if (!host->SCpnt) {
host->SCpnt = queue_remove_tgtluntag(&host->queues.disconnected,
host->scsi.reconnected.target,
host->scsi.reconnected.lun,
host->scsi.reconnected.tag);
#if (DEBUG & (DEBUG_QUEUES|DEBUG_DISCON))
DBG(host->SCpnt, printk("scsi%d.%c: had to get command",
host->host->host_no, acornscsi_target(host)));
#endif
}
if (!host->SCpnt)
acornscsi_abortcmd(host, host->scsi.reconnected.tag);
else {
/*
* Restore data pointer from SAVED pointers.
*/
host->scsi.SCp = host->SCpnt->SCp;
#if (DEBUG & (DEBUG_QUEUES|DEBUG_DISCON))
printk(", data pointers: [%p, %X]",
host->scsi.SCp.ptr, host->scsi.SCp.this_residual);
#endif
}
#if (DEBUG & (DEBUG_QUEUES|DEBUG_DISCON))
printk("\n");
#endif
host->dma.transferred = host->scsi.SCp.scsi_xferred;
return host->SCpnt != NULL;
}
/*
* Function: void acornscsi_disconnect_unexpected(AS_Host *host)
* Purpose : handle an unexpected disconnect
* Params : host - host on which disconnect occurred
*/
static
void acornscsi_disconnect_unexpected(AS_Host *host)
{
printk(KERN_ERR "scsi%d.%c: unexpected disconnect\n",
host->host->host_no, acornscsi_target(host));
#if (DEBUG & DEBUG_ABORT)
acornscsi_dumplog(host, 8);
#endif
acornscsi_done(host, &host->SCpnt, DID_ERROR);
}
/*
* Function: void acornscsi_abortcmd(AS_host *host, unsigned char tag)
* Purpose : abort a currently executing command
* Params : host - host with connected command to abort
* tag - tag to abort
*/
static
void acornscsi_abortcmd(AS_Host *host, unsigned char tag)
{
host->scsi.phase = PHASE_ABORTED;
sbic_arm_write(host, SBIC_CMND, CMND_ASSERTATN);
msgqueue_flush(&host->scsi.msgs);
#ifdef CONFIG_SCSI_ACORNSCSI_TAGGED_QUEUE
if (tag)
msgqueue_addmsg(&host->scsi.msgs, 2, ABORT_TAG, tag);
else
#endif
msgqueue_addmsg(&host->scsi.msgs, 1, ABORT);
}
/* ==========================================================================================
* Interrupt routines.
*/
/*
* Function: int acornscsi_sbicintr(AS_Host *host)
* Purpose : handle interrupts from SCSI device
* Params : host - host to process
* Returns : INTR_PROCESS if expecting another SBIC interrupt
* INTR_IDLE if no interrupt
* INTR_NEXT_COMMAND if we have finished processing the command
*/
static
intr_ret_t acornscsi_sbicintr(AS_Host *host, int in_irq)
{
unsigned int asr, ssr;
asr = sbic_arm_read(host, SBIC_ASR);
if (!(asr & ASR_INT))
return INTR_IDLE;
ssr = sbic_arm_read(host, SBIC_SSR);
#if (DEBUG & DEBUG_PHASES)
print_sbic_status(asr, ssr, host->scsi.phase);
#endif
ADD_STATUS(8, ssr, host->scsi.phase, in_irq);
if (host->SCpnt && !host->scsi.disconnectable)
ADD_STATUS(host->SCpnt->device->id, ssr, host->scsi.phase, in_irq);
switch (ssr) {
case 0x00: /* reset state - not advanced */
printk(KERN_ERR "scsi%d: reset in standard mode but wanted advanced mode.\n",
host->host->host_no);
/* setup sbic - WD33C93A */
sbic_arm_write(host, SBIC_OWNID, OWNID_EAF | host->host->this_id);
sbic_arm_write(host, SBIC_CMND, CMND_RESET);
return INTR_IDLE;
case 0x01: /* reset state - advanced */
sbic_arm_write(host, SBIC_CTRL, INIT_SBICDMA | CTRL_IDI);
sbic_arm_write(host, SBIC_TIMEOUT, TIMEOUT_TIME);
sbic_arm_write(host, SBIC_SYNCHTRANSFER, SYNCHTRANSFER_2DBA);
sbic_arm_write(host, SBIC_SOURCEID, SOURCEID_ER | SOURCEID_DSP);
msgqueue_flush(&host->scsi.msgs);
return INTR_IDLE;
case 0x41: /* unexpected disconnect aborted command */
acornscsi_disconnect_unexpected(host);
return INTR_NEXT_COMMAND;
}
switch (host->scsi.phase) {
case PHASE_CONNECTING: /* STATE: command removed from issue queue */
switch (ssr) {
case 0x11: /* -> PHASE_CONNECTED */
/* BUS FREE -> SELECTION */
host->scsi.phase = PHASE_CONNECTED;
msgqueue_flush(&host->scsi.msgs);
host->dma.transferred = host->scsi.SCp.scsi_xferred;
/* 33C93 gives next interrupt indicating bus phase */
asr = sbic_arm_read(host, SBIC_ASR);
if (!(asr & ASR_INT))
break;
ssr = sbic_arm_read(host, SBIC_SSR);
ADD_STATUS(8, ssr, host->scsi.phase, 1);
ADD_STATUS(host->SCpnt->device->id, ssr, host->scsi.phase, 1);
goto connected;
case 0x42: /* select timed out */
/* -> PHASE_IDLE */
acornscsi_done(host, &host->SCpnt, DID_NO_CONNECT);
return INTR_NEXT_COMMAND;
case 0x81: /* -> PHASE_RECONNECTED or PHASE_ABORTED */
/* BUS FREE -> RESELECTION */
host->origSCpnt = host->SCpnt;
host->SCpnt = NULL;
msgqueue_flush(&host->scsi.msgs);
acornscsi_reconnect(host);
break;
default:
printk(KERN_ERR "scsi%d.%c: PHASE_CONNECTING, SSR %02X?\n",
host->host->host_no, acornscsi_target(host), ssr);
acornscsi_dumplog(host, host->SCpnt ? host->SCpnt->device->id : 8);
acornscsi_abortcmd(host, host->SCpnt->tag);
}
return INTR_PROCESSING;
connected:
case PHASE_CONNECTED: /* STATE: device selected ok */
switch (ssr) {
#ifdef NONSTANDARD
case 0x8a: /* -> PHASE_COMMAND, PHASE_COMMANDPAUSED */
/* SELECTION -> COMMAND */
acornscsi_sendcommand(host);
break;
case 0x8b: /* -> PHASE_STATUS */
/* SELECTION -> STATUS */
acornscsi_readstatusbyte(host);
host->scsi.phase = PHASE_STATUSIN;
break;
#endif
case 0x8e: /* -> PHASE_MSGOUT */
/* SELECTION ->MESSAGE OUT */
host->scsi.phase = PHASE_MSGOUT;
acornscsi_buildmessages(host);
acornscsi_sendmessage(host);
break;
/* these should not happen */
case 0x85: /* target disconnected */
acornscsi_done(host, &host->SCpnt, DID_ERROR);
break;
default:
printk(KERN_ERR "scsi%d.%c: PHASE_CONNECTED, SSR %02X?\n",
host->host->host_no, acornscsi_target(host), ssr);
acornscsi_dumplog(host, host->SCpnt ? host->SCpnt->device->id : 8);
acornscsi_abortcmd(host, host->SCpnt->tag);
}
return INTR_PROCESSING;
case PHASE_MSGOUT: /* STATE: connected & sent IDENTIFY message */
/*
* SCSI standard says that MESSAGE OUT phases can be followed by a
* DATA phase, STATUS phase, MESSAGE IN phase or COMMAND phase
*/
switch (ssr) {
case 0x8a: /* -> PHASE_COMMAND, PHASE_COMMANDPAUSED */
case 0x1a: /* -> PHASE_COMMAND, PHASE_COMMANDPAUSED */
/* MESSAGE OUT -> COMMAND */
acornscsi_sendcommand(host);
break;
case 0x8b: /* -> PHASE_STATUS */
case 0x1b: /* -> PHASE_STATUS */
/* MESSAGE OUT -> STATUS */
acornscsi_readstatusbyte(host);
host->scsi.phase = PHASE_STATUSIN;
break;
case 0x8e: /* -> PHASE_MSGOUT */
/* MESSAGE_OUT(MESSAGE_IN) ->MESSAGE OUT */
acornscsi_sendmessage(host);
break;
case 0x4f: /* -> PHASE_MSGIN, PHASE_DISCONNECT */
case 0x1f: /* -> PHASE_MSGIN, PHASE_DISCONNECT */
/* MESSAGE OUT -> MESSAGE IN */
acornscsi_message(host);
break;
default:
printk(KERN_ERR "scsi%d.%c: PHASE_MSGOUT, SSR %02X?\n",
host->host->host_no, acornscsi_target(host), ssr);
acornscsi_dumplog(host, host->SCpnt ? host->SCpnt->device->id : 8);
}
return INTR_PROCESSING;
case PHASE_COMMAND: /* STATE: connected & command sent */
switch (ssr) {
case 0x18: /* -> PHASE_DATAOUT */
/* COMMAND -> DATA OUT */
if (host->scsi.SCp.sent_command != host->SCpnt->cmd_len)
acornscsi_abortcmd(host, host->SCpnt->tag);
acornscsi_dma_setup(host, DMA_OUT);
if (!acornscsi_starttransfer(host))
acornscsi_abortcmd(host, host->SCpnt->tag);
host->scsi.phase = PHASE_DATAOUT;
return INTR_IDLE;
case 0x19: /* -> PHASE_DATAIN */
/* COMMAND -> DATA IN */
if (host->scsi.SCp.sent_command != host->SCpnt->cmd_len)
acornscsi_abortcmd(host, host->SCpnt->tag);
acornscsi_dma_setup(host, DMA_IN);
if (!acornscsi_starttransfer(host))
acornscsi_abortcmd(host, host->SCpnt->tag);
host->scsi.phase = PHASE_DATAIN;
return INTR_IDLE;
case 0x1b: /* -> PHASE_STATUS */
/* COMMAND -> STATUS */
acornscsi_readstatusbyte(host);
host->scsi.phase = PHASE_STATUSIN;
break;
case 0x1e: /* -> PHASE_MSGOUT */
/* COMMAND -> MESSAGE OUT */
acornscsi_sendmessage(host);
break;
case 0x1f: /* -> PHASE_MSGIN, PHASE_DISCONNECT */
/* COMMAND -> MESSAGE IN */
acornscsi_message(host);
break;
default:
printk(KERN_ERR "scsi%d.%c: PHASE_COMMAND, SSR %02X?\n",
host->host->host_no, acornscsi_target(host), ssr);
acornscsi_dumplog(host, host->SCpnt ? host->SCpnt->device->id : 8);
}
return INTR_PROCESSING;
case PHASE_DISCONNECT: /* STATE: connected, received DISCONNECT msg */
if (ssr == 0x85) { /* -> PHASE_IDLE */
host->scsi.disconnectable = 1;
host->scsi.reconnected.tag = 0;
host->scsi.phase = PHASE_IDLE;
host->stats.disconnects += 1;
} else {
printk(KERN_ERR "scsi%d.%c: PHASE_DISCONNECT, SSR %02X instead of disconnect?\n",
host->host->host_no, acornscsi_target(host), ssr);
acornscsi_dumplog(host, host->SCpnt ? host->SCpnt->device->id : 8);
}
return INTR_NEXT_COMMAND;
case PHASE_IDLE: /* STATE: disconnected */
if (ssr == 0x81) /* -> PHASE_RECONNECTED or PHASE_ABORTED */
acornscsi_reconnect(host);
else {
printk(KERN_ERR "scsi%d.%c: PHASE_IDLE, SSR %02X while idle?\n",
host->host->host_no, acornscsi_target(host), ssr);
acornscsi_dumplog(host, host->SCpnt ? host->SCpnt->device->id : 8);
}
return INTR_PROCESSING;
case PHASE_RECONNECTED: /* STATE: device reconnected to initiator */
/*
* Command reconnected - if MESGIN, get message - it may be
* the tag. If not, get command out of disconnected queue
*/
/*
* If we reconnected and we're not in MESSAGE IN phase after IDENTIFY,
* reconnect I_T_L command
*/
if (ssr != 0x8f && !acornscsi_reconnect_finish(host))
return INTR_IDLE;
ADD_STATUS(host->SCpnt->device->id, ssr, host->scsi.phase, in_irq);
switch (ssr) {
case 0x88: /* data out phase */
/* -> PHASE_DATAOUT */
/* MESSAGE IN -> DATA OUT */
acornscsi_dma_setup(host, DMA_OUT);
if (!acornscsi_starttransfer(host))
acornscsi_abortcmd(host, host->SCpnt->tag);
host->scsi.phase = PHASE_DATAOUT;
return INTR_IDLE;
case 0x89: /* data in phase */
/* -> PHASE_DATAIN */
/* MESSAGE IN -> DATA IN */
acornscsi_dma_setup(host, DMA_IN);
if (!acornscsi_starttransfer(host))
acornscsi_abortcmd(host, host->SCpnt->tag);
host->scsi.phase = PHASE_DATAIN;
return INTR_IDLE;
case 0x8a: /* command out */
/* MESSAGE IN -> COMMAND */
acornscsi_sendcommand(host);/* -> PHASE_COMMAND, PHASE_COMMANDPAUSED */
break;
case 0x8b: /* status in */
/* -> PHASE_STATUSIN */
/* MESSAGE IN -> STATUS */
acornscsi_readstatusbyte(host);
host->scsi.phase = PHASE_STATUSIN;
break;
case 0x8e: /* message out */
/* -> PHASE_MSGOUT */
/* MESSAGE IN -> MESSAGE OUT */
acornscsi_sendmessage(host);
break;
case 0x8f: /* message in */
acornscsi_message(host); /* -> PHASE_MSGIN, PHASE_DISCONNECT */
break;
default:
printk(KERN_ERR "scsi%d.%c: PHASE_RECONNECTED, SSR %02X after reconnect?\n",
host->host->host_no, acornscsi_target(host), ssr);
acornscsi_dumplog(host, host->SCpnt ? host->SCpnt->device->id : 8);
}
return INTR_PROCESSING;
case PHASE_DATAIN: /* STATE: transferred data in */
/*
* This is simple - if we disconnect then the DMA address & count is
* correct.
*/
switch (ssr) {
case 0x19: /* -> PHASE_DATAIN */
case 0x89: /* -> PHASE_DATAIN */
acornscsi_abortcmd(host, host->SCpnt->tag);
return INTR_IDLE;
case 0x1b: /* -> PHASE_STATUSIN */
case 0x4b: /* -> PHASE_STATUSIN */
case 0x8b: /* -> PHASE_STATUSIN */
/* DATA IN -> STATUS */
host->scsi.SCp.scsi_xferred = scsi_bufflen(host->SCpnt) -
acornscsi_sbic_xfcount(host);
acornscsi_dma_stop(host);
acornscsi_readstatusbyte(host);
host->scsi.phase = PHASE_STATUSIN;
break;
case 0x1e: /* -> PHASE_MSGOUT */
case 0x4e: /* -> PHASE_MSGOUT */
case 0x8e: /* -> PHASE_MSGOUT */
/* DATA IN -> MESSAGE OUT */
host->scsi.SCp.scsi_xferred = scsi_bufflen(host->SCpnt) -
acornscsi_sbic_xfcount(host);
acornscsi_dma_stop(host);
acornscsi_sendmessage(host);
break;
case 0x1f: /* message in */
case 0x4f: /* message in */
case 0x8f: /* message in */
/* DATA IN -> MESSAGE IN */
host->scsi.SCp.scsi_xferred = scsi_bufflen(host->SCpnt) -
acornscsi_sbic_xfcount(host);
acornscsi_dma_stop(host);
acornscsi_message(host); /* -> PHASE_MSGIN, PHASE_DISCONNECT */
break;
default:
printk(KERN_ERR "scsi%d.%c: PHASE_DATAIN, SSR %02X?\n",
host->host->host_no, acornscsi_target(host), ssr);
acornscsi_dumplog(host, host->SCpnt ? host->SCpnt->device->id : 8);
}
return INTR_PROCESSING;
case PHASE_DATAOUT: /* STATE: transferred data out */
/*
* This is more complicated - if we disconnect, the DMA could be 12
* bytes ahead of us. We need to correct this.
*/
switch (ssr) {
case 0x18: /* -> PHASE_DATAOUT */
case 0x88: /* -> PHASE_DATAOUT */
acornscsi_abortcmd(host, host->SCpnt->tag);
return INTR_IDLE;
case 0x1b: /* -> PHASE_STATUSIN */
case 0x4b: /* -> PHASE_STATUSIN */
case 0x8b: /* -> PHASE_STATUSIN */
/* DATA OUT -> STATUS */
host->scsi.SCp.scsi_xferred = scsi_bufflen(host->SCpnt) -
acornscsi_sbic_xfcount(host);
acornscsi_dma_stop(host);
acornscsi_dma_adjust(host);
acornscsi_readstatusbyte(host);
host->scsi.phase = PHASE_STATUSIN;
break;
case 0x1e: /* -> PHASE_MSGOUT */
case 0x4e: /* -> PHASE_MSGOUT */
case 0x8e: /* -> PHASE_MSGOUT */
/* DATA OUT -> MESSAGE OUT */
host->scsi.SCp.scsi_xferred = scsi_bufflen(host->SCpnt) -
acornscsi_sbic_xfcount(host);
acornscsi_dma_stop(host);
acornscsi_dma_adjust(host);
acornscsi_sendmessage(host);
break;
case 0x1f: /* message in */
case 0x4f: /* message in */
case 0x8f: /* message in */
/* DATA OUT -> MESSAGE IN */
host->scsi.SCp.scsi_xferred = scsi_bufflen(host->SCpnt) -
acornscsi_sbic_xfcount(host);
acornscsi_dma_stop(host);
acornscsi_dma_adjust(host);
acornscsi_message(host); /* -> PHASE_MSGIN, PHASE_DISCONNECT */
break;
default:
printk(KERN_ERR "scsi%d.%c: PHASE_DATAOUT, SSR %02X?\n",
host->host->host_no, acornscsi_target(host), ssr);
acornscsi_dumplog(host, host->SCpnt ? host->SCpnt->device->id : 8);
}
return INTR_PROCESSING;
case PHASE_STATUSIN: /* STATE: status in complete */
switch (ssr) {
case 0x1f: /* -> PHASE_MSGIN, PHASE_DONE, PHASE_DISCONNECT */
case 0x8f: /* -> PHASE_MSGIN, PHASE_DONE, PHASE_DISCONNECT */
/* STATUS -> MESSAGE IN */
acornscsi_message(host);
break;
case 0x1e: /* -> PHASE_MSGOUT */
case 0x8e: /* -> PHASE_MSGOUT */
/* STATUS -> MESSAGE OUT */
acornscsi_sendmessage(host);
break;
default:
printk(KERN_ERR "scsi%d.%c: PHASE_STATUSIN, SSR %02X instead of MESSAGE_IN?\n",
host->host->host_no, acornscsi_target(host), ssr);
acornscsi_dumplog(host, host->SCpnt ? host->SCpnt->device->id : 8);
}
return INTR_PROCESSING;
case PHASE_MSGIN: /* STATE: message in */
switch (ssr) {
case 0x1e: /* -> PHASE_MSGOUT */
case 0x4e: /* -> PHASE_MSGOUT */
case 0x8e: /* -> PHASE_MSGOUT */
/* MESSAGE IN -> MESSAGE OUT */
acornscsi_sendmessage(host);
break;
case 0x1f: /* -> PHASE_MSGIN, PHASE_DONE, PHASE_DISCONNECT */
case 0x2f:
case 0x4f:
case 0x8f:
acornscsi_message(host);
break;
case 0x85:
printk("scsi%d.%c: strange message in disconnection\n",
host->host->host_no, acornscsi_target(host));
acornscsi_dumplog(host, host->SCpnt ? host->SCpnt->device->id : 8);
acornscsi_done(host, &host->SCpnt, DID_ERROR);
break;
default:
printk(KERN_ERR "scsi%d.%c: PHASE_MSGIN, SSR %02X after message in?\n",
host->host->host_no, acornscsi_target(host), ssr);
acornscsi_dumplog(host, host->SCpnt ? host->SCpnt->device->id : 8);
}
return INTR_PROCESSING;
case PHASE_DONE: /* STATE: received status & message */
switch (ssr) {
case 0x85: /* -> PHASE_IDLE */
acornscsi_done(host, &host->SCpnt, DID_OK);
return INTR_NEXT_COMMAND;
case 0x1e:
case 0x8e:
acornscsi_sendmessage(host);
break;
default:
printk(KERN_ERR "scsi%d.%c: PHASE_DONE, SSR %02X instead of disconnect?\n",
host->host->host_no, acornscsi_target(host), ssr);
acornscsi_dumplog(host, host->SCpnt ? host->SCpnt->device->id : 8);
}
return INTR_PROCESSING;
case PHASE_ABORTED:
switch (ssr) {
case 0x85:
if (host->SCpnt)
acornscsi_done(host, &host->SCpnt, DID_ABORT);
else {
clear_bit(host->scsi.reconnected.target * 8 + host->scsi.reconnected.lun,
host->busyluns);
host->scsi.phase = PHASE_IDLE;
}
return INTR_NEXT_COMMAND;
case 0x1e:
case 0x2e:
case 0x4e:
case 0x8e:
acornscsi_sendmessage(host);
break;
default:
printk(KERN_ERR "scsi%d.%c: PHASE_ABORTED, SSR %02X?\n",
host->host->host_no, acornscsi_target(host), ssr);
acornscsi_dumplog(host, host->SCpnt ? host->SCpnt->device->id : 8);
}
return INTR_PROCESSING;
default:
printk(KERN_ERR "scsi%d.%c: unknown driver phase %d\n",
host->host->host_no, acornscsi_target(host), ssr);
acornscsi_dumplog(host, host->SCpnt ? host->SCpnt->device->id : 8);
}
return INTR_PROCESSING;
}
/*
* Prototype: void acornscsi_intr(int irq, void *dev_id)
* Purpose : handle interrupts from Acorn SCSI card
* Params : irq - interrupt number
* dev_id - device specific data (AS_Host structure)
*/
static irqreturn_t
acornscsi_intr(int irq, void *dev_id)
{
AS_Host *host = (AS_Host *)dev_id;
intr_ret_t ret;
int iostatus;
int in_irq = 0;
do {
ret = INTR_IDLE;
iostatus = readb(host->fast + INT_REG);
if (iostatus & 2) {
acornscsi_dma_intr(host);
iostatus = readb(host->fast + INT_REG);
}
if (iostatus & 8)
ret = acornscsi_sbicintr(host, in_irq);
/*
* If we have a transfer pending, start it.
* Only start it if the interface has already started transferring
* it's data
*/
if (host->dma.xfer_required)
acornscsi_dma_xfer(host);
if (ret == INTR_NEXT_COMMAND)
ret = acornscsi_kick(host);
in_irq = 1;
} while (ret != INTR_IDLE);
return IRQ_HANDLED;
}
/*=============================================================================================
* Interfaces between interrupt handler and rest of scsi code
*/
/*
* Function : acornscsi_queuecmd(struct scsi_cmnd *cmd, void (*done)(struct scsi_cmnd *))
* Purpose : queues a SCSI command
* Params : cmd - SCSI command
* done - function called on completion, with pointer to command descriptor
* Returns : 0, or < 0 on error.
*/
static int acornscsi_queuecmd_lck(struct scsi_cmnd *SCpnt,
void (*done)(struct scsi_cmnd *))
{
AS_Host *host = (AS_Host *)SCpnt->device->host->hostdata;
if (!done) {
/* there should be some way of rejecting errors like this without panicing... */
panic("scsi%d: queuecommand called with NULL done function [cmd=%p]",
host->host->host_no, SCpnt);
return -EINVAL;
}
#if (DEBUG & DEBUG_NO_WRITE)
if (acornscsi_cmdtype(SCpnt->cmnd[0]) == CMD_WRITE && (NO_WRITE & (1 << SCpnt->device->id))) {
printk(KERN_CRIT "scsi%d.%c: WRITE attempted with NO_WRITE flag set\n",
host->host->host_no, '0' + SCpnt->device->id);
SCpnt->result = DID_NO_CONNECT << 16;
done(SCpnt);
return 0;
}
#endif
SCpnt->scsi_done = done;
SCpnt->host_scribble = NULL;
SCpnt->result = 0;
SCpnt->tag = 0;
SCpnt->SCp.phase = (int)acornscsi_datadirection(SCpnt->cmnd[0]);
SCpnt->SCp.sent_command = 0;
SCpnt->SCp.scsi_xferred = 0;
init_SCp(SCpnt);
host->stats.queues += 1;
{
unsigned long flags;
if (!queue_add_cmd_ordered(&host->queues.issue, SCpnt)) {
SCpnt->result = DID_ERROR << 16;
done(SCpnt);
return 0;
}
local_irq_save(flags);
if (host->scsi.phase == PHASE_IDLE)
acornscsi_kick(host);
local_irq_restore(flags);
}
return 0;
}
DEF_SCSI_QCMD(acornscsi_queuecmd)
/*
* Prototype: void acornscsi_reportstatus(struct scsi_cmnd **SCpntp1, struct scsi_cmnd **SCpntp2, int result)
* Purpose : pass a result to *SCpntp1, and check if *SCpntp1 = *SCpntp2
* Params : SCpntp1 - pointer to command to return
* SCpntp2 - pointer to command to check
* result - result to pass back to mid-level done function
* Returns : *SCpntp2 = NULL if *SCpntp1 is the same command structure as *SCpntp2.
*/
static inline void acornscsi_reportstatus(struct scsi_cmnd **SCpntp1,
struct scsi_cmnd **SCpntp2,
int result)
{
struct scsi_cmnd *SCpnt = *SCpntp1;
if (SCpnt) {
*SCpntp1 = NULL;
SCpnt->result = result;
SCpnt->scsi_done(SCpnt);
}
if (SCpnt == *SCpntp2)
*SCpntp2 = NULL;
}
enum res_abort { res_not_running, res_success, res_success_clear, res_snooze };
/*
* Prototype: enum res acornscsi_do_abort(struct scsi_cmnd *SCpnt)
* Purpose : abort a command on this host
* Params : SCpnt - command to abort
* Returns : our abort status
*/
static enum res_abort acornscsi_do_abort(AS_Host *host, struct scsi_cmnd *SCpnt)
{
enum res_abort res = res_not_running;
if (queue_remove_cmd(&host->queues.issue, SCpnt)) {
/*
* The command was on the issue queue, and has not been
* issued yet. We can remove the command from the queue,
* and acknowledge the abort. Neither the devices nor the
* interface know about the command.
*/
//#if (DEBUG & DEBUG_ABORT)
printk("on issue queue ");
//#endif
res = res_success;
} else if (queue_remove_cmd(&host->queues.disconnected, SCpnt)) {
/*
* The command was on the disconnected queue. Simply
* acknowledge the abort condition, and when the target
* reconnects, we will give it an ABORT message. The
* target should then disconnect, and we will clear
* the busylun bit.
*/
//#if (DEBUG & DEBUG_ABORT)
printk("on disconnected queue ");
//#endif
res = res_success;
} else if (host->SCpnt == SCpnt) {
unsigned long flags;
//#if (DEBUG & DEBUG_ABORT)
printk("executing ");
//#endif
local_irq_save(flags);
switch (host->scsi.phase) {
/*
* If the interface is idle, and the command is 'disconnectable',
* then it is the same as on the disconnected queue. We simply
* remove all traces of the command. When the target reconnects,
* we will give it an ABORT message since the command could not
* be found. When the target finally disconnects, we will clear
* the busylun bit.
*/
case PHASE_IDLE:
if (host->scsi.disconnectable) {
host->scsi.disconnectable = 0;
host->SCpnt = NULL;
res = res_success;
}
break;
/*
* If the command has connected and done nothing further,
* simply force a disconnect. We also need to clear the
* busylun bit.
*/
case PHASE_CONNECTED:
sbic_arm_write(host, SBIC_CMND, CMND_DISCONNECT);
host->SCpnt = NULL;
res = res_success_clear;
break;
default:
acornscsi_abortcmd(host, host->SCpnt->tag);
res = res_snooze;
}
local_irq_restore(flags);
} else if (host->origSCpnt == SCpnt) {
/*
* The command will be executed next, but a command
* is currently using the interface. This is similar to
* being on the issue queue, except the busylun bit has
* been set.
*/
host->origSCpnt = NULL;
//#if (DEBUG & DEBUG_ABORT)
printk("waiting for execution ");
//#endif
res = res_success_clear;
} else
printk("unknown ");
return res;
}
/*
* Prototype: int acornscsi_abort(struct scsi_cmnd *SCpnt)
* Purpose : abort a command on this host
* Params : SCpnt - command to abort
* Returns : one of SCSI_ABORT_ macros
*/
int acornscsi_abort(struct scsi_cmnd *SCpnt)
{
AS_Host *host = (AS_Host *) SCpnt->device->host->hostdata;
int result;
host->stats.aborts += 1;
#if (DEBUG & DEBUG_ABORT)
{
int asr, ssr;
asr = sbic_arm_read(host, SBIC_ASR);
ssr = sbic_arm_read(host, SBIC_SSR);
printk(KERN_WARNING "acornscsi_abort: ");
print_sbic_status(asr, ssr, host->scsi.phase);
acornscsi_dumplog(host, SCpnt->device->id);
}
#endif
printk("scsi%d: ", host->host->host_no);
switch (acornscsi_do_abort(host, SCpnt)) {
/*
* We managed to find the command and cleared it out.
* We do not expect the command to be executing on the
* target, but we have set the busylun bit.
*/
case res_success_clear:
//#if (DEBUG & DEBUG_ABORT)
printk("clear ");
//#endif
clear_bit(SCpnt->device->id * 8 + SCpnt->device->lun, host->busyluns);
/*
* We found the command, and cleared it out. Either
* the command is still known to be executing on the
* target, or the busylun bit is not set.
*/
case res_success:
//#if (DEBUG & DEBUG_ABORT)
printk("success\n");
//#endif
result = SUCCESS;
break;
/*
* We did find the command, but unfortunately we couldn't
* unhook it from ourselves. Wait some more, and if it
* still doesn't complete, reset the interface.
*/
case res_snooze:
//#if (DEBUG & DEBUG_ABORT)
printk("snooze\n");
//#endif
result = FAILED;
break;
/*
* The command could not be found (either because it completed,
* or it got dropped.
*/
default:
case res_not_running:
acornscsi_dumplog(host, SCpnt->device->id);
result = FAILED;
//#if (DEBUG & DEBUG_ABORT)
printk("not running\n");
//#endif
break;
}
return result;
}
/*
* Prototype: int acornscsi_reset(struct scsi_cmnd *SCpnt)
* Purpose : reset a command on this host/reset this host
* Params : SCpnt - command causing reset
* Returns : one of SCSI_RESET_ macros
*/
int acornscsi_bus_reset(struct scsi_cmnd *SCpnt)
{
AS_Host *host = (AS_Host *)SCpnt->device->host->hostdata;
struct scsi_cmnd *SCptr;
host->stats.resets += 1;
#if (DEBUG & DEBUG_RESET)
{
int asr, ssr;
asr = sbic_arm_read(host, SBIC_ASR);
ssr = sbic_arm_read(host, SBIC_SSR);
printk(KERN_WARNING "acornscsi_reset: ");
print_sbic_status(asr, ssr, host->scsi.phase);
acornscsi_dumplog(host, SCpnt->device->id);
}
#endif
acornscsi_dma_stop(host);
/*
* do hard reset. This resets all devices on this host, and so we
* must set the reset status on all commands.
*/
acornscsi_resetcard(host);
while ((SCptr = queue_remove(&host->queues.disconnected)) != NULL)
;
return SUCCESS;
}
/*==============================================================================================
* initialisation & miscellaneous support
*/
/*
* Function: char *acornscsi_info(struct Scsi_Host *host)
* Purpose : return a string describing this interface
* Params : host - host to give information on
* Returns : a constant string
*/
const
char *acornscsi_info(struct Scsi_Host *host)
{
static char string[100], *p;
p = string;
p += sprintf(string, "%s at port %08lX irq %d v%d.%d.%d"
#ifdef CONFIG_SCSI_ACORNSCSI_SYNC
" SYNC"
#endif
#ifdef CONFIG_SCSI_ACORNSCSI_TAGGED_QUEUE
" TAG"
#endif
#ifdef CONFIG_SCSI_ACORNSCSI_LINK
" LINK"
#endif
#if (DEBUG & DEBUG_NO_WRITE)
" NOWRITE (" __stringify(NO_WRITE) ")"
#endif
, host->hostt->name, host->io_port, host->irq,
VER_MAJOR, VER_MINOR, VER_PATCH);
return string;
}
int acornscsi_proc_info(struct Scsi_Host *instance, char *buffer, char **start, off_t offset,
int length, int inout)
{
int pos, begin = 0, devidx;
struct scsi_device *scd;
AS_Host *host;
char *p = buffer;
if (inout == 1)
return -EINVAL;
host = (AS_Host *)instance->hostdata;
p += sprintf(p, "AcornSCSI driver v%d.%d.%d"
#ifdef CONFIG_SCSI_ACORNSCSI_SYNC
" SYNC"
#endif
#ifdef CONFIG_SCSI_ACORNSCSI_TAGGED_QUEUE
" TAG"
#endif
#ifdef CONFIG_SCSI_ACORNSCSI_LINK
" LINK"
#endif
#if (DEBUG & DEBUG_NO_WRITE)
" NOWRITE (" __stringify(NO_WRITE) ")"
#endif
"\n\n", VER_MAJOR, VER_MINOR, VER_PATCH);
p += sprintf(p, "SBIC: WD33C93A Address: %p IRQ : %d\n",
host->base + SBIC_REGIDX, host->scsi.irq);
#ifdef USE_DMAC
p += sprintf(p, "DMAC: uPC71071 Address: %p IRQ : %d\n\n",
host->base + DMAC_OFFSET, host->scsi.irq);
#endif
p += sprintf(p, "Statistics:\n"
"Queued commands: %-10u Issued commands: %-10u\n"
"Done commands : %-10u Reads : %-10u\n"
"Writes : %-10u Others : %-10u\n"
"Disconnects : %-10u Aborts : %-10u\n"
"Resets : %-10u\n\nLast phases:",
host->stats.queues, host->stats.removes,
host->stats.fins, host->stats.reads,
host->stats.writes, host->stats.miscs,
host->stats.disconnects, host->stats.aborts,
host->stats.resets);
for (devidx = 0; devidx < 9; devidx ++) {
unsigned int statptr, prev;
p += sprintf(p, "\n%c:", devidx == 8 ? 'H' : ('0' + devidx));
statptr = host->status_ptr[devidx] - 10;
if ((signed int)statptr < 0)
statptr += STATUS_BUFFER_SIZE;
prev = host->status[devidx][statptr].when;
for (; statptr != host->status_ptr[devidx]; statptr = (statptr + 1) & (STATUS_BUFFER_SIZE - 1)) {
if (host->status[devidx][statptr].when) {
p += sprintf(p, "%c%02X:%02X+%2ld",
host->status[devidx][statptr].irq ? '-' : ' ',
host->status[devidx][statptr].ph,
host->status[devidx][statptr].ssr,
(host->status[devidx][statptr].when - prev) < 100 ?
(host->status[devidx][statptr].when - prev) : 99);
prev = host->status[devidx][statptr].when;
}
}
}
p += sprintf(p, "\nAttached devices:\n");
shost_for_each_device(scd, instance) {
p += sprintf(p, "Device/Lun TaggedQ Sync\n");
p += sprintf(p, " %d/%d ", scd->id, scd->lun);
if (scd->tagged_supported)
p += sprintf(p, "%3sabled(%3d) ",
scd->simple_tags ? "en" : "dis",
scd->current_tag);
else
p += sprintf(p, "unsupported ");
if (host->device[scd->id].sync_xfer & 15)
p += sprintf(p, "offset %d, %d ns\n",
host->device[scd->id].sync_xfer & 15,
acornscsi_getperiod(host->device[scd->id].sync_xfer));
else
p += sprintf(p, "async\n");
pos = p - buffer;
if (pos + begin < offset) {
begin += pos;
p = buffer;
}
pos = p - buffer;
if (pos + begin > offset + length) {
scsi_device_put(scd);
break;
}
}
pos = p - buffer;
*start = buffer + (offset - begin);
pos -= offset - begin;
if (pos > length)
pos = length;
return pos;
}
static struct scsi_host_template acornscsi_template = {
.module = THIS_MODULE,
.proc_info = acornscsi_proc_info,
.name = "AcornSCSI",
.info = acornscsi_info,
.queuecommand = acornscsi_queuecmd,
.eh_abort_handler = acornscsi_abort,
.eh_bus_reset_handler = acornscsi_bus_reset,
.can_queue = 16,
.this_id = 7,
.sg_tablesize = SG_ALL,
.cmd_per_lun = 2,
.use_clustering = DISABLE_CLUSTERING,
.proc_name = "acornscsi",
};
static int __devinit
acornscsi_probe(struct expansion_card *ec, const struct ecard_id *id)
{
struct Scsi_Host *host;
AS_Host *ashost;
int ret;
ret = ecard_request_resources(ec);
if (ret)
goto out;
host = scsi_host_alloc(&acornscsi_template, sizeof(AS_Host));
if (!host) {
ret = -ENOMEM;
goto out_release;
}
ashost = (AS_Host *)host->hostdata;
ashost->base = ecardm_iomap(ec, ECARD_RES_MEMC, 0, 0);
ashost->fast = ecardm_iomap(ec, ECARD_RES_IOCFAST, 0, 0);
if (!ashost->base || !ashost->fast)
goto out_put;
host->irq = ec->irq;
ashost->host = host;
ashost->scsi.irq = host->irq;
ec->irqaddr = ashost->fast + INT_REG;
ec->irqmask = 0x0a;
ret = request_irq(host->irq, acornscsi_intr, IRQF_DISABLED, "acornscsi", ashost);
if (ret) {
printk(KERN_CRIT "scsi%d: IRQ%d not free: %d\n",
host->host_no, ashost->scsi.irq, ret);
goto out_put;
}
memset(&ashost->stats, 0, sizeof (ashost->stats));
queue_initialise(&ashost->queues.issue);
queue_initialise(&ashost->queues.disconnected);
msgqueue_initialise(&ashost->scsi.msgs);
acornscsi_resetcard(ashost);
ret = scsi_add_host(host, &ec->dev);
if (ret)
goto out_irq;
scsi_scan_host(host);
goto out;
out_irq:
free_irq(host->irq, ashost);
msgqueue_free(&ashost->scsi.msgs);
queue_free(&ashost->queues.disconnected);
queue_free(&ashost->queues.issue);
out_put:
ecardm_iounmap(ec, ashost->fast);
ecardm_iounmap(ec, ashost->base);
scsi_host_put(host);
out_release:
ecard_release_resources(ec);
out:
return ret;
}
static void __devexit acornscsi_remove(struct expansion_card *ec)
{
struct Scsi_Host *host = ecard_get_drvdata(ec);
AS_Host *ashost = (AS_Host *)host->hostdata;
ecard_set_drvdata(ec, NULL);
scsi_remove_host(host);
/*
* Put card into RESET state
*/
writeb(0x80, ashost->fast + PAGE_REG);
free_irq(host->irq, ashost);
msgqueue_free(&ashost->scsi.msgs);
queue_free(&ashost->queues.disconnected);
queue_free(&ashost->queues.issue);
ecardm_iounmap(ec, ashost->fast);
ecardm_iounmap(ec, ashost->base);
scsi_host_put(host);
ecard_release_resources(ec);
}
static const struct ecard_id acornscsi_cids[] = {
{ MANU_ACORN, PROD_ACORN_SCSI },
{ 0xffff, 0xffff },
};
static struct ecard_driver acornscsi_driver = {
.probe = acornscsi_probe,
.remove = __devexit_p(acornscsi_remove),
.id_table = acornscsi_cids,
.drv = {
.name = "acornscsi",
},
};
static int __init acornscsi_init(void)
{
return ecard_register_driver(&acornscsi_driver);
}
static void __exit acornscsi_exit(void)
{
ecard_remove_driver(&acornscsi_driver);
}
module_init(acornscsi_init);
module_exit(acornscsi_exit);
MODULE_AUTHOR("Russell King");
MODULE_DESCRIPTION("AcornSCSI driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
KylinUI/android_kernel_htc_m7 | drivers/net/phy/national.c | 5499 | 4360 | /*
* drivers/net/phy/national.c
*
* Driver for National Semiconductor PHYs
*
* Author: Stuart Menefy <stuart.menefy@st.com>
* Maintainer: Giuseppe Cavallaro <peppe.cavallaro@st.com>
*
* Copyright (c) 2008 STMicroelectronics Limited
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/phy.h>
#include <linux/netdevice.h>
/* DP83865 phy identifier values */
#define DP83865_PHY_ID 0x20005c7a
#define DP83865_INT_STATUS 0x14
#define DP83865_INT_MASK 0x15
#define DP83865_INT_CLEAR 0x17
#define DP83865_INT_REMOTE_FAULT 0x0008
#define DP83865_INT_ANE_COMPLETED 0x0010
#define DP83865_INT_LINK_CHANGE 0xe000
#define DP83865_INT_MASK_DEFAULT (DP83865_INT_REMOTE_FAULT | \
DP83865_INT_ANE_COMPLETED | \
DP83865_INT_LINK_CHANGE)
/* Advanced proprietary configuration */
#define NS_EXP_MEM_CTL 0x16
#define NS_EXP_MEM_DATA 0x1d
#define NS_EXP_MEM_ADD 0x1e
#define LED_CTRL_REG 0x13
#define AN_FALLBACK_AN 0x0001
#define AN_FALLBACK_CRC 0x0002
#define AN_FALLBACK_IE 0x0004
#define ALL_FALLBACK_ON (AN_FALLBACK_AN | AN_FALLBACK_CRC | AN_FALLBACK_IE)
enum hdx_loopback {
hdx_loopback_on = 0,
hdx_loopback_off = 1,
};
static u8 ns_exp_read(struct phy_device *phydev, u16 reg)
{
phy_write(phydev, NS_EXP_MEM_ADD, reg);
return phy_read(phydev, NS_EXP_MEM_DATA);
}
static void ns_exp_write(struct phy_device *phydev, u16 reg, u8 data)
{
phy_write(phydev, NS_EXP_MEM_ADD, reg);
phy_write(phydev, NS_EXP_MEM_DATA, data);
}
static int ns_config_intr(struct phy_device *phydev)
{
int err;
if (phydev->interrupts == PHY_INTERRUPT_ENABLED)
err = phy_write(phydev, DP83865_INT_MASK,
DP83865_INT_MASK_DEFAULT);
else
err = phy_write(phydev, DP83865_INT_MASK, 0);
return err;
}
static int ns_ack_interrupt(struct phy_device *phydev)
{
int ret = phy_read(phydev, DP83865_INT_STATUS);
if (ret < 0)
return ret;
/* Clear the interrupt status bit by writing a “1”
* to the corresponding bit in INT_CLEAR (2:0 are reserved) */
ret = phy_write(phydev, DP83865_INT_CLEAR, ret & ~0x7);
return ret;
}
static void ns_giga_speed_fallback(struct phy_device *phydev, int mode)
{
int bmcr = phy_read(phydev, MII_BMCR);
phy_write(phydev, MII_BMCR, (bmcr | BMCR_PDOWN));
/* Enable 8 bit expended memory read/write (no auto increment) */
phy_write(phydev, NS_EXP_MEM_CTL, 0);
phy_write(phydev, NS_EXP_MEM_ADD, 0x1C0);
phy_write(phydev, NS_EXP_MEM_DATA, 0x0008);
phy_write(phydev, MII_BMCR, (bmcr & ~BMCR_PDOWN));
phy_write(phydev, LED_CTRL_REG, mode);
}
static void ns_10_base_t_hdx_loopack(struct phy_device *phydev, int disable)
{
if (disable)
ns_exp_write(phydev, 0x1c0, ns_exp_read(phydev, 0x1c0) | 1);
else
ns_exp_write(phydev, 0x1c0,
ns_exp_read(phydev, 0x1c0) & 0xfffe);
printk(KERN_DEBUG "DP83865 PHY: 10BASE-T HDX loopback %s\n",
(ns_exp_read(phydev, 0x1c0) & 0x0001) ? "off" : "on");
}
static int ns_config_init(struct phy_device *phydev)
{
ns_giga_speed_fallback(phydev, ALL_FALLBACK_ON);
/* In the latest MAC or switches design, the 10 Mbps loopback
is desired to be turned off. */
ns_10_base_t_hdx_loopack(phydev, hdx_loopback_off);
return ns_ack_interrupt(phydev);
}
static struct phy_driver dp83865_driver = {
.phy_id = DP83865_PHY_ID,
.phy_id_mask = 0xfffffff0,
.name = "NatSemi DP83865",
.features = PHY_GBIT_FEATURES | SUPPORTED_Pause | SUPPORTED_Asym_Pause,
.flags = PHY_HAS_INTERRUPT,
.config_init = ns_config_init,
.config_aneg = genphy_config_aneg,
.read_status = genphy_read_status,
.ack_interrupt = ns_ack_interrupt,
.config_intr = ns_config_intr,
.driver = {.owner = THIS_MODULE,}
};
static int __init ns_init(void)
{
return phy_driver_register(&dp83865_driver);
}
static void __exit ns_exit(void)
{
phy_driver_unregister(&dp83865_driver);
}
MODULE_DESCRIPTION("NatSemi PHY driver");
MODULE_AUTHOR("Stuart Menefy");
MODULE_LICENSE("GPL");
module_init(ns_init);
module_exit(ns_exit);
static struct mdio_device_id __maybe_unused ns_tbl[] = {
{ DP83865_PHY_ID, 0xfffffff0 },
{ }
};
MODULE_DEVICE_TABLE(mdio, ns_tbl);
| gpl-2.0 |
Nokius/android_kernel_yotaphone2 | drivers/net/phy/national.c | 5499 | 4360 | /*
* drivers/net/phy/national.c
*
* Driver for National Semiconductor PHYs
*
* Author: Stuart Menefy <stuart.menefy@st.com>
* Maintainer: Giuseppe Cavallaro <peppe.cavallaro@st.com>
*
* Copyright (c) 2008 STMicroelectronics Limited
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/phy.h>
#include <linux/netdevice.h>
/* DP83865 phy identifier values */
#define DP83865_PHY_ID 0x20005c7a
#define DP83865_INT_STATUS 0x14
#define DP83865_INT_MASK 0x15
#define DP83865_INT_CLEAR 0x17
#define DP83865_INT_REMOTE_FAULT 0x0008
#define DP83865_INT_ANE_COMPLETED 0x0010
#define DP83865_INT_LINK_CHANGE 0xe000
#define DP83865_INT_MASK_DEFAULT (DP83865_INT_REMOTE_FAULT | \
DP83865_INT_ANE_COMPLETED | \
DP83865_INT_LINK_CHANGE)
/* Advanced proprietary configuration */
#define NS_EXP_MEM_CTL 0x16
#define NS_EXP_MEM_DATA 0x1d
#define NS_EXP_MEM_ADD 0x1e
#define LED_CTRL_REG 0x13
#define AN_FALLBACK_AN 0x0001
#define AN_FALLBACK_CRC 0x0002
#define AN_FALLBACK_IE 0x0004
#define ALL_FALLBACK_ON (AN_FALLBACK_AN | AN_FALLBACK_CRC | AN_FALLBACK_IE)
enum hdx_loopback {
hdx_loopback_on = 0,
hdx_loopback_off = 1,
};
static u8 ns_exp_read(struct phy_device *phydev, u16 reg)
{
phy_write(phydev, NS_EXP_MEM_ADD, reg);
return phy_read(phydev, NS_EXP_MEM_DATA);
}
static void ns_exp_write(struct phy_device *phydev, u16 reg, u8 data)
{
phy_write(phydev, NS_EXP_MEM_ADD, reg);
phy_write(phydev, NS_EXP_MEM_DATA, data);
}
static int ns_config_intr(struct phy_device *phydev)
{
int err;
if (phydev->interrupts == PHY_INTERRUPT_ENABLED)
err = phy_write(phydev, DP83865_INT_MASK,
DP83865_INT_MASK_DEFAULT);
else
err = phy_write(phydev, DP83865_INT_MASK, 0);
return err;
}
static int ns_ack_interrupt(struct phy_device *phydev)
{
int ret = phy_read(phydev, DP83865_INT_STATUS);
if (ret < 0)
return ret;
/* Clear the interrupt status bit by writing a “1”
* to the corresponding bit in INT_CLEAR (2:0 are reserved) */
ret = phy_write(phydev, DP83865_INT_CLEAR, ret & ~0x7);
return ret;
}
static void ns_giga_speed_fallback(struct phy_device *phydev, int mode)
{
int bmcr = phy_read(phydev, MII_BMCR);
phy_write(phydev, MII_BMCR, (bmcr | BMCR_PDOWN));
/* Enable 8 bit expended memory read/write (no auto increment) */
phy_write(phydev, NS_EXP_MEM_CTL, 0);
phy_write(phydev, NS_EXP_MEM_ADD, 0x1C0);
phy_write(phydev, NS_EXP_MEM_DATA, 0x0008);
phy_write(phydev, MII_BMCR, (bmcr & ~BMCR_PDOWN));
phy_write(phydev, LED_CTRL_REG, mode);
}
static void ns_10_base_t_hdx_loopack(struct phy_device *phydev, int disable)
{
if (disable)
ns_exp_write(phydev, 0x1c0, ns_exp_read(phydev, 0x1c0) | 1);
else
ns_exp_write(phydev, 0x1c0,
ns_exp_read(phydev, 0x1c0) & 0xfffe);
printk(KERN_DEBUG "DP83865 PHY: 10BASE-T HDX loopback %s\n",
(ns_exp_read(phydev, 0x1c0) & 0x0001) ? "off" : "on");
}
static int ns_config_init(struct phy_device *phydev)
{
ns_giga_speed_fallback(phydev, ALL_FALLBACK_ON);
/* In the latest MAC or switches design, the 10 Mbps loopback
is desired to be turned off. */
ns_10_base_t_hdx_loopack(phydev, hdx_loopback_off);
return ns_ack_interrupt(phydev);
}
static struct phy_driver dp83865_driver = {
.phy_id = DP83865_PHY_ID,
.phy_id_mask = 0xfffffff0,
.name = "NatSemi DP83865",
.features = PHY_GBIT_FEATURES | SUPPORTED_Pause | SUPPORTED_Asym_Pause,
.flags = PHY_HAS_INTERRUPT,
.config_init = ns_config_init,
.config_aneg = genphy_config_aneg,
.read_status = genphy_read_status,
.ack_interrupt = ns_ack_interrupt,
.config_intr = ns_config_intr,
.driver = {.owner = THIS_MODULE,}
};
static int __init ns_init(void)
{
return phy_driver_register(&dp83865_driver);
}
static void __exit ns_exit(void)
{
phy_driver_unregister(&dp83865_driver);
}
MODULE_DESCRIPTION("NatSemi PHY driver");
MODULE_AUTHOR("Stuart Menefy");
MODULE_LICENSE("GPL");
module_init(ns_init);
module_exit(ns_exit);
static struct mdio_device_id __maybe_unused ns_tbl[] = {
{ DP83865_PHY_ID, 0xfffffff0 },
{ }
};
MODULE_DEVICE_TABLE(mdio, ns_tbl);
| gpl-2.0 |
defconoi/L-Kernel-Mako | drivers/mtd/chips/map_rom.c | 8315 | 2791 | /*
* Common code to handle map devices which are simple ROM
* (C) 2000 Red Hat. GPL'd.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <asm/io.h>
#include <asm/byteorder.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
static int maprom_read (struct mtd_info *, loff_t, size_t, size_t *, u_char *);
static int maprom_write (struct mtd_info *, loff_t, size_t, size_t *, const u_char *);
static void maprom_nop (struct mtd_info *);
static struct mtd_info *map_rom_probe(struct map_info *map);
static int maprom_erase (struct mtd_info *mtd, struct erase_info *info);
static unsigned long maprom_unmapped_area(struct mtd_info *, unsigned long,
unsigned long, unsigned long);
static struct mtd_chip_driver maprom_chipdrv = {
.probe = map_rom_probe,
.name = "map_rom",
.module = THIS_MODULE
};
static struct mtd_info *map_rom_probe(struct map_info *map)
{
struct mtd_info *mtd;
mtd = kzalloc(sizeof(*mtd), GFP_KERNEL);
if (!mtd)
return NULL;
map->fldrv = &maprom_chipdrv;
mtd->priv = map;
mtd->name = map->name;
mtd->type = MTD_ROM;
mtd->size = map->size;
mtd->_get_unmapped_area = maprom_unmapped_area;
mtd->_read = maprom_read;
mtd->_write = maprom_write;
mtd->_sync = maprom_nop;
mtd->_erase = maprom_erase;
mtd->flags = MTD_CAP_ROM;
mtd->erasesize = map->size;
mtd->writesize = 1;
__module_get(THIS_MODULE);
return mtd;
}
/*
* Allow NOMMU mmap() to directly map the device (if not NULL)
* - return the address to which the offset maps
* - return -ENOSYS to indicate refusal to do the mapping
*/
static unsigned long maprom_unmapped_area(struct mtd_info *mtd,
unsigned long len,
unsigned long offset,
unsigned long flags)
{
struct map_info *map = mtd->priv;
return (unsigned long) map->virt + offset;
}
static int maprom_read (struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen, u_char *buf)
{
struct map_info *map = mtd->priv;
map_copy_from(map, buf, from, len);
*retlen = len;
return 0;
}
static void maprom_nop(struct mtd_info *mtd)
{
/* Nothing to see here */
}
static int maprom_write (struct mtd_info *mtd, loff_t to, size_t len, size_t *retlen, const u_char *buf)
{
return -EROFS;
}
static int maprom_erase (struct mtd_info *mtd, struct erase_info *info)
{
/* We do our best 8) */
return -EROFS;
}
static int __init map_rom_init(void)
{
register_mtd_chip_driver(&maprom_chipdrv);
return 0;
}
static void __exit map_rom_exit(void)
{
unregister_mtd_chip_driver(&maprom_chipdrv);
}
module_init(map_rom_init);
module_exit(map_rom_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("David Woodhouse <dwmw2@infradead.org>");
MODULE_DESCRIPTION("MTD chip driver for ROM chips");
| gpl-2.0 |
MuddyPlump/android_kernel_motorola_msm8226 | net/core/netevent.c | 8571 | 2103 | /*
* Network event notifiers
*
* Authors:
* Tom Tucker <tom@opengridcomputing.com>
* Steve Wise <swise@opengridcomputing.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.
*
* Fixes:
*/
#include <linux/rtnetlink.h>
#include <linux/notifier.h>
#include <linux/export.h>
#include <net/netevent.h>
static ATOMIC_NOTIFIER_HEAD(netevent_notif_chain);
/**
* register_netevent_notifier - register a netevent notifier block
* @nb: notifier
*
* Register a notifier to be called when a netevent occurs.
* The notifier passed is linked into the kernel structures and must
* not be reused until it has been unregistered. A negative errno code
* is returned on a failure.
*/
int register_netevent_notifier(struct notifier_block *nb)
{
int err;
err = atomic_notifier_chain_register(&netevent_notif_chain, nb);
return err;
}
EXPORT_SYMBOL_GPL(register_netevent_notifier);
/**
* netevent_unregister_notifier - unregister a netevent notifier block
* @nb: notifier
*
* Unregister a notifier previously registered by
* register_neigh_notifier(). The notifier is unlinked into the
* kernel structures and may then be reused. A negative errno code
* is returned on a failure.
*/
int unregister_netevent_notifier(struct notifier_block *nb)
{
return atomic_notifier_chain_unregister(&netevent_notif_chain, nb);
}
EXPORT_SYMBOL_GPL(unregister_netevent_notifier);
/**
* call_netevent_notifiers - call all netevent notifier blocks
* @val: value passed unmodified to notifier function
* @v: pointer passed unmodified to notifier function
*
* Call all neighbour notifier blocks. Parameters and return value
* are as for notifier_call_chain().
*/
int call_netevent_notifiers(unsigned long val, void *v)
{
return atomic_notifier_call_chain(&netevent_notif_chain, val, v);
}
EXPORT_SYMBOL_GPL(call_netevent_notifiers);
| gpl-2.0 |
GuneetAtwal/kernel_a210 | drivers/ide/ide-probe.c | 10619 | 38318 | /*
* Copyright (C) 1994-1998 Linus Torvalds & authors (see below)
* Copyright (C) 2005, 2007 Bartlomiej Zolnierkiewicz
*/
/*
* Mostly written by Mark Lord <mlord@pobox.com>
* and Gadi Oxman <gadio@netvision.net.il>
* and Andre Hedrick <andre@linux-ide.org>
*
* See linux/MAINTAINERS for address of current maintainer.
*
* This is the IDE probe module, as evolved from hd.c and ide.c.
*
* -- increase WAIT_PIDENTIFY to avoid CD-ROM locking at boot
* by Andrea Arcangeli
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/major.h>
#include <linux/errno.h>
#include <linux/genhd.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/ide.h>
#include <linux/spinlock.h>
#include <linux/kmod.h>
#include <linux/pci.h>
#include <linux/scatterlist.h>
#include <asm/byteorder.h>
#include <asm/irq.h>
#include <asm/uaccess.h>
#include <asm/io.h>
/**
* generic_id - add a generic drive id
* @drive: drive to make an ID block for
*
* Add a fake id field to the drive we are passed. This allows
* use to skip a ton of NULL checks (which people always miss)
* and make drive properties unconditional outside of this file
*/
static void generic_id(ide_drive_t *drive)
{
u16 *id = drive->id;
id[ATA_ID_CUR_CYLS] = id[ATA_ID_CYLS] = drive->cyl;
id[ATA_ID_CUR_HEADS] = id[ATA_ID_HEADS] = drive->head;
id[ATA_ID_CUR_SECTORS] = id[ATA_ID_SECTORS] = drive->sect;
}
static void ide_disk_init_chs(ide_drive_t *drive)
{
u16 *id = drive->id;
/* Extract geometry if we did not already have one for the drive */
if (!drive->cyl || !drive->head || !drive->sect) {
drive->cyl = drive->bios_cyl = id[ATA_ID_CYLS];
drive->head = drive->bios_head = id[ATA_ID_HEADS];
drive->sect = drive->bios_sect = id[ATA_ID_SECTORS];
}
/* Handle logical geometry translation by the drive */
if (ata_id_current_chs_valid(id)) {
drive->cyl = id[ATA_ID_CUR_CYLS];
drive->head = id[ATA_ID_CUR_HEADS];
drive->sect = id[ATA_ID_CUR_SECTORS];
}
/* Use physical geometry if what we have still makes no sense */
if (drive->head > 16 && id[ATA_ID_HEADS] && id[ATA_ID_HEADS] <= 16) {
drive->cyl = id[ATA_ID_CYLS];
drive->head = id[ATA_ID_HEADS];
drive->sect = id[ATA_ID_SECTORS];
}
}
static void ide_disk_init_mult_count(ide_drive_t *drive)
{
u16 *id = drive->id;
u8 max_multsect = id[ATA_ID_MAX_MULTSECT] & 0xff;
if (max_multsect) {
if ((max_multsect / 2) > 1)
id[ATA_ID_MULTSECT] = max_multsect | 0x100;
else
id[ATA_ID_MULTSECT] &= ~0x1ff;
drive->mult_req = id[ATA_ID_MULTSECT] & 0xff;
if (drive->mult_req)
drive->special_flags |= IDE_SFLAG_SET_MULTMODE;
}
}
static void ide_classify_ata_dev(ide_drive_t *drive)
{
u16 *id = drive->id;
char *m = (char *)&id[ATA_ID_PROD];
int is_cfa = ata_id_is_cfa(id);
/* CF devices are *not* removable in Linux definition of the term */
if (is_cfa == 0 && (id[ATA_ID_CONFIG] & (1 << 7)))
drive->dev_flags |= IDE_DFLAG_REMOVABLE;
drive->media = ide_disk;
if (!ata_id_has_unload(drive->id))
drive->dev_flags |= IDE_DFLAG_NO_UNLOAD;
printk(KERN_INFO "%s: %s, %s DISK drive\n", drive->name, m,
is_cfa ? "CFA" : "ATA");
}
static void ide_classify_atapi_dev(ide_drive_t *drive)
{
u16 *id = drive->id;
char *m = (char *)&id[ATA_ID_PROD];
u8 type = (id[ATA_ID_CONFIG] >> 8) & 0x1f;
printk(KERN_INFO "%s: %s, ATAPI ", drive->name, m);
switch (type) {
case ide_floppy:
if (!strstr(m, "CD-ROM")) {
if (!strstr(m, "oppy") &&
!strstr(m, "poyp") &&
!strstr(m, "ZIP"))
printk(KERN_CONT "cdrom or floppy?, assuming ");
if (drive->media != ide_cdrom) {
printk(KERN_CONT "FLOPPY");
drive->dev_flags |= IDE_DFLAG_REMOVABLE;
break;
}
}
/* Early cdrom models used zero */
type = ide_cdrom;
case ide_cdrom:
drive->dev_flags |= IDE_DFLAG_REMOVABLE;
#ifdef CONFIG_PPC
/* kludge for Apple PowerBook internal zip */
if (!strstr(m, "CD-ROM") && strstr(m, "ZIP")) {
printk(KERN_CONT "FLOPPY");
type = ide_floppy;
break;
}
#endif
printk(KERN_CONT "CD/DVD-ROM");
break;
case ide_tape:
printk(KERN_CONT "TAPE");
break;
case ide_optical:
printk(KERN_CONT "OPTICAL");
drive->dev_flags |= IDE_DFLAG_REMOVABLE;
break;
default:
printk(KERN_CONT "UNKNOWN (type %d)", type);
break;
}
printk(KERN_CONT " drive\n");
drive->media = type;
/* an ATAPI device ignores DRDY */
drive->ready_stat = 0;
if (ata_id_cdb_intr(id))
drive->atapi_flags |= IDE_AFLAG_DRQ_INTERRUPT;
drive->dev_flags |= IDE_DFLAG_DOORLOCKING;
/* we don't do head unloading on ATAPI devices */
drive->dev_flags |= IDE_DFLAG_NO_UNLOAD;
}
/**
* do_identify - identify a drive
* @drive: drive to identify
* @cmd: command used
* @id: buffer for IDENTIFY data
*
* Called when we have issued a drive identify command to
* read and parse the results. This function is run with
* interrupts disabled.
*/
static void do_identify(ide_drive_t *drive, u8 cmd, u16 *id)
{
ide_hwif_t *hwif = drive->hwif;
char *m = (char *)&id[ATA_ID_PROD];
unsigned long flags;
int bswap = 1;
/* local CPU only; some systems need this */
local_irq_save(flags);
/* read 512 bytes of id info */
hwif->tp_ops->input_data(drive, NULL, id, SECTOR_SIZE);
local_irq_restore(flags);
drive->dev_flags |= IDE_DFLAG_ID_READ;
#ifdef DEBUG
printk(KERN_INFO "%s: dumping identify data\n", drive->name);
ide_dump_identify((u8 *)id);
#endif
ide_fix_driveid(id);
/*
* ATA_CMD_ID_ATA returns little-endian info,
* ATA_CMD_ID_ATAPI *usually* returns little-endian info.
*/
if (cmd == ATA_CMD_ID_ATAPI) {
if ((m[0] == 'N' && m[1] == 'E') || /* NEC */
(m[0] == 'F' && m[1] == 'X') || /* Mitsumi */
(m[0] == 'P' && m[1] == 'i')) /* Pioneer */
/* Vertos drives may still be weird */
bswap ^= 1;
}
ide_fixstring(m, ATA_ID_PROD_LEN, bswap);
ide_fixstring((char *)&id[ATA_ID_FW_REV], ATA_ID_FW_REV_LEN, bswap);
ide_fixstring((char *)&id[ATA_ID_SERNO], ATA_ID_SERNO_LEN, bswap);
/* we depend on this a lot! */
m[ATA_ID_PROD_LEN - 1] = '\0';
if (strstr(m, "E X A B Y T E N E S T"))
drive->dev_flags &= ~IDE_DFLAG_PRESENT;
else
drive->dev_flags |= IDE_DFLAG_PRESENT;
}
/**
* ide_dev_read_id - send ATA/ATAPI IDENTIFY command
* @drive: drive to identify
* @cmd: command to use
* @id: buffer for IDENTIFY data
* @irq_ctx: flag set when called from the IRQ context
*
* Sends an ATA(PI) IDENTIFY request to a drive and waits for a response.
*
* Returns: 0 device was identified
* 1 device timed-out (no response to identify request)
* 2 device aborted the command (refused to identify itself)
*/
int ide_dev_read_id(ide_drive_t *drive, u8 cmd, u16 *id, int irq_ctx)
{
ide_hwif_t *hwif = drive->hwif;
struct ide_io_ports *io_ports = &hwif->io_ports;
const struct ide_tp_ops *tp_ops = hwif->tp_ops;
int use_altstatus = 0, rc;
unsigned long timeout;
u8 s = 0, a = 0;
/*
* Disable device IRQ. Otherwise we'll get spurious interrupts
* during the identify phase that the IRQ handler isn't expecting.
*/
if (io_ports->ctl_addr)
tp_ops->write_devctl(hwif, ATA_NIEN | ATA_DEVCTL_OBS);
/* take a deep breath */
if (irq_ctx)
mdelay(50);
else
msleep(50);
if (io_ports->ctl_addr &&
(hwif->host_flags & IDE_HFLAG_BROKEN_ALTSTATUS) == 0) {
a = tp_ops->read_altstatus(hwif);
s = tp_ops->read_status(hwif);
if ((a ^ s) & ~ATA_IDX)
/* ancient Seagate drives, broken interfaces */
printk(KERN_INFO "%s: probing with STATUS(0x%02x) "
"instead of ALTSTATUS(0x%02x)\n",
drive->name, s, a);
else
/* use non-intrusive polling */
use_altstatus = 1;
}
/* set features register for atapi
* identify command to be sure of reply
*/
if (cmd == ATA_CMD_ID_ATAPI) {
struct ide_taskfile tf;
memset(&tf, 0, sizeof(tf));
/* disable DMA & overlap */
tp_ops->tf_load(drive, &tf, IDE_VALID_FEATURE);
}
/* ask drive for ID */
tp_ops->exec_command(hwif, cmd);
timeout = ((cmd == ATA_CMD_ID_ATA) ? WAIT_WORSTCASE : WAIT_PIDENTIFY) / 2;
/* wait for IRQ and ATA_DRQ */
if (irq_ctx) {
rc = __ide_wait_stat(drive, ATA_DRQ, BAD_R_STAT, timeout, &s);
if (rc)
return 1;
} else {
rc = ide_busy_sleep(drive, timeout, use_altstatus);
if (rc)
return 1;
msleep(50);
s = tp_ops->read_status(hwif);
}
if (OK_STAT(s, ATA_DRQ, BAD_R_STAT)) {
/* drive returned ID */
do_identify(drive, cmd, id);
/* drive responded with ID */
rc = 0;
/* clear drive IRQ */
(void)tp_ops->read_status(hwif);
} else {
/* drive refused ID */
rc = 2;
}
return rc;
}
int ide_busy_sleep(ide_drive_t *drive, unsigned long timeout, int altstatus)
{
ide_hwif_t *hwif = drive->hwif;
u8 stat;
timeout += jiffies;
do {
msleep(50); /* give drive a breather */
stat = altstatus ? hwif->tp_ops->read_altstatus(hwif)
: hwif->tp_ops->read_status(hwif);
if ((stat & ATA_BUSY) == 0)
return 0;
} while (time_before(jiffies, timeout));
printk(KERN_ERR "%s: timeout in %s\n", drive->name, __func__);
return 1; /* drive timed-out */
}
static u8 ide_read_device(ide_drive_t *drive)
{
struct ide_taskfile tf;
drive->hwif->tp_ops->tf_read(drive, &tf, IDE_VALID_DEVICE);
return tf.device;
}
/**
* do_probe - probe an IDE device
* @drive: drive to probe
* @cmd: command to use
*
* do_probe() has the difficult job of finding a drive if it exists,
* without getting hung up if it doesn't exist, without trampling on
* ethernet cards, and without leaving any IRQs dangling to haunt us later.
*
* If a drive is "known" to exist (from CMOS or kernel parameters),
* but does not respond right away, the probe will "hang in there"
* for the maximum wait time (about 30 seconds), otherwise it will
* exit much more quickly.
*
* Returns: 0 device was identified
* 1 device timed-out (no response to identify request)
* 2 device aborted the command (refused to identify itself)
* 3 bad status from device (possible for ATAPI drives)
* 4 probe was not attempted because failure was obvious
*/
static int do_probe (ide_drive_t *drive, u8 cmd)
{
ide_hwif_t *hwif = drive->hwif;
const struct ide_tp_ops *tp_ops = hwif->tp_ops;
u16 *id = drive->id;
int rc;
u8 present = !!(drive->dev_flags & IDE_DFLAG_PRESENT), stat;
/* avoid waiting for inappropriate probes */
if (present && drive->media != ide_disk && cmd == ATA_CMD_ID_ATA)
return 4;
#ifdef DEBUG
printk(KERN_INFO "probing for %s: present=%d, media=%d, probetype=%s\n",
drive->name, present, drive->media,
(cmd == ATA_CMD_ID_ATA) ? "ATA" : "ATAPI");
#endif
/* needed for some systems
* (e.g. crw9624 as drive0 with disk as slave)
*/
msleep(50);
tp_ops->dev_select(drive);
msleep(50);
if (ide_read_device(drive) != drive->select && present == 0) {
if (drive->dn & 1) {
/* exit with drive0 selected */
tp_ops->dev_select(hwif->devices[0]);
/* allow ATA_BUSY to assert & clear */
msleep(50);
}
/* no i/f present: mmm.. this should be a 4 -ml */
return 3;
}
stat = tp_ops->read_status(hwif);
if (OK_STAT(stat, ATA_DRDY, ATA_BUSY) ||
present || cmd == ATA_CMD_ID_ATAPI) {
rc = ide_dev_read_id(drive, cmd, id, 0);
if (rc)
/* failed: try again */
rc = ide_dev_read_id(drive, cmd, id, 0);
stat = tp_ops->read_status(hwif);
if (stat == (ATA_BUSY | ATA_DRDY))
return 4;
if (rc == 1 && cmd == ATA_CMD_ID_ATAPI) {
printk(KERN_ERR "%s: no response (status = 0x%02x), "
"resetting drive\n", drive->name, stat);
msleep(50);
tp_ops->dev_select(drive);
msleep(50);
tp_ops->exec_command(hwif, ATA_CMD_DEV_RESET);
(void)ide_busy_sleep(drive, WAIT_WORSTCASE, 0);
rc = ide_dev_read_id(drive, cmd, id, 0);
}
/* ensure drive IRQ is clear */
stat = tp_ops->read_status(hwif);
if (rc == 1)
printk(KERN_ERR "%s: no response (status = 0x%02x)\n",
drive->name, stat);
} else {
/* not present or maybe ATAPI */
rc = 3;
}
if (drive->dn & 1) {
/* exit with drive0 selected */
tp_ops->dev_select(hwif->devices[0]);
msleep(50);
/* ensure drive irq is clear */
(void)tp_ops->read_status(hwif);
}
return rc;
}
/**
* probe_for_drives - upper level drive probe
* @drive: drive to probe for
*
* probe_for_drive() tests for existence of a given drive using do_probe()
* and presents things to the user as needed.
*
* Returns: 0 no device was found
* 1 device was found
* (note: IDE_DFLAG_PRESENT might still be not set)
*/
static u8 probe_for_drive(ide_drive_t *drive)
{
char *m;
int rc;
u8 cmd;
drive->dev_flags &= ~IDE_DFLAG_ID_READ;
m = (char *)&drive->id[ATA_ID_PROD];
strcpy(m, "UNKNOWN");
/* skip probing? */
if ((drive->dev_flags & IDE_DFLAG_NOPROBE) == 0) {
/* if !(success||timed-out) */
cmd = ATA_CMD_ID_ATA;
rc = do_probe(drive, cmd);
if (rc >= 2) {
/* look for ATAPI device */
cmd = ATA_CMD_ID_ATAPI;
rc = do_probe(drive, cmd);
}
if ((drive->dev_flags & IDE_DFLAG_PRESENT) == 0)
return 0;
/* identification failed? */
if ((drive->dev_flags & IDE_DFLAG_ID_READ) == 0) {
if (drive->media == ide_disk) {
printk(KERN_INFO "%s: non-IDE drive, CHS=%d/%d/%d\n",
drive->name, drive->cyl,
drive->head, drive->sect);
} else if (drive->media == ide_cdrom) {
printk(KERN_INFO "%s: ATAPI cdrom (?)\n", drive->name);
} else {
/* nuke it */
printk(KERN_WARNING "%s: Unknown device on bus refused identification. Ignoring.\n", drive->name);
drive->dev_flags &= ~IDE_DFLAG_PRESENT;
}
} else {
if (cmd == ATA_CMD_ID_ATAPI)
ide_classify_atapi_dev(drive);
else
ide_classify_ata_dev(drive);
}
}
if ((drive->dev_flags & IDE_DFLAG_PRESENT) == 0)
return 0;
/* The drive wasn't being helpful. Add generic info only */
if ((drive->dev_flags & IDE_DFLAG_ID_READ) == 0) {
generic_id(drive);
return 1;
}
if (drive->media == ide_disk) {
ide_disk_init_chs(drive);
ide_disk_init_mult_count(drive);
}
return 1;
}
static void hwif_release_dev(struct device *dev)
{
ide_hwif_t *hwif = container_of(dev, ide_hwif_t, gendev);
complete(&hwif->gendev_rel_comp);
}
static int ide_register_port(ide_hwif_t *hwif)
{
int ret;
/* register with global device tree */
dev_set_name(&hwif->gendev, hwif->name);
dev_set_drvdata(&hwif->gendev, hwif);
if (hwif->gendev.parent == NULL)
hwif->gendev.parent = hwif->dev;
hwif->gendev.release = hwif_release_dev;
ret = device_register(&hwif->gendev);
if (ret < 0) {
printk(KERN_WARNING "IDE: %s: device_register error: %d\n",
__func__, ret);
goto out;
}
hwif->portdev = device_create(ide_port_class, &hwif->gendev,
MKDEV(0, 0), hwif, hwif->name);
if (IS_ERR(hwif->portdev)) {
ret = PTR_ERR(hwif->portdev);
device_unregister(&hwif->gendev);
}
out:
return ret;
}
/**
* ide_port_wait_ready - wait for port to become ready
* @hwif: IDE port
*
* This is needed on some PPCs and a bunch of BIOS-less embedded
* platforms. Typical cases are:
*
* - The firmware hard reset the disk before booting the kernel,
* the drive is still doing it's poweron-reset sequence, that
* can take up to 30 seconds.
*
* - The firmware does nothing (or no firmware), the device is
* still in POST state (same as above actually).
*
* - Some CD/DVD/Writer combo drives tend to drive the bus during
* their reset sequence even when they are non-selected slave
* devices, thus preventing discovery of the main HD.
*
* Doing this wait-for-non-busy should not harm any existing
* configuration and fix some issues like the above.
*
* BenH.
*
* Returns 0 on success, error code (< 0) otherwise.
*/
static int ide_port_wait_ready(ide_hwif_t *hwif)
{
const struct ide_tp_ops *tp_ops = hwif->tp_ops;
ide_drive_t *drive;
int i, rc;
printk(KERN_DEBUG "Probing IDE interface %s...\n", hwif->name);
/* Let HW settle down a bit from whatever init state we
* come from */
mdelay(2);
/* Wait for BSY bit to go away, spec timeout is 30 seconds,
* I know of at least one disk who takes 31 seconds, I use 35
* here to be safe
*/
rc = ide_wait_not_busy(hwif, 35000);
if (rc)
return rc;
/* Now make sure both master & slave are ready */
ide_port_for_each_dev(i, drive, hwif) {
/* Ignore disks that we will not probe for later. */
if ((drive->dev_flags & IDE_DFLAG_NOPROBE) == 0 ||
(drive->dev_flags & IDE_DFLAG_PRESENT)) {
tp_ops->dev_select(drive);
tp_ops->write_devctl(hwif, ATA_DEVCTL_OBS);
mdelay(2);
rc = ide_wait_not_busy(hwif, 35000);
if (rc)
goto out;
} else
printk(KERN_DEBUG "%s: ide_wait_not_busy() skipped\n",
drive->name);
}
out:
/* Exit function with master reselected (let's be sane) */
if (i)
tp_ops->dev_select(hwif->devices[0]);
return rc;
}
/**
* ide_undecoded_slave - look for bad CF adapters
* @dev1: slave device
*
* Analyse the drives on the interface and attempt to decide if we
* have the same drive viewed twice. This occurs with crap CF adapters
* and PCMCIA sometimes.
*/
void ide_undecoded_slave(ide_drive_t *dev1)
{
ide_drive_t *dev0 = dev1->hwif->devices[0];
if ((dev1->dn & 1) == 0 || (dev0->dev_flags & IDE_DFLAG_PRESENT) == 0)
return;
/* If the models don't match they are not the same product */
if (strcmp((char *)&dev0->id[ATA_ID_PROD],
(char *)&dev1->id[ATA_ID_PROD]))
return;
/* Serial numbers do not match */
if (strncmp((char *)&dev0->id[ATA_ID_SERNO],
(char *)&dev1->id[ATA_ID_SERNO], ATA_ID_SERNO_LEN))
return;
/* No serial number, thankfully very rare for CF */
if (*(char *)&dev0->id[ATA_ID_SERNO] == 0)
return;
/* Appears to be an IDE flash adapter with decode bugs */
printk(KERN_WARNING "ide-probe: ignoring undecoded slave\n");
dev1->dev_flags &= ~IDE_DFLAG_PRESENT;
}
EXPORT_SYMBOL_GPL(ide_undecoded_slave);
static int ide_probe_port(ide_hwif_t *hwif)
{
ide_drive_t *drive;
unsigned int irqd;
int i, rc = -ENODEV;
BUG_ON(hwif->present);
if ((hwif->devices[0]->dev_flags & IDE_DFLAG_NOPROBE) &&
(hwif->devices[1]->dev_flags & IDE_DFLAG_NOPROBE))
return -EACCES;
/*
* We must always disable IRQ, as probe_for_drive will assert IRQ, but
* we'll install our IRQ driver much later...
*/
irqd = hwif->irq;
if (irqd)
disable_irq(hwif->irq);
if (ide_port_wait_ready(hwif) == -EBUSY)
printk(KERN_DEBUG "%s: Wait for ready failed before probe !\n", hwif->name);
/*
* Second drive should only exist if first drive was found,
* but a lot of cdrom drives are configured as single slaves.
*/
ide_port_for_each_dev(i, drive, hwif) {
(void) probe_for_drive(drive);
if (drive->dev_flags & IDE_DFLAG_PRESENT)
rc = 0;
}
/*
* Use cached IRQ number. It might be (and is...) changed by probe
* code above
*/
if (irqd)
enable_irq(irqd);
return rc;
}
static void ide_port_tune_devices(ide_hwif_t *hwif)
{
const struct ide_port_ops *port_ops = hwif->port_ops;
ide_drive_t *drive;
int i;
ide_port_for_each_present_dev(i, drive, hwif) {
ide_check_nien_quirk_list(drive);
if (port_ops && port_ops->quirkproc)
port_ops->quirkproc(drive);
}
ide_port_for_each_present_dev(i, drive, hwif) {
ide_set_max_pio(drive);
drive->dev_flags |= IDE_DFLAG_NICE1;
if (hwif->dma_ops)
ide_set_dma(drive);
}
}
/*
* init request queue
*/
static int ide_init_queue(ide_drive_t *drive)
{
struct request_queue *q;
ide_hwif_t *hwif = drive->hwif;
int max_sectors = 256;
int max_sg_entries = PRD_ENTRIES;
/*
* Our default set up assumes the normal IDE case,
* that is 64K segmenting, standard PRD setup
* and LBA28. Some drivers then impose their own
* limits and LBA48 we could raise it but as yet
* do not.
*/
q = blk_init_queue_node(do_ide_request, NULL, hwif_to_node(hwif));
if (!q)
return 1;
q->queuedata = drive;
blk_queue_segment_boundary(q, 0xffff);
if (hwif->rqsize < max_sectors)
max_sectors = hwif->rqsize;
blk_queue_max_hw_sectors(q, max_sectors);
#ifdef CONFIG_PCI
/* When we have an IOMMU, we may have a problem where pci_map_sg()
* creates segments that don't completely match our boundary
* requirements and thus need to be broken up again. Because it
* doesn't align properly either, we may actually have to break up
* to more segments than what was we got in the first place, a max
* worst case is twice as many.
* This will be fixed once we teach pci_map_sg() about our boundary
* requirements, hopefully soon. *FIXME*
*/
if (!PCI_DMA_BUS_IS_PHYS)
max_sg_entries >>= 1;
#endif /* CONFIG_PCI */
blk_queue_max_segments(q, max_sg_entries);
/* assign drive queue */
drive->queue = q;
/* needs drive->queue to be set */
ide_toggle_bounce(drive, 1);
return 0;
}
static DEFINE_MUTEX(ide_cfg_mtx);
/*
* For any present drive:
* - allocate the block device queue
*/
static int ide_port_setup_devices(ide_hwif_t *hwif)
{
ide_drive_t *drive;
int i, j = 0;
mutex_lock(&ide_cfg_mtx);
ide_port_for_each_present_dev(i, drive, hwif) {
if (ide_init_queue(drive)) {
printk(KERN_ERR "ide: failed to init %s\n",
drive->name);
drive->dev_flags &= ~IDE_DFLAG_PRESENT;
continue;
}
j++;
}
mutex_unlock(&ide_cfg_mtx);
return j;
}
static void ide_host_enable_irqs(struct ide_host *host)
{
ide_hwif_t *hwif;
int i;
ide_host_for_each_port(i, hwif, host) {
if (hwif == NULL)
continue;
/* clear any pending IRQs */
hwif->tp_ops->read_status(hwif);
/* unmask IRQs */
if (hwif->io_ports.ctl_addr)
hwif->tp_ops->write_devctl(hwif, ATA_DEVCTL_OBS);
}
}
/*
* This routine sets up the IRQ for an IDE interface.
*/
static int init_irq (ide_hwif_t *hwif)
{
struct ide_io_ports *io_ports = &hwif->io_ports;
struct ide_host *host = hwif->host;
irq_handler_t irq_handler = host->irq_handler;
int sa = host->irq_flags;
if (irq_handler == NULL)
irq_handler = ide_intr;
if (request_irq(hwif->irq, irq_handler, sa, hwif->name, hwif))
goto out_up;
#if !defined(__mc68000__)
printk(KERN_INFO "%s at 0x%03lx-0x%03lx,0x%03lx on irq %d", hwif->name,
io_ports->data_addr, io_ports->status_addr,
io_ports->ctl_addr, hwif->irq);
#else
printk(KERN_INFO "%s at 0x%08lx on irq %d", hwif->name,
io_ports->data_addr, hwif->irq);
#endif /* __mc68000__ */
if (hwif->host->host_flags & IDE_HFLAG_SERIALIZE)
printk(KERN_CONT " (serialized)");
printk(KERN_CONT "\n");
return 0;
out_up:
return 1;
}
static int ata_lock(dev_t dev, void *data)
{
/* FIXME: we want to pin hwif down */
return 0;
}
static struct kobject *ata_probe(dev_t dev, int *part, void *data)
{
ide_hwif_t *hwif = data;
int unit = *part >> PARTN_BITS;
ide_drive_t *drive = hwif->devices[unit];
if ((drive->dev_flags & IDE_DFLAG_PRESENT) == 0)
return NULL;
if (drive->media == ide_disk)
request_module("ide-disk");
if (drive->media == ide_cdrom || drive->media == ide_optical)
request_module("ide-cd");
if (drive->media == ide_tape)
request_module("ide-tape");
if (drive->media == ide_floppy)
request_module("ide-floppy");
return NULL;
}
static struct kobject *exact_match(dev_t dev, int *part, void *data)
{
struct gendisk *p = data;
*part &= (1 << PARTN_BITS) - 1;
return &disk_to_dev(p)->kobj;
}
static int exact_lock(dev_t dev, void *data)
{
struct gendisk *p = data;
if (!get_disk(p))
return -1;
return 0;
}
void ide_register_region(struct gendisk *disk)
{
blk_register_region(MKDEV(disk->major, disk->first_minor),
disk->minors, NULL, exact_match, exact_lock, disk);
}
EXPORT_SYMBOL_GPL(ide_register_region);
void ide_unregister_region(struct gendisk *disk)
{
blk_unregister_region(MKDEV(disk->major, disk->first_minor),
disk->minors);
}
EXPORT_SYMBOL_GPL(ide_unregister_region);
void ide_init_disk(struct gendisk *disk, ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
unsigned int unit = drive->dn & 1;
disk->major = hwif->major;
disk->first_minor = unit << PARTN_BITS;
sprintf(disk->disk_name, "hd%c", 'a' + hwif->index * MAX_DRIVES + unit);
disk->queue = drive->queue;
}
EXPORT_SYMBOL_GPL(ide_init_disk);
static void drive_release_dev (struct device *dev)
{
ide_drive_t *drive = container_of(dev, ide_drive_t, gendev);
ide_proc_unregister_device(drive);
blk_cleanup_queue(drive->queue);
drive->queue = NULL;
drive->dev_flags &= ~IDE_DFLAG_PRESENT;
complete(&drive->gendev_rel_comp);
}
static int hwif_init(ide_hwif_t *hwif)
{
if (!hwif->irq) {
printk(KERN_ERR "%s: disabled, no IRQ\n", hwif->name);
return 0;
}
if (register_blkdev(hwif->major, hwif->name))
return 0;
if (!hwif->sg_max_nents)
hwif->sg_max_nents = PRD_ENTRIES;
hwif->sg_table = kmalloc(sizeof(struct scatterlist)*hwif->sg_max_nents,
GFP_KERNEL);
if (!hwif->sg_table) {
printk(KERN_ERR "%s: unable to allocate SG table.\n", hwif->name);
goto out;
}
sg_init_table(hwif->sg_table, hwif->sg_max_nents);
if (init_irq(hwif)) {
printk(KERN_ERR "%s: disabled, unable to get IRQ %d\n",
hwif->name, hwif->irq);
goto out;
}
blk_register_region(MKDEV(hwif->major, 0), MAX_DRIVES << PARTN_BITS,
THIS_MODULE, ata_probe, ata_lock, hwif);
return 1;
out:
unregister_blkdev(hwif->major, hwif->name);
return 0;
}
static void hwif_register_devices(ide_hwif_t *hwif)
{
ide_drive_t *drive;
unsigned int i;
ide_port_for_each_present_dev(i, drive, hwif) {
struct device *dev = &drive->gendev;
int ret;
dev_set_name(dev, "%u.%u", hwif->index, i);
dev_set_drvdata(dev, drive);
dev->parent = &hwif->gendev;
dev->bus = &ide_bus_type;
dev->release = drive_release_dev;
ret = device_register(dev);
if (ret < 0)
printk(KERN_WARNING "IDE: %s: device_register error: "
"%d\n", __func__, ret);
}
}
static void ide_port_init_devices(ide_hwif_t *hwif)
{
const struct ide_port_ops *port_ops = hwif->port_ops;
ide_drive_t *drive;
int i;
ide_port_for_each_dev(i, drive, hwif) {
drive->dn = i + hwif->channel * 2;
if (hwif->host_flags & IDE_HFLAG_IO_32BIT)
drive->io_32bit = 1;
if (hwif->host_flags & IDE_HFLAG_NO_IO_32BIT)
drive->dev_flags |= IDE_DFLAG_NO_IO_32BIT;
if (hwif->host_flags & IDE_HFLAG_UNMASK_IRQS)
drive->dev_flags |= IDE_DFLAG_UNMASK;
if (hwif->host_flags & IDE_HFLAG_NO_UNMASK_IRQS)
drive->dev_flags |= IDE_DFLAG_NO_UNMASK;
drive->pio_mode = XFER_PIO_0;
if (port_ops && port_ops->init_dev)
port_ops->init_dev(drive);
}
}
static void ide_init_port(ide_hwif_t *hwif, unsigned int port,
const struct ide_port_info *d)
{
hwif->channel = port;
hwif->chipset = d->chipset ? d->chipset : ide_pci;
if (d->init_iops)
d->init_iops(hwif);
/* ->host_flags may be set by ->init_iops (or even earlier...) */
hwif->host_flags |= d->host_flags;
hwif->pio_mask = d->pio_mask;
if (d->tp_ops)
hwif->tp_ops = d->tp_ops;
/* ->set_pio_mode for DTC2278 is currently limited to port 0 */
if ((hwif->host_flags & IDE_HFLAG_DTC2278) == 0 || hwif->channel == 0)
hwif->port_ops = d->port_ops;
hwif->swdma_mask = d->swdma_mask;
hwif->mwdma_mask = d->mwdma_mask;
hwif->ultra_mask = d->udma_mask;
if ((d->host_flags & IDE_HFLAG_NO_DMA) == 0) {
int rc;
hwif->dma_ops = d->dma_ops;
if (d->init_dma)
rc = d->init_dma(hwif, d);
else
rc = ide_hwif_setup_dma(hwif, d);
if (rc < 0) {
printk(KERN_INFO "%s: DMA disabled\n", hwif->name);
hwif->dma_ops = NULL;
hwif->dma_base = 0;
hwif->swdma_mask = 0;
hwif->mwdma_mask = 0;
hwif->ultra_mask = 0;
}
}
if ((d->host_flags & IDE_HFLAG_SERIALIZE) ||
((d->host_flags & IDE_HFLAG_SERIALIZE_DMA) && hwif->dma_base))
hwif->host->host_flags |= IDE_HFLAG_SERIALIZE;
if (d->max_sectors)
hwif->rqsize = d->max_sectors;
else {
if ((hwif->host_flags & IDE_HFLAG_NO_LBA48) ||
(hwif->host_flags & IDE_HFLAG_NO_LBA48_DMA))
hwif->rqsize = 256;
else
hwif->rqsize = 65536;
}
/* call chipset specific routine for each enabled port */
if (d->init_hwif)
d->init_hwif(hwif);
}
static void ide_port_cable_detect(ide_hwif_t *hwif)
{
const struct ide_port_ops *port_ops = hwif->port_ops;
if (port_ops && port_ops->cable_detect && (hwif->ultra_mask & 0x78)) {
if (hwif->cbl != ATA_CBL_PATA40_SHORT)
hwif->cbl = port_ops->cable_detect(hwif);
}
}
static const u8 ide_hwif_to_major[] =
{ IDE0_MAJOR, IDE1_MAJOR, IDE2_MAJOR, IDE3_MAJOR, IDE4_MAJOR,
IDE5_MAJOR, IDE6_MAJOR, IDE7_MAJOR, IDE8_MAJOR, IDE9_MAJOR };
static void ide_port_init_devices_data(ide_hwif_t *hwif)
{
ide_drive_t *drive;
int i;
ide_port_for_each_dev(i, drive, hwif) {
u8 j = (hwif->index * MAX_DRIVES) + i;
u16 *saved_id = drive->id;
memset(drive, 0, sizeof(*drive));
memset(saved_id, 0, SECTOR_SIZE);
drive->id = saved_id;
drive->media = ide_disk;
drive->select = (i << 4) | ATA_DEVICE_OBS;
drive->hwif = hwif;
drive->ready_stat = ATA_DRDY;
drive->bad_wstat = BAD_W_STAT;
drive->special_flags = IDE_SFLAG_RECALIBRATE |
IDE_SFLAG_SET_GEOMETRY;
drive->name[0] = 'h';
drive->name[1] = 'd';
drive->name[2] = 'a' + j;
drive->max_failures = IDE_DEFAULT_MAX_FAILURES;
INIT_LIST_HEAD(&drive->list);
init_completion(&drive->gendev_rel_comp);
}
}
static void ide_init_port_data(ide_hwif_t *hwif, unsigned int index)
{
/* fill in any non-zero initial values */
hwif->index = index;
hwif->major = ide_hwif_to_major[index];
hwif->name[0] = 'i';
hwif->name[1] = 'd';
hwif->name[2] = 'e';
hwif->name[3] = '0' + index;
spin_lock_init(&hwif->lock);
init_timer(&hwif->timer);
hwif->timer.function = &ide_timer_expiry;
hwif->timer.data = (unsigned long)hwif;
init_completion(&hwif->gendev_rel_comp);
hwif->tp_ops = &default_tp_ops;
ide_port_init_devices_data(hwif);
}
static void ide_init_port_hw(ide_hwif_t *hwif, struct ide_hw *hw)
{
memcpy(&hwif->io_ports, &hw->io_ports, sizeof(hwif->io_ports));
hwif->irq = hw->irq;
hwif->dev = hw->dev;
hwif->gendev.parent = hw->parent ? hw->parent : hw->dev;
hwif->config_data = hw->config;
}
static unsigned int ide_indexes;
/**
* ide_find_port_slot - find free port slot
* @d: IDE port info
*
* Return the new port slot index or -ENOENT if we are out of free slots.
*/
static int ide_find_port_slot(const struct ide_port_info *d)
{
int idx = -ENOENT;
u8 bootable = (d && (d->host_flags & IDE_HFLAG_NON_BOOTABLE)) ? 0 : 1;
u8 i = (d && (d->host_flags & IDE_HFLAG_QD_2ND_PORT)) ? 1 : 0;
/*
* Claim an unassigned slot.
*
* Give preference to claiming other slots before claiming ide0/ide1,
* just in case there's another interface yet-to-be-scanned
* which uses ports 0x1f0/0x170 (the ide0/ide1 defaults).
*
* Unless there is a bootable card that does not use the standard
* ports 0x1f0/0x170 (the ide0/ide1 defaults).
*/
mutex_lock(&ide_cfg_mtx);
if (bootable) {
if ((ide_indexes | i) != (1 << MAX_HWIFS) - 1)
idx = ffz(ide_indexes | i);
} else {
if ((ide_indexes | 3) != (1 << MAX_HWIFS) - 1)
idx = ffz(ide_indexes | 3);
else if ((ide_indexes & 3) != 3)
idx = ffz(ide_indexes);
}
if (idx >= 0)
ide_indexes |= (1 << idx);
mutex_unlock(&ide_cfg_mtx);
return idx;
}
static void ide_free_port_slot(int idx)
{
mutex_lock(&ide_cfg_mtx);
ide_indexes &= ~(1 << idx);
mutex_unlock(&ide_cfg_mtx);
}
static void ide_port_free_devices(ide_hwif_t *hwif)
{
ide_drive_t *drive;
int i;
ide_port_for_each_dev(i, drive, hwif) {
kfree(drive->id);
kfree(drive);
}
}
static int ide_port_alloc_devices(ide_hwif_t *hwif, int node)
{
int i;
for (i = 0; i < MAX_DRIVES; i++) {
ide_drive_t *drive;
drive = kzalloc_node(sizeof(*drive), GFP_KERNEL, node);
if (drive == NULL)
goto out_nomem;
/*
* In order to keep things simple we have an id
* block for all drives at all times. If the device
* is pre ATA or refuses ATA/ATAPI identify we
* will add faked data to this.
*
* Also note that 0 everywhere means "can't do X"
*/
drive->id = kzalloc_node(SECTOR_SIZE, GFP_KERNEL, node);
if (drive->id == NULL)
goto out_nomem;
hwif->devices[i] = drive;
}
return 0;
out_nomem:
ide_port_free_devices(hwif);
return -ENOMEM;
}
struct ide_host *ide_host_alloc(const struct ide_port_info *d,
struct ide_hw **hws, unsigned int n_ports)
{
struct ide_host *host;
struct device *dev = hws[0] ? hws[0]->dev : NULL;
int node = dev ? dev_to_node(dev) : -1;
int i;
host = kzalloc_node(sizeof(*host), GFP_KERNEL, node);
if (host == NULL)
return NULL;
for (i = 0; i < n_ports; i++) {
ide_hwif_t *hwif;
int idx;
if (hws[i] == NULL)
continue;
hwif = kzalloc_node(sizeof(*hwif), GFP_KERNEL, node);
if (hwif == NULL)
continue;
if (ide_port_alloc_devices(hwif, node) < 0) {
kfree(hwif);
continue;
}
idx = ide_find_port_slot(d);
if (idx < 0) {
printk(KERN_ERR "%s: no free slot for interface\n",
d ? d->name : "ide");
ide_port_free_devices(hwif);
kfree(hwif);
continue;
}
ide_init_port_data(hwif, idx);
hwif->host = host;
host->ports[i] = hwif;
host->n_ports++;
}
if (host->n_ports == 0) {
kfree(host);
return NULL;
}
host->dev[0] = dev;
if (d) {
host->init_chipset = d->init_chipset;
host->get_lock = d->get_lock;
host->release_lock = d->release_lock;
host->host_flags = d->host_flags;
host->irq_flags = d->irq_flags;
}
return host;
}
EXPORT_SYMBOL_GPL(ide_host_alloc);
static void ide_port_free(ide_hwif_t *hwif)
{
ide_port_free_devices(hwif);
ide_free_port_slot(hwif->index);
kfree(hwif);
}
static void ide_disable_port(ide_hwif_t *hwif)
{
struct ide_host *host = hwif->host;
int i;
printk(KERN_INFO "%s: disabling port\n", hwif->name);
for (i = 0; i < MAX_HOST_PORTS; i++) {
if (host->ports[i] == hwif) {
host->ports[i] = NULL;
host->n_ports--;
}
}
ide_port_free(hwif);
}
int ide_host_register(struct ide_host *host, const struct ide_port_info *d,
struct ide_hw **hws)
{
ide_hwif_t *hwif, *mate = NULL;
int i, j = 0;
ide_host_for_each_port(i, hwif, host) {
if (hwif == NULL) {
mate = NULL;
continue;
}
ide_init_port_hw(hwif, hws[i]);
ide_port_apply_params(hwif);
if ((i & 1) && mate) {
hwif->mate = mate;
mate->mate = hwif;
}
mate = (i & 1) ? NULL : hwif;
ide_init_port(hwif, i & 1, d);
ide_port_cable_detect(hwif);
hwif->port_flags |= IDE_PFLAG_PROBING;
ide_port_init_devices(hwif);
}
ide_host_for_each_port(i, hwif, host) {
if (hwif == NULL)
continue;
if (ide_probe_port(hwif) == 0)
hwif->present = 1;
hwif->port_flags &= ~IDE_PFLAG_PROBING;
if ((hwif->host_flags & IDE_HFLAG_4DRIVES) == 0 ||
hwif->mate == NULL || hwif->mate->present == 0) {
if (ide_register_port(hwif)) {
ide_disable_port(hwif);
continue;
}
}
if (hwif->present)
ide_port_tune_devices(hwif);
}
ide_host_enable_irqs(host);
ide_host_for_each_port(i, hwif, host) {
if (hwif == NULL)
continue;
if (hwif_init(hwif) == 0) {
printk(KERN_INFO "%s: failed to initialize IDE "
"interface\n", hwif->name);
device_unregister(&hwif->gendev);
ide_disable_port(hwif);
continue;
}
if (hwif->present)
if (ide_port_setup_devices(hwif) == 0) {
hwif->present = 0;
continue;
}
j++;
ide_acpi_init_port(hwif);
if (hwif->present)
ide_acpi_port_init_devices(hwif);
}
ide_host_for_each_port(i, hwif, host) {
if (hwif == NULL)
continue;
ide_sysfs_register_port(hwif);
ide_proc_register_port(hwif);
if (hwif->present) {
ide_proc_port_register_devices(hwif);
hwif_register_devices(hwif);
}
}
return j ? 0 : -1;
}
EXPORT_SYMBOL_GPL(ide_host_register);
int ide_host_add(const struct ide_port_info *d, struct ide_hw **hws,
unsigned int n_ports, struct ide_host **hostp)
{
struct ide_host *host;
int rc;
host = ide_host_alloc(d, hws, n_ports);
if (host == NULL)
return -ENOMEM;
rc = ide_host_register(host, d, hws);
if (rc) {
ide_host_free(host);
return rc;
}
if (hostp)
*hostp = host;
return 0;
}
EXPORT_SYMBOL_GPL(ide_host_add);
static void __ide_port_unregister_devices(ide_hwif_t *hwif)
{
ide_drive_t *drive;
int i;
ide_port_for_each_present_dev(i, drive, hwif) {
device_unregister(&drive->gendev);
wait_for_completion(&drive->gendev_rel_comp);
}
}
void ide_port_unregister_devices(ide_hwif_t *hwif)
{
mutex_lock(&ide_cfg_mtx);
__ide_port_unregister_devices(hwif);
hwif->present = 0;
ide_port_init_devices_data(hwif);
mutex_unlock(&ide_cfg_mtx);
}
EXPORT_SYMBOL_GPL(ide_port_unregister_devices);
/**
* ide_unregister - free an IDE interface
* @hwif: IDE interface
*
* Perform the final unregister of an IDE interface.
*
* Locking:
* The caller must not hold the IDE locks.
*
* It is up to the caller to be sure there is no pending I/O here,
* and that the interface will not be reopened (present/vanishing
* locking isn't yet done BTW).
*/
static void ide_unregister(ide_hwif_t *hwif)
{
BUG_ON(in_interrupt());
BUG_ON(irqs_disabled());
mutex_lock(&ide_cfg_mtx);
if (hwif->present) {
__ide_port_unregister_devices(hwif);
hwif->present = 0;
}
ide_proc_unregister_port(hwif);
free_irq(hwif->irq, hwif);
device_unregister(hwif->portdev);
device_unregister(&hwif->gendev);
wait_for_completion(&hwif->gendev_rel_comp);
/*
* Remove us from the kernel's knowledge
*/
blk_unregister_region(MKDEV(hwif->major, 0), MAX_DRIVES<<PARTN_BITS);
kfree(hwif->sg_table);
unregister_blkdev(hwif->major, hwif->name);
ide_release_dma_engine(hwif);
mutex_unlock(&ide_cfg_mtx);
}
void ide_host_free(struct ide_host *host)
{
ide_hwif_t *hwif;
int i;
ide_host_for_each_port(i, hwif, host) {
if (hwif)
ide_port_free(hwif);
}
kfree(host);
}
EXPORT_SYMBOL_GPL(ide_host_free);
void ide_host_remove(struct ide_host *host)
{
ide_hwif_t *hwif;
int i;
ide_host_for_each_port(i, hwif, host) {
if (hwif)
ide_unregister(hwif);
}
ide_host_free(host);
}
EXPORT_SYMBOL_GPL(ide_host_remove);
void ide_port_scan(ide_hwif_t *hwif)
{
int rc;
ide_port_apply_params(hwif);
ide_port_cable_detect(hwif);
hwif->port_flags |= IDE_PFLAG_PROBING;
ide_port_init_devices(hwif);
rc = ide_probe_port(hwif);
hwif->port_flags &= ~IDE_PFLAG_PROBING;
if (rc < 0)
return;
hwif->present = 1;
ide_port_tune_devices(hwif);
ide_port_setup_devices(hwif);
ide_acpi_port_init_devices(hwif);
hwif_register_devices(hwif);
ide_proc_port_register_devices(hwif);
}
EXPORT_SYMBOL_GPL(ide_port_scan);
| gpl-2.0 |
RepoBackups/android_kernel_caf_msm8960 | drivers/ide/ide-probe.c | 10619 | 38318 | /*
* Copyright (C) 1994-1998 Linus Torvalds & authors (see below)
* Copyright (C) 2005, 2007 Bartlomiej Zolnierkiewicz
*/
/*
* Mostly written by Mark Lord <mlord@pobox.com>
* and Gadi Oxman <gadio@netvision.net.il>
* and Andre Hedrick <andre@linux-ide.org>
*
* See linux/MAINTAINERS for address of current maintainer.
*
* This is the IDE probe module, as evolved from hd.c and ide.c.
*
* -- increase WAIT_PIDENTIFY to avoid CD-ROM locking at boot
* by Andrea Arcangeli
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/major.h>
#include <linux/errno.h>
#include <linux/genhd.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/ide.h>
#include <linux/spinlock.h>
#include <linux/kmod.h>
#include <linux/pci.h>
#include <linux/scatterlist.h>
#include <asm/byteorder.h>
#include <asm/irq.h>
#include <asm/uaccess.h>
#include <asm/io.h>
/**
* generic_id - add a generic drive id
* @drive: drive to make an ID block for
*
* Add a fake id field to the drive we are passed. This allows
* use to skip a ton of NULL checks (which people always miss)
* and make drive properties unconditional outside of this file
*/
static void generic_id(ide_drive_t *drive)
{
u16 *id = drive->id;
id[ATA_ID_CUR_CYLS] = id[ATA_ID_CYLS] = drive->cyl;
id[ATA_ID_CUR_HEADS] = id[ATA_ID_HEADS] = drive->head;
id[ATA_ID_CUR_SECTORS] = id[ATA_ID_SECTORS] = drive->sect;
}
static void ide_disk_init_chs(ide_drive_t *drive)
{
u16 *id = drive->id;
/* Extract geometry if we did not already have one for the drive */
if (!drive->cyl || !drive->head || !drive->sect) {
drive->cyl = drive->bios_cyl = id[ATA_ID_CYLS];
drive->head = drive->bios_head = id[ATA_ID_HEADS];
drive->sect = drive->bios_sect = id[ATA_ID_SECTORS];
}
/* Handle logical geometry translation by the drive */
if (ata_id_current_chs_valid(id)) {
drive->cyl = id[ATA_ID_CUR_CYLS];
drive->head = id[ATA_ID_CUR_HEADS];
drive->sect = id[ATA_ID_CUR_SECTORS];
}
/* Use physical geometry if what we have still makes no sense */
if (drive->head > 16 && id[ATA_ID_HEADS] && id[ATA_ID_HEADS] <= 16) {
drive->cyl = id[ATA_ID_CYLS];
drive->head = id[ATA_ID_HEADS];
drive->sect = id[ATA_ID_SECTORS];
}
}
static void ide_disk_init_mult_count(ide_drive_t *drive)
{
u16 *id = drive->id;
u8 max_multsect = id[ATA_ID_MAX_MULTSECT] & 0xff;
if (max_multsect) {
if ((max_multsect / 2) > 1)
id[ATA_ID_MULTSECT] = max_multsect | 0x100;
else
id[ATA_ID_MULTSECT] &= ~0x1ff;
drive->mult_req = id[ATA_ID_MULTSECT] & 0xff;
if (drive->mult_req)
drive->special_flags |= IDE_SFLAG_SET_MULTMODE;
}
}
static void ide_classify_ata_dev(ide_drive_t *drive)
{
u16 *id = drive->id;
char *m = (char *)&id[ATA_ID_PROD];
int is_cfa = ata_id_is_cfa(id);
/* CF devices are *not* removable in Linux definition of the term */
if (is_cfa == 0 && (id[ATA_ID_CONFIG] & (1 << 7)))
drive->dev_flags |= IDE_DFLAG_REMOVABLE;
drive->media = ide_disk;
if (!ata_id_has_unload(drive->id))
drive->dev_flags |= IDE_DFLAG_NO_UNLOAD;
printk(KERN_INFO "%s: %s, %s DISK drive\n", drive->name, m,
is_cfa ? "CFA" : "ATA");
}
static void ide_classify_atapi_dev(ide_drive_t *drive)
{
u16 *id = drive->id;
char *m = (char *)&id[ATA_ID_PROD];
u8 type = (id[ATA_ID_CONFIG] >> 8) & 0x1f;
printk(KERN_INFO "%s: %s, ATAPI ", drive->name, m);
switch (type) {
case ide_floppy:
if (!strstr(m, "CD-ROM")) {
if (!strstr(m, "oppy") &&
!strstr(m, "poyp") &&
!strstr(m, "ZIP"))
printk(KERN_CONT "cdrom or floppy?, assuming ");
if (drive->media != ide_cdrom) {
printk(KERN_CONT "FLOPPY");
drive->dev_flags |= IDE_DFLAG_REMOVABLE;
break;
}
}
/* Early cdrom models used zero */
type = ide_cdrom;
case ide_cdrom:
drive->dev_flags |= IDE_DFLAG_REMOVABLE;
#ifdef CONFIG_PPC
/* kludge for Apple PowerBook internal zip */
if (!strstr(m, "CD-ROM") && strstr(m, "ZIP")) {
printk(KERN_CONT "FLOPPY");
type = ide_floppy;
break;
}
#endif
printk(KERN_CONT "CD/DVD-ROM");
break;
case ide_tape:
printk(KERN_CONT "TAPE");
break;
case ide_optical:
printk(KERN_CONT "OPTICAL");
drive->dev_flags |= IDE_DFLAG_REMOVABLE;
break;
default:
printk(KERN_CONT "UNKNOWN (type %d)", type);
break;
}
printk(KERN_CONT " drive\n");
drive->media = type;
/* an ATAPI device ignores DRDY */
drive->ready_stat = 0;
if (ata_id_cdb_intr(id))
drive->atapi_flags |= IDE_AFLAG_DRQ_INTERRUPT;
drive->dev_flags |= IDE_DFLAG_DOORLOCKING;
/* we don't do head unloading on ATAPI devices */
drive->dev_flags |= IDE_DFLAG_NO_UNLOAD;
}
/**
* do_identify - identify a drive
* @drive: drive to identify
* @cmd: command used
* @id: buffer for IDENTIFY data
*
* Called when we have issued a drive identify command to
* read and parse the results. This function is run with
* interrupts disabled.
*/
static void do_identify(ide_drive_t *drive, u8 cmd, u16 *id)
{
ide_hwif_t *hwif = drive->hwif;
char *m = (char *)&id[ATA_ID_PROD];
unsigned long flags;
int bswap = 1;
/* local CPU only; some systems need this */
local_irq_save(flags);
/* read 512 bytes of id info */
hwif->tp_ops->input_data(drive, NULL, id, SECTOR_SIZE);
local_irq_restore(flags);
drive->dev_flags |= IDE_DFLAG_ID_READ;
#ifdef DEBUG
printk(KERN_INFO "%s: dumping identify data\n", drive->name);
ide_dump_identify((u8 *)id);
#endif
ide_fix_driveid(id);
/*
* ATA_CMD_ID_ATA returns little-endian info,
* ATA_CMD_ID_ATAPI *usually* returns little-endian info.
*/
if (cmd == ATA_CMD_ID_ATAPI) {
if ((m[0] == 'N' && m[1] == 'E') || /* NEC */
(m[0] == 'F' && m[1] == 'X') || /* Mitsumi */
(m[0] == 'P' && m[1] == 'i')) /* Pioneer */
/* Vertos drives may still be weird */
bswap ^= 1;
}
ide_fixstring(m, ATA_ID_PROD_LEN, bswap);
ide_fixstring((char *)&id[ATA_ID_FW_REV], ATA_ID_FW_REV_LEN, bswap);
ide_fixstring((char *)&id[ATA_ID_SERNO], ATA_ID_SERNO_LEN, bswap);
/* we depend on this a lot! */
m[ATA_ID_PROD_LEN - 1] = '\0';
if (strstr(m, "E X A B Y T E N E S T"))
drive->dev_flags &= ~IDE_DFLAG_PRESENT;
else
drive->dev_flags |= IDE_DFLAG_PRESENT;
}
/**
* ide_dev_read_id - send ATA/ATAPI IDENTIFY command
* @drive: drive to identify
* @cmd: command to use
* @id: buffer for IDENTIFY data
* @irq_ctx: flag set when called from the IRQ context
*
* Sends an ATA(PI) IDENTIFY request to a drive and waits for a response.
*
* Returns: 0 device was identified
* 1 device timed-out (no response to identify request)
* 2 device aborted the command (refused to identify itself)
*/
int ide_dev_read_id(ide_drive_t *drive, u8 cmd, u16 *id, int irq_ctx)
{
ide_hwif_t *hwif = drive->hwif;
struct ide_io_ports *io_ports = &hwif->io_ports;
const struct ide_tp_ops *tp_ops = hwif->tp_ops;
int use_altstatus = 0, rc;
unsigned long timeout;
u8 s = 0, a = 0;
/*
* Disable device IRQ. Otherwise we'll get spurious interrupts
* during the identify phase that the IRQ handler isn't expecting.
*/
if (io_ports->ctl_addr)
tp_ops->write_devctl(hwif, ATA_NIEN | ATA_DEVCTL_OBS);
/* take a deep breath */
if (irq_ctx)
mdelay(50);
else
msleep(50);
if (io_ports->ctl_addr &&
(hwif->host_flags & IDE_HFLAG_BROKEN_ALTSTATUS) == 0) {
a = tp_ops->read_altstatus(hwif);
s = tp_ops->read_status(hwif);
if ((a ^ s) & ~ATA_IDX)
/* ancient Seagate drives, broken interfaces */
printk(KERN_INFO "%s: probing with STATUS(0x%02x) "
"instead of ALTSTATUS(0x%02x)\n",
drive->name, s, a);
else
/* use non-intrusive polling */
use_altstatus = 1;
}
/* set features register for atapi
* identify command to be sure of reply
*/
if (cmd == ATA_CMD_ID_ATAPI) {
struct ide_taskfile tf;
memset(&tf, 0, sizeof(tf));
/* disable DMA & overlap */
tp_ops->tf_load(drive, &tf, IDE_VALID_FEATURE);
}
/* ask drive for ID */
tp_ops->exec_command(hwif, cmd);
timeout = ((cmd == ATA_CMD_ID_ATA) ? WAIT_WORSTCASE : WAIT_PIDENTIFY) / 2;
/* wait for IRQ and ATA_DRQ */
if (irq_ctx) {
rc = __ide_wait_stat(drive, ATA_DRQ, BAD_R_STAT, timeout, &s);
if (rc)
return 1;
} else {
rc = ide_busy_sleep(drive, timeout, use_altstatus);
if (rc)
return 1;
msleep(50);
s = tp_ops->read_status(hwif);
}
if (OK_STAT(s, ATA_DRQ, BAD_R_STAT)) {
/* drive returned ID */
do_identify(drive, cmd, id);
/* drive responded with ID */
rc = 0;
/* clear drive IRQ */
(void)tp_ops->read_status(hwif);
} else {
/* drive refused ID */
rc = 2;
}
return rc;
}
int ide_busy_sleep(ide_drive_t *drive, unsigned long timeout, int altstatus)
{
ide_hwif_t *hwif = drive->hwif;
u8 stat;
timeout += jiffies;
do {
msleep(50); /* give drive a breather */
stat = altstatus ? hwif->tp_ops->read_altstatus(hwif)
: hwif->tp_ops->read_status(hwif);
if ((stat & ATA_BUSY) == 0)
return 0;
} while (time_before(jiffies, timeout));
printk(KERN_ERR "%s: timeout in %s\n", drive->name, __func__);
return 1; /* drive timed-out */
}
static u8 ide_read_device(ide_drive_t *drive)
{
struct ide_taskfile tf;
drive->hwif->tp_ops->tf_read(drive, &tf, IDE_VALID_DEVICE);
return tf.device;
}
/**
* do_probe - probe an IDE device
* @drive: drive to probe
* @cmd: command to use
*
* do_probe() has the difficult job of finding a drive if it exists,
* without getting hung up if it doesn't exist, without trampling on
* ethernet cards, and without leaving any IRQs dangling to haunt us later.
*
* If a drive is "known" to exist (from CMOS or kernel parameters),
* but does not respond right away, the probe will "hang in there"
* for the maximum wait time (about 30 seconds), otherwise it will
* exit much more quickly.
*
* Returns: 0 device was identified
* 1 device timed-out (no response to identify request)
* 2 device aborted the command (refused to identify itself)
* 3 bad status from device (possible for ATAPI drives)
* 4 probe was not attempted because failure was obvious
*/
static int do_probe (ide_drive_t *drive, u8 cmd)
{
ide_hwif_t *hwif = drive->hwif;
const struct ide_tp_ops *tp_ops = hwif->tp_ops;
u16 *id = drive->id;
int rc;
u8 present = !!(drive->dev_flags & IDE_DFLAG_PRESENT), stat;
/* avoid waiting for inappropriate probes */
if (present && drive->media != ide_disk && cmd == ATA_CMD_ID_ATA)
return 4;
#ifdef DEBUG
printk(KERN_INFO "probing for %s: present=%d, media=%d, probetype=%s\n",
drive->name, present, drive->media,
(cmd == ATA_CMD_ID_ATA) ? "ATA" : "ATAPI");
#endif
/* needed for some systems
* (e.g. crw9624 as drive0 with disk as slave)
*/
msleep(50);
tp_ops->dev_select(drive);
msleep(50);
if (ide_read_device(drive) != drive->select && present == 0) {
if (drive->dn & 1) {
/* exit with drive0 selected */
tp_ops->dev_select(hwif->devices[0]);
/* allow ATA_BUSY to assert & clear */
msleep(50);
}
/* no i/f present: mmm.. this should be a 4 -ml */
return 3;
}
stat = tp_ops->read_status(hwif);
if (OK_STAT(stat, ATA_DRDY, ATA_BUSY) ||
present || cmd == ATA_CMD_ID_ATAPI) {
rc = ide_dev_read_id(drive, cmd, id, 0);
if (rc)
/* failed: try again */
rc = ide_dev_read_id(drive, cmd, id, 0);
stat = tp_ops->read_status(hwif);
if (stat == (ATA_BUSY | ATA_DRDY))
return 4;
if (rc == 1 && cmd == ATA_CMD_ID_ATAPI) {
printk(KERN_ERR "%s: no response (status = 0x%02x), "
"resetting drive\n", drive->name, stat);
msleep(50);
tp_ops->dev_select(drive);
msleep(50);
tp_ops->exec_command(hwif, ATA_CMD_DEV_RESET);
(void)ide_busy_sleep(drive, WAIT_WORSTCASE, 0);
rc = ide_dev_read_id(drive, cmd, id, 0);
}
/* ensure drive IRQ is clear */
stat = tp_ops->read_status(hwif);
if (rc == 1)
printk(KERN_ERR "%s: no response (status = 0x%02x)\n",
drive->name, stat);
} else {
/* not present or maybe ATAPI */
rc = 3;
}
if (drive->dn & 1) {
/* exit with drive0 selected */
tp_ops->dev_select(hwif->devices[0]);
msleep(50);
/* ensure drive irq is clear */
(void)tp_ops->read_status(hwif);
}
return rc;
}
/**
* probe_for_drives - upper level drive probe
* @drive: drive to probe for
*
* probe_for_drive() tests for existence of a given drive using do_probe()
* and presents things to the user as needed.
*
* Returns: 0 no device was found
* 1 device was found
* (note: IDE_DFLAG_PRESENT might still be not set)
*/
static u8 probe_for_drive(ide_drive_t *drive)
{
char *m;
int rc;
u8 cmd;
drive->dev_flags &= ~IDE_DFLAG_ID_READ;
m = (char *)&drive->id[ATA_ID_PROD];
strcpy(m, "UNKNOWN");
/* skip probing? */
if ((drive->dev_flags & IDE_DFLAG_NOPROBE) == 0) {
/* if !(success||timed-out) */
cmd = ATA_CMD_ID_ATA;
rc = do_probe(drive, cmd);
if (rc >= 2) {
/* look for ATAPI device */
cmd = ATA_CMD_ID_ATAPI;
rc = do_probe(drive, cmd);
}
if ((drive->dev_flags & IDE_DFLAG_PRESENT) == 0)
return 0;
/* identification failed? */
if ((drive->dev_flags & IDE_DFLAG_ID_READ) == 0) {
if (drive->media == ide_disk) {
printk(KERN_INFO "%s: non-IDE drive, CHS=%d/%d/%d\n",
drive->name, drive->cyl,
drive->head, drive->sect);
} else if (drive->media == ide_cdrom) {
printk(KERN_INFO "%s: ATAPI cdrom (?)\n", drive->name);
} else {
/* nuke it */
printk(KERN_WARNING "%s: Unknown device on bus refused identification. Ignoring.\n", drive->name);
drive->dev_flags &= ~IDE_DFLAG_PRESENT;
}
} else {
if (cmd == ATA_CMD_ID_ATAPI)
ide_classify_atapi_dev(drive);
else
ide_classify_ata_dev(drive);
}
}
if ((drive->dev_flags & IDE_DFLAG_PRESENT) == 0)
return 0;
/* The drive wasn't being helpful. Add generic info only */
if ((drive->dev_flags & IDE_DFLAG_ID_READ) == 0) {
generic_id(drive);
return 1;
}
if (drive->media == ide_disk) {
ide_disk_init_chs(drive);
ide_disk_init_mult_count(drive);
}
return 1;
}
static void hwif_release_dev(struct device *dev)
{
ide_hwif_t *hwif = container_of(dev, ide_hwif_t, gendev);
complete(&hwif->gendev_rel_comp);
}
static int ide_register_port(ide_hwif_t *hwif)
{
int ret;
/* register with global device tree */
dev_set_name(&hwif->gendev, hwif->name);
dev_set_drvdata(&hwif->gendev, hwif);
if (hwif->gendev.parent == NULL)
hwif->gendev.parent = hwif->dev;
hwif->gendev.release = hwif_release_dev;
ret = device_register(&hwif->gendev);
if (ret < 0) {
printk(KERN_WARNING "IDE: %s: device_register error: %d\n",
__func__, ret);
goto out;
}
hwif->portdev = device_create(ide_port_class, &hwif->gendev,
MKDEV(0, 0), hwif, hwif->name);
if (IS_ERR(hwif->portdev)) {
ret = PTR_ERR(hwif->portdev);
device_unregister(&hwif->gendev);
}
out:
return ret;
}
/**
* ide_port_wait_ready - wait for port to become ready
* @hwif: IDE port
*
* This is needed on some PPCs and a bunch of BIOS-less embedded
* platforms. Typical cases are:
*
* - The firmware hard reset the disk before booting the kernel,
* the drive is still doing it's poweron-reset sequence, that
* can take up to 30 seconds.
*
* - The firmware does nothing (or no firmware), the device is
* still in POST state (same as above actually).
*
* - Some CD/DVD/Writer combo drives tend to drive the bus during
* their reset sequence even when they are non-selected slave
* devices, thus preventing discovery of the main HD.
*
* Doing this wait-for-non-busy should not harm any existing
* configuration and fix some issues like the above.
*
* BenH.
*
* Returns 0 on success, error code (< 0) otherwise.
*/
static int ide_port_wait_ready(ide_hwif_t *hwif)
{
const struct ide_tp_ops *tp_ops = hwif->tp_ops;
ide_drive_t *drive;
int i, rc;
printk(KERN_DEBUG "Probing IDE interface %s...\n", hwif->name);
/* Let HW settle down a bit from whatever init state we
* come from */
mdelay(2);
/* Wait for BSY bit to go away, spec timeout is 30 seconds,
* I know of at least one disk who takes 31 seconds, I use 35
* here to be safe
*/
rc = ide_wait_not_busy(hwif, 35000);
if (rc)
return rc;
/* Now make sure both master & slave are ready */
ide_port_for_each_dev(i, drive, hwif) {
/* Ignore disks that we will not probe for later. */
if ((drive->dev_flags & IDE_DFLAG_NOPROBE) == 0 ||
(drive->dev_flags & IDE_DFLAG_PRESENT)) {
tp_ops->dev_select(drive);
tp_ops->write_devctl(hwif, ATA_DEVCTL_OBS);
mdelay(2);
rc = ide_wait_not_busy(hwif, 35000);
if (rc)
goto out;
} else
printk(KERN_DEBUG "%s: ide_wait_not_busy() skipped\n",
drive->name);
}
out:
/* Exit function with master reselected (let's be sane) */
if (i)
tp_ops->dev_select(hwif->devices[0]);
return rc;
}
/**
* ide_undecoded_slave - look for bad CF adapters
* @dev1: slave device
*
* Analyse the drives on the interface and attempt to decide if we
* have the same drive viewed twice. This occurs with crap CF adapters
* and PCMCIA sometimes.
*/
void ide_undecoded_slave(ide_drive_t *dev1)
{
ide_drive_t *dev0 = dev1->hwif->devices[0];
if ((dev1->dn & 1) == 0 || (dev0->dev_flags & IDE_DFLAG_PRESENT) == 0)
return;
/* If the models don't match they are not the same product */
if (strcmp((char *)&dev0->id[ATA_ID_PROD],
(char *)&dev1->id[ATA_ID_PROD]))
return;
/* Serial numbers do not match */
if (strncmp((char *)&dev0->id[ATA_ID_SERNO],
(char *)&dev1->id[ATA_ID_SERNO], ATA_ID_SERNO_LEN))
return;
/* No serial number, thankfully very rare for CF */
if (*(char *)&dev0->id[ATA_ID_SERNO] == 0)
return;
/* Appears to be an IDE flash adapter with decode bugs */
printk(KERN_WARNING "ide-probe: ignoring undecoded slave\n");
dev1->dev_flags &= ~IDE_DFLAG_PRESENT;
}
EXPORT_SYMBOL_GPL(ide_undecoded_slave);
static int ide_probe_port(ide_hwif_t *hwif)
{
ide_drive_t *drive;
unsigned int irqd;
int i, rc = -ENODEV;
BUG_ON(hwif->present);
if ((hwif->devices[0]->dev_flags & IDE_DFLAG_NOPROBE) &&
(hwif->devices[1]->dev_flags & IDE_DFLAG_NOPROBE))
return -EACCES;
/*
* We must always disable IRQ, as probe_for_drive will assert IRQ, but
* we'll install our IRQ driver much later...
*/
irqd = hwif->irq;
if (irqd)
disable_irq(hwif->irq);
if (ide_port_wait_ready(hwif) == -EBUSY)
printk(KERN_DEBUG "%s: Wait for ready failed before probe !\n", hwif->name);
/*
* Second drive should only exist if first drive was found,
* but a lot of cdrom drives are configured as single slaves.
*/
ide_port_for_each_dev(i, drive, hwif) {
(void) probe_for_drive(drive);
if (drive->dev_flags & IDE_DFLAG_PRESENT)
rc = 0;
}
/*
* Use cached IRQ number. It might be (and is...) changed by probe
* code above
*/
if (irqd)
enable_irq(irqd);
return rc;
}
static void ide_port_tune_devices(ide_hwif_t *hwif)
{
const struct ide_port_ops *port_ops = hwif->port_ops;
ide_drive_t *drive;
int i;
ide_port_for_each_present_dev(i, drive, hwif) {
ide_check_nien_quirk_list(drive);
if (port_ops && port_ops->quirkproc)
port_ops->quirkproc(drive);
}
ide_port_for_each_present_dev(i, drive, hwif) {
ide_set_max_pio(drive);
drive->dev_flags |= IDE_DFLAG_NICE1;
if (hwif->dma_ops)
ide_set_dma(drive);
}
}
/*
* init request queue
*/
static int ide_init_queue(ide_drive_t *drive)
{
struct request_queue *q;
ide_hwif_t *hwif = drive->hwif;
int max_sectors = 256;
int max_sg_entries = PRD_ENTRIES;
/*
* Our default set up assumes the normal IDE case,
* that is 64K segmenting, standard PRD setup
* and LBA28. Some drivers then impose their own
* limits and LBA48 we could raise it but as yet
* do not.
*/
q = blk_init_queue_node(do_ide_request, NULL, hwif_to_node(hwif));
if (!q)
return 1;
q->queuedata = drive;
blk_queue_segment_boundary(q, 0xffff);
if (hwif->rqsize < max_sectors)
max_sectors = hwif->rqsize;
blk_queue_max_hw_sectors(q, max_sectors);
#ifdef CONFIG_PCI
/* When we have an IOMMU, we may have a problem where pci_map_sg()
* creates segments that don't completely match our boundary
* requirements and thus need to be broken up again. Because it
* doesn't align properly either, we may actually have to break up
* to more segments than what was we got in the first place, a max
* worst case is twice as many.
* This will be fixed once we teach pci_map_sg() about our boundary
* requirements, hopefully soon. *FIXME*
*/
if (!PCI_DMA_BUS_IS_PHYS)
max_sg_entries >>= 1;
#endif /* CONFIG_PCI */
blk_queue_max_segments(q, max_sg_entries);
/* assign drive queue */
drive->queue = q;
/* needs drive->queue to be set */
ide_toggle_bounce(drive, 1);
return 0;
}
static DEFINE_MUTEX(ide_cfg_mtx);
/*
* For any present drive:
* - allocate the block device queue
*/
static int ide_port_setup_devices(ide_hwif_t *hwif)
{
ide_drive_t *drive;
int i, j = 0;
mutex_lock(&ide_cfg_mtx);
ide_port_for_each_present_dev(i, drive, hwif) {
if (ide_init_queue(drive)) {
printk(KERN_ERR "ide: failed to init %s\n",
drive->name);
drive->dev_flags &= ~IDE_DFLAG_PRESENT;
continue;
}
j++;
}
mutex_unlock(&ide_cfg_mtx);
return j;
}
static void ide_host_enable_irqs(struct ide_host *host)
{
ide_hwif_t *hwif;
int i;
ide_host_for_each_port(i, hwif, host) {
if (hwif == NULL)
continue;
/* clear any pending IRQs */
hwif->tp_ops->read_status(hwif);
/* unmask IRQs */
if (hwif->io_ports.ctl_addr)
hwif->tp_ops->write_devctl(hwif, ATA_DEVCTL_OBS);
}
}
/*
* This routine sets up the IRQ for an IDE interface.
*/
static int init_irq (ide_hwif_t *hwif)
{
struct ide_io_ports *io_ports = &hwif->io_ports;
struct ide_host *host = hwif->host;
irq_handler_t irq_handler = host->irq_handler;
int sa = host->irq_flags;
if (irq_handler == NULL)
irq_handler = ide_intr;
if (request_irq(hwif->irq, irq_handler, sa, hwif->name, hwif))
goto out_up;
#if !defined(__mc68000__)
printk(KERN_INFO "%s at 0x%03lx-0x%03lx,0x%03lx on irq %d", hwif->name,
io_ports->data_addr, io_ports->status_addr,
io_ports->ctl_addr, hwif->irq);
#else
printk(KERN_INFO "%s at 0x%08lx on irq %d", hwif->name,
io_ports->data_addr, hwif->irq);
#endif /* __mc68000__ */
if (hwif->host->host_flags & IDE_HFLAG_SERIALIZE)
printk(KERN_CONT " (serialized)");
printk(KERN_CONT "\n");
return 0;
out_up:
return 1;
}
static int ata_lock(dev_t dev, void *data)
{
/* FIXME: we want to pin hwif down */
return 0;
}
static struct kobject *ata_probe(dev_t dev, int *part, void *data)
{
ide_hwif_t *hwif = data;
int unit = *part >> PARTN_BITS;
ide_drive_t *drive = hwif->devices[unit];
if ((drive->dev_flags & IDE_DFLAG_PRESENT) == 0)
return NULL;
if (drive->media == ide_disk)
request_module("ide-disk");
if (drive->media == ide_cdrom || drive->media == ide_optical)
request_module("ide-cd");
if (drive->media == ide_tape)
request_module("ide-tape");
if (drive->media == ide_floppy)
request_module("ide-floppy");
return NULL;
}
static struct kobject *exact_match(dev_t dev, int *part, void *data)
{
struct gendisk *p = data;
*part &= (1 << PARTN_BITS) - 1;
return &disk_to_dev(p)->kobj;
}
static int exact_lock(dev_t dev, void *data)
{
struct gendisk *p = data;
if (!get_disk(p))
return -1;
return 0;
}
void ide_register_region(struct gendisk *disk)
{
blk_register_region(MKDEV(disk->major, disk->first_minor),
disk->minors, NULL, exact_match, exact_lock, disk);
}
EXPORT_SYMBOL_GPL(ide_register_region);
void ide_unregister_region(struct gendisk *disk)
{
blk_unregister_region(MKDEV(disk->major, disk->first_minor),
disk->minors);
}
EXPORT_SYMBOL_GPL(ide_unregister_region);
void ide_init_disk(struct gendisk *disk, ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
unsigned int unit = drive->dn & 1;
disk->major = hwif->major;
disk->first_minor = unit << PARTN_BITS;
sprintf(disk->disk_name, "hd%c", 'a' + hwif->index * MAX_DRIVES + unit);
disk->queue = drive->queue;
}
EXPORT_SYMBOL_GPL(ide_init_disk);
static void drive_release_dev (struct device *dev)
{
ide_drive_t *drive = container_of(dev, ide_drive_t, gendev);
ide_proc_unregister_device(drive);
blk_cleanup_queue(drive->queue);
drive->queue = NULL;
drive->dev_flags &= ~IDE_DFLAG_PRESENT;
complete(&drive->gendev_rel_comp);
}
static int hwif_init(ide_hwif_t *hwif)
{
if (!hwif->irq) {
printk(KERN_ERR "%s: disabled, no IRQ\n", hwif->name);
return 0;
}
if (register_blkdev(hwif->major, hwif->name))
return 0;
if (!hwif->sg_max_nents)
hwif->sg_max_nents = PRD_ENTRIES;
hwif->sg_table = kmalloc(sizeof(struct scatterlist)*hwif->sg_max_nents,
GFP_KERNEL);
if (!hwif->sg_table) {
printk(KERN_ERR "%s: unable to allocate SG table.\n", hwif->name);
goto out;
}
sg_init_table(hwif->sg_table, hwif->sg_max_nents);
if (init_irq(hwif)) {
printk(KERN_ERR "%s: disabled, unable to get IRQ %d\n",
hwif->name, hwif->irq);
goto out;
}
blk_register_region(MKDEV(hwif->major, 0), MAX_DRIVES << PARTN_BITS,
THIS_MODULE, ata_probe, ata_lock, hwif);
return 1;
out:
unregister_blkdev(hwif->major, hwif->name);
return 0;
}
static void hwif_register_devices(ide_hwif_t *hwif)
{
ide_drive_t *drive;
unsigned int i;
ide_port_for_each_present_dev(i, drive, hwif) {
struct device *dev = &drive->gendev;
int ret;
dev_set_name(dev, "%u.%u", hwif->index, i);
dev_set_drvdata(dev, drive);
dev->parent = &hwif->gendev;
dev->bus = &ide_bus_type;
dev->release = drive_release_dev;
ret = device_register(dev);
if (ret < 0)
printk(KERN_WARNING "IDE: %s: device_register error: "
"%d\n", __func__, ret);
}
}
static void ide_port_init_devices(ide_hwif_t *hwif)
{
const struct ide_port_ops *port_ops = hwif->port_ops;
ide_drive_t *drive;
int i;
ide_port_for_each_dev(i, drive, hwif) {
drive->dn = i + hwif->channel * 2;
if (hwif->host_flags & IDE_HFLAG_IO_32BIT)
drive->io_32bit = 1;
if (hwif->host_flags & IDE_HFLAG_NO_IO_32BIT)
drive->dev_flags |= IDE_DFLAG_NO_IO_32BIT;
if (hwif->host_flags & IDE_HFLAG_UNMASK_IRQS)
drive->dev_flags |= IDE_DFLAG_UNMASK;
if (hwif->host_flags & IDE_HFLAG_NO_UNMASK_IRQS)
drive->dev_flags |= IDE_DFLAG_NO_UNMASK;
drive->pio_mode = XFER_PIO_0;
if (port_ops && port_ops->init_dev)
port_ops->init_dev(drive);
}
}
static void ide_init_port(ide_hwif_t *hwif, unsigned int port,
const struct ide_port_info *d)
{
hwif->channel = port;
hwif->chipset = d->chipset ? d->chipset : ide_pci;
if (d->init_iops)
d->init_iops(hwif);
/* ->host_flags may be set by ->init_iops (or even earlier...) */
hwif->host_flags |= d->host_flags;
hwif->pio_mask = d->pio_mask;
if (d->tp_ops)
hwif->tp_ops = d->tp_ops;
/* ->set_pio_mode for DTC2278 is currently limited to port 0 */
if ((hwif->host_flags & IDE_HFLAG_DTC2278) == 0 || hwif->channel == 0)
hwif->port_ops = d->port_ops;
hwif->swdma_mask = d->swdma_mask;
hwif->mwdma_mask = d->mwdma_mask;
hwif->ultra_mask = d->udma_mask;
if ((d->host_flags & IDE_HFLAG_NO_DMA) == 0) {
int rc;
hwif->dma_ops = d->dma_ops;
if (d->init_dma)
rc = d->init_dma(hwif, d);
else
rc = ide_hwif_setup_dma(hwif, d);
if (rc < 0) {
printk(KERN_INFO "%s: DMA disabled\n", hwif->name);
hwif->dma_ops = NULL;
hwif->dma_base = 0;
hwif->swdma_mask = 0;
hwif->mwdma_mask = 0;
hwif->ultra_mask = 0;
}
}
if ((d->host_flags & IDE_HFLAG_SERIALIZE) ||
((d->host_flags & IDE_HFLAG_SERIALIZE_DMA) && hwif->dma_base))
hwif->host->host_flags |= IDE_HFLAG_SERIALIZE;
if (d->max_sectors)
hwif->rqsize = d->max_sectors;
else {
if ((hwif->host_flags & IDE_HFLAG_NO_LBA48) ||
(hwif->host_flags & IDE_HFLAG_NO_LBA48_DMA))
hwif->rqsize = 256;
else
hwif->rqsize = 65536;
}
/* call chipset specific routine for each enabled port */
if (d->init_hwif)
d->init_hwif(hwif);
}
static void ide_port_cable_detect(ide_hwif_t *hwif)
{
const struct ide_port_ops *port_ops = hwif->port_ops;
if (port_ops && port_ops->cable_detect && (hwif->ultra_mask & 0x78)) {
if (hwif->cbl != ATA_CBL_PATA40_SHORT)
hwif->cbl = port_ops->cable_detect(hwif);
}
}
static const u8 ide_hwif_to_major[] =
{ IDE0_MAJOR, IDE1_MAJOR, IDE2_MAJOR, IDE3_MAJOR, IDE4_MAJOR,
IDE5_MAJOR, IDE6_MAJOR, IDE7_MAJOR, IDE8_MAJOR, IDE9_MAJOR };
static void ide_port_init_devices_data(ide_hwif_t *hwif)
{
ide_drive_t *drive;
int i;
ide_port_for_each_dev(i, drive, hwif) {
u8 j = (hwif->index * MAX_DRIVES) + i;
u16 *saved_id = drive->id;
memset(drive, 0, sizeof(*drive));
memset(saved_id, 0, SECTOR_SIZE);
drive->id = saved_id;
drive->media = ide_disk;
drive->select = (i << 4) | ATA_DEVICE_OBS;
drive->hwif = hwif;
drive->ready_stat = ATA_DRDY;
drive->bad_wstat = BAD_W_STAT;
drive->special_flags = IDE_SFLAG_RECALIBRATE |
IDE_SFLAG_SET_GEOMETRY;
drive->name[0] = 'h';
drive->name[1] = 'd';
drive->name[2] = 'a' + j;
drive->max_failures = IDE_DEFAULT_MAX_FAILURES;
INIT_LIST_HEAD(&drive->list);
init_completion(&drive->gendev_rel_comp);
}
}
static void ide_init_port_data(ide_hwif_t *hwif, unsigned int index)
{
/* fill in any non-zero initial values */
hwif->index = index;
hwif->major = ide_hwif_to_major[index];
hwif->name[0] = 'i';
hwif->name[1] = 'd';
hwif->name[2] = 'e';
hwif->name[3] = '0' + index;
spin_lock_init(&hwif->lock);
init_timer(&hwif->timer);
hwif->timer.function = &ide_timer_expiry;
hwif->timer.data = (unsigned long)hwif;
init_completion(&hwif->gendev_rel_comp);
hwif->tp_ops = &default_tp_ops;
ide_port_init_devices_data(hwif);
}
static void ide_init_port_hw(ide_hwif_t *hwif, struct ide_hw *hw)
{
memcpy(&hwif->io_ports, &hw->io_ports, sizeof(hwif->io_ports));
hwif->irq = hw->irq;
hwif->dev = hw->dev;
hwif->gendev.parent = hw->parent ? hw->parent : hw->dev;
hwif->config_data = hw->config;
}
static unsigned int ide_indexes;
/**
* ide_find_port_slot - find free port slot
* @d: IDE port info
*
* Return the new port slot index or -ENOENT if we are out of free slots.
*/
static int ide_find_port_slot(const struct ide_port_info *d)
{
int idx = -ENOENT;
u8 bootable = (d && (d->host_flags & IDE_HFLAG_NON_BOOTABLE)) ? 0 : 1;
u8 i = (d && (d->host_flags & IDE_HFLAG_QD_2ND_PORT)) ? 1 : 0;
/*
* Claim an unassigned slot.
*
* Give preference to claiming other slots before claiming ide0/ide1,
* just in case there's another interface yet-to-be-scanned
* which uses ports 0x1f0/0x170 (the ide0/ide1 defaults).
*
* Unless there is a bootable card that does not use the standard
* ports 0x1f0/0x170 (the ide0/ide1 defaults).
*/
mutex_lock(&ide_cfg_mtx);
if (bootable) {
if ((ide_indexes | i) != (1 << MAX_HWIFS) - 1)
idx = ffz(ide_indexes | i);
} else {
if ((ide_indexes | 3) != (1 << MAX_HWIFS) - 1)
idx = ffz(ide_indexes | 3);
else if ((ide_indexes & 3) != 3)
idx = ffz(ide_indexes);
}
if (idx >= 0)
ide_indexes |= (1 << idx);
mutex_unlock(&ide_cfg_mtx);
return idx;
}
static void ide_free_port_slot(int idx)
{
mutex_lock(&ide_cfg_mtx);
ide_indexes &= ~(1 << idx);
mutex_unlock(&ide_cfg_mtx);
}
static void ide_port_free_devices(ide_hwif_t *hwif)
{
ide_drive_t *drive;
int i;
ide_port_for_each_dev(i, drive, hwif) {
kfree(drive->id);
kfree(drive);
}
}
static int ide_port_alloc_devices(ide_hwif_t *hwif, int node)
{
int i;
for (i = 0; i < MAX_DRIVES; i++) {
ide_drive_t *drive;
drive = kzalloc_node(sizeof(*drive), GFP_KERNEL, node);
if (drive == NULL)
goto out_nomem;
/*
* In order to keep things simple we have an id
* block for all drives at all times. If the device
* is pre ATA or refuses ATA/ATAPI identify we
* will add faked data to this.
*
* Also note that 0 everywhere means "can't do X"
*/
drive->id = kzalloc_node(SECTOR_SIZE, GFP_KERNEL, node);
if (drive->id == NULL)
goto out_nomem;
hwif->devices[i] = drive;
}
return 0;
out_nomem:
ide_port_free_devices(hwif);
return -ENOMEM;
}
struct ide_host *ide_host_alloc(const struct ide_port_info *d,
struct ide_hw **hws, unsigned int n_ports)
{
struct ide_host *host;
struct device *dev = hws[0] ? hws[0]->dev : NULL;
int node = dev ? dev_to_node(dev) : -1;
int i;
host = kzalloc_node(sizeof(*host), GFP_KERNEL, node);
if (host == NULL)
return NULL;
for (i = 0; i < n_ports; i++) {
ide_hwif_t *hwif;
int idx;
if (hws[i] == NULL)
continue;
hwif = kzalloc_node(sizeof(*hwif), GFP_KERNEL, node);
if (hwif == NULL)
continue;
if (ide_port_alloc_devices(hwif, node) < 0) {
kfree(hwif);
continue;
}
idx = ide_find_port_slot(d);
if (idx < 0) {
printk(KERN_ERR "%s: no free slot for interface\n",
d ? d->name : "ide");
ide_port_free_devices(hwif);
kfree(hwif);
continue;
}
ide_init_port_data(hwif, idx);
hwif->host = host;
host->ports[i] = hwif;
host->n_ports++;
}
if (host->n_ports == 0) {
kfree(host);
return NULL;
}
host->dev[0] = dev;
if (d) {
host->init_chipset = d->init_chipset;
host->get_lock = d->get_lock;
host->release_lock = d->release_lock;
host->host_flags = d->host_flags;
host->irq_flags = d->irq_flags;
}
return host;
}
EXPORT_SYMBOL_GPL(ide_host_alloc);
static void ide_port_free(ide_hwif_t *hwif)
{
ide_port_free_devices(hwif);
ide_free_port_slot(hwif->index);
kfree(hwif);
}
static void ide_disable_port(ide_hwif_t *hwif)
{
struct ide_host *host = hwif->host;
int i;
printk(KERN_INFO "%s: disabling port\n", hwif->name);
for (i = 0; i < MAX_HOST_PORTS; i++) {
if (host->ports[i] == hwif) {
host->ports[i] = NULL;
host->n_ports--;
}
}
ide_port_free(hwif);
}
int ide_host_register(struct ide_host *host, const struct ide_port_info *d,
struct ide_hw **hws)
{
ide_hwif_t *hwif, *mate = NULL;
int i, j = 0;
ide_host_for_each_port(i, hwif, host) {
if (hwif == NULL) {
mate = NULL;
continue;
}
ide_init_port_hw(hwif, hws[i]);
ide_port_apply_params(hwif);
if ((i & 1) && mate) {
hwif->mate = mate;
mate->mate = hwif;
}
mate = (i & 1) ? NULL : hwif;
ide_init_port(hwif, i & 1, d);
ide_port_cable_detect(hwif);
hwif->port_flags |= IDE_PFLAG_PROBING;
ide_port_init_devices(hwif);
}
ide_host_for_each_port(i, hwif, host) {
if (hwif == NULL)
continue;
if (ide_probe_port(hwif) == 0)
hwif->present = 1;
hwif->port_flags &= ~IDE_PFLAG_PROBING;
if ((hwif->host_flags & IDE_HFLAG_4DRIVES) == 0 ||
hwif->mate == NULL || hwif->mate->present == 0) {
if (ide_register_port(hwif)) {
ide_disable_port(hwif);
continue;
}
}
if (hwif->present)
ide_port_tune_devices(hwif);
}
ide_host_enable_irqs(host);
ide_host_for_each_port(i, hwif, host) {
if (hwif == NULL)
continue;
if (hwif_init(hwif) == 0) {
printk(KERN_INFO "%s: failed to initialize IDE "
"interface\n", hwif->name);
device_unregister(&hwif->gendev);
ide_disable_port(hwif);
continue;
}
if (hwif->present)
if (ide_port_setup_devices(hwif) == 0) {
hwif->present = 0;
continue;
}
j++;
ide_acpi_init_port(hwif);
if (hwif->present)
ide_acpi_port_init_devices(hwif);
}
ide_host_for_each_port(i, hwif, host) {
if (hwif == NULL)
continue;
ide_sysfs_register_port(hwif);
ide_proc_register_port(hwif);
if (hwif->present) {
ide_proc_port_register_devices(hwif);
hwif_register_devices(hwif);
}
}
return j ? 0 : -1;
}
EXPORT_SYMBOL_GPL(ide_host_register);
int ide_host_add(const struct ide_port_info *d, struct ide_hw **hws,
unsigned int n_ports, struct ide_host **hostp)
{
struct ide_host *host;
int rc;
host = ide_host_alloc(d, hws, n_ports);
if (host == NULL)
return -ENOMEM;
rc = ide_host_register(host, d, hws);
if (rc) {
ide_host_free(host);
return rc;
}
if (hostp)
*hostp = host;
return 0;
}
EXPORT_SYMBOL_GPL(ide_host_add);
static void __ide_port_unregister_devices(ide_hwif_t *hwif)
{
ide_drive_t *drive;
int i;
ide_port_for_each_present_dev(i, drive, hwif) {
device_unregister(&drive->gendev);
wait_for_completion(&drive->gendev_rel_comp);
}
}
void ide_port_unregister_devices(ide_hwif_t *hwif)
{
mutex_lock(&ide_cfg_mtx);
__ide_port_unregister_devices(hwif);
hwif->present = 0;
ide_port_init_devices_data(hwif);
mutex_unlock(&ide_cfg_mtx);
}
EXPORT_SYMBOL_GPL(ide_port_unregister_devices);
/**
* ide_unregister - free an IDE interface
* @hwif: IDE interface
*
* Perform the final unregister of an IDE interface.
*
* Locking:
* The caller must not hold the IDE locks.
*
* It is up to the caller to be sure there is no pending I/O here,
* and that the interface will not be reopened (present/vanishing
* locking isn't yet done BTW).
*/
static void ide_unregister(ide_hwif_t *hwif)
{
BUG_ON(in_interrupt());
BUG_ON(irqs_disabled());
mutex_lock(&ide_cfg_mtx);
if (hwif->present) {
__ide_port_unregister_devices(hwif);
hwif->present = 0;
}
ide_proc_unregister_port(hwif);
free_irq(hwif->irq, hwif);
device_unregister(hwif->portdev);
device_unregister(&hwif->gendev);
wait_for_completion(&hwif->gendev_rel_comp);
/*
* Remove us from the kernel's knowledge
*/
blk_unregister_region(MKDEV(hwif->major, 0), MAX_DRIVES<<PARTN_BITS);
kfree(hwif->sg_table);
unregister_blkdev(hwif->major, hwif->name);
ide_release_dma_engine(hwif);
mutex_unlock(&ide_cfg_mtx);
}
void ide_host_free(struct ide_host *host)
{
ide_hwif_t *hwif;
int i;
ide_host_for_each_port(i, hwif, host) {
if (hwif)
ide_port_free(hwif);
}
kfree(host);
}
EXPORT_SYMBOL_GPL(ide_host_free);
void ide_host_remove(struct ide_host *host)
{
ide_hwif_t *hwif;
int i;
ide_host_for_each_port(i, hwif, host) {
if (hwif)
ide_unregister(hwif);
}
ide_host_free(host);
}
EXPORT_SYMBOL_GPL(ide_host_remove);
void ide_port_scan(ide_hwif_t *hwif)
{
int rc;
ide_port_apply_params(hwif);
ide_port_cable_detect(hwif);
hwif->port_flags |= IDE_PFLAG_PROBING;
ide_port_init_devices(hwif);
rc = ide_probe_port(hwif);
hwif->port_flags &= ~IDE_PFLAG_PROBING;
if (rc < 0)
return;
hwif->present = 1;
ide_port_tune_devices(hwif);
ide_port_setup_devices(hwif);
ide_acpi_port_init_devices(hwif);
hwif_register_devices(hwif);
ide_proc_port_register_devices(hwif);
}
EXPORT_SYMBOL_GPL(ide_port_scan);
| gpl-2.0 |
GrandPrime/stock_kernel_grandprime | arch/tile/lib/delay.c | 12155 | 1184 | /*
* Copyright 2010 Tilera Corporation. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, 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, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for
* more details.
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/thread_info.h>
#include <asm/timex.h>
void __udelay(unsigned long usecs)
{
if (usecs > ULONG_MAX / 1000) {
WARN_ON_ONCE(usecs > ULONG_MAX / 1000);
usecs = ULONG_MAX / 1000;
}
__ndelay(usecs * 1000);
}
EXPORT_SYMBOL(__udelay);
void __ndelay(unsigned long nsecs)
{
cycles_t target = get_cycles();
target += ns2cycles(nsecs);
while (get_cycles() < target)
cpu_relax();
}
EXPORT_SYMBOL(__ndelay);
void __delay(unsigned long cycles)
{
cycles_t target = get_cycles() + cycles;
while (get_cycles() < target)
cpu_relax();
}
EXPORT_SYMBOL(__delay);
| gpl-2.0 |
followtheart/linux | sound/soc/codecs/ssm4567.c | 124 | 12611 | /*
* SSM4567 amplifier audio driver
*
* Copyright 2014 Google Chromium project.
* Author: Anatol Pomozov <anatol@chromium.org>
*
* Based on code copyright/by:
* Copyright 2013 Analog Devices Inc.
*
* Licensed under the GPL-2.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/i2c.h>
#include <linux/regmap.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/initval.h>
#include <sound/tlv.h>
#define SSM4567_REG_POWER_CTRL 0x00
#define SSM4567_REG_AMP_SNS_CTRL 0x01
#define SSM4567_REG_DAC_CTRL 0x02
#define SSM4567_REG_DAC_VOLUME 0x03
#define SSM4567_REG_SAI_CTRL_1 0x04
#define SSM4567_REG_SAI_CTRL_2 0x05
#define SSM4567_REG_SAI_PLACEMENT_1 0x06
#define SSM4567_REG_SAI_PLACEMENT_2 0x07
#define SSM4567_REG_SAI_PLACEMENT_3 0x08
#define SSM4567_REG_SAI_PLACEMENT_4 0x09
#define SSM4567_REG_SAI_PLACEMENT_5 0x0a
#define SSM4567_REG_SAI_PLACEMENT_6 0x0b
#define SSM4567_REG_BATTERY_V_OUT 0x0c
#define SSM4567_REG_LIMITER_CTRL_1 0x0d
#define SSM4567_REG_LIMITER_CTRL_2 0x0e
#define SSM4567_REG_LIMITER_CTRL_3 0x0f
#define SSM4567_REG_STATUS_1 0x10
#define SSM4567_REG_STATUS_2 0x11
#define SSM4567_REG_FAULT_CTRL 0x12
#define SSM4567_REG_PDM_CTRL 0x13
#define SSM4567_REG_MCLK_RATIO 0x14
#define SSM4567_REG_BOOST_CTRL_1 0x15
#define SSM4567_REG_BOOST_CTRL_2 0x16
#define SSM4567_REG_SOFT_RESET 0xff
/* POWER_CTRL */
#define SSM4567_POWER_APWDN_EN BIT(7)
#define SSM4567_POWER_BSNS_PWDN BIT(6)
#define SSM4567_POWER_VSNS_PWDN BIT(5)
#define SSM4567_POWER_ISNS_PWDN BIT(4)
#define SSM4567_POWER_BOOST_PWDN BIT(3)
#define SSM4567_POWER_AMP_PWDN BIT(2)
#define SSM4567_POWER_VBAT_ONLY BIT(1)
#define SSM4567_POWER_SPWDN BIT(0)
/* DAC_CTRL */
#define SSM4567_DAC_HV BIT(7)
#define SSM4567_DAC_MUTE BIT(6)
#define SSM4567_DAC_HPF BIT(5)
#define SSM4567_DAC_LPM BIT(4)
#define SSM4567_DAC_FS_MASK 0x7
#define SSM4567_DAC_FS_8000_12000 0x0
#define SSM4567_DAC_FS_16000_24000 0x1
#define SSM4567_DAC_FS_32000_48000 0x2
#define SSM4567_DAC_FS_64000_96000 0x3
#define SSM4567_DAC_FS_128000_192000 0x4
/* SAI_CTRL_1 */
#define SSM4567_SAI_CTRL_1_BCLK BIT(6)
#define SSM4567_SAI_CTRL_1_TDM_BLCKS_MASK (0x3 << 4)
#define SSM4567_SAI_CTRL_1_TDM_BLCKS_32 (0x0 << 4)
#define SSM4567_SAI_CTRL_1_TDM_BLCKS_48 (0x1 << 4)
#define SSM4567_SAI_CTRL_1_TDM_BLCKS_64 (0x2 << 4)
#define SSM4567_SAI_CTRL_1_FSYNC BIT(3)
#define SSM4567_SAI_CTRL_1_LJ BIT(2)
#define SSM4567_SAI_CTRL_1_TDM BIT(1)
#define SSM4567_SAI_CTRL_1_PDM BIT(0)
/* SAI_CTRL_2 */
#define SSM4567_SAI_CTRL_2_AUTO_SLOT BIT(3)
#define SSM4567_SAI_CTRL_2_TDM_SLOT_MASK 0x7
#define SSM4567_SAI_CTRL_2_TDM_SLOT(x) (x)
struct ssm4567 {
struct regmap *regmap;
};
static const struct reg_default ssm4567_reg_defaults[] = {
{ SSM4567_REG_POWER_CTRL, 0x81 },
{ SSM4567_REG_AMP_SNS_CTRL, 0x09 },
{ SSM4567_REG_DAC_CTRL, 0x32 },
{ SSM4567_REG_DAC_VOLUME, 0x40 },
{ SSM4567_REG_SAI_CTRL_1, 0x00 },
{ SSM4567_REG_SAI_CTRL_2, 0x08 },
{ SSM4567_REG_SAI_PLACEMENT_1, 0x01 },
{ SSM4567_REG_SAI_PLACEMENT_2, 0x20 },
{ SSM4567_REG_SAI_PLACEMENT_3, 0x32 },
{ SSM4567_REG_SAI_PLACEMENT_4, 0x07 },
{ SSM4567_REG_SAI_PLACEMENT_5, 0x07 },
{ SSM4567_REG_SAI_PLACEMENT_6, 0x07 },
{ SSM4567_REG_BATTERY_V_OUT, 0x00 },
{ SSM4567_REG_LIMITER_CTRL_1, 0xa4 },
{ SSM4567_REG_LIMITER_CTRL_2, 0x73 },
{ SSM4567_REG_LIMITER_CTRL_3, 0x00 },
{ SSM4567_REG_STATUS_1, 0x00 },
{ SSM4567_REG_STATUS_2, 0x00 },
{ SSM4567_REG_FAULT_CTRL, 0x30 },
{ SSM4567_REG_PDM_CTRL, 0x40 },
{ SSM4567_REG_MCLK_RATIO, 0x11 },
{ SSM4567_REG_BOOST_CTRL_1, 0x03 },
{ SSM4567_REG_BOOST_CTRL_2, 0x00 },
{ SSM4567_REG_SOFT_RESET, 0x00 },
};
static bool ssm4567_readable_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case SSM4567_REG_POWER_CTRL ... SSM4567_REG_BOOST_CTRL_2:
return true;
default:
return false;
}
}
static bool ssm4567_writeable_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case SSM4567_REG_POWER_CTRL ... SSM4567_REG_SAI_PLACEMENT_6:
case SSM4567_REG_LIMITER_CTRL_1 ... SSM4567_REG_LIMITER_CTRL_3:
case SSM4567_REG_FAULT_CTRL ... SSM4567_REG_BOOST_CTRL_2:
/* The datasheet states that soft reset register is read-only,
* but logically it is write-only. */
case SSM4567_REG_SOFT_RESET:
return true;
default:
return false;
}
}
static bool ssm4567_volatile_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case SSM4567_REG_BATTERY_V_OUT:
case SSM4567_REG_STATUS_1 ... SSM4567_REG_STATUS_2:
case SSM4567_REG_SOFT_RESET:
return true;
default:
return false;
}
}
static const DECLARE_TLV_DB_MINMAX_MUTE(ssm4567_vol_tlv, -7125, 2400);
static const struct snd_kcontrol_new ssm4567_snd_controls[] = {
SOC_SINGLE_TLV("Master Playback Volume", SSM4567_REG_DAC_VOLUME, 0,
0xff, 1, ssm4567_vol_tlv),
SOC_SINGLE("DAC Low Power Mode Switch", SSM4567_REG_DAC_CTRL, 4, 1, 0),
SOC_SINGLE("DAC High Pass Filter Switch", SSM4567_REG_DAC_CTRL,
5, 1, 0),
};
static const struct snd_kcontrol_new ssm4567_amplifier_boost_control =
SOC_DAPM_SINGLE("Switch", SSM4567_REG_POWER_CTRL, 1, 1, 1);
static const struct snd_soc_dapm_widget ssm4567_dapm_widgets[] = {
SND_SOC_DAPM_DAC("DAC", "HiFi Playback", SSM4567_REG_POWER_CTRL, 2, 1),
SND_SOC_DAPM_SWITCH("Amplifier Boost", SSM4567_REG_POWER_CTRL, 3, 1,
&ssm4567_amplifier_boost_control),
SND_SOC_DAPM_OUTPUT("OUT"),
};
static const struct snd_soc_dapm_route ssm4567_routes[] = {
{ "OUT", NULL, "Amplifier Boost" },
{ "Amplifier Boost", "Switch", "DAC" },
{ "OUT", NULL, "DAC" },
};
static int ssm4567_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params, struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct ssm4567 *ssm4567 = snd_soc_codec_get_drvdata(codec);
unsigned int rate = params_rate(params);
unsigned int dacfs;
if (rate >= 8000 && rate <= 12000)
dacfs = SSM4567_DAC_FS_8000_12000;
else if (rate >= 16000 && rate <= 24000)
dacfs = SSM4567_DAC_FS_16000_24000;
else if (rate >= 32000 && rate <= 48000)
dacfs = SSM4567_DAC_FS_32000_48000;
else if (rate >= 64000 && rate <= 96000)
dacfs = SSM4567_DAC_FS_64000_96000;
else if (rate >= 128000 && rate <= 192000)
dacfs = SSM4567_DAC_FS_128000_192000;
else
return -EINVAL;
return regmap_update_bits(ssm4567->regmap, SSM4567_REG_DAC_CTRL,
SSM4567_DAC_FS_MASK, dacfs);
}
static int ssm4567_mute(struct snd_soc_dai *dai, int mute)
{
struct ssm4567 *ssm4567 = snd_soc_codec_get_drvdata(dai->codec);
unsigned int val;
val = mute ? SSM4567_DAC_MUTE : 0;
return regmap_update_bits(ssm4567->regmap, SSM4567_REG_DAC_CTRL,
SSM4567_DAC_MUTE, val);
}
static int ssm4567_set_tdm_slot(struct snd_soc_dai *dai, unsigned int tx_mask,
unsigned int rx_mask, int slots, int width)
{
struct ssm4567 *ssm4567 = snd_soc_dai_get_drvdata(dai);
unsigned int blcks;
int slot;
int ret;
if (tx_mask == 0)
return -EINVAL;
if (rx_mask && rx_mask != tx_mask)
return -EINVAL;
slot = __ffs(tx_mask);
if (tx_mask != BIT(slot))
return -EINVAL;
switch (width) {
case 32:
blcks = SSM4567_SAI_CTRL_1_TDM_BLCKS_32;
break;
case 48:
blcks = SSM4567_SAI_CTRL_1_TDM_BLCKS_48;
break;
case 64:
blcks = SSM4567_SAI_CTRL_1_TDM_BLCKS_64;
break;
default:
return -EINVAL;
}
ret = regmap_update_bits(ssm4567->regmap, SSM4567_REG_SAI_CTRL_2,
SSM4567_SAI_CTRL_2_AUTO_SLOT | SSM4567_SAI_CTRL_2_TDM_SLOT_MASK,
SSM4567_SAI_CTRL_2_TDM_SLOT(slot));
if (ret)
return ret;
return regmap_update_bits(ssm4567->regmap, SSM4567_REG_SAI_CTRL_1,
SSM4567_SAI_CTRL_1_TDM_BLCKS_MASK, blcks);
}
static int ssm4567_set_dai_fmt(struct snd_soc_dai *dai, unsigned int fmt)
{
struct ssm4567 *ssm4567 = snd_soc_dai_get_drvdata(dai);
unsigned int ctrl1 = 0;
bool invert_fclk;
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBS_CFS:
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
invert_fclk = false;
break;
case SND_SOC_DAIFMT_IB_NF:
ctrl1 |= SSM4567_SAI_CTRL_1_BCLK;
invert_fclk = false;
break;
case SND_SOC_DAIFMT_NB_IF:
ctrl1 |= SSM4567_SAI_CTRL_1_FSYNC;
invert_fclk = true;
break;
case SND_SOC_DAIFMT_IB_IF:
ctrl1 |= SSM4567_SAI_CTRL_1_BCLK;
invert_fclk = true;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
break;
case SND_SOC_DAIFMT_LEFT_J:
ctrl1 |= SSM4567_SAI_CTRL_1_LJ;
invert_fclk = !invert_fclk;
break;
case SND_SOC_DAIFMT_DSP_A:
ctrl1 |= SSM4567_SAI_CTRL_1_TDM;
break;
case SND_SOC_DAIFMT_DSP_B:
ctrl1 |= SSM4567_SAI_CTRL_1_TDM | SSM4567_SAI_CTRL_1_LJ;
break;
case SND_SOC_DAIFMT_PDM:
ctrl1 |= SSM4567_SAI_CTRL_1_PDM;
break;
default:
return -EINVAL;
}
if (invert_fclk)
ctrl1 |= SSM4567_SAI_CTRL_1_FSYNC;
return regmap_update_bits(ssm4567->regmap, SSM4567_REG_SAI_CTRL_1,
SSM4567_SAI_CTRL_1_BCLK |
SSM4567_SAI_CTRL_1_FSYNC |
SSM4567_SAI_CTRL_1_LJ |
SSM4567_SAI_CTRL_1_TDM |
SSM4567_SAI_CTRL_1_PDM,
ctrl1);
}
static int ssm4567_set_power(struct ssm4567 *ssm4567, bool enable)
{
int ret = 0;
if (!enable) {
ret = regmap_update_bits(ssm4567->regmap,
SSM4567_REG_POWER_CTRL,
SSM4567_POWER_SPWDN, SSM4567_POWER_SPWDN);
regcache_mark_dirty(ssm4567->regmap);
}
regcache_cache_only(ssm4567->regmap, !enable);
if (enable) {
ret = regmap_update_bits(ssm4567->regmap,
SSM4567_REG_POWER_CTRL,
SSM4567_POWER_SPWDN, 0x00);
regcache_sync(ssm4567->regmap);
}
return ret;
}
static int ssm4567_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
struct ssm4567 *ssm4567 = snd_soc_codec_get_drvdata(codec);
int ret = 0;
switch (level) {
case SND_SOC_BIAS_ON:
break;
case SND_SOC_BIAS_PREPARE:
break;
case SND_SOC_BIAS_STANDBY:
if (snd_soc_codec_get_bias_level(codec) == SND_SOC_BIAS_OFF)
ret = ssm4567_set_power(ssm4567, true);
break;
case SND_SOC_BIAS_OFF:
ret = ssm4567_set_power(ssm4567, false);
break;
}
return ret;
}
static const struct snd_soc_dai_ops ssm4567_dai_ops = {
.hw_params = ssm4567_hw_params,
.digital_mute = ssm4567_mute,
.set_fmt = ssm4567_set_dai_fmt,
.set_tdm_slot = ssm4567_set_tdm_slot,
};
static struct snd_soc_dai_driver ssm4567_dai = {
.name = "ssm4567-hifi",
.playback = {
.stream_name = "Playback",
.channels_min = 1,
.channels_max = 1,
.rates = SNDRV_PCM_RATE_8000_192000,
.formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S24_LE |
SNDRV_PCM_FMTBIT_S32,
},
.ops = &ssm4567_dai_ops,
};
static struct snd_soc_codec_driver ssm4567_codec_driver = {
.set_bias_level = ssm4567_set_bias_level,
.idle_bias_off = true,
.controls = ssm4567_snd_controls,
.num_controls = ARRAY_SIZE(ssm4567_snd_controls),
.dapm_widgets = ssm4567_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(ssm4567_dapm_widgets),
.dapm_routes = ssm4567_routes,
.num_dapm_routes = ARRAY_SIZE(ssm4567_routes),
};
static const struct regmap_config ssm4567_regmap_config = {
.val_bits = 8,
.reg_bits = 8,
.max_register = SSM4567_REG_SOFT_RESET,
.readable_reg = ssm4567_readable_reg,
.writeable_reg = ssm4567_writeable_reg,
.volatile_reg = ssm4567_volatile_reg,
.cache_type = REGCACHE_RBTREE,
.reg_defaults = ssm4567_reg_defaults,
.num_reg_defaults = ARRAY_SIZE(ssm4567_reg_defaults),
};
static int ssm4567_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct ssm4567 *ssm4567;
int ret;
ssm4567 = devm_kzalloc(&i2c->dev, sizeof(*ssm4567), GFP_KERNEL);
if (ssm4567 == NULL)
return -ENOMEM;
i2c_set_clientdata(i2c, ssm4567);
ssm4567->regmap = devm_regmap_init_i2c(i2c, &ssm4567_regmap_config);
if (IS_ERR(ssm4567->regmap))
return PTR_ERR(ssm4567->regmap);
ret = regmap_write(ssm4567->regmap, SSM4567_REG_SOFT_RESET, 0x00);
if (ret)
return ret;
ret = ssm4567_set_power(ssm4567, false);
if (ret)
return ret;
return snd_soc_register_codec(&i2c->dev, &ssm4567_codec_driver,
&ssm4567_dai, 1);
}
static int ssm4567_i2c_remove(struct i2c_client *client)
{
snd_soc_unregister_codec(&client->dev);
return 0;
}
static const struct i2c_device_id ssm4567_i2c_ids[] = {
{ "ssm4567", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, ssm4567_i2c_ids);
static struct i2c_driver ssm4567_driver = {
.driver = {
.name = "ssm4567",
.owner = THIS_MODULE,
},
.probe = ssm4567_i2c_probe,
.remove = ssm4567_i2c_remove,
.id_table = ssm4567_i2c_ids,
};
module_i2c_driver(ssm4567_driver);
MODULE_DESCRIPTION("ASoC SSM4567 driver");
MODULE_AUTHOR("Anatol Pomozov <anatol@chromium.org>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ShikharArvind/myriad_eye | drivers/video/msm/mdss/mdss_mdp_util.c | 124 | 16397 | /* Copyright (c) 2012-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.
*
*/
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/dma-mapping.h>
#include <linux/errno.h>
#include <linux/file.h>
#include <linux/msm_ion.h>
#include <linux/iommu.h>
#include <linux/msm_kgsl.h>
#include <linux/spinlock.h>
#include <linux/types.h>
#include <media/msm_media_info.h>
#include <mach/iommu_domains.h>
#include "mdss_fb.h"
#include "mdss_mdp.h"
#include "mdss_mdp_formats.h"
#include "mdss_debug.h"
enum {
MDP_INTR_VSYNC_INTF_0,
MDP_INTR_VSYNC_INTF_1,
MDP_INTR_VSYNC_INTF_2,
MDP_INTR_VSYNC_INTF_3,
MDP_INTR_UNDERRUN_INTF_0,
MDP_INTR_UNDERRUN_INTF_1,
MDP_INTR_UNDERRUN_INTF_2,
MDP_INTR_UNDERRUN_INTF_3,
MDP_INTR_PING_PONG_0,
MDP_INTR_PING_PONG_1,
MDP_INTR_PING_PONG_2,
MDP_INTR_PING_PONG_3,
MDP_INTR_PING_PONG_0_RD_PTR,
MDP_INTR_PING_PONG_1_RD_PTR,
MDP_INTR_PING_PONG_2_RD_PTR,
MDP_INTR_PING_PONG_3_RD_PTR,
MDP_INTR_WB_0,
MDP_INTR_WB_1,
MDP_INTR_WB_2,
MDP_INTR_MAX,
};
struct intr_callback {
void (*func)(void *);
void *arg;
};
struct intr_callback mdp_intr_cb[MDP_INTR_MAX];
static DEFINE_SPINLOCK(mdss_mdp_intr_lock);
static int mdss_mdp_intr2index(u32 intr_type, u32 intf_num)
{
int index = -1;
switch (intr_type) {
case MDSS_MDP_IRQ_INTF_UNDER_RUN:
index = MDP_INTR_UNDERRUN_INTF_0 + (intf_num - MDSS_MDP_INTF0);
break;
case MDSS_MDP_IRQ_INTF_VSYNC:
index = MDP_INTR_VSYNC_INTF_0 + (intf_num - MDSS_MDP_INTF0);
break;
case MDSS_MDP_IRQ_PING_PONG_COMP:
index = MDP_INTR_PING_PONG_0 + intf_num;
break;
case MDSS_MDP_IRQ_PING_PONG_RD_PTR:
index = MDP_INTR_PING_PONG_0_RD_PTR + intf_num;
break;
case MDSS_MDP_IRQ_WB_ROT_COMP:
index = MDP_INTR_WB_0 + intf_num;
break;
case MDSS_MDP_IRQ_WB_WFD:
index = MDP_INTR_WB_2 + intf_num;
break;
}
return index;
}
int mdss_mdp_set_intr_callback(u32 intr_type, u32 intf_num,
void (*fnc_ptr)(void *), void *arg)
{
unsigned long flags;
int index;
index = mdss_mdp_intr2index(intr_type, intf_num);
if (index < 0) {
pr_warn("invalid intr type=%u intf_num=%u\n",
intr_type, intf_num);
return -EINVAL;
}
spin_lock_irqsave(&mdss_mdp_intr_lock, flags);
WARN(mdp_intr_cb[index].func && fnc_ptr,
"replacing current intr callback for ndx=%d\n", index);
mdp_intr_cb[index].func = fnc_ptr;
mdp_intr_cb[index].arg = arg;
spin_unlock_irqrestore(&mdss_mdp_intr_lock, flags);
return 0;
}
static inline void mdss_mdp_intr_done(int index)
{
void (*fnc)(void *);
void *arg;
spin_lock(&mdss_mdp_intr_lock);
fnc = mdp_intr_cb[index].func;
arg = mdp_intr_cb[index].arg;
spin_unlock(&mdss_mdp_intr_lock);
if (fnc)
fnc(arg);
}
irqreturn_t mdss_mdp_isr(int irq, void *ptr)
{
struct mdss_data_type *mdata = ptr;
u32 isr, mask, hist_isr, hist_mask;
isr = MDSS_MDP_REG_READ(MDSS_MDP_REG_INTR_STATUS);
if (isr == 0)
goto mdp_isr_done;
mask = MDSS_MDP_REG_READ(MDSS_MDP_REG_INTR_EN);
MDSS_MDP_REG_WRITE(MDSS_MDP_REG_INTR_CLEAR, isr);
pr_debug("%s: isr=%x mask=%x\n", __func__, isr, mask);
isr &= mask;
if (isr == 0)
goto mdp_isr_done;
if (isr & MDSS_MDP_INTR_INTF_0_UNDERRUN)
mdss_mdp_intr_done(MDP_INTR_UNDERRUN_INTF_0);
if (isr & MDSS_MDP_INTR_INTF_1_UNDERRUN)
mdss_mdp_intr_done(MDP_INTR_UNDERRUN_INTF_1);
if (isr & MDSS_MDP_INTR_INTF_2_UNDERRUN)
mdss_mdp_intr_done(MDP_INTR_UNDERRUN_INTF_2);
if (isr & MDSS_MDP_INTR_INTF_3_UNDERRUN)
mdss_mdp_intr_done(MDP_INTR_UNDERRUN_INTF_3);
if (isr & MDSS_MDP_INTR_PING_PONG_0_DONE)
mdss_mdp_intr_done(MDP_INTR_PING_PONG_0);
if (isr & MDSS_MDP_INTR_PING_PONG_1_DONE)
mdss_mdp_intr_done(MDP_INTR_PING_PONG_1);
if (isr & MDSS_MDP_INTR_PING_PONG_2_DONE)
mdss_mdp_intr_done(MDP_INTR_PING_PONG_2);
if (isr & MDSS_MDP_INTR_PING_PONG_3_DONE)
mdss_mdp_intr_done(MDP_INTR_PING_PONG_3);
if (isr & MDSS_MDP_INTR_PING_PONG_0_RD_PTR)
mdss_mdp_intr_done(MDP_INTR_PING_PONG_0_RD_PTR);
if (isr & MDSS_MDP_INTR_PING_PONG_1_RD_PTR)
mdss_mdp_intr_done(MDP_INTR_PING_PONG_1_RD_PTR);
if (isr & MDSS_MDP_INTR_PING_PONG_2_RD_PTR)
mdss_mdp_intr_done(MDP_INTR_PING_PONG_2_RD_PTR);
if (isr & MDSS_MDP_INTR_PING_PONG_3_RD_PTR)
mdss_mdp_intr_done(MDP_INTR_PING_PONG_3_RD_PTR);
if (isr & MDSS_MDP_INTR_INTF_0_VSYNC) {
mdss_mdp_intr_done(MDP_INTR_VSYNC_INTF_0);
mdss_misr_crc_collect(mdata, DISPLAY_MISR_EDP);
}
if (isr & MDSS_MDP_INTR_INTF_1_VSYNC) {
mdss_mdp_intr_done(MDP_INTR_VSYNC_INTF_1);
mdss_misr_crc_collect(mdata, DISPLAY_MISR_DSI0);
}
if (isr & MDSS_MDP_INTR_INTF_2_VSYNC) {
mdss_mdp_intr_done(MDP_INTR_VSYNC_INTF_2);
mdss_misr_crc_collect(mdata, DISPLAY_MISR_DSI1);
}
if (isr & MDSS_MDP_INTR_INTF_3_VSYNC) {
mdss_mdp_intr_done(MDP_INTR_VSYNC_INTF_3);
mdss_misr_crc_collect(mdata, DISPLAY_MISR_HDMI);
}
if (isr & MDSS_MDP_INTR_WB_0_DONE) {
mdss_mdp_intr_done(MDP_INTR_WB_0);
mdss_misr_crc_collect(mdata, DISPLAY_MISR_MDP);
}
if (isr & MDSS_MDP_INTR_WB_1_DONE) {
mdss_mdp_intr_done(MDP_INTR_WB_1);
mdss_misr_crc_collect(mdata, DISPLAY_MISR_MDP);
}
if (isr & MDSS_MDP_INTR_WB_2_DONE) {
mdss_mdp_intr_done(MDP_INTR_WB_2);
mdss_misr_crc_collect(mdata, DISPLAY_MISR_MDP);
}
mdp_isr_done:
hist_isr = MDSS_MDP_REG_READ(MDSS_MDP_REG_HIST_INTR_STATUS);
if (hist_isr == 0)
goto hist_isr_done;
hist_mask = MDSS_MDP_REG_READ(MDSS_MDP_REG_HIST_INTR_EN);
MDSS_MDP_REG_WRITE(MDSS_MDP_REG_HIST_INTR_CLEAR, hist_isr);
hist_isr &= hist_mask;
if (hist_isr == 0)
goto hist_isr_done;
mdss_mdp_hist_intr_done(hist_isr);
hist_isr_done:
return IRQ_HANDLED;
}
struct mdss_mdp_format_params *mdss_mdp_get_format_params(u32 format)
{
if (format < MDP_IMGTYPE_LIMIT) {
struct mdss_mdp_format_params *fmt = NULL;
int i;
for (i = 0; i < ARRAY_SIZE(mdss_mdp_format_map); i++) {
fmt = &mdss_mdp_format_map[i];
if (format == fmt->format)
return fmt;
}
}
return NULL;
}
void mdss_mdp_intersect_rect(struct mdss_mdp_img_rect *res_rect,
const struct mdss_mdp_img_rect *dst_rect,
const struct mdss_mdp_img_rect *sci_rect)
{
int l = max(dst_rect->x, sci_rect->x);
int t = max(dst_rect->y, sci_rect->y);
int r = min((dst_rect->x + dst_rect->w), (sci_rect->x + sci_rect->w));
int b = min((dst_rect->y + dst_rect->h), (sci_rect->y + sci_rect->h));
if (r < l || b < t)
*res_rect = (struct mdss_mdp_img_rect){0, 0, 0, 0};
else
*res_rect = (struct mdss_mdp_img_rect){l, t, (r-l), (b-t)};
}
void mdss_mdp_crop_rect(struct mdss_mdp_img_rect *src_rect,
struct mdss_mdp_img_rect *dst_rect,
const struct mdss_mdp_img_rect *sci_rect)
{
struct mdss_mdp_img_rect res;
mdss_mdp_intersect_rect(&res, dst_rect, sci_rect);
if (res.w && res.h) {
if ((res.w != dst_rect->w) || (res.h != dst_rect->h)) {
src_rect->x = src_rect->x + (res.x - dst_rect->x);
src_rect->y = src_rect->y + (res.y - dst_rect->y);
src_rect->w = res.w;
src_rect->h = res.h;
}
*dst_rect = (struct mdss_mdp_img_rect)
{(res.x - sci_rect->x), (res.y - sci_rect->y),
res.w, res.h};
}
}
int mdss_mdp_get_rau_strides(u32 w, u32 h,
struct mdss_mdp_format_params *fmt,
struct mdss_mdp_plane_sizes *ps)
{
if (fmt->is_yuv) {
ps->rau_cnt = DIV_ROUND_UP(w, 64);
ps->ystride[0] = 64 * 4;
ps->rau_h[0] = 4;
ps->rau_h[1] = 2;
if (fmt->chroma_sample == MDSS_MDP_CHROMA_H1V2)
ps->ystride[1] = 64 * 2;
else if (fmt->chroma_sample == MDSS_MDP_CHROMA_H2V1) {
ps->ystride[1] = 32 * 4;
ps->rau_h[1] = 4;
} else
ps->ystride[1] = 32 * 2;
ps->ystride[1] <<= 1;
} else if (fmt->fetch_planes == MDSS_MDP_PLANE_INTERLEAVED) {
ps->rau_cnt = DIV_ROUND_UP(w, 32);
ps->ystride[0] = 32 * 4 * fmt->bpp;
ps->ystride[1] = 0;
ps->rau_h[0] = 4;
ps->rau_h[1] = 0;
} else {
pr_err("Invalid format=%d\n", fmt->format);
return -EINVAL;
}
ps->ystride[0] *= ps->rau_cnt;
ps->ystride[1] *= ps->rau_cnt;
ps->num_planes = 2;
pr_debug("BWC rau_cnt=%d strides={%d,%d} heights={%d,%d}\n",
ps->rau_cnt, ps->ystride[0], ps->ystride[1],
ps->rau_h[0], ps->rau_h[1]);
return 0;
}
int mdss_mdp_get_plane_sizes(u32 format, u32 w, u32 h,
struct mdss_mdp_plane_sizes *ps, u32 bwc_mode)
{
struct mdss_mdp_format_params *fmt;
int i, rc;
u32 bpp;
if (ps == NULL)
return -EINVAL;
if ((w > MAX_IMG_WIDTH) || (h > MAX_IMG_HEIGHT))
return -ERANGE;
fmt = mdss_mdp_get_format_params(format);
if (!fmt)
return -EINVAL;
bpp = fmt->bpp;
memset(ps, 0, sizeof(struct mdss_mdp_plane_sizes));
if (bwc_mode) {
u32 height, meta_size;
rc = mdss_mdp_get_rau_strides(w, h, fmt, ps);
if (rc)
return rc;
height = DIV_ROUND_UP(h, ps->rau_h[0]);
meta_size = DIV_ROUND_UP(ps->rau_cnt, 8);
ps->ystride[1] += meta_size;
ps->ystride[0] += ps->ystride[1] + meta_size;
ps->plane_size[0] = ps->ystride[0] * height;
ps->ystride[1] = 2;
ps->plane_size[1] = 2 * ps->rau_cnt * height;
pr_debug("BWC data stride=%d size=%d meta size=%d\n",
ps->ystride[0], ps->plane_size[0], ps->plane_size[1]);
} else {
if (fmt->fetch_planes == MDSS_MDP_PLANE_INTERLEAVED) {
ps->num_planes = 1;
ps->plane_size[0] = w * h * bpp;
ps->ystride[0] = w * bpp;
} else if (format == MDP_Y_CBCR_H2V2_VENUS) {
int cf = COLOR_FMT_NV12;
ps->num_planes = 2;
ps->ystride[0] = VENUS_Y_STRIDE(cf, w);
ps->ystride[1] = VENUS_UV_STRIDE(cf, w);
ps->plane_size[0] = VENUS_Y_SCANLINES(cf, h) *
ps->ystride[0];
ps->plane_size[1] = VENUS_UV_SCANLINES(cf, h) *
ps->ystride[1];
} else {
u8 hmap[] = { 1, 2, 1, 2 };
u8 vmap[] = { 1, 1, 2, 2 };
u8 horiz, vert, stride_align, height_align;
horiz = hmap[fmt->chroma_sample];
vert = vmap[fmt->chroma_sample];
switch (format) {
case MDP_Y_CR_CB_GH2V2:
stride_align = 16;
height_align = 1;
break;
default:
stride_align = 1;
height_align = 1;
break;
}
ps->ystride[0] = ALIGN(w, stride_align);
ps->ystride[1] = ALIGN(w / horiz, stride_align);
ps->plane_size[0] = ps->ystride[0] *
ALIGN(h, height_align);
ps->plane_size[1] = ps->ystride[1] * (h / vert);
if (fmt->fetch_planes == MDSS_MDP_PLANE_PSEUDO_PLANAR) {
ps->num_planes = 2;
ps->plane_size[1] *= 2;
ps->ystride[1] *= 2;
} else {
ps->num_planes = 3;
ps->plane_size[2] = ps->plane_size[1];
ps->ystride[2] = ps->ystride[1];
}
}
}
for (i = 0; i < ps->num_planes; i++)
ps->total_size += ps->plane_size[i];
return 0;
}
int mdss_mdp_data_check(struct mdss_mdp_data *data,
struct mdss_mdp_plane_sizes *ps)
{
struct mdss_mdp_img_data *prev, *curr;
int i;
if (!ps)
return 0;
if (!data || data->num_planes == 0)
return -ENOMEM;
pr_debug("srcp0=%x len=%u frame_size=%u\n", data->p[0].addr,
data->p[0].len, ps->total_size);
for (i = 0; i < ps->num_planes; i++) {
curr = &data->p[i];
if (i >= data->num_planes) {
u32 psize = ps->plane_size[i-1];
prev = &data->p[i-1];
if (prev->len > psize) {
curr->len = prev->len - psize;
prev->len = psize;
}
curr->addr = prev->addr + psize;
}
if (curr->len < ps->plane_size[i]) {
pr_err("insufficient mem=%u p=%d len=%u\n",
curr->len, i, ps->plane_size[i]);
return -ENOMEM;
}
pr_debug("plane[%d] addr=%x len=%u\n", i,
curr->addr, curr->len);
}
data->num_planes = ps->num_planes;
return 0;
}
void mdss_mdp_data_calc_offset(struct mdss_mdp_data *data, u16 x, u16 y,
struct mdss_mdp_plane_sizes *ps, struct mdss_mdp_format_params *fmt)
{
if ((x == 0) && (y == 0))
return;
data->p[0].addr += y * ps->ystride[0];
if (data->num_planes == 1) {
data->p[0].addr += x * fmt->bpp;
} else {
u8 hmap[] = { 1, 2, 1, 2 };
u8 vmap[] = { 1, 1, 2, 2 };
u16 xoff = x / hmap[fmt->chroma_sample];
u16 yoff = y / vmap[fmt->chroma_sample];
data->p[0].addr += x;
data->p[1].addr += xoff + (yoff * ps->ystride[1]);
if (data->num_planes == 2)
data->p[1].addr += xoff;
else
data->p[2].addr += xoff + (yoff * ps->ystride[2]);
}
}
int mdss_mdp_put_img(struct mdss_mdp_img_data *data)
{
struct ion_client *iclient = mdss_get_ionclient();
if (data->flags & MDP_MEMORY_ID_TYPE_FB) {
pr_debug("fb mem buf=0x%x\n", data->addr);
fput_light(data->srcp_file, data->p_need);
data->srcp_file = NULL;
} else if (data->srcp_file) {
pr_debug("pmem buf=0x%x\n", data->addr);
data->srcp_file = NULL;
} else if (!IS_ERR_OR_NULL(data->srcp_ihdl) && iclient) {
pr_debug("ion hdl=%p buf=0x%x\n", data->srcp_ihdl, data->addr);
if (!iclient) {
pr_err("invalid ion client\n");
return -ENOMEM;
} else {
if (is_mdss_iommu_attached()) {
int domain;
if (data->flags & MDP_SECURE_OVERLAY_SESSION)
domain = MDSS_IOMMU_DOMAIN_SECURE;
else
domain = MDSS_IOMMU_DOMAIN_UNSECURE;
ion_unmap_iommu(iclient, data->srcp_ihdl,
mdss_get_iommu_domain(domain), 0);
if (domain == MDSS_IOMMU_DOMAIN_SECURE) {
msm_ion_unsecure_buffer(iclient,
data->srcp_ihdl);
}
}
ion_free(iclient, data->srcp_ihdl);
data->srcp_ihdl = NULL;
}
} else {
return -ENOMEM;
}
return 0;
}
int mdss_mdp_get_img(struct msmfb_data *img, struct mdss_mdp_img_data *data)
{
struct file *file;
int ret = -EINVAL;
int fb_num;
unsigned long *start, *len;
struct ion_client *iclient = mdss_get_ionclient();
start = (unsigned long *) &data->addr;
len = (unsigned long *) &data->len;
data->flags |= img->flags;
data->p_need = 0;
if (img->flags & MDP_BLIT_SRC_GEM) {
data->srcp_file = NULL;
ret = kgsl_gem_obj_addr(img->memory_id, (int) img->priv,
start, len);
} else if (img->flags & MDP_MEMORY_ID_TYPE_FB) {
file = fget_light(img->memory_id, &data->p_need);
if (file == NULL) {
pr_err("invalid framebuffer file (%d)\n",
img->memory_id);
return -EINVAL;
}
data->srcp_file = file;
if (MAJOR(file->f_dentry->d_inode->i_rdev) == FB_MAJOR) {
fb_num = MINOR(file->f_dentry->d_inode->i_rdev);
ret = mdss_fb_get_phys_info(start, len, fb_num);
if (ret)
pr_err("mdss_fb_get_phys_info() failed\n");
} else {
pr_err("invalid FB_MAJOR\n");
ret = -1;
}
} else if (iclient) {
data->srcp_ihdl = ion_import_dma_buf(iclient, img->memory_id);
if (IS_ERR_OR_NULL(data->srcp_ihdl)) {
pr_err("error on ion_import_fd\n");
ret = PTR_ERR(data->srcp_ihdl);
data->srcp_ihdl = NULL;
return ret;
}
if (is_mdss_iommu_attached()) {
int domain;
if (data->flags & MDP_SECURE_OVERLAY_SESSION) {
domain = MDSS_IOMMU_DOMAIN_SECURE;
ret = msm_ion_secure_buffer(iclient,
data->srcp_ihdl, 0x2, 0);
if (IS_ERR_VALUE(ret)) {
ion_free(iclient, data->srcp_ihdl);
pr_err("failed to secure handle (%d)\n",
ret);
return ret;
}
} else {
domain = MDSS_IOMMU_DOMAIN_UNSECURE;
}
ret = ion_map_iommu(iclient, data->srcp_ihdl,
mdss_get_iommu_domain(domain),
0, SZ_4K, 0, start, len, 0, 0);
if (ret && (domain == MDSS_IOMMU_DOMAIN_SECURE))
msm_ion_unsecure_buffer(iclient,
data->srcp_ihdl);
} else {
ret = ion_phys(iclient, data->srcp_ihdl, start,
(size_t *) len);
}
if (IS_ERR_VALUE(ret)) {
ion_free(iclient, data->srcp_ihdl);
pr_err("failed to map ion handle (%d)\n", ret);
return ret;
}
}
if (!*start) {
pr_err("start address is zero!\n");
mdss_mdp_put_img(data);
return -ENOMEM;
}
if (!ret && (img->offset < data->len)) {
data->addr += img->offset;
data->len -= img->offset;
pr_debug("mem=%d ihdl=%p buf=0x%x len=0x%x\n", img->memory_id,
data->srcp_ihdl, data->addr, data->len);
} else {
mdss_mdp_put_img(data);
return ret ? : -EOVERFLOW;
}
return ret;
}
int mdss_mdp_calc_phase_step(u32 src, u32 dst, u32 *out_phase)
{
u32 unit, residue, result;
if (src == 0 || dst == 0)
return -EINVAL;
unit = 1 << PHASE_STEP_SHIFT;
*out_phase = mult_frac(unit, src, dst);
if (src > dst) {
residue = *out_phase - unit;
result = (residue * dst) + residue;
while (result > (unit + (unit >> 1)))
result -= unit;
if ((result > residue) && (result < unit))
return -EOVERFLOW;
}
return 0;
}
| gpl-2.0 |
Anteater-GitHub/edison-linux | fs/ubifs/io.c | 1148 | 34240 | /*
* This file is part of UBIFS.
*
* Copyright (C) 2006-2008 Nokia Corporation.
* Copyright (C) 2006, 2007 University of Szeged, Hungary
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Authors: Artem Bityutskiy (Битюцкий Артём)
* Adrian Hunter
* Zoltan Sogor
*/
/*
* This file implements UBIFS I/O subsystem which provides various I/O-related
* helper functions (reading/writing/checking/validating nodes) and implements
* write-buffering support. Write buffers help to save space which otherwise
* would have been wasted for padding to the nearest minimal I/O unit boundary.
* Instead, data first goes to the write-buffer and is flushed when the
* buffer is full or when it is not used for some time (by timer). This is
* similar to the mechanism is used by JFFS2.
*
* UBIFS distinguishes between minimum write size (@c->min_io_size) and maximum
* write size (@c->max_write_size). The latter is the maximum amount of bytes
* the underlying flash is able to program at a time, and writing in
* @c->max_write_size units should presumably be faster. Obviously,
* @c->min_io_size <= @c->max_write_size. Write-buffers are of
* @c->max_write_size bytes in size for maximum performance. However, when a
* write-buffer is flushed, only the portion of it (aligned to @c->min_io_size
* boundary) which contains data is written, not the whole write-buffer,
* because this is more space-efficient.
*
* This optimization adds few complications to the code. Indeed, on the one
* hand, we want to write in optimal @c->max_write_size bytes chunks, which
* also means aligning writes at the @c->max_write_size bytes offsets. On the
* other hand, we do not want to waste space when synchronizing the write
* buffer, so during synchronization we writes in smaller chunks. And this makes
* the next write offset to be not aligned to @c->max_write_size bytes. So the
* have to make sure that the write-buffer offset (@wbuf->offs) becomes aligned
* to @c->max_write_size bytes again. We do this by temporarily shrinking
* write-buffer size (@wbuf->size).
*
* Write-buffers are defined by 'struct ubifs_wbuf' objects and protected by
* mutexes defined inside these objects. Since sometimes upper-level code
* has to lock the write-buffer (e.g. journal space reservation code), many
* functions related to write-buffers have "nolock" suffix which means that the
* caller has to lock the write-buffer before calling this function.
*
* UBIFS stores nodes at 64 bit-aligned addresses. If the node length is not
* aligned, UBIFS starts the next node from the aligned address, and the padded
* bytes may contain any rubbish. In other words, UBIFS does not put padding
* bytes in those small gaps. Common headers of nodes store real node lengths,
* not aligned lengths. Indexing nodes also store real lengths in branches.
*
* UBIFS uses padding when it pads to the next min. I/O unit. In this case it
* uses padding nodes or padding bytes, if the padding node does not fit.
*
* All UBIFS nodes are protected by CRC checksums and UBIFS checks CRC when
* they are read from the flash media.
*/
#include <linux/crc32.h>
#include <linux/slab.h>
#include "ubifs.h"
/**
* ubifs_ro_mode - switch UBIFS to read read-only mode.
* @c: UBIFS file-system description object
* @err: error code which is the reason of switching to R/O mode
*/
void ubifs_ro_mode(struct ubifs_info *c, int err)
{
if (!c->ro_error) {
c->ro_error = 1;
c->no_chk_data_crc = 0;
c->vfs_sb->s_flags |= MS_RDONLY;
ubifs_warn(c, "switched to read-only mode, error %d", err);
dump_stack();
}
}
/*
* Below are simple wrappers over UBI I/O functions which include some
* additional checks and UBIFS debugging stuff. See corresponding UBI function
* for more information.
*/
int ubifs_leb_read(const struct ubifs_info *c, int lnum, void *buf, int offs,
int len, int even_ebadmsg)
{
int err;
err = ubi_read(c->ubi, lnum, buf, offs, len);
/*
* In case of %-EBADMSG print the error message only if the
* @even_ebadmsg is true.
*/
if (err && (err != -EBADMSG || even_ebadmsg)) {
ubifs_err(c, "reading %d bytes from LEB %d:%d failed, error %d",
len, lnum, offs, err);
dump_stack();
}
return err;
}
int ubifs_leb_write(struct ubifs_info *c, int lnum, const void *buf, int offs,
int len)
{
int err;
ubifs_assert(!c->ro_media && !c->ro_mount);
if (c->ro_error)
return -EROFS;
if (!dbg_is_tst_rcvry(c))
err = ubi_leb_write(c->ubi, lnum, buf, offs, len);
else
err = dbg_leb_write(c, lnum, buf, offs, len);
if (err) {
ubifs_err(c, "writing %d bytes to LEB %d:%d failed, error %d",
len, lnum, offs, err);
ubifs_ro_mode(c, err);
dump_stack();
}
return err;
}
int ubifs_leb_change(struct ubifs_info *c, int lnum, const void *buf, int len)
{
int err;
ubifs_assert(!c->ro_media && !c->ro_mount);
if (c->ro_error)
return -EROFS;
if (!dbg_is_tst_rcvry(c))
err = ubi_leb_change(c->ubi, lnum, buf, len);
else
err = dbg_leb_change(c, lnum, buf, len);
if (err) {
ubifs_err(c, "changing %d bytes in LEB %d failed, error %d",
len, lnum, err);
ubifs_ro_mode(c, err);
dump_stack();
}
return err;
}
int ubifs_leb_unmap(struct ubifs_info *c, int lnum)
{
int err;
ubifs_assert(!c->ro_media && !c->ro_mount);
if (c->ro_error)
return -EROFS;
if (!dbg_is_tst_rcvry(c))
err = ubi_leb_unmap(c->ubi, lnum);
else
err = dbg_leb_unmap(c, lnum);
if (err) {
ubifs_err(c, "unmap LEB %d failed, error %d", lnum, err);
ubifs_ro_mode(c, err);
dump_stack();
}
return err;
}
int ubifs_leb_map(struct ubifs_info *c, int lnum)
{
int err;
ubifs_assert(!c->ro_media && !c->ro_mount);
if (c->ro_error)
return -EROFS;
if (!dbg_is_tst_rcvry(c))
err = ubi_leb_map(c->ubi, lnum);
else
err = dbg_leb_map(c, lnum);
if (err) {
ubifs_err(c, "mapping LEB %d failed, error %d", lnum, err);
ubifs_ro_mode(c, err);
dump_stack();
}
return err;
}
int ubifs_is_mapped(const struct ubifs_info *c, int lnum)
{
int err;
err = ubi_is_mapped(c->ubi, lnum);
if (err < 0) {
ubifs_err(c, "ubi_is_mapped failed for LEB %d, error %d",
lnum, err);
dump_stack();
}
return err;
}
/**
* ubifs_check_node - check node.
* @c: UBIFS file-system description object
* @buf: node to check
* @lnum: logical eraseblock number
* @offs: offset within the logical eraseblock
* @quiet: print no messages
* @must_chk_crc: indicates whether to always check the CRC
*
* This function checks node magic number and CRC checksum. This function also
* validates node length to prevent UBIFS from becoming crazy when an attacker
* feeds it a file-system image with incorrect nodes. For example, too large
* node length in the common header could cause UBIFS to read memory outside of
* allocated buffer when checking the CRC checksum.
*
* This function may skip data nodes CRC checking if @c->no_chk_data_crc is
* true, which is controlled by corresponding UBIFS mount option. However, if
* @must_chk_crc is true, then @c->no_chk_data_crc is ignored and CRC is
* checked. Similarly, if @c->mounting or @c->remounting_rw is true (we are
* mounting or re-mounting to R/W mode), @c->no_chk_data_crc is ignored and CRC
* is checked. This is because during mounting or re-mounting from R/O mode to
* R/W mode we may read journal nodes (when replying the journal or doing the
* recovery) and the journal nodes may potentially be corrupted, so checking is
* required.
*
* This function returns zero in case of success and %-EUCLEAN in case of bad
* CRC or magic.
*/
int ubifs_check_node(const struct ubifs_info *c, const void *buf, int lnum,
int offs, int quiet, int must_chk_crc)
{
int err = -EINVAL, type, node_len;
uint32_t crc, node_crc, magic;
const struct ubifs_ch *ch = buf;
ubifs_assert(lnum >= 0 && lnum < c->leb_cnt && offs >= 0);
ubifs_assert(!(offs & 7) && offs < c->leb_size);
magic = le32_to_cpu(ch->magic);
if (magic != UBIFS_NODE_MAGIC) {
if (!quiet)
ubifs_err(c, "bad magic %#08x, expected %#08x",
magic, UBIFS_NODE_MAGIC);
err = -EUCLEAN;
goto out;
}
type = ch->node_type;
if (type < 0 || type >= UBIFS_NODE_TYPES_CNT) {
if (!quiet)
ubifs_err(c, "bad node type %d", type);
goto out;
}
node_len = le32_to_cpu(ch->len);
if (node_len + offs > c->leb_size)
goto out_len;
if (c->ranges[type].max_len == 0) {
if (node_len != c->ranges[type].len)
goto out_len;
} else if (node_len < c->ranges[type].min_len ||
node_len > c->ranges[type].max_len)
goto out_len;
if (!must_chk_crc && type == UBIFS_DATA_NODE && !c->mounting &&
!c->remounting_rw && c->no_chk_data_crc)
return 0;
crc = crc32(UBIFS_CRC32_INIT, buf + 8, node_len - 8);
node_crc = le32_to_cpu(ch->crc);
if (crc != node_crc) {
if (!quiet)
ubifs_err(c, "bad CRC: calculated %#08x, read %#08x",
crc, node_crc);
err = -EUCLEAN;
goto out;
}
return 0;
out_len:
if (!quiet)
ubifs_err(c, "bad node length %d", node_len);
out:
if (!quiet) {
ubifs_err(c, "bad node at LEB %d:%d", lnum, offs);
ubifs_dump_node(c, buf);
dump_stack();
}
return err;
}
/**
* ubifs_pad - pad flash space.
* @c: UBIFS file-system description object
* @buf: buffer to put padding to
* @pad: how many bytes to pad
*
* The flash media obliges us to write only in chunks of %c->min_io_size and
* when we have to write less data we add padding node to the write-buffer and
* pad it to the next minimal I/O unit's boundary. Padding nodes help when the
* media is being scanned. If the amount of wasted space is not enough to fit a
* padding node which takes %UBIFS_PAD_NODE_SZ bytes, we write padding bytes
* pattern (%UBIFS_PADDING_BYTE).
*
* Padding nodes are also used to fill gaps when the "commit-in-gaps" method is
* used.
*/
void ubifs_pad(const struct ubifs_info *c, void *buf, int pad)
{
uint32_t crc;
ubifs_assert(pad >= 0 && !(pad & 7));
if (pad >= UBIFS_PAD_NODE_SZ) {
struct ubifs_ch *ch = buf;
struct ubifs_pad_node *pad_node = buf;
ch->magic = cpu_to_le32(UBIFS_NODE_MAGIC);
ch->node_type = UBIFS_PAD_NODE;
ch->group_type = UBIFS_NO_NODE_GROUP;
ch->padding[0] = ch->padding[1] = 0;
ch->sqnum = 0;
ch->len = cpu_to_le32(UBIFS_PAD_NODE_SZ);
pad -= UBIFS_PAD_NODE_SZ;
pad_node->pad_len = cpu_to_le32(pad);
crc = crc32(UBIFS_CRC32_INIT, buf + 8, UBIFS_PAD_NODE_SZ - 8);
ch->crc = cpu_to_le32(crc);
memset(buf + UBIFS_PAD_NODE_SZ, 0, pad);
} else if (pad > 0)
/* Too little space, padding node won't fit */
memset(buf, UBIFS_PADDING_BYTE, pad);
}
/**
* next_sqnum - get next sequence number.
* @c: UBIFS file-system description object
*/
static unsigned long long next_sqnum(struct ubifs_info *c)
{
unsigned long long sqnum;
spin_lock(&c->cnt_lock);
sqnum = ++c->max_sqnum;
spin_unlock(&c->cnt_lock);
if (unlikely(sqnum >= SQNUM_WARN_WATERMARK)) {
if (sqnum >= SQNUM_WATERMARK) {
ubifs_err(c, "sequence number overflow %llu, end of life",
sqnum);
ubifs_ro_mode(c, -EINVAL);
}
ubifs_warn(c, "running out of sequence numbers, end of life soon");
}
return sqnum;
}
/**
* ubifs_prepare_node - prepare node to be written to flash.
* @c: UBIFS file-system description object
* @node: the node to pad
* @len: node length
* @pad: if the buffer has to be padded
*
* This function prepares node at @node to be written to the media - it
* calculates node CRC, fills the common header, and adds proper padding up to
* the next minimum I/O unit if @pad is not zero.
*/
void ubifs_prepare_node(struct ubifs_info *c, void *node, int len, int pad)
{
uint32_t crc;
struct ubifs_ch *ch = node;
unsigned long long sqnum = next_sqnum(c);
ubifs_assert(len >= UBIFS_CH_SZ);
ch->magic = cpu_to_le32(UBIFS_NODE_MAGIC);
ch->len = cpu_to_le32(len);
ch->group_type = UBIFS_NO_NODE_GROUP;
ch->sqnum = cpu_to_le64(sqnum);
ch->padding[0] = ch->padding[1] = 0;
crc = crc32(UBIFS_CRC32_INIT, node + 8, len - 8);
ch->crc = cpu_to_le32(crc);
if (pad) {
len = ALIGN(len, 8);
pad = ALIGN(len, c->min_io_size) - len;
ubifs_pad(c, node + len, pad);
}
}
/**
* ubifs_prep_grp_node - prepare node of a group to be written to flash.
* @c: UBIFS file-system description object
* @node: the node to pad
* @len: node length
* @last: indicates the last node of the group
*
* This function prepares node at @node to be written to the media - it
* calculates node CRC and fills the common header.
*/
void ubifs_prep_grp_node(struct ubifs_info *c, void *node, int len, int last)
{
uint32_t crc;
struct ubifs_ch *ch = node;
unsigned long long sqnum = next_sqnum(c);
ubifs_assert(len >= UBIFS_CH_SZ);
ch->magic = cpu_to_le32(UBIFS_NODE_MAGIC);
ch->len = cpu_to_le32(len);
if (last)
ch->group_type = UBIFS_LAST_OF_NODE_GROUP;
else
ch->group_type = UBIFS_IN_NODE_GROUP;
ch->sqnum = cpu_to_le64(sqnum);
ch->padding[0] = ch->padding[1] = 0;
crc = crc32(UBIFS_CRC32_INIT, node + 8, len - 8);
ch->crc = cpu_to_le32(crc);
}
/**
* wbuf_timer_callback - write-buffer timer callback function.
* @timer: timer data (write-buffer descriptor)
*
* This function is called when the write-buffer timer expires.
*/
static enum hrtimer_restart wbuf_timer_callback_nolock(struct hrtimer *timer)
{
struct ubifs_wbuf *wbuf = container_of(timer, struct ubifs_wbuf, timer);
dbg_io("jhead %s", dbg_jhead(wbuf->jhead));
wbuf->need_sync = 1;
wbuf->c->need_wbuf_sync = 1;
ubifs_wake_up_bgt(wbuf->c);
return HRTIMER_NORESTART;
}
/**
* new_wbuf_timer - start new write-buffer timer.
* @wbuf: write-buffer descriptor
*/
static void new_wbuf_timer_nolock(struct ubifs_wbuf *wbuf)
{
ubifs_assert(!hrtimer_active(&wbuf->timer));
if (wbuf->no_timer)
return;
dbg_io("set timer for jhead %s, %llu-%llu millisecs",
dbg_jhead(wbuf->jhead),
div_u64(ktime_to_ns(wbuf->softlimit), USEC_PER_SEC),
div_u64(ktime_to_ns(wbuf->softlimit) + wbuf->delta,
USEC_PER_SEC));
hrtimer_start_range_ns(&wbuf->timer, wbuf->softlimit, wbuf->delta,
HRTIMER_MODE_REL);
}
/**
* cancel_wbuf_timer - cancel write-buffer timer.
* @wbuf: write-buffer descriptor
*/
static void cancel_wbuf_timer_nolock(struct ubifs_wbuf *wbuf)
{
if (wbuf->no_timer)
return;
wbuf->need_sync = 0;
hrtimer_cancel(&wbuf->timer);
}
/**
* ubifs_wbuf_sync_nolock - synchronize write-buffer.
* @wbuf: write-buffer to synchronize
*
* This function synchronizes write-buffer @buf and returns zero in case of
* success or a negative error code in case of failure.
*
* Note, although write-buffers are of @c->max_write_size, this function does
* not necessarily writes all @c->max_write_size bytes to the flash. Instead,
* if the write-buffer is only partially filled with data, only the used part
* of the write-buffer (aligned on @c->min_io_size boundary) is synchronized.
* This way we waste less space.
*/
int ubifs_wbuf_sync_nolock(struct ubifs_wbuf *wbuf)
{
struct ubifs_info *c = wbuf->c;
int err, dirt, sync_len;
cancel_wbuf_timer_nolock(wbuf);
if (!wbuf->used || wbuf->lnum == -1)
/* Write-buffer is empty or not seeked */
return 0;
dbg_io("LEB %d:%d, %d bytes, jhead %s",
wbuf->lnum, wbuf->offs, wbuf->used, dbg_jhead(wbuf->jhead));
ubifs_assert(!(wbuf->avail & 7));
ubifs_assert(wbuf->offs + wbuf->size <= c->leb_size);
ubifs_assert(wbuf->size >= c->min_io_size);
ubifs_assert(wbuf->size <= c->max_write_size);
ubifs_assert(wbuf->size % c->min_io_size == 0);
ubifs_assert(!c->ro_media && !c->ro_mount);
if (c->leb_size - wbuf->offs >= c->max_write_size)
ubifs_assert(!((wbuf->offs + wbuf->size) % c->max_write_size));
if (c->ro_error)
return -EROFS;
/*
* Do not write whole write buffer but write only the minimum necessary
* amount of min. I/O units.
*/
sync_len = ALIGN(wbuf->used, c->min_io_size);
dirt = sync_len - wbuf->used;
if (dirt)
ubifs_pad(c, wbuf->buf + wbuf->used, dirt);
err = ubifs_leb_write(c, wbuf->lnum, wbuf->buf, wbuf->offs, sync_len);
if (err)
return err;
spin_lock(&wbuf->lock);
wbuf->offs += sync_len;
/*
* Now @wbuf->offs is not necessarily aligned to @c->max_write_size.
* But our goal is to optimize writes and make sure we write in
* @c->max_write_size chunks and to @c->max_write_size-aligned offset.
* Thus, if @wbuf->offs is not aligned to @c->max_write_size now, make
* sure that @wbuf->offs + @wbuf->size is aligned to
* @c->max_write_size. This way we make sure that after next
* write-buffer flush we are again at the optimal offset (aligned to
* @c->max_write_size).
*/
if (c->leb_size - wbuf->offs < c->max_write_size)
wbuf->size = c->leb_size - wbuf->offs;
else if (wbuf->offs & (c->max_write_size - 1))
wbuf->size = ALIGN(wbuf->offs, c->max_write_size) - wbuf->offs;
else
wbuf->size = c->max_write_size;
wbuf->avail = wbuf->size;
wbuf->used = 0;
wbuf->next_ino = 0;
spin_unlock(&wbuf->lock);
if (wbuf->sync_callback)
err = wbuf->sync_callback(c, wbuf->lnum,
c->leb_size - wbuf->offs, dirt);
return err;
}
/**
* ubifs_wbuf_seek_nolock - seek write-buffer.
* @wbuf: write-buffer
* @lnum: logical eraseblock number to seek to
* @offs: logical eraseblock offset to seek to
*
* This function targets the write-buffer to logical eraseblock @lnum:@offs.
* The write-buffer has to be empty. Returns zero in case of success and a
* negative error code in case of failure.
*/
int ubifs_wbuf_seek_nolock(struct ubifs_wbuf *wbuf, int lnum, int offs)
{
const struct ubifs_info *c = wbuf->c;
dbg_io("LEB %d:%d, jhead %s", lnum, offs, dbg_jhead(wbuf->jhead));
ubifs_assert(lnum >= 0 && lnum < c->leb_cnt);
ubifs_assert(offs >= 0 && offs <= c->leb_size);
ubifs_assert(offs % c->min_io_size == 0 && !(offs & 7));
ubifs_assert(lnum != wbuf->lnum);
ubifs_assert(wbuf->used == 0);
spin_lock(&wbuf->lock);
wbuf->lnum = lnum;
wbuf->offs = offs;
if (c->leb_size - wbuf->offs < c->max_write_size)
wbuf->size = c->leb_size - wbuf->offs;
else if (wbuf->offs & (c->max_write_size - 1))
wbuf->size = ALIGN(wbuf->offs, c->max_write_size) - wbuf->offs;
else
wbuf->size = c->max_write_size;
wbuf->avail = wbuf->size;
wbuf->used = 0;
spin_unlock(&wbuf->lock);
return 0;
}
/**
* ubifs_bg_wbufs_sync - synchronize write-buffers.
* @c: UBIFS file-system description object
*
* This function is called by background thread to synchronize write-buffers.
* Returns zero in case of success and a negative error code in case of
* failure.
*/
int ubifs_bg_wbufs_sync(struct ubifs_info *c)
{
int err, i;
ubifs_assert(!c->ro_media && !c->ro_mount);
if (!c->need_wbuf_sync)
return 0;
c->need_wbuf_sync = 0;
if (c->ro_error) {
err = -EROFS;
goto out_timers;
}
dbg_io("synchronize");
for (i = 0; i < c->jhead_cnt; i++) {
struct ubifs_wbuf *wbuf = &c->jheads[i].wbuf;
cond_resched();
/*
* If the mutex is locked then wbuf is being changed, so
* synchronization is not necessary.
*/
if (mutex_is_locked(&wbuf->io_mutex))
continue;
mutex_lock_nested(&wbuf->io_mutex, wbuf->jhead);
if (!wbuf->need_sync) {
mutex_unlock(&wbuf->io_mutex);
continue;
}
err = ubifs_wbuf_sync_nolock(wbuf);
mutex_unlock(&wbuf->io_mutex);
if (err) {
ubifs_err(c, "cannot sync write-buffer, error %d", err);
ubifs_ro_mode(c, err);
goto out_timers;
}
}
return 0;
out_timers:
/* Cancel all timers to prevent repeated errors */
for (i = 0; i < c->jhead_cnt; i++) {
struct ubifs_wbuf *wbuf = &c->jheads[i].wbuf;
mutex_lock_nested(&wbuf->io_mutex, wbuf->jhead);
cancel_wbuf_timer_nolock(wbuf);
mutex_unlock(&wbuf->io_mutex);
}
return err;
}
/**
* ubifs_wbuf_write_nolock - write data to flash via write-buffer.
* @wbuf: write-buffer
* @buf: node to write
* @len: node length
*
* This function writes data to flash via write-buffer @wbuf. This means that
* the last piece of the node won't reach the flash media immediately if it
* does not take whole max. write unit (@c->max_write_size). Instead, the node
* will sit in RAM until the write-buffer is synchronized (e.g., by timer, or
* because more data are appended to the write-buffer).
*
* This function returns zero in case of success and a negative error code in
* case of failure. If the node cannot be written because there is no more
* space in this logical eraseblock, %-ENOSPC is returned.
*/
int ubifs_wbuf_write_nolock(struct ubifs_wbuf *wbuf, void *buf, int len)
{
struct ubifs_info *c = wbuf->c;
int err, written, n, aligned_len = ALIGN(len, 8);
dbg_io("%d bytes (%s) to jhead %s wbuf at LEB %d:%d", len,
dbg_ntype(((struct ubifs_ch *)buf)->node_type),
dbg_jhead(wbuf->jhead), wbuf->lnum, wbuf->offs + wbuf->used);
ubifs_assert(len > 0 && wbuf->lnum >= 0 && wbuf->lnum < c->leb_cnt);
ubifs_assert(wbuf->offs >= 0 && wbuf->offs % c->min_io_size == 0);
ubifs_assert(!(wbuf->offs & 7) && wbuf->offs <= c->leb_size);
ubifs_assert(wbuf->avail > 0 && wbuf->avail <= wbuf->size);
ubifs_assert(wbuf->size >= c->min_io_size);
ubifs_assert(wbuf->size <= c->max_write_size);
ubifs_assert(wbuf->size % c->min_io_size == 0);
ubifs_assert(mutex_is_locked(&wbuf->io_mutex));
ubifs_assert(!c->ro_media && !c->ro_mount);
ubifs_assert(!c->space_fixup);
if (c->leb_size - wbuf->offs >= c->max_write_size)
ubifs_assert(!((wbuf->offs + wbuf->size) % c->max_write_size));
if (c->leb_size - wbuf->offs - wbuf->used < aligned_len) {
err = -ENOSPC;
goto out;
}
cancel_wbuf_timer_nolock(wbuf);
if (c->ro_error)
return -EROFS;
if (aligned_len <= wbuf->avail) {
/*
* The node is not very large and fits entirely within
* write-buffer.
*/
memcpy(wbuf->buf + wbuf->used, buf, len);
if (aligned_len == wbuf->avail) {
dbg_io("flush jhead %s wbuf to LEB %d:%d",
dbg_jhead(wbuf->jhead), wbuf->lnum, wbuf->offs);
err = ubifs_leb_write(c, wbuf->lnum, wbuf->buf,
wbuf->offs, wbuf->size);
if (err)
goto out;
spin_lock(&wbuf->lock);
wbuf->offs += wbuf->size;
if (c->leb_size - wbuf->offs >= c->max_write_size)
wbuf->size = c->max_write_size;
else
wbuf->size = c->leb_size - wbuf->offs;
wbuf->avail = wbuf->size;
wbuf->used = 0;
wbuf->next_ino = 0;
spin_unlock(&wbuf->lock);
} else {
spin_lock(&wbuf->lock);
wbuf->avail -= aligned_len;
wbuf->used += aligned_len;
spin_unlock(&wbuf->lock);
}
goto exit;
}
written = 0;
if (wbuf->used) {
/*
* The node is large enough and does not fit entirely within
* current available space. We have to fill and flush
* write-buffer and switch to the next max. write unit.
*/
dbg_io("flush jhead %s wbuf to LEB %d:%d",
dbg_jhead(wbuf->jhead), wbuf->lnum, wbuf->offs);
memcpy(wbuf->buf + wbuf->used, buf, wbuf->avail);
err = ubifs_leb_write(c, wbuf->lnum, wbuf->buf, wbuf->offs,
wbuf->size);
if (err)
goto out;
wbuf->offs += wbuf->size;
len -= wbuf->avail;
aligned_len -= wbuf->avail;
written += wbuf->avail;
} else if (wbuf->offs & (c->max_write_size - 1)) {
/*
* The write-buffer offset is not aligned to
* @c->max_write_size and @wbuf->size is less than
* @c->max_write_size. Write @wbuf->size bytes to make sure the
* following writes are done in optimal @c->max_write_size
* chunks.
*/
dbg_io("write %d bytes to LEB %d:%d",
wbuf->size, wbuf->lnum, wbuf->offs);
err = ubifs_leb_write(c, wbuf->lnum, buf, wbuf->offs,
wbuf->size);
if (err)
goto out;
wbuf->offs += wbuf->size;
len -= wbuf->size;
aligned_len -= wbuf->size;
written += wbuf->size;
}
/*
* The remaining data may take more whole max. write units, so write the
* remains multiple to max. write unit size directly to the flash media.
* We align node length to 8-byte boundary because we anyway flash wbuf
* if the remaining space is less than 8 bytes.
*/
n = aligned_len >> c->max_write_shift;
if (n) {
n <<= c->max_write_shift;
dbg_io("write %d bytes to LEB %d:%d", n, wbuf->lnum,
wbuf->offs);
err = ubifs_leb_write(c, wbuf->lnum, buf + written,
wbuf->offs, n);
if (err)
goto out;
wbuf->offs += n;
aligned_len -= n;
len -= n;
written += n;
}
spin_lock(&wbuf->lock);
if (aligned_len)
/*
* And now we have what's left and what does not take whole
* max. write unit, so write it to the write-buffer and we are
* done.
*/
memcpy(wbuf->buf, buf + written, len);
if (c->leb_size - wbuf->offs >= c->max_write_size)
wbuf->size = c->max_write_size;
else
wbuf->size = c->leb_size - wbuf->offs;
wbuf->avail = wbuf->size - aligned_len;
wbuf->used = aligned_len;
wbuf->next_ino = 0;
spin_unlock(&wbuf->lock);
exit:
if (wbuf->sync_callback) {
int free = c->leb_size - wbuf->offs - wbuf->used;
err = wbuf->sync_callback(c, wbuf->lnum, free, 0);
if (err)
goto out;
}
if (wbuf->used)
new_wbuf_timer_nolock(wbuf);
return 0;
out:
ubifs_err(c, "cannot write %d bytes to LEB %d:%d, error %d",
len, wbuf->lnum, wbuf->offs, err);
ubifs_dump_node(c, buf);
dump_stack();
ubifs_dump_leb(c, wbuf->lnum);
return err;
}
/**
* ubifs_write_node - write node to the media.
* @c: UBIFS file-system description object
* @buf: the node to write
* @len: node length
* @lnum: logical eraseblock number
* @offs: offset within the logical eraseblock
*
* This function automatically fills node magic number, assigns sequence
* number, and calculates node CRC checksum. The length of the @buf buffer has
* to be aligned to the minimal I/O unit size. This function automatically
* appends padding node and padding bytes if needed. Returns zero in case of
* success and a negative error code in case of failure.
*/
int ubifs_write_node(struct ubifs_info *c, void *buf, int len, int lnum,
int offs)
{
int err, buf_len = ALIGN(len, c->min_io_size);
dbg_io("LEB %d:%d, %s, length %d (aligned %d)",
lnum, offs, dbg_ntype(((struct ubifs_ch *)buf)->node_type), len,
buf_len);
ubifs_assert(lnum >= 0 && lnum < c->leb_cnt && offs >= 0);
ubifs_assert(offs % c->min_io_size == 0 && offs < c->leb_size);
ubifs_assert(!c->ro_media && !c->ro_mount);
ubifs_assert(!c->space_fixup);
if (c->ro_error)
return -EROFS;
ubifs_prepare_node(c, buf, len, 1);
err = ubifs_leb_write(c, lnum, buf, offs, buf_len);
if (err)
ubifs_dump_node(c, buf);
return err;
}
/**
* ubifs_read_node_wbuf - read node from the media or write-buffer.
* @wbuf: wbuf to check for un-written data
* @buf: buffer to read to
* @type: node type
* @len: node length
* @lnum: logical eraseblock number
* @offs: offset within the logical eraseblock
*
* This function reads a node of known type and length, checks it and stores
* in @buf. If the node partially or fully sits in the write-buffer, this
* function takes data from the buffer, otherwise it reads the flash media.
* Returns zero in case of success, %-EUCLEAN if CRC mismatched and a negative
* error code in case of failure.
*/
int ubifs_read_node_wbuf(struct ubifs_wbuf *wbuf, void *buf, int type, int len,
int lnum, int offs)
{
const struct ubifs_info *c = wbuf->c;
int err, rlen, overlap;
struct ubifs_ch *ch = buf;
dbg_io("LEB %d:%d, %s, length %d, jhead %s", lnum, offs,
dbg_ntype(type), len, dbg_jhead(wbuf->jhead));
ubifs_assert(wbuf && lnum >= 0 && lnum < c->leb_cnt && offs >= 0);
ubifs_assert(!(offs & 7) && offs < c->leb_size);
ubifs_assert(type >= 0 && type < UBIFS_NODE_TYPES_CNT);
spin_lock(&wbuf->lock);
overlap = (lnum == wbuf->lnum && offs + len > wbuf->offs);
if (!overlap) {
/* We may safely unlock the write-buffer and read the data */
spin_unlock(&wbuf->lock);
return ubifs_read_node(c, buf, type, len, lnum, offs);
}
/* Don't read under wbuf */
rlen = wbuf->offs - offs;
if (rlen < 0)
rlen = 0;
/* Copy the rest from the write-buffer */
memcpy(buf + rlen, wbuf->buf + offs + rlen - wbuf->offs, len - rlen);
spin_unlock(&wbuf->lock);
if (rlen > 0) {
/* Read everything that goes before write-buffer */
err = ubifs_leb_read(c, lnum, buf, offs, rlen, 0);
if (err && err != -EBADMSG)
return err;
}
if (type != ch->node_type) {
ubifs_err(c, "bad node type (%d but expected %d)",
ch->node_type, type);
goto out;
}
err = ubifs_check_node(c, buf, lnum, offs, 0, 0);
if (err) {
ubifs_err(c, "expected node type %d", type);
return err;
}
rlen = le32_to_cpu(ch->len);
if (rlen != len) {
ubifs_err(c, "bad node length %d, expected %d", rlen, len);
goto out;
}
return 0;
out:
ubifs_err(c, "bad node at LEB %d:%d", lnum, offs);
ubifs_dump_node(c, buf);
dump_stack();
return -EINVAL;
}
/**
* ubifs_read_node - read node.
* @c: UBIFS file-system description object
* @buf: buffer to read to
* @type: node type
* @len: node length (not aligned)
* @lnum: logical eraseblock number
* @offs: offset within the logical eraseblock
*
* This function reads a node of known type and and length, checks it and
* stores in @buf. Returns zero in case of success, %-EUCLEAN if CRC mismatched
* and a negative error code in case of failure.
*/
int ubifs_read_node(const struct ubifs_info *c, void *buf, int type, int len,
int lnum, int offs)
{
int err, l;
struct ubifs_ch *ch = buf;
dbg_io("LEB %d:%d, %s, length %d", lnum, offs, dbg_ntype(type), len);
ubifs_assert(lnum >= 0 && lnum < c->leb_cnt && offs >= 0);
ubifs_assert(len >= UBIFS_CH_SZ && offs + len <= c->leb_size);
ubifs_assert(!(offs & 7) && offs < c->leb_size);
ubifs_assert(type >= 0 && type < UBIFS_NODE_TYPES_CNT);
err = ubifs_leb_read(c, lnum, buf, offs, len, 0);
if (err && err != -EBADMSG)
return err;
if (type != ch->node_type) {
ubifs_errc(c, "bad node type (%d but expected %d)",
ch->node_type, type);
goto out;
}
err = ubifs_check_node(c, buf, lnum, offs, 0, 0);
if (err) {
ubifs_errc(c, "expected node type %d", type);
return err;
}
l = le32_to_cpu(ch->len);
if (l != len) {
ubifs_errc(c, "bad node length %d, expected %d", l, len);
goto out;
}
return 0;
out:
ubifs_errc(c, "bad node at LEB %d:%d, LEB mapping status %d", lnum,
offs, ubi_is_mapped(c->ubi, lnum));
if (!c->probing) {
ubifs_dump_node(c, buf);
dump_stack();
}
return -EINVAL;
}
/**
* ubifs_wbuf_init - initialize write-buffer.
* @c: UBIFS file-system description object
* @wbuf: write-buffer to initialize
*
* This function initializes write-buffer. Returns zero in case of success
* %-ENOMEM in case of failure.
*/
int ubifs_wbuf_init(struct ubifs_info *c, struct ubifs_wbuf *wbuf)
{
size_t size;
wbuf->buf = kmalloc(c->max_write_size, GFP_KERNEL);
if (!wbuf->buf)
return -ENOMEM;
size = (c->max_write_size / UBIFS_CH_SZ + 1) * sizeof(ino_t);
wbuf->inodes = kmalloc(size, GFP_KERNEL);
if (!wbuf->inodes) {
kfree(wbuf->buf);
wbuf->buf = NULL;
return -ENOMEM;
}
wbuf->used = 0;
wbuf->lnum = wbuf->offs = -1;
/*
* If the LEB starts at the max. write size aligned address, then
* write-buffer size has to be set to @c->max_write_size. Otherwise,
* set it to something smaller so that it ends at the closest max.
* write size boundary.
*/
size = c->max_write_size - (c->leb_start % c->max_write_size);
wbuf->avail = wbuf->size = size;
wbuf->sync_callback = NULL;
mutex_init(&wbuf->io_mutex);
spin_lock_init(&wbuf->lock);
wbuf->c = c;
wbuf->next_ino = 0;
hrtimer_init(&wbuf->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
wbuf->timer.function = wbuf_timer_callback_nolock;
wbuf->softlimit = ktime_set(WBUF_TIMEOUT_SOFTLIMIT, 0);
wbuf->delta = WBUF_TIMEOUT_HARDLIMIT - WBUF_TIMEOUT_SOFTLIMIT;
wbuf->delta *= 1000000000ULL;
ubifs_assert(wbuf->delta <= ULONG_MAX);
return 0;
}
/**
* ubifs_wbuf_add_ino_nolock - add an inode number into the wbuf inode array.
* @wbuf: the write-buffer where to add
* @inum: the inode number
*
* This function adds an inode number to the inode array of the write-buffer.
*/
void ubifs_wbuf_add_ino_nolock(struct ubifs_wbuf *wbuf, ino_t inum)
{
if (!wbuf->buf)
/* NOR flash or something similar */
return;
spin_lock(&wbuf->lock);
if (wbuf->used)
wbuf->inodes[wbuf->next_ino++] = inum;
spin_unlock(&wbuf->lock);
}
/**
* wbuf_has_ino - returns if the wbuf contains data from the inode.
* @wbuf: the write-buffer
* @inum: the inode number
*
* This function returns with %1 if the write-buffer contains some data from the
* given inode otherwise it returns with %0.
*/
static int wbuf_has_ino(struct ubifs_wbuf *wbuf, ino_t inum)
{
int i, ret = 0;
spin_lock(&wbuf->lock);
for (i = 0; i < wbuf->next_ino; i++)
if (inum == wbuf->inodes[i]) {
ret = 1;
break;
}
spin_unlock(&wbuf->lock);
return ret;
}
/**
* ubifs_sync_wbufs_by_inode - synchronize write-buffers for an inode.
* @c: UBIFS file-system description object
* @inode: inode to synchronize
*
* This function synchronizes write-buffers which contain nodes belonging to
* @inode. Returns zero in case of success and a negative error code in case of
* failure.
*/
int ubifs_sync_wbufs_by_inode(struct ubifs_info *c, struct inode *inode)
{
int i, err = 0;
for (i = 0; i < c->jhead_cnt; i++) {
struct ubifs_wbuf *wbuf = &c->jheads[i].wbuf;
if (i == GCHD)
/*
* GC head is special, do not look at it. Even if the
* head contains something related to this inode, it is
* a _copy_ of corresponding on-flash node which sits
* somewhere else.
*/
continue;
if (!wbuf_has_ino(wbuf, inode->i_ino))
continue;
mutex_lock_nested(&wbuf->io_mutex, wbuf->jhead);
if (wbuf_has_ino(wbuf, inode->i_ino))
err = ubifs_wbuf_sync_nolock(wbuf);
mutex_unlock(&wbuf->io_mutex);
if (err) {
ubifs_ro_mode(c, err);
return err;
}
}
return 0;
}
| gpl-2.0 |
psyke83/android_kernel_samsung_msm-codeaurora | net/netfilter/ipvs/ip_vs_sed.c | 1660 | 3952 | /*
* IPVS: Shortest Expected Delay scheduling module
*
* Authors: Wensong Zhang <wensong@linuxvirtualserver.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.
*
* Changes:
*
*/
/*
* The SED algorithm attempts to minimize each job's expected delay until
* completion. The expected delay that the job will experience is
* (Ci + 1) / Ui if sent to the ith server, in which Ci is the number of
* jobs on the ith server and Ui is the fixed service rate (weight) of
* the ith server. The SED algorithm adopts a greedy policy that each does
* what is in its own best interest, i.e. to join the queue which would
* minimize its expected delay of completion.
*
* See the following paper for more information:
* A. Weinrib and S. Shenker, Greed is not enough: Adaptive load sharing
* in large heterogeneous systems. In Proceedings IEEE INFOCOM'88,
* pages 986-994, 1988.
*
* Thanks must go to Marko Buuri <marko@buuri.name> for talking SED to me.
*
* The difference between SED and WLC is that SED includes the incoming
* job in the cost function (the increment of 1). SED may outperform
* WLC, while scheduling big jobs under larger heterogeneous systems
* (the server weight varies a lot).
*
*/
#define KMSG_COMPONENT "IPVS"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/module.h>
#include <linux/kernel.h>
#include <net/ip_vs.h>
static inline unsigned int
ip_vs_sed_dest_overhead(struct ip_vs_dest *dest)
{
/*
* We only use the active connection number in the cost
* calculation here.
*/
return atomic_read(&dest->activeconns) + 1;
}
/*
* Weighted Least Connection scheduling
*/
static struct ip_vs_dest *
ip_vs_sed_schedule(struct ip_vs_service *svc, const struct sk_buff *skb)
{
struct ip_vs_dest *dest, *least;
unsigned int loh, doh;
IP_VS_DBG(6, "%s(): Scheduling...\n", __func__);
/*
* We calculate the load of each dest server as follows:
* (server expected overhead) / dest->weight
*
* Remember -- no floats in kernel mode!!!
* The comparison of h1*w2 > h2*w1 is equivalent to that of
* h1/w1 > h2/w2
* if every weight is larger than zero.
*
* The server with weight=0 is quiesced and will not receive any
* new connections.
*/
list_for_each_entry(dest, &svc->destinations, n_list) {
if (!(dest->flags & IP_VS_DEST_F_OVERLOAD) &&
atomic_read(&dest->weight) > 0) {
least = dest;
loh = ip_vs_sed_dest_overhead(least);
goto nextstage;
}
}
IP_VS_ERR_RL("SED: no destination available\n");
return NULL;
/*
* Find the destination with the least load.
*/
nextstage:
list_for_each_entry_continue(dest, &svc->destinations, n_list) {
if (dest->flags & IP_VS_DEST_F_OVERLOAD)
continue;
doh = ip_vs_sed_dest_overhead(dest);
if (loh * atomic_read(&dest->weight) >
doh * atomic_read(&least->weight)) {
least = dest;
loh = doh;
}
}
IP_VS_DBG_BUF(6, "SED: server %s:%u "
"activeconns %d refcnt %d weight %d overhead %d\n",
IP_VS_DBG_ADDR(svc->af, &least->addr), ntohs(least->port),
atomic_read(&least->activeconns),
atomic_read(&least->refcnt),
atomic_read(&least->weight), loh);
return least;
}
static struct ip_vs_scheduler ip_vs_sed_scheduler =
{
.name = "sed",
.refcnt = ATOMIC_INIT(0),
.module = THIS_MODULE,
.n_list = LIST_HEAD_INIT(ip_vs_sed_scheduler.n_list),
.schedule = ip_vs_sed_schedule,
};
static int __init ip_vs_sed_init(void)
{
return register_ip_vs_scheduler(&ip_vs_sed_scheduler);
}
static void __exit ip_vs_sed_cleanup(void)
{
unregister_ip_vs_scheduler(&ip_vs_sed_scheduler);
}
module_init(ip_vs_sed_init);
module_exit(ip_vs_sed_cleanup);
MODULE_LICENSE("GPL");
| gpl-2.0 |
L-Insomnia-P/kernel-msm | drivers/gpu/drm/ttm/ttm_tt.c | 1916 | 9152 | /**************************************************************************
*
* Copyright (c) 2006-2009 VMware, Inc., Palo Alto, CA., USA
* All Rights Reserved.
*
* 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, sub license, 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 NON-INFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS 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: Thomas Hellstrom <thellstrom-at-vmware-dot-com>
*/
#define pr_fmt(fmt) "[TTM] " fmt
#include <linux/sched.h>
#include <linux/highmem.h>
#include <linux/pagemap.h>
#include <linux/shmem_fs.h>
#include <linux/file.h>
#include <linux/swap.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <drm/drm_cache.h>
#include <drm/drm_mem_util.h>
#include <drm/ttm/ttm_module.h>
#include <drm/ttm/ttm_bo_driver.h>
#include <drm/ttm/ttm_placement.h>
#include <drm/ttm/ttm_page_alloc.h>
/**
* Allocates storage for pointers to the pages that back the ttm.
*/
static void ttm_tt_alloc_page_directory(struct ttm_tt *ttm)
{
ttm->pages = drm_calloc_large(ttm->num_pages, sizeof(void*));
}
static void ttm_dma_tt_alloc_page_directory(struct ttm_dma_tt *ttm)
{
ttm->ttm.pages = drm_calloc_large(ttm->ttm.num_pages, sizeof(void*));
ttm->dma_address = drm_calloc_large(ttm->ttm.num_pages,
sizeof(*ttm->dma_address));
}
#ifdef CONFIG_X86
static inline int ttm_tt_set_page_caching(struct page *p,
enum ttm_caching_state c_old,
enum ttm_caching_state c_new)
{
int ret = 0;
if (PageHighMem(p))
return 0;
if (c_old != tt_cached) {
/* p isn't in the default caching state, set it to
* writeback first to free its current memtype. */
ret = set_pages_wb(p, 1);
if (ret)
return ret;
}
if (c_new == tt_wc)
ret = set_memory_wc((unsigned long) page_address(p), 1);
else if (c_new == tt_uncached)
ret = set_pages_uc(p, 1);
return ret;
}
#else /* CONFIG_X86 */
static inline int ttm_tt_set_page_caching(struct page *p,
enum ttm_caching_state c_old,
enum ttm_caching_state c_new)
{
return 0;
}
#endif /* CONFIG_X86 */
/*
* Change caching policy for the linear kernel map
* for range of pages in a ttm.
*/
static int ttm_tt_set_caching(struct ttm_tt *ttm,
enum ttm_caching_state c_state)
{
int i, j;
struct page *cur_page;
int ret;
if (ttm->caching_state == c_state)
return 0;
if (ttm->state == tt_unpopulated) {
/* Change caching but don't populate */
ttm->caching_state = c_state;
return 0;
}
if (ttm->caching_state == tt_cached)
drm_clflush_pages(ttm->pages, ttm->num_pages);
for (i = 0; i < ttm->num_pages; ++i) {
cur_page = ttm->pages[i];
if (likely(cur_page != NULL)) {
ret = ttm_tt_set_page_caching(cur_page,
ttm->caching_state,
c_state);
if (unlikely(ret != 0))
goto out_err;
}
}
ttm->caching_state = c_state;
return 0;
out_err:
for (j = 0; j < i; ++j) {
cur_page = ttm->pages[j];
if (likely(cur_page != NULL)) {
(void)ttm_tt_set_page_caching(cur_page, c_state,
ttm->caching_state);
}
}
return ret;
}
int ttm_tt_set_placement_caching(struct ttm_tt *ttm, uint32_t placement)
{
enum ttm_caching_state state;
if (placement & TTM_PL_FLAG_WC)
state = tt_wc;
else if (placement & TTM_PL_FLAG_UNCACHED)
state = tt_uncached;
else
state = tt_cached;
return ttm_tt_set_caching(ttm, state);
}
EXPORT_SYMBOL(ttm_tt_set_placement_caching);
void ttm_tt_destroy(struct ttm_tt *ttm)
{
if (unlikely(ttm == NULL))
return;
if (ttm->state == tt_bound) {
ttm_tt_unbind(ttm);
}
if (ttm->state == tt_unbound) {
ttm->bdev->driver->ttm_tt_unpopulate(ttm);
}
if (!(ttm->page_flags & TTM_PAGE_FLAG_PERSISTENT_SWAP) &&
ttm->swap_storage)
fput(ttm->swap_storage);
ttm->swap_storage = NULL;
ttm->func->destroy(ttm);
}
int ttm_tt_init(struct ttm_tt *ttm, struct ttm_bo_device *bdev,
unsigned long size, uint32_t page_flags,
struct page *dummy_read_page)
{
ttm->bdev = bdev;
ttm->glob = bdev->glob;
ttm->num_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
ttm->caching_state = tt_cached;
ttm->page_flags = page_flags;
ttm->dummy_read_page = dummy_read_page;
ttm->state = tt_unpopulated;
ttm->swap_storage = NULL;
ttm_tt_alloc_page_directory(ttm);
if (!ttm->pages) {
ttm_tt_destroy(ttm);
pr_err("Failed allocating page table\n");
return -ENOMEM;
}
return 0;
}
EXPORT_SYMBOL(ttm_tt_init);
void ttm_tt_fini(struct ttm_tt *ttm)
{
drm_free_large(ttm->pages);
ttm->pages = NULL;
}
EXPORT_SYMBOL(ttm_tt_fini);
int ttm_dma_tt_init(struct ttm_dma_tt *ttm_dma, struct ttm_bo_device *bdev,
unsigned long size, uint32_t page_flags,
struct page *dummy_read_page)
{
struct ttm_tt *ttm = &ttm_dma->ttm;
ttm->bdev = bdev;
ttm->glob = bdev->glob;
ttm->num_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
ttm->caching_state = tt_cached;
ttm->page_flags = page_flags;
ttm->dummy_read_page = dummy_read_page;
ttm->state = tt_unpopulated;
ttm->swap_storage = NULL;
INIT_LIST_HEAD(&ttm_dma->pages_list);
ttm_dma_tt_alloc_page_directory(ttm_dma);
if (!ttm->pages || !ttm_dma->dma_address) {
ttm_tt_destroy(ttm);
pr_err("Failed allocating page table\n");
return -ENOMEM;
}
return 0;
}
EXPORT_SYMBOL(ttm_dma_tt_init);
void ttm_dma_tt_fini(struct ttm_dma_tt *ttm_dma)
{
struct ttm_tt *ttm = &ttm_dma->ttm;
drm_free_large(ttm->pages);
ttm->pages = NULL;
drm_free_large(ttm_dma->dma_address);
ttm_dma->dma_address = NULL;
}
EXPORT_SYMBOL(ttm_dma_tt_fini);
void ttm_tt_unbind(struct ttm_tt *ttm)
{
int ret;
if (ttm->state == tt_bound) {
ret = ttm->func->unbind(ttm);
BUG_ON(ret);
ttm->state = tt_unbound;
}
}
int ttm_tt_bind(struct ttm_tt *ttm, struct ttm_mem_reg *bo_mem)
{
int ret = 0;
if (!ttm)
return -EINVAL;
if (ttm->state == tt_bound)
return 0;
ret = ttm->bdev->driver->ttm_tt_populate(ttm);
if (ret)
return ret;
ret = ttm->func->bind(ttm, bo_mem);
if (unlikely(ret != 0))
return ret;
ttm->state = tt_bound;
return 0;
}
EXPORT_SYMBOL(ttm_tt_bind);
int ttm_tt_swapin(struct ttm_tt *ttm)
{
struct address_space *swap_space;
struct file *swap_storage;
struct page *from_page;
struct page *to_page;
int i;
int ret = -ENOMEM;
swap_storage = ttm->swap_storage;
BUG_ON(swap_storage == NULL);
swap_space = file_inode(swap_storage)->i_mapping;
for (i = 0; i < ttm->num_pages; ++i) {
from_page = shmem_read_mapping_page(swap_space, i);
if (IS_ERR(from_page)) {
ret = PTR_ERR(from_page);
goto out_err;
}
to_page = ttm->pages[i];
if (unlikely(to_page == NULL))
goto out_err;
copy_highpage(to_page, from_page);
page_cache_release(from_page);
}
if (!(ttm->page_flags & TTM_PAGE_FLAG_PERSISTENT_SWAP))
fput(swap_storage);
ttm->swap_storage = NULL;
ttm->page_flags &= ~TTM_PAGE_FLAG_SWAPPED;
return 0;
out_err:
return ret;
}
int ttm_tt_swapout(struct ttm_tt *ttm, struct file *persistent_swap_storage)
{
struct address_space *swap_space;
struct file *swap_storage;
struct page *from_page;
struct page *to_page;
int i;
int ret = -ENOMEM;
BUG_ON(ttm->state != tt_unbound && ttm->state != tt_unpopulated);
BUG_ON(ttm->caching_state != tt_cached);
if (!persistent_swap_storage) {
swap_storage = shmem_file_setup("ttm swap",
ttm->num_pages << PAGE_SHIFT,
0);
if (unlikely(IS_ERR(swap_storage))) {
pr_err("Failed allocating swap storage\n");
return PTR_ERR(swap_storage);
}
} else
swap_storage = persistent_swap_storage;
swap_space = file_inode(swap_storage)->i_mapping;
for (i = 0; i < ttm->num_pages; ++i) {
from_page = ttm->pages[i];
if (unlikely(from_page == NULL))
continue;
to_page = shmem_read_mapping_page(swap_space, i);
if (unlikely(IS_ERR(to_page))) {
ret = PTR_ERR(to_page);
goto out_err;
}
copy_highpage(to_page, from_page);
set_page_dirty(to_page);
mark_page_accessed(to_page);
page_cache_release(to_page);
}
ttm->bdev->driver->ttm_tt_unpopulate(ttm);
ttm->swap_storage = swap_storage;
ttm->page_flags |= TTM_PAGE_FLAG_SWAPPED;
if (persistent_swap_storage)
ttm->page_flags |= TTM_PAGE_FLAG_PERSISTENT_SWAP;
return 0;
out_err:
if (!persistent_swap_storage)
fput(swap_storage);
return ret;
}
| gpl-2.0 |
CODEG3EK/Odin | drivers/mtd/nand/fsl_ifc_nand.c | 2172 | 30845 | /*
* Freescale Integrated Flash Controller NAND driver
*
* Copyright 2011-2012 Freescale Semiconductor, Inc
*
* Author: Dipen Dudhat <Dipen.Dudhat@freescale.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/nand_ecc.h>
#include <asm/fsl_ifc.h>
#define FSL_IFC_V1_1_0 0x01010000
#define ERR_BYTE 0xFF /* Value returned for read
bytes when read failed */
#define IFC_TIMEOUT_MSECS 500 /* Maximum number of mSecs to wait
for IFC NAND Machine */
struct fsl_ifc_ctrl;
/* mtd information per set */
struct fsl_ifc_mtd {
struct mtd_info mtd;
struct nand_chip chip;
struct fsl_ifc_ctrl *ctrl;
struct device *dev;
int bank; /* Chip select bank number */
unsigned int bufnum_mask; /* bufnum = page & bufnum_mask */
u8 __iomem *vbase; /* Chip select base virtual address */
};
/* overview of the fsl ifc controller */
struct fsl_ifc_nand_ctrl {
struct nand_hw_control controller;
struct fsl_ifc_mtd *chips[FSL_IFC_BANK_COUNT];
u8 __iomem *addr; /* Address of assigned IFC buffer */
unsigned int page; /* Last page written to / read from */
unsigned int read_bytes;/* Number of bytes read during command */
unsigned int column; /* Saved column from SEQIN */
unsigned int index; /* Pointer to next byte to 'read' */
unsigned int oob; /* Non zero if operating on OOB data */
unsigned int eccread; /* Non zero for a full-page ECC read */
unsigned int counter; /* counter for the initializations */
unsigned int max_bitflips; /* Saved during READ0 cmd */
};
static struct fsl_ifc_nand_ctrl *ifc_nand_ctrl;
/* 512-byte page with 4-bit ECC, 8-bit */
static struct nand_ecclayout oob_512_8bit_ecc4 = {
.eccbytes = 8,
.eccpos = {8, 9, 10, 11, 12, 13, 14, 15},
.oobfree = { {0, 5}, {6, 2} },
};
/* 512-byte page with 4-bit ECC, 16-bit */
static struct nand_ecclayout oob_512_16bit_ecc4 = {
.eccbytes = 8,
.eccpos = {8, 9, 10, 11, 12, 13, 14, 15},
.oobfree = { {2, 6}, },
};
/* 2048-byte page size with 4-bit ECC */
static struct nand_ecclayout oob_2048_ecc4 = {
.eccbytes = 32,
.eccpos = {
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39,
},
.oobfree = { {2, 6}, {40, 24} },
};
/* 4096-byte page size with 4-bit ECC */
static struct nand_ecclayout oob_4096_ecc4 = {
.eccbytes = 64,
.eccpos = {
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71,
},
.oobfree = { {2, 6}, {72, 56} },
};
/* 4096-byte page size with 8-bit ECC -- requires 218-byte OOB */
static struct nand_ecclayout oob_4096_ecc8 = {
.eccbytes = 128,
.eccpos = {
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71,
72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87,
88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99, 100, 101, 102, 103,
104, 105, 106, 107, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 118, 119,
120, 121, 122, 123, 124, 125, 126, 127,
128, 129, 130, 131, 132, 133, 134, 135,
},
.oobfree = { {2, 6}, {136, 82} },
};
/*
* Generic flash bbt descriptors
*/
static u8 bbt_pattern[] = {'B', 'b', 't', '0' };
static u8 mirror_pattern[] = {'1', 't', 'b', 'B' };
static struct nand_bbt_descr bbt_main_descr = {
.options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE | NAND_BBT_WRITE |
NAND_BBT_2BIT | NAND_BBT_VERSION,
.offs = 2, /* 0 on 8-bit small page */
.len = 4,
.veroffs = 6,
.maxblocks = 4,
.pattern = bbt_pattern,
};
static struct nand_bbt_descr bbt_mirror_descr = {
.options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE | NAND_BBT_WRITE |
NAND_BBT_2BIT | NAND_BBT_VERSION,
.offs = 2, /* 0 on 8-bit small page */
.len = 4,
.veroffs = 6,
.maxblocks = 4,
.pattern = mirror_pattern,
};
/*
* Set up the IFC hardware block and page address fields, and the ifc nand
* structure addr field to point to the correct IFC buffer in memory
*/
static void set_addr(struct mtd_info *mtd, int column, int page_addr, int oob)
{
struct nand_chip *chip = mtd->priv;
struct fsl_ifc_mtd *priv = chip->priv;
struct fsl_ifc_ctrl *ctrl = priv->ctrl;
struct fsl_ifc_regs __iomem *ifc = ctrl->regs;
int buf_num;
ifc_nand_ctrl->page = page_addr;
/* Program ROW0/COL0 */
iowrite32be(page_addr, &ifc->ifc_nand.row0);
iowrite32be((oob ? IFC_NAND_COL_MS : 0) | column, &ifc->ifc_nand.col0);
buf_num = page_addr & priv->bufnum_mask;
ifc_nand_ctrl->addr = priv->vbase + buf_num * (mtd->writesize * 2);
ifc_nand_ctrl->index = column;
/* for OOB data point to the second half of the buffer */
if (oob)
ifc_nand_ctrl->index += mtd->writesize;
}
static int is_blank(struct mtd_info *mtd, unsigned int bufnum)
{
struct nand_chip *chip = mtd->priv;
struct fsl_ifc_mtd *priv = chip->priv;
u8 __iomem *addr = priv->vbase + bufnum * (mtd->writesize * 2);
u32 __iomem *mainarea = (u32 __iomem *)addr;
u8 __iomem *oob = addr + mtd->writesize;
int i;
for (i = 0; i < mtd->writesize / 4; i++) {
if (__raw_readl(&mainarea[i]) != 0xffffffff)
return 0;
}
for (i = 0; i < chip->ecc.layout->eccbytes; i++) {
int pos = chip->ecc.layout->eccpos[i];
if (__raw_readb(&oob[pos]) != 0xff)
return 0;
}
return 1;
}
/* returns nonzero if entire page is blank */
static int check_read_ecc(struct mtd_info *mtd, struct fsl_ifc_ctrl *ctrl,
u32 *eccstat, unsigned int bufnum)
{
u32 reg = eccstat[bufnum / 4];
int errors;
errors = (reg >> ((3 - bufnum % 4) * 8)) & 15;
return errors;
}
/*
* execute IFC NAND command and wait for it to complete
*/
static void fsl_ifc_run_command(struct mtd_info *mtd)
{
struct nand_chip *chip = mtd->priv;
struct fsl_ifc_mtd *priv = chip->priv;
struct fsl_ifc_ctrl *ctrl = priv->ctrl;
struct fsl_ifc_nand_ctrl *nctrl = ifc_nand_ctrl;
struct fsl_ifc_regs __iomem *ifc = ctrl->regs;
u32 eccstat[4];
int i;
/* set the chip select for NAND Transaction */
iowrite32be(priv->bank << IFC_NAND_CSEL_SHIFT,
&ifc->ifc_nand.nand_csel);
dev_vdbg(priv->dev,
"%s: fir0=%08x fcr0=%08x\n",
__func__,
ioread32be(&ifc->ifc_nand.nand_fir0),
ioread32be(&ifc->ifc_nand.nand_fcr0));
ctrl->nand_stat = 0;
/* start read/write seq */
iowrite32be(IFC_NAND_SEQ_STRT_FIR_STRT, &ifc->ifc_nand.nandseq_strt);
/* wait for command complete flag or timeout */
wait_event_timeout(ctrl->nand_wait, ctrl->nand_stat,
IFC_TIMEOUT_MSECS * HZ/1000);
/* ctrl->nand_stat will be updated from IRQ context */
if (!ctrl->nand_stat)
dev_err(priv->dev, "Controller is not responding\n");
if (ctrl->nand_stat & IFC_NAND_EVTER_STAT_FTOER)
dev_err(priv->dev, "NAND Flash Timeout Error\n");
if (ctrl->nand_stat & IFC_NAND_EVTER_STAT_WPER)
dev_err(priv->dev, "NAND Flash Write Protect Error\n");
nctrl->max_bitflips = 0;
if (nctrl->eccread) {
int errors;
int bufnum = nctrl->page & priv->bufnum_mask;
int sector = bufnum * chip->ecc.steps;
int sector_end = sector + chip->ecc.steps - 1;
for (i = sector / 4; i <= sector_end / 4; i++)
eccstat[i] = ioread32be(&ifc->ifc_nand.nand_eccstat[i]);
for (i = sector; i <= sector_end; i++) {
errors = check_read_ecc(mtd, ctrl, eccstat, i);
if (errors == 15) {
/*
* Uncorrectable error.
* OK only if the whole page is blank.
*
* We disable ECCER reporting due to...
* erratum IFC-A002770 -- so report it now if we
* see an uncorrectable error in ECCSTAT.
*/
if (!is_blank(mtd, bufnum))
ctrl->nand_stat |=
IFC_NAND_EVTER_STAT_ECCER;
break;
}
mtd->ecc_stats.corrected += errors;
nctrl->max_bitflips = max_t(unsigned int,
nctrl->max_bitflips,
errors);
}
nctrl->eccread = 0;
}
}
static void fsl_ifc_do_read(struct nand_chip *chip,
int oob,
struct mtd_info *mtd)
{
struct fsl_ifc_mtd *priv = chip->priv;
struct fsl_ifc_ctrl *ctrl = priv->ctrl;
struct fsl_ifc_regs __iomem *ifc = ctrl->regs;
/* Program FIR/IFC_NAND_FCR0 for Small/Large page */
if (mtd->writesize > 512) {
iowrite32be((IFC_FIR_OP_CW0 << IFC_NAND_FIR0_OP0_SHIFT) |
(IFC_FIR_OP_CA0 << IFC_NAND_FIR0_OP1_SHIFT) |
(IFC_FIR_OP_RA0 << IFC_NAND_FIR0_OP2_SHIFT) |
(IFC_FIR_OP_CMD1 << IFC_NAND_FIR0_OP3_SHIFT) |
(IFC_FIR_OP_RBCD << IFC_NAND_FIR0_OP4_SHIFT),
&ifc->ifc_nand.nand_fir0);
iowrite32be(0x0, &ifc->ifc_nand.nand_fir1);
iowrite32be((NAND_CMD_READ0 << IFC_NAND_FCR0_CMD0_SHIFT) |
(NAND_CMD_READSTART << IFC_NAND_FCR0_CMD1_SHIFT),
&ifc->ifc_nand.nand_fcr0);
} else {
iowrite32be((IFC_FIR_OP_CW0 << IFC_NAND_FIR0_OP0_SHIFT) |
(IFC_FIR_OP_CA0 << IFC_NAND_FIR0_OP1_SHIFT) |
(IFC_FIR_OP_RA0 << IFC_NAND_FIR0_OP2_SHIFT) |
(IFC_FIR_OP_RBCD << IFC_NAND_FIR0_OP3_SHIFT),
&ifc->ifc_nand.nand_fir0);
iowrite32be(0x0, &ifc->ifc_nand.nand_fir1);
if (oob)
iowrite32be(NAND_CMD_READOOB <<
IFC_NAND_FCR0_CMD0_SHIFT,
&ifc->ifc_nand.nand_fcr0);
else
iowrite32be(NAND_CMD_READ0 <<
IFC_NAND_FCR0_CMD0_SHIFT,
&ifc->ifc_nand.nand_fcr0);
}
}
/* cmdfunc send commands to the IFC NAND Machine */
static void fsl_ifc_cmdfunc(struct mtd_info *mtd, unsigned int command,
int column, int page_addr) {
struct nand_chip *chip = mtd->priv;
struct fsl_ifc_mtd *priv = chip->priv;
struct fsl_ifc_ctrl *ctrl = priv->ctrl;
struct fsl_ifc_regs __iomem *ifc = ctrl->regs;
/* clear the read buffer */
ifc_nand_ctrl->read_bytes = 0;
if (command != NAND_CMD_PAGEPROG)
ifc_nand_ctrl->index = 0;
switch (command) {
/* READ0 read the entire buffer to use hardware ECC. */
case NAND_CMD_READ0:
iowrite32be(0, &ifc->ifc_nand.nand_fbcr);
set_addr(mtd, 0, page_addr, 0);
ifc_nand_ctrl->read_bytes = mtd->writesize + mtd->oobsize;
ifc_nand_ctrl->index += column;
if (chip->ecc.mode == NAND_ECC_HW)
ifc_nand_ctrl->eccread = 1;
fsl_ifc_do_read(chip, 0, mtd);
fsl_ifc_run_command(mtd);
return;
/* READOOB reads only the OOB because no ECC is performed. */
case NAND_CMD_READOOB:
iowrite32be(mtd->oobsize - column, &ifc->ifc_nand.nand_fbcr);
set_addr(mtd, column, page_addr, 1);
ifc_nand_ctrl->read_bytes = mtd->writesize + mtd->oobsize;
fsl_ifc_do_read(chip, 1, mtd);
fsl_ifc_run_command(mtd);
return;
case NAND_CMD_READID:
case NAND_CMD_PARAM: {
int timing = IFC_FIR_OP_RB;
if (command == NAND_CMD_PARAM)
timing = IFC_FIR_OP_RBCD;
iowrite32be((IFC_FIR_OP_CW0 << IFC_NAND_FIR0_OP0_SHIFT) |
(IFC_FIR_OP_UA << IFC_NAND_FIR0_OP1_SHIFT) |
(timing << IFC_NAND_FIR0_OP2_SHIFT),
&ifc->ifc_nand.nand_fir0);
iowrite32be(command << IFC_NAND_FCR0_CMD0_SHIFT,
&ifc->ifc_nand.nand_fcr0);
iowrite32be(column, &ifc->ifc_nand.row3);
/*
* although currently it's 8 bytes for READID, we always read
* the maximum 256 bytes(for PARAM)
*/
iowrite32be(256, &ifc->ifc_nand.nand_fbcr);
ifc_nand_ctrl->read_bytes = 256;
set_addr(mtd, 0, 0, 0);
fsl_ifc_run_command(mtd);
return;
}
/* ERASE1 stores the block and page address */
case NAND_CMD_ERASE1:
set_addr(mtd, 0, page_addr, 0);
return;
/* ERASE2 uses the block and page address from ERASE1 */
case NAND_CMD_ERASE2:
iowrite32be((IFC_FIR_OP_CW0 << IFC_NAND_FIR0_OP0_SHIFT) |
(IFC_FIR_OP_RA0 << IFC_NAND_FIR0_OP1_SHIFT) |
(IFC_FIR_OP_CMD1 << IFC_NAND_FIR0_OP2_SHIFT),
&ifc->ifc_nand.nand_fir0);
iowrite32be((NAND_CMD_ERASE1 << IFC_NAND_FCR0_CMD0_SHIFT) |
(NAND_CMD_ERASE2 << IFC_NAND_FCR0_CMD1_SHIFT),
&ifc->ifc_nand.nand_fcr0);
iowrite32be(0, &ifc->ifc_nand.nand_fbcr);
ifc_nand_ctrl->read_bytes = 0;
fsl_ifc_run_command(mtd);
return;
/* SEQIN sets up the addr buffer and all registers except the length */
case NAND_CMD_SEQIN: {
u32 nand_fcr0;
ifc_nand_ctrl->column = column;
ifc_nand_ctrl->oob = 0;
if (mtd->writesize > 512) {
nand_fcr0 =
(NAND_CMD_SEQIN << IFC_NAND_FCR0_CMD0_SHIFT) |
(NAND_CMD_PAGEPROG << IFC_NAND_FCR0_CMD1_SHIFT);
iowrite32be(
(IFC_FIR_OP_CW0 << IFC_NAND_FIR0_OP0_SHIFT) |
(IFC_FIR_OP_CA0 << IFC_NAND_FIR0_OP1_SHIFT) |
(IFC_FIR_OP_RA0 << IFC_NAND_FIR0_OP2_SHIFT) |
(IFC_FIR_OP_WBCD << IFC_NAND_FIR0_OP3_SHIFT) |
(IFC_FIR_OP_CW1 << IFC_NAND_FIR0_OP4_SHIFT),
&ifc->ifc_nand.nand_fir0);
} else {
nand_fcr0 = ((NAND_CMD_PAGEPROG <<
IFC_NAND_FCR0_CMD1_SHIFT) |
(NAND_CMD_SEQIN <<
IFC_NAND_FCR0_CMD2_SHIFT));
iowrite32be(
(IFC_FIR_OP_CW0 << IFC_NAND_FIR0_OP0_SHIFT) |
(IFC_FIR_OP_CMD2 << IFC_NAND_FIR0_OP1_SHIFT) |
(IFC_FIR_OP_CA0 << IFC_NAND_FIR0_OP2_SHIFT) |
(IFC_FIR_OP_RA0 << IFC_NAND_FIR0_OP3_SHIFT) |
(IFC_FIR_OP_WBCD << IFC_NAND_FIR0_OP4_SHIFT),
&ifc->ifc_nand.nand_fir0);
iowrite32be(IFC_FIR_OP_CW1 << IFC_NAND_FIR1_OP5_SHIFT,
&ifc->ifc_nand.nand_fir1);
if (column >= mtd->writesize)
nand_fcr0 |=
NAND_CMD_READOOB << IFC_NAND_FCR0_CMD0_SHIFT;
else
nand_fcr0 |=
NAND_CMD_READ0 << IFC_NAND_FCR0_CMD0_SHIFT;
}
if (column >= mtd->writesize) {
/* OOB area --> READOOB */
column -= mtd->writesize;
ifc_nand_ctrl->oob = 1;
}
iowrite32be(nand_fcr0, &ifc->ifc_nand.nand_fcr0);
set_addr(mtd, column, page_addr, ifc_nand_ctrl->oob);
return;
}
/* PAGEPROG reuses all of the setup from SEQIN and adds the length */
case NAND_CMD_PAGEPROG: {
if (ifc_nand_ctrl->oob) {
iowrite32be(ifc_nand_ctrl->index -
ifc_nand_ctrl->column,
&ifc->ifc_nand.nand_fbcr);
} else {
iowrite32be(0, &ifc->ifc_nand.nand_fbcr);
}
fsl_ifc_run_command(mtd);
return;
}
case NAND_CMD_STATUS:
iowrite32be((IFC_FIR_OP_CW0 << IFC_NAND_FIR0_OP0_SHIFT) |
(IFC_FIR_OP_RB << IFC_NAND_FIR0_OP1_SHIFT),
&ifc->ifc_nand.nand_fir0);
iowrite32be(NAND_CMD_STATUS << IFC_NAND_FCR0_CMD0_SHIFT,
&ifc->ifc_nand.nand_fcr0);
iowrite32be(1, &ifc->ifc_nand.nand_fbcr);
set_addr(mtd, 0, 0, 0);
ifc_nand_ctrl->read_bytes = 1;
fsl_ifc_run_command(mtd);
/*
* The chip always seems to report that it is
* write-protected, even when it is not.
*/
setbits8(ifc_nand_ctrl->addr, NAND_STATUS_WP);
return;
case NAND_CMD_RESET:
iowrite32be(IFC_FIR_OP_CW0 << IFC_NAND_FIR0_OP0_SHIFT,
&ifc->ifc_nand.nand_fir0);
iowrite32be(NAND_CMD_RESET << IFC_NAND_FCR0_CMD0_SHIFT,
&ifc->ifc_nand.nand_fcr0);
fsl_ifc_run_command(mtd);
return;
default:
dev_err(priv->dev, "%s: error, unsupported command 0x%x.\n",
__func__, command);
}
}
static void fsl_ifc_select_chip(struct mtd_info *mtd, int chip)
{
/* The hardware does not seem to support multiple
* chips per bank.
*/
}
/*
* Write buf to the IFC NAND Controller Data Buffer
*/
static void fsl_ifc_write_buf(struct mtd_info *mtd, const u8 *buf, int len)
{
struct nand_chip *chip = mtd->priv;
struct fsl_ifc_mtd *priv = chip->priv;
unsigned int bufsize = mtd->writesize + mtd->oobsize;
if (len <= 0) {
dev_err(priv->dev, "%s: len %d bytes", __func__, len);
return;
}
if ((unsigned int)len > bufsize - ifc_nand_ctrl->index) {
dev_err(priv->dev,
"%s: beyond end of buffer (%d requested, %u available)\n",
__func__, len, bufsize - ifc_nand_ctrl->index);
len = bufsize - ifc_nand_ctrl->index;
}
memcpy_toio(&ifc_nand_ctrl->addr[ifc_nand_ctrl->index], buf, len);
ifc_nand_ctrl->index += len;
}
/*
* Read a byte from either the IFC hardware buffer
* read function for 8-bit buswidth
*/
static uint8_t fsl_ifc_read_byte(struct mtd_info *mtd)
{
struct nand_chip *chip = mtd->priv;
struct fsl_ifc_mtd *priv = chip->priv;
/*
* If there are still bytes in the IFC buffer, then use the
* next byte.
*/
if (ifc_nand_ctrl->index < ifc_nand_ctrl->read_bytes)
return in_8(&ifc_nand_ctrl->addr[ifc_nand_ctrl->index++]);
dev_err(priv->dev, "%s: beyond end of buffer\n", __func__);
return ERR_BYTE;
}
/*
* Read two bytes from the IFC hardware buffer
* read function for 16-bit buswith
*/
static uint8_t fsl_ifc_read_byte16(struct mtd_info *mtd)
{
struct nand_chip *chip = mtd->priv;
struct fsl_ifc_mtd *priv = chip->priv;
uint16_t data;
/*
* If there are still bytes in the IFC buffer, then use the
* next byte.
*/
if (ifc_nand_ctrl->index < ifc_nand_ctrl->read_bytes) {
data = in_be16((uint16_t __iomem *)&ifc_nand_ctrl->
addr[ifc_nand_ctrl->index]);
ifc_nand_ctrl->index += 2;
return (uint8_t) data;
}
dev_err(priv->dev, "%s: beyond end of buffer\n", __func__);
return ERR_BYTE;
}
/*
* Read from the IFC Controller Data Buffer
*/
static void fsl_ifc_read_buf(struct mtd_info *mtd, u8 *buf, int len)
{
struct nand_chip *chip = mtd->priv;
struct fsl_ifc_mtd *priv = chip->priv;
int avail;
if (len < 0) {
dev_err(priv->dev, "%s: len %d bytes", __func__, len);
return;
}
avail = min((unsigned int)len,
ifc_nand_ctrl->read_bytes - ifc_nand_ctrl->index);
memcpy_fromio(buf, &ifc_nand_ctrl->addr[ifc_nand_ctrl->index], avail);
ifc_nand_ctrl->index += avail;
if (len > avail)
dev_err(priv->dev,
"%s: beyond end of buffer (%d requested, %d available)\n",
__func__, len, avail);
}
/*
* This function is called after Program and Erase Operations to
* check for success or failure.
*/
static int fsl_ifc_wait(struct mtd_info *mtd, struct nand_chip *chip)
{
struct fsl_ifc_mtd *priv = chip->priv;
struct fsl_ifc_ctrl *ctrl = priv->ctrl;
struct fsl_ifc_regs __iomem *ifc = ctrl->regs;
u32 nand_fsr;
/* Use READ_STATUS command, but wait for the device to be ready */
iowrite32be((IFC_FIR_OP_CW0 << IFC_NAND_FIR0_OP0_SHIFT) |
(IFC_FIR_OP_RDSTAT << IFC_NAND_FIR0_OP1_SHIFT),
&ifc->ifc_nand.nand_fir0);
iowrite32be(NAND_CMD_STATUS << IFC_NAND_FCR0_CMD0_SHIFT,
&ifc->ifc_nand.nand_fcr0);
iowrite32be(1, &ifc->ifc_nand.nand_fbcr);
set_addr(mtd, 0, 0, 0);
ifc_nand_ctrl->read_bytes = 1;
fsl_ifc_run_command(mtd);
nand_fsr = ioread32be(&ifc->ifc_nand.nand_fsr);
/*
* The chip always seems to report that it is
* write-protected, even when it is not.
*/
return nand_fsr | NAND_STATUS_WP;
}
static int fsl_ifc_read_page(struct mtd_info *mtd, struct nand_chip *chip,
uint8_t *buf, int oob_required, int page)
{
struct fsl_ifc_mtd *priv = chip->priv;
struct fsl_ifc_ctrl *ctrl = priv->ctrl;
struct fsl_ifc_nand_ctrl *nctrl = ifc_nand_ctrl;
fsl_ifc_read_buf(mtd, buf, mtd->writesize);
if (oob_required)
fsl_ifc_read_buf(mtd, chip->oob_poi, mtd->oobsize);
if (ctrl->nand_stat & IFC_NAND_EVTER_STAT_ECCER)
dev_err(priv->dev, "NAND Flash ECC Uncorrectable Error\n");
if (ctrl->nand_stat != IFC_NAND_EVTER_STAT_OPC)
mtd->ecc_stats.failed++;
return nctrl->max_bitflips;
}
/* ECC will be calculated automatically, and errors will be detected in
* waitfunc.
*/
static int fsl_ifc_write_page(struct mtd_info *mtd, struct nand_chip *chip,
const uint8_t *buf, int oob_required)
{
fsl_ifc_write_buf(mtd, buf, mtd->writesize);
fsl_ifc_write_buf(mtd, chip->oob_poi, mtd->oobsize);
return 0;
}
static int fsl_ifc_chip_init_tail(struct mtd_info *mtd)
{
struct nand_chip *chip = mtd->priv;
struct fsl_ifc_mtd *priv = chip->priv;
dev_dbg(priv->dev, "%s: nand->numchips = %d\n", __func__,
chip->numchips);
dev_dbg(priv->dev, "%s: nand->chipsize = %lld\n", __func__,
chip->chipsize);
dev_dbg(priv->dev, "%s: nand->pagemask = %8x\n", __func__,
chip->pagemask);
dev_dbg(priv->dev, "%s: nand->chip_delay = %d\n", __func__,
chip->chip_delay);
dev_dbg(priv->dev, "%s: nand->badblockpos = %d\n", __func__,
chip->badblockpos);
dev_dbg(priv->dev, "%s: nand->chip_shift = %d\n", __func__,
chip->chip_shift);
dev_dbg(priv->dev, "%s: nand->page_shift = %d\n", __func__,
chip->page_shift);
dev_dbg(priv->dev, "%s: nand->phys_erase_shift = %d\n", __func__,
chip->phys_erase_shift);
dev_dbg(priv->dev, "%s: nand->ecclayout = %p\n", __func__,
chip->ecclayout);
dev_dbg(priv->dev, "%s: nand->ecc.mode = %d\n", __func__,
chip->ecc.mode);
dev_dbg(priv->dev, "%s: nand->ecc.steps = %d\n", __func__,
chip->ecc.steps);
dev_dbg(priv->dev, "%s: nand->ecc.bytes = %d\n", __func__,
chip->ecc.bytes);
dev_dbg(priv->dev, "%s: nand->ecc.total = %d\n", __func__,
chip->ecc.total);
dev_dbg(priv->dev, "%s: nand->ecc.layout = %p\n", __func__,
chip->ecc.layout);
dev_dbg(priv->dev, "%s: mtd->flags = %08x\n", __func__, mtd->flags);
dev_dbg(priv->dev, "%s: mtd->size = %lld\n", __func__, mtd->size);
dev_dbg(priv->dev, "%s: mtd->erasesize = %d\n", __func__,
mtd->erasesize);
dev_dbg(priv->dev, "%s: mtd->writesize = %d\n", __func__,
mtd->writesize);
dev_dbg(priv->dev, "%s: mtd->oobsize = %d\n", __func__,
mtd->oobsize);
return 0;
}
static void fsl_ifc_sram_init(struct fsl_ifc_mtd *priv)
{
struct fsl_ifc_ctrl *ctrl = priv->ctrl;
struct fsl_ifc_regs __iomem *ifc = ctrl->regs;
uint32_t csor = 0, csor_8k = 0, csor_ext = 0;
uint32_t cs = priv->bank;
/* Save CSOR and CSOR_ext */
csor = ioread32be(&ifc->csor_cs[cs].csor);
csor_ext = ioread32be(&ifc->csor_cs[cs].csor_ext);
/* chage PageSize 8K and SpareSize 1K*/
csor_8k = (csor & ~(CSOR_NAND_PGS_MASK)) | 0x0018C000;
iowrite32be(csor_8k, &ifc->csor_cs[cs].csor);
iowrite32be(0x0000400, &ifc->csor_cs[cs].csor_ext);
/* READID */
iowrite32be((IFC_FIR_OP_CW0 << IFC_NAND_FIR0_OP0_SHIFT) |
(IFC_FIR_OP_UA << IFC_NAND_FIR0_OP1_SHIFT) |
(IFC_FIR_OP_RB << IFC_NAND_FIR0_OP2_SHIFT),
&ifc->ifc_nand.nand_fir0);
iowrite32be(NAND_CMD_READID << IFC_NAND_FCR0_CMD0_SHIFT,
&ifc->ifc_nand.nand_fcr0);
iowrite32be(0x0, &ifc->ifc_nand.row3);
iowrite32be(0x0, &ifc->ifc_nand.nand_fbcr);
/* Program ROW0/COL0 */
iowrite32be(0x0, &ifc->ifc_nand.row0);
iowrite32be(0x0, &ifc->ifc_nand.col0);
/* set the chip select for NAND Transaction */
iowrite32be(cs << IFC_NAND_CSEL_SHIFT, &ifc->ifc_nand.nand_csel);
/* start read seq */
iowrite32be(IFC_NAND_SEQ_STRT_FIR_STRT, &ifc->ifc_nand.nandseq_strt);
/* wait for command complete flag or timeout */
wait_event_timeout(ctrl->nand_wait, ctrl->nand_stat,
IFC_TIMEOUT_MSECS * HZ/1000);
if (ctrl->nand_stat != IFC_NAND_EVTER_STAT_OPC)
printk(KERN_ERR "fsl-ifc: Failed to Initialise SRAM\n");
/* Restore CSOR and CSOR_ext */
iowrite32be(csor, &ifc->csor_cs[cs].csor);
iowrite32be(csor_ext, &ifc->csor_cs[cs].csor_ext);
}
static int fsl_ifc_chip_init(struct fsl_ifc_mtd *priv)
{
struct fsl_ifc_ctrl *ctrl = priv->ctrl;
struct fsl_ifc_regs __iomem *ifc = ctrl->regs;
struct nand_chip *chip = &priv->chip;
struct nand_ecclayout *layout;
u32 csor, ver;
/* Fill in fsl_ifc_mtd structure */
priv->mtd.priv = chip;
priv->mtd.owner = THIS_MODULE;
/* fill in nand_chip structure */
/* set up function call table */
if ((ioread32be(&ifc->cspr_cs[priv->bank].cspr)) & CSPR_PORT_SIZE_16)
chip->read_byte = fsl_ifc_read_byte16;
else
chip->read_byte = fsl_ifc_read_byte;
chip->write_buf = fsl_ifc_write_buf;
chip->read_buf = fsl_ifc_read_buf;
chip->select_chip = fsl_ifc_select_chip;
chip->cmdfunc = fsl_ifc_cmdfunc;
chip->waitfunc = fsl_ifc_wait;
chip->bbt_td = &bbt_main_descr;
chip->bbt_md = &bbt_mirror_descr;
iowrite32be(0x0, &ifc->ifc_nand.ncfgr);
/* set up nand options */
chip->bbt_options = NAND_BBT_USE_FLASH;
if (ioread32be(&ifc->cspr_cs[priv->bank].cspr) & CSPR_PORT_SIZE_16) {
chip->read_byte = fsl_ifc_read_byte16;
chip->options |= NAND_BUSWIDTH_16;
} else {
chip->read_byte = fsl_ifc_read_byte;
}
chip->controller = &ifc_nand_ctrl->controller;
chip->priv = priv;
chip->ecc.read_page = fsl_ifc_read_page;
chip->ecc.write_page = fsl_ifc_write_page;
csor = ioread32be(&ifc->csor_cs[priv->bank].csor);
/* Hardware generates ECC per 512 Bytes */
chip->ecc.size = 512;
chip->ecc.bytes = 8;
chip->ecc.strength = 4;
switch (csor & CSOR_NAND_PGS_MASK) {
case CSOR_NAND_PGS_512:
if (chip->options & NAND_BUSWIDTH_16) {
layout = &oob_512_16bit_ecc4;
} else {
layout = &oob_512_8bit_ecc4;
/* Avoid conflict with bad block marker */
bbt_main_descr.offs = 0;
bbt_mirror_descr.offs = 0;
}
priv->bufnum_mask = 15;
break;
case CSOR_NAND_PGS_2K:
layout = &oob_2048_ecc4;
priv->bufnum_mask = 3;
break;
case CSOR_NAND_PGS_4K:
if ((csor & CSOR_NAND_ECC_MODE_MASK) ==
CSOR_NAND_ECC_MODE_4) {
layout = &oob_4096_ecc4;
} else {
layout = &oob_4096_ecc8;
chip->ecc.bytes = 16;
}
priv->bufnum_mask = 1;
break;
default:
dev_err(priv->dev, "bad csor %#x: bad page size\n", csor);
return -ENODEV;
}
/* Must also set CSOR_NAND_ECC_ENC_EN if DEC_EN set */
if (csor & CSOR_NAND_ECC_DEC_EN) {
chip->ecc.mode = NAND_ECC_HW;
chip->ecc.layout = layout;
} else {
chip->ecc.mode = NAND_ECC_SOFT;
}
ver = ioread32be(&ifc->ifc_rev);
if (ver == FSL_IFC_V1_1_0)
fsl_ifc_sram_init(priv);
return 0;
}
static int fsl_ifc_chip_remove(struct fsl_ifc_mtd *priv)
{
nand_release(&priv->mtd);
kfree(priv->mtd.name);
if (priv->vbase)
iounmap(priv->vbase);
ifc_nand_ctrl->chips[priv->bank] = NULL;
dev_set_drvdata(priv->dev, NULL);
kfree(priv);
return 0;
}
static int match_bank(struct fsl_ifc_regs __iomem *ifc, int bank,
phys_addr_t addr)
{
u32 cspr = ioread32be(&ifc->cspr_cs[bank].cspr);
if (!(cspr & CSPR_V))
return 0;
if ((cspr & CSPR_MSEL) != CSPR_MSEL_NAND)
return 0;
return (cspr & CSPR_BA) == convert_ifc_address(addr);
}
static DEFINE_MUTEX(fsl_ifc_nand_mutex);
static int fsl_ifc_nand_probe(struct platform_device *dev)
{
struct fsl_ifc_regs __iomem *ifc;
struct fsl_ifc_mtd *priv;
struct resource res;
static const char *part_probe_types[]
= { "cmdlinepart", "RedBoot", "ofpart", NULL };
int ret;
int bank;
struct device_node *node = dev->dev.of_node;
struct mtd_part_parser_data ppdata;
ppdata.of_node = dev->dev.of_node;
if (!fsl_ifc_ctrl_dev || !fsl_ifc_ctrl_dev->regs)
return -ENODEV;
ifc = fsl_ifc_ctrl_dev->regs;
/* get, allocate and map the memory resource */
ret = of_address_to_resource(node, 0, &res);
if (ret) {
dev_err(&dev->dev, "%s: failed to get resource\n", __func__);
return ret;
}
/* find which chip select it is connected to */
for (bank = 0; bank < FSL_IFC_BANK_COUNT; bank++) {
if (match_bank(ifc, bank, res.start))
break;
}
if (bank >= FSL_IFC_BANK_COUNT) {
dev_err(&dev->dev, "%s: address did not match any chip selects\n",
__func__);
return -ENODEV;
}
priv = devm_kzalloc(&dev->dev, sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
mutex_lock(&fsl_ifc_nand_mutex);
if (!fsl_ifc_ctrl_dev->nand) {
ifc_nand_ctrl = kzalloc(sizeof(*ifc_nand_ctrl), GFP_KERNEL);
if (!ifc_nand_ctrl) {
dev_err(&dev->dev, "failed to allocate memory\n");
mutex_unlock(&fsl_ifc_nand_mutex);
return -ENOMEM;
}
ifc_nand_ctrl->read_bytes = 0;
ifc_nand_ctrl->index = 0;
ifc_nand_ctrl->addr = NULL;
fsl_ifc_ctrl_dev->nand = ifc_nand_ctrl;
spin_lock_init(&ifc_nand_ctrl->controller.lock);
init_waitqueue_head(&ifc_nand_ctrl->controller.wq);
} else {
ifc_nand_ctrl = fsl_ifc_ctrl_dev->nand;
}
mutex_unlock(&fsl_ifc_nand_mutex);
ifc_nand_ctrl->chips[bank] = priv;
priv->bank = bank;
priv->ctrl = fsl_ifc_ctrl_dev;
priv->dev = &dev->dev;
priv->vbase = ioremap(res.start, resource_size(&res));
if (!priv->vbase) {
dev_err(priv->dev, "%s: failed to map chip region\n", __func__);
ret = -ENOMEM;
goto err;
}
dev_set_drvdata(priv->dev, priv);
iowrite32be(IFC_NAND_EVTER_EN_OPC_EN |
IFC_NAND_EVTER_EN_FTOER_EN |
IFC_NAND_EVTER_EN_WPER_EN,
&ifc->ifc_nand.nand_evter_en);
/* enable NAND Machine Interrupts */
iowrite32be(IFC_NAND_EVTER_INTR_OPCIR_EN |
IFC_NAND_EVTER_INTR_FTOERIR_EN |
IFC_NAND_EVTER_INTR_WPERIR_EN,
&ifc->ifc_nand.nand_evter_intr_en);
priv->mtd.name = kasprintf(GFP_KERNEL, "%x.flash", (unsigned)res.start);
if (!priv->mtd.name) {
ret = -ENOMEM;
goto err;
}
ret = fsl_ifc_chip_init(priv);
if (ret)
goto err;
ret = nand_scan_ident(&priv->mtd, 1, NULL);
if (ret)
goto err;
ret = fsl_ifc_chip_init_tail(&priv->mtd);
if (ret)
goto err;
ret = nand_scan_tail(&priv->mtd);
if (ret)
goto err;
/* First look for RedBoot table or partitions on the command
* line, these take precedence over device tree information */
mtd_device_parse_register(&priv->mtd, part_probe_types, &ppdata,
NULL, 0);
dev_info(priv->dev, "IFC NAND device at 0x%llx, bank %d\n",
(unsigned long long)res.start, priv->bank);
return 0;
err:
fsl_ifc_chip_remove(priv);
return ret;
}
static int fsl_ifc_nand_remove(struct platform_device *dev)
{
struct fsl_ifc_mtd *priv = dev_get_drvdata(&dev->dev);
fsl_ifc_chip_remove(priv);
mutex_lock(&fsl_ifc_nand_mutex);
ifc_nand_ctrl->counter--;
if (!ifc_nand_ctrl->counter) {
fsl_ifc_ctrl_dev->nand = NULL;
kfree(ifc_nand_ctrl);
}
mutex_unlock(&fsl_ifc_nand_mutex);
return 0;
}
static const struct of_device_id fsl_ifc_nand_match[] = {
{
.compatible = "fsl,ifc-nand",
},
{}
};
static struct platform_driver fsl_ifc_nand_driver = {
.driver = {
.name = "fsl,ifc-nand",
.owner = THIS_MODULE,
.of_match_table = fsl_ifc_nand_match,
},
.probe = fsl_ifc_nand_probe,
.remove = fsl_ifc_nand_remove,
};
static int __init fsl_ifc_nand_init(void)
{
int ret;
ret = platform_driver_register(&fsl_ifc_nand_driver);
if (ret)
printk(KERN_ERR "fsl-ifc: Failed to register platform"
"driver\n");
return ret;
}
static void __exit fsl_ifc_nand_exit(void)
{
platform_driver_unregister(&fsl_ifc_nand_driver);
}
module_init(fsl_ifc_nand_init);
module_exit(fsl_ifc_nand_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Freescale");
MODULE_DESCRIPTION("Freescale Integrated Flash Controller MTD NAND driver");
| gpl-2.0 |
DC07/android_kernel_lge_dory | drivers/pinctrl/sh-pfc/pfc-sh7785.c | 2172 | 38730 | /*
* SH7785 Pinmux
*
* Copyright (C) 2008 Magnus Damm
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <cpu/sh7785.h>
#include "sh_pfc.h"
enum {
PINMUX_RESERVED = 0,
PINMUX_DATA_BEGIN,
PA7_DATA, PA6_DATA, PA5_DATA, PA4_DATA,
PA3_DATA, PA2_DATA, PA1_DATA, PA0_DATA,
PB7_DATA, PB6_DATA, PB5_DATA, PB4_DATA,
PB3_DATA, PB2_DATA, PB1_DATA, PB0_DATA,
PC7_DATA, PC6_DATA, PC5_DATA, PC4_DATA,
PC3_DATA, PC2_DATA, PC1_DATA, PC0_DATA,
PD7_DATA, PD6_DATA, PD5_DATA, PD4_DATA,
PD3_DATA, PD2_DATA, PD1_DATA, PD0_DATA,
PE5_DATA, PE4_DATA, PE3_DATA, PE2_DATA, PE1_DATA, PE0_DATA,
PF7_DATA, PF6_DATA, PF5_DATA, PF4_DATA,
PF3_DATA, PF2_DATA, PF1_DATA, PF0_DATA,
PG7_DATA, PG6_DATA, PG5_DATA, PG4_DATA,
PG3_DATA, PG2_DATA, PG1_DATA, PG0_DATA,
PH7_DATA, PH6_DATA, PH5_DATA, PH4_DATA,
PH3_DATA, PH2_DATA, PH1_DATA, PH0_DATA,
PJ7_DATA, PJ6_DATA, PJ5_DATA, PJ4_DATA,
PJ3_DATA, PJ2_DATA, PJ1_DATA, PJ0_DATA,
PK7_DATA, PK6_DATA, PK5_DATA, PK4_DATA,
PK3_DATA, PK2_DATA, PK1_DATA, PK0_DATA,
PL7_DATA, PL6_DATA, PL5_DATA, PL4_DATA,
PL3_DATA, PL2_DATA, PL1_DATA, PL0_DATA,
PM1_DATA, PM0_DATA,
PN7_DATA, PN6_DATA, PN5_DATA, PN4_DATA,
PN3_DATA, PN2_DATA, PN1_DATA, PN0_DATA,
PP5_DATA, PP4_DATA, PP3_DATA, PP2_DATA, PP1_DATA, PP0_DATA,
PQ4_DATA, PQ3_DATA, PQ2_DATA, PQ1_DATA, PQ0_DATA,
PR3_DATA, PR2_DATA, PR1_DATA, PR0_DATA,
PINMUX_DATA_END,
PINMUX_INPUT_BEGIN,
PA7_IN, PA6_IN, PA5_IN, PA4_IN,
PA3_IN, PA2_IN, PA1_IN, PA0_IN,
PB7_IN, PB6_IN, PB5_IN, PB4_IN,
PB3_IN, PB2_IN, PB1_IN, PB0_IN,
PC7_IN, PC6_IN, PC5_IN, PC4_IN,
PC3_IN, PC2_IN, PC1_IN, PC0_IN,
PD7_IN, PD6_IN, PD5_IN, PD4_IN,
PD3_IN, PD2_IN, PD1_IN, PD0_IN,
PE5_IN, PE4_IN, PE3_IN, PE2_IN, PE1_IN, PE0_IN,
PF7_IN, PF6_IN, PF5_IN, PF4_IN,
PF3_IN, PF2_IN, PF1_IN, PF0_IN,
PG7_IN, PG6_IN, PG5_IN, PG4_IN,
PG3_IN, PG2_IN, PG1_IN, PG0_IN,
PH7_IN, PH6_IN, PH5_IN, PH4_IN,
PH3_IN, PH2_IN, PH1_IN, PH0_IN,
PJ7_IN, PJ6_IN, PJ5_IN, PJ4_IN,
PJ3_IN, PJ2_IN, PJ1_IN, PJ0_IN,
PK7_IN, PK6_IN, PK5_IN, PK4_IN,
PK3_IN, PK2_IN, PK1_IN, PK0_IN,
PL7_IN, PL6_IN, PL5_IN, PL4_IN,
PL3_IN, PL2_IN, PL1_IN, PL0_IN,
PM1_IN, PM0_IN,
PN7_IN, PN6_IN, PN5_IN, PN4_IN,
PN3_IN, PN2_IN, PN1_IN, PN0_IN,
PP5_IN, PP4_IN, PP3_IN, PP2_IN, PP1_IN, PP0_IN,
PQ4_IN, PQ3_IN, PQ2_IN, PQ1_IN, PQ0_IN,
PR3_IN, PR2_IN, PR1_IN, PR0_IN,
PINMUX_INPUT_END,
PINMUX_INPUT_PULLUP_BEGIN,
PA7_IN_PU, PA6_IN_PU, PA5_IN_PU, PA4_IN_PU,
PA3_IN_PU, PA2_IN_PU, PA1_IN_PU, PA0_IN_PU,
PB7_IN_PU, PB6_IN_PU, PB5_IN_PU, PB4_IN_PU,
PB3_IN_PU, PB2_IN_PU, PB1_IN_PU, PB0_IN_PU,
PC7_IN_PU, PC6_IN_PU, PC5_IN_PU, PC4_IN_PU,
PC3_IN_PU, PC2_IN_PU, PC1_IN_PU, PC0_IN_PU,
PD7_IN_PU, PD6_IN_PU, PD5_IN_PU, PD4_IN_PU,
PD3_IN_PU, PD2_IN_PU, PD1_IN_PU, PD0_IN_PU,
PE5_IN_PU, PE4_IN_PU, PE3_IN_PU, PE2_IN_PU, PE1_IN_PU, PE0_IN_PU,
PF7_IN_PU, PF6_IN_PU, PF5_IN_PU, PF4_IN_PU,
PF3_IN_PU, PF2_IN_PU, PF1_IN_PU, PF0_IN_PU,
PG7_IN_PU, PG6_IN_PU, PG5_IN_PU, PG4_IN_PU,
PG3_IN_PU, PG2_IN_PU, PG1_IN_PU, PG0_IN_PU,
PH7_IN_PU, PH6_IN_PU, PH5_IN_PU, PH4_IN_PU,
PH3_IN_PU, PH2_IN_PU, PH1_IN_PU, PH0_IN_PU,
PJ7_IN_PU, PJ6_IN_PU, PJ5_IN_PU, PJ4_IN_PU,
PJ3_IN_PU, PJ2_IN_PU, PJ1_IN_PU, PJ0_IN_PU,
PK7_IN_PU, PK6_IN_PU, PK5_IN_PU, PK4_IN_PU,
PK3_IN_PU, PK2_IN_PU, PK1_IN_PU, PK0_IN_PU,
PL7_IN_PU, PL6_IN_PU, PL5_IN_PU, PL4_IN_PU,
PL3_IN_PU, PL2_IN_PU, PL1_IN_PU, PL0_IN_PU,
PM1_IN_PU, PM0_IN_PU,
PN7_IN_PU, PN6_IN_PU, PN5_IN_PU, PN4_IN_PU,
PN3_IN_PU, PN2_IN_PU, PN1_IN_PU, PN0_IN_PU,
PP5_IN_PU, PP4_IN_PU, PP3_IN_PU, PP2_IN_PU, PP1_IN_PU, PP0_IN_PU,
PQ4_IN_PU, PQ3_IN_PU, PQ2_IN_PU, PQ1_IN_PU, PQ0_IN_PU,
PR3_IN_PU, PR2_IN_PU, PR1_IN_PU, PR0_IN_PU,
PINMUX_INPUT_PULLUP_END,
PINMUX_OUTPUT_BEGIN,
PA7_OUT, PA6_OUT, PA5_OUT, PA4_OUT,
PA3_OUT, PA2_OUT, PA1_OUT, PA0_OUT,
PB7_OUT, PB6_OUT, PB5_OUT, PB4_OUT,
PB3_OUT, PB2_OUT, PB1_OUT, PB0_OUT,
PC7_OUT, PC6_OUT, PC5_OUT, PC4_OUT,
PC3_OUT, PC2_OUT, PC1_OUT, PC0_OUT,
PD7_OUT, PD6_OUT, PD5_OUT, PD4_OUT,
PD3_OUT, PD2_OUT, PD1_OUT, PD0_OUT,
PE5_OUT, PE4_OUT, PE3_OUT, PE2_OUT, PE1_OUT, PE0_OUT,
PF7_OUT, PF6_OUT, PF5_OUT, PF4_OUT,
PF3_OUT, PF2_OUT, PF1_OUT, PF0_OUT,
PG7_OUT, PG6_OUT, PG5_OUT, PG4_OUT,
PG3_OUT, PG2_OUT, PG1_OUT, PG0_OUT,
PH7_OUT, PH6_OUT, PH5_OUT, PH4_OUT,
PH3_OUT, PH2_OUT, PH1_OUT, PH0_OUT,
PJ7_OUT, PJ6_OUT, PJ5_OUT, PJ4_OUT,
PJ3_OUT, PJ2_OUT, PJ1_OUT, PJ0_OUT,
PK7_OUT, PK6_OUT, PK5_OUT, PK4_OUT,
PK3_OUT, PK2_OUT, PK1_OUT, PK0_OUT,
PL7_OUT, PL6_OUT, PL5_OUT, PL4_OUT,
PL3_OUT, PL2_OUT, PL1_OUT, PL0_OUT,
PM1_OUT, PM0_OUT,
PN7_OUT, PN6_OUT, PN5_OUT, PN4_OUT,
PN3_OUT, PN2_OUT, PN1_OUT, PN0_OUT,
PP5_OUT, PP4_OUT, PP3_OUT, PP2_OUT, PP1_OUT, PP0_OUT,
PQ4_OUT, PQ3_OUT, PQ2_OUT, PQ1_OUT, PQ0_OUT,
PR3_OUT, PR2_OUT, PR1_OUT, PR0_OUT,
PINMUX_OUTPUT_END,
PINMUX_FUNCTION_BEGIN,
PA7_FN, PA6_FN, PA5_FN, PA4_FN,
PA3_FN, PA2_FN, PA1_FN, PA0_FN,
PB7_FN, PB6_FN, PB5_FN, PB4_FN,
PB3_FN, PB2_FN, PB1_FN, PB0_FN,
PC7_FN, PC6_FN, PC5_FN, PC4_FN,
PC3_FN, PC2_FN, PC1_FN, PC0_FN,
PD7_FN, PD6_FN, PD5_FN, PD4_FN,
PD3_FN, PD2_FN, PD1_FN, PD0_FN,
PE5_FN, PE4_FN, PE3_FN, PE2_FN, PE1_FN, PE0_FN,
PF7_FN, PF6_FN, PF5_FN, PF4_FN,
PF3_FN, PF2_FN, PF1_FN, PF0_FN,
PG7_FN, PG6_FN, PG5_FN, PG4_FN,
PG3_FN, PG2_FN, PG1_FN, PG0_FN,
PH7_FN, PH6_FN, PH5_FN, PH4_FN,
PH3_FN, PH2_FN, PH1_FN, PH0_FN,
PJ7_FN, PJ6_FN, PJ5_FN, PJ4_FN,
PJ3_FN, PJ2_FN, PJ1_FN, PJ0_FN,
PK7_FN, PK6_FN, PK5_FN, PK4_FN,
PK3_FN, PK2_FN, PK1_FN, PK0_FN,
PL7_FN, PL6_FN, PL5_FN, PL4_FN,
PL3_FN, PL2_FN, PL1_FN, PL0_FN,
PM1_FN, PM0_FN,
PN7_FN, PN6_FN, PN5_FN, PN4_FN,
PN3_FN, PN2_FN, PN1_FN, PN0_FN,
PP5_FN, PP4_FN, PP3_FN, PP2_FN, PP1_FN, PP0_FN,
PQ4_FN, PQ3_FN, PQ2_FN, PQ1_FN, PQ0_FN,
PR3_FN, PR2_FN, PR1_FN, PR0_FN,
P1MSEL15_0, P1MSEL15_1,
P1MSEL14_0, P1MSEL14_1,
P1MSEL13_0, P1MSEL13_1,
P1MSEL12_0, P1MSEL12_1,
P1MSEL11_0, P1MSEL11_1,
P1MSEL10_0, P1MSEL10_1,
P1MSEL9_0, P1MSEL9_1,
P1MSEL8_0, P1MSEL8_1,
P1MSEL7_0, P1MSEL7_1,
P1MSEL6_0, P1MSEL6_1,
P1MSEL5_0,
P1MSEL4_0, P1MSEL4_1,
P1MSEL3_0, P1MSEL3_1,
P1MSEL2_0, P1MSEL2_1,
P1MSEL1_0, P1MSEL1_1,
P1MSEL0_0, P1MSEL0_1,
P2MSEL2_0, P2MSEL2_1,
P2MSEL1_0, P2MSEL1_1,
P2MSEL0_0, P2MSEL0_1,
PINMUX_FUNCTION_END,
PINMUX_MARK_BEGIN,
D63_AD31_MARK,
D62_AD30_MARK,
D61_AD29_MARK,
D60_AD28_MARK,
D59_AD27_MARK,
D58_AD26_MARK,
D57_AD25_MARK,
D56_AD24_MARK,
D55_AD23_MARK,
D54_AD22_MARK,
D53_AD21_MARK,
D52_AD20_MARK,
D51_AD19_MARK,
D50_AD18_MARK,
D49_AD17_DB5_MARK,
D48_AD16_DB4_MARK,
D47_AD15_DB3_MARK,
D46_AD14_DB2_MARK,
D45_AD13_DB1_MARK,
D44_AD12_DB0_MARK,
D43_AD11_DG5_MARK,
D42_AD10_DG4_MARK,
D41_AD9_DG3_MARK,
D40_AD8_DG2_MARK,
D39_AD7_DG1_MARK,
D38_AD6_DG0_MARK,
D37_AD5_DR5_MARK,
D36_AD4_DR4_MARK,
D35_AD3_DR3_MARK,
D34_AD2_DR2_MARK,
D33_AD1_DR1_MARK,
D32_AD0_DR0_MARK,
REQ1_MARK,
REQ2_MARK,
REQ3_MARK,
GNT1_MARK,
GNT2_MARK,
GNT3_MARK,
MMCCLK_MARK,
D31_MARK,
D30_MARK,
D29_MARK,
D28_MARK,
D27_MARK,
D26_MARK,
D25_MARK,
D24_MARK,
D23_MARK,
D22_MARK,
D21_MARK,
D20_MARK,
D19_MARK,
D18_MARK,
D17_MARK,
D16_MARK,
SCIF1_SCK_MARK,
SCIF1_RXD_MARK,
SCIF1_TXD_MARK,
SCIF0_CTS_MARK,
INTD_MARK,
FCE_MARK,
SCIF0_RTS_MARK,
HSPI_CS_MARK,
FSE_MARK,
SCIF0_SCK_MARK,
HSPI_CLK_MARK,
FRE_MARK,
SCIF0_RXD_MARK,
HSPI_RX_MARK,
FRB_MARK,
SCIF0_TXD_MARK,
HSPI_TX_MARK,
FWE_MARK,
SCIF5_TXD_MARK,
HAC1_SYNC_MARK,
SSI1_WS_MARK,
SIOF_TXD_PJ_MARK,
HAC0_SDOUT_MARK,
SSI0_SDATA_MARK,
SIOF_RXD_PJ_MARK,
HAC0_SDIN_MARK,
SSI0_SCK_MARK,
SIOF_SYNC_PJ_MARK,
HAC0_SYNC_MARK,
SSI0_WS_MARK,
SIOF_MCLK_PJ_MARK,
HAC_RES_MARK,
SIOF_SCK_PJ_MARK,
HAC0_BITCLK_MARK,
SSI0_CLK_MARK,
HAC1_BITCLK_MARK,
SSI1_CLK_MARK,
TCLK_MARK,
IOIS16_MARK,
STATUS0_MARK,
DRAK0_PK3_MARK,
STATUS1_MARK,
DRAK1_PK2_MARK,
DACK2_MARK,
SCIF2_TXD_MARK,
MMCCMD_MARK,
SIOF_TXD_PK_MARK,
DACK3_MARK,
SCIF2_SCK_MARK,
MMCDAT_MARK,
SIOF_SCK_PK_MARK,
DREQ0_MARK,
DREQ1_MARK,
DRAK0_PK1_MARK,
DRAK1_PK0_MARK,
DREQ2_MARK,
INTB_MARK,
DREQ3_MARK,
INTC_MARK,
DRAK2_MARK,
CE2A_MARK,
IRL4_MARK,
FD4_MARK,
IRL5_MARK,
FD5_MARK,
IRL6_MARK,
FD6_MARK,
IRL7_MARK,
FD7_MARK,
DRAK3_MARK,
CE2B_MARK,
BREQ_BSACK_MARK,
BACK_BSREQ_MARK,
SCIF5_RXD_MARK,
HAC1_SDIN_MARK,
SSI1_SCK_MARK,
SCIF5_SCK_MARK,
HAC1_SDOUT_MARK,
SSI1_SDATA_MARK,
SCIF3_TXD_MARK,
FCLE_MARK,
SCIF3_RXD_MARK,
FALE_MARK,
SCIF3_SCK_MARK,
FD0_MARK,
SCIF4_TXD_MARK,
FD1_MARK,
SCIF4_RXD_MARK,
FD2_MARK,
SCIF4_SCK_MARK,
FD3_MARK,
DEVSEL_DCLKOUT_MARK,
STOP_CDE_MARK,
LOCK_ODDF_MARK,
TRDY_DISPL_MARK,
IRDY_HSYNC_MARK,
PCIFRAME_VSYNC_MARK,
INTA_MARK,
GNT0_GNTIN_MARK,
REQ0_REQOUT_MARK,
PERR_MARK,
SERR_MARK,
WE7_CBE3_MARK,
WE6_CBE2_MARK,
WE5_CBE1_MARK,
WE4_CBE0_MARK,
SCIF2_RXD_MARK,
SIOF_RXD_MARK,
MRESETOUT_MARK,
IRQOUT_MARK,
PINMUX_MARK_END,
};
static const pinmux_enum_t pinmux_data[] = {
/* PA GPIO */
PINMUX_DATA(PA7_DATA, PA7_IN, PA7_OUT, PA7_IN_PU),
PINMUX_DATA(PA6_DATA, PA6_IN, PA6_OUT, PA6_IN_PU),
PINMUX_DATA(PA5_DATA, PA5_IN, PA5_OUT, PA5_IN_PU),
PINMUX_DATA(PA4_DATA, PA4_IN, PA4_OUT, PA4_IN_PU),
PINMUX_DATA(PA3_DATA, PA3_IN, PA3_OUT, PA3_IN_PU),
PINMUX_DATA(PA2_DATA, PA2_IN, PA2_OUT, PA2_IN_PU),
PINMUX_DATA(PA1_DATA, PA1_IN, PA1_OUT, PA1_IN_PU),
PINMUX_DATA(PA0_DATA, PA0_IN, PA0_OUT, PA0_IN_PU),
/* PB GPIO */
PINMUX_DATA(PB7_DATA, PB7_IN, PB7_OUT, PB7_IN_PU),
PINMUX_DATA(PB6_DATA, PB6_IN, PB6_OUT, PB6_IN_PU),
PINMUX_DATA(PB5_DATA, PB5_IN, PB5_OUT, PB5_IN_PU),
PINMUX_DATA(PB4_DATA, PB4_IN, PB4_OUT, PB4_IN_PU),
PINMUX_DATA(PB3_DATA, PB3_IN, PB3_OUT, PB3_IN_PU),
PINMUX_DATA(PB2_DATA, PB2_IN, PB2_OUT, PB2_IN_PU),
PINMUX_DATA(PB1_DATA, PB1_IN, PB1_OUT, PB1_IN_PU),
PINMUX_DATA(PB0_DATA, PB0_IN, PB0_OUT, PB0_IN_PU),
/* PC GPIO */
PINMUX_DATA(PC7_DATA, PC7_IN, PC7_OUT, PC7_IN_PU),
PINMUX_DATA(PC6_DATA, PC6_IN, PC6_OUT, PC6_IN_PU),
PINMUX_DATA(PC5_DATA, PC5_IN, PC5_OUT, PC5_IN_PU),
PINMUX_DATA(PC4_DATA, PC4_IN, PC4_OUT, PC4_IN_PU),
PINMUX_DATA(PC3_DATA, PC3_IN, PC3_OUT, PC3_IN_PU),
PINMUX_DATA(PC2_DATA, PC2_IN, PC2_OUT, PC2_IN_PU),
PINMUX_DATA(PC1_DATA, PC1_IN, PC1_OUT, PC1_IN_PU),
PINMUX_DATA(PC0_DATA, PC0_IN, PC0_OUT, PC0_IN_PU),
/* PD GPIO */
PINMUX_DATA(PD7_DATA, PD7_IN, PD7_OUT, PD7_IN_PU),
PINMUX_DATA(PD6_DATA, PD6_IN, PD6_OUT, PD6_IN_PU),
PINMUX_DATA(PD5_DATA, PD5_IN, PD5_OUT, PD5_IN_PU),
PINMUX_DATA(PD4_DATA, PD4_IN, PD4_OUT, PD4_IN_PU),
PINMUX_DATA(PD3_DATA, PD3_IN, PD3_OUT, PD3_IN_PU),
PINMUX_DATA(PD2_DATA, PD2_IN, PD2_OUT, PD2_IN_PU),
PINMUX_DATA(PD1_DATA, PD1_IN, PD1_OUT, PD1_IN_PU),
PINMUX_DATA(PD0_DATA, PD0_IN, PD0_OUT, PD0_IN_PU),
/* PE GPIO */
PINMUX_DATA(PE5_DATA, PE5_IN, PE5_OUT, PE5_IN_PU),
PINMUX_DATA(PE4_DATA, PE4_IN, PE4_OUT, PE4_IN_PU),
PINMUX_DATA(PE3_DATA, PE3_IN, PE3_OUT, PE3_IN_PU),
PINMUX_DATA(PE2_DATA, PE2_IN, PE2_OUT, PE2_IN_PU),
PINMUX_DATA(PE1_DATA, PE1_IN, PE1_OUT, PE1_IN_PU),
PINMUX_DATA(PE0_DATA, PE0_IN, PE0_OUT, PE0_IN_PU),
/* PF GPIO */
PINMUX_DATA(PF7_DATA, PF7_IN, PF7_OUT, PF7_IN_PU),
PINMUX_DATA(PF6_DATA, PF6_IN, PF6_OUT, PF6_IN_PU),
PINMUX_DATA(PF5_DATA, PF5_IN, PF5_OUT, PF5_IN_PU),
PINMUX_DATA(PF4_DATA, PF4_IN, PF4_OUT, PF4_IN_PU),
PINMUX_DATA(PF3_DATA, PF3_IN, PF3_OUT, PF3_IN_PU),
PINMUX_DATA(PF2_DATA, PF2_IN, PF2_OUT, PF2_IN_PU),
PINMUX_DATA(PF1_DATA, PF1_IN, PF1_OUT, PF1_IN_PU),
PINMUX_DATA(PF0_DATA, PF0_IN, PF0_OUT, PF0_IN_PU),
/* PG GPIO */
PINMUX_DATA(PG7_DATA, PG7_IN, PG7_OUT, PG7_IN_PU),
PINMUX_DATA(PG6_DATA, PG6_IN, PG6_OUT, PG6_IN_PU),
PINMUX_DATA(PG5_DATA, PG5_IN, PG5_OUT, PG5_IN_PU),
PINMUX_DATA(PG4_DATA, PG4_IN, PG4_OUT, PG4_IN_PU),
PINMUX_DATA(PG3_DATA, PG3_IN, PG3_OUT, PG3_IN_PU),
PINMUX_DATA(PG2_DATA, PG2_IN, PG2_OUT, PG2_IN_PU),
PINMUX_DATA(PG1_DATA, PG1_IN, PG1_OUT, PG1_IN_PU),
PINMUX_DATA(PG0_DATA, PG0_IN, PG0_OUT, PG0_IN_PU),
/* PH GPIO */
PINMUX_DATA(PH7_DATA, PH7_IN, PH7_OUT, PH7_IN_PU),
PINMUX_DATA(PH6_DATA, PH6_IN, PH6_OUT, PH6_IN_PU),
PINMUX_DATA(PH5_DATA, PH5_IN, PH5_OUT, PH5_IN_PU),
PINMUX_DATA(PH4_DATA, PH4_IN, PH4_OUT, PH4_IN_PU),
PINMUX_DATA(PH3_DATA, PH3_IN, PH3_OUT, PH3_IN_PU),
PINMUX_DATA(PH2_DATA, PH2_IN, PH2_OUT, PH2_IN_PU),
PINMUX_DATA(PH1_DATA, PH1_IN, PH1_OUT, PH1_IN_PU),
PINMUX_DATA(PH0_DATA, PH0_IN, PH0_OUT, PH0_IN_PU),
/* PJ GPIO */
PINMUX_DATA(PJ7_DATA, PJ7_IN, PJ7_OUT, PJ7_IN_PU),
PINMUX_DATA(PJ6_DATA, PJ6_IN, PJ6_OUT, PJ6_IN_PU),
PINMUX_DATA(PJ5_DATA, PJ5_IN, PJ5_OUT, PJ5_IN_PU),
PINMUX_DATA(PJ4_DATA, PJ4_IN, PJ4_OUT, PJ4_IN_PU),
PINMUX_DATA(PJ3_DATA, PJ3_IN, PJ3_OUT, PJ3_IN_PU),
PINMUX_DATA(PJ2_DATA, PJ2_IN, PJ2_OUT, PJ2_IN_PU),
PINMUX_DATA(PJ1_DATA, PJ1_IN, PJ1_OUT, PJ1_IN_PU),
PINMUX_DATA(PJ0_DATA, PJ0_IN, PJ0_OUT, PJ0_IN_PU),
/* PK GPIO */
PINMUX_DATA(PK7_DATA, PK7_IN, PK7_OUT, PK7_IN_PU),
PINMUX_DATA(PK6_DATA, PK6_IN, PK6_OUT, PK6_IN_PU),
PINMUX_DATA(PK5_DATA, PK5_IN, PK5_OUT, PK5_IN_PU),
PINMUX_DATA(PK4_DATA, PK4_IN, PK4_OUT, PK4_IN_PU),
PINMUX_DATA(PK3_DATA, PK3_IN, PK3_OUT, PK3_IN_PU),
PINMUX_DATA(PK2_DATA, PK2_IN, PK2_OUT, PK2_IN_PU),
PINMUX_DATA(PK1_DATA, PK1_IN, PK1_OUT, PK1_IN_PU),
PINMUX_DATA(PK0_DATA, PK0_IN, PK0_OUT, PK0_IN_PU),
/* PL GPIO */
PINMUX_DATA(PL7_DATA, PL7_IN, PL7_OUT, PL7_IN_PU),
PINMUX_DATA(PL6_DATA, PL6_IN, PL6_OUT, PL6_IN_PU),
PINMUX_DATA(PL5_DATA, PL5_IN, PL5_OUT, PL5_IN_PU),
PINMUX_DATA(PL4_DATA, PL4_IN, PL4_OUT, PL4_IN_PU),
PINMUX_DATA(PL3_DATA, PL3_IN, PL3_OUT, PL3_IN_PU),
PINMUX_DATA(PL2_DATA, PL2_IN, PL2_OUT, PL2_IN_PU),
PINMUX_DATA(PL1_DATA, PL1_IN, PL1_OUT, PL1_IN_PU),
PINMUX_DATA(PL0_DATA, PL0_IN, PL0_OUT, PL0_IN_PU),
/* PM GPIO */
PINMUX_DATA(PM1_DATA, PM1_IN, PM1_OUT, PM1_IN_PU),
PINMUX_DATA(PM0_DATA, PM0_IN, PM0_OUT, PM0_IN_PU),
/* PN GPIO */
PINMUX_DATA(PN7_DATA, PN7_IN, PN7_OUT, PN7_IN_PU),
PINMUX_DATA(PN6_DATA, PN6_IN, PN6_OUT, PN6_IN_PU),
PINMUX_DATA(PN5_DATA, PN5_IN, PN5_OUT, PN5_IN_PU),
PINMUX_DATA(PN4_DATA, PN4_IN, PN4_OUT, PN4_IN_PU),
PINMUX_DATA(PN3_DATA, PN3_IN, PN3_OUT, PN3_IN_PU),
PINMUX_DATA(PN2_DATA, PN2_IN, PN2_OUT, PN2_IN_PU),
PINMUX_DATA(PN1_DATA, PN1_IN, PN1_OUT, PN1_IN_PU),
PINMUX_DATA(PN0_DATA, PN0_IN, PN0_OUT, PN0_IN_PU),
/* PP GPIO */
PINMUX_DATA(PP5_DATA, PP5_IN, PP5_OUT, PP5_IN_PU),
PINMUX_DATA(PP4_DATA, PP4_IN, PP4_OUT, PP4_IN_PU),
PINMUX_DATA(PP3_DATA, PP3_IN, PP3_OUT, PP3_IN_PU),
PINMUX_DATA(PP2_DATA, PP2_IN, PP2_OUT, PP2_IN_PU),
PINMUX_DATA(PP1_DATA, PP1_IN, PP1_OUT, PP1_IN_PU),
PINMUX_DATA(PP0_DATA, PP0_IN, PP0_OUT, PP0_IN_PU),
/* PQ GPIO */
PINMUX_DATA(PQ4_DATA, PQ4_IN, PQ4_OUT, PQ4_IN_PU),
PINMUX_DATA(PQ3_DATA, PQ3_IN, PQ3_OUT, PQ3_IN_PU),
PINMUX_DATA(PQ2_DATA, PQ2_IN, PQ2_OUT, PQ2_IN_PU),
PINMUX_DATA(PQ1_DATA, PQ1_IN, PQ1_OUT, PQ1_IN_PU),
PINMUX_DATA(PQ0_DATA, PQ0_IN, PQ0_OUT, PQ0_IN_PU),
/* PR GPIO */
PINMUX_DATA(PR3_DATA, PR3_IN, PR3_OUT, PR3_IN_PU),
PINMUX_DATA(PR2_DATA, PR2_IN, PR2_OUT, PR2_IN_PU),
PINMUX_DATA(PR1_DATA, PR1_IN, PR1_OUT, PR1_IN_PU),
PINMUX_DATA(PR0_DATA, PR0_IN, PR0_OUT, PR0_IN_PU),
/* PA FN */
PINMUX_DATA(D63_AD31_MARK, PA7_FN),
PINMUX_DATA(D62_AD30_MARK, PA6_FN),
PINMUX_DATA(D61_AD29_MARK, PA5_FN),
PINMUX_DATA(D60_AD28_MARK, PA4_FN),
PINMUX_DATA(D59_AD27_MARK, PA3_FN),
PINMUX_DATA(D58_AD26_MARK, PA2_FN),
PINMUX_DATA(D57_AD25_MARK, PA1_FN),
PINMUX_DATA(D56_AD24_MARK, PA0_FN),
/* PB FN */
PINMUX_DATA(D55_AD23_MARK, PB7_FN),
PINMUX_DATA(D54_AD22_MARK, PB6_FN),
PINMUX_DATA(D53_AD21_MARK, PB5_FN),
PINMUX_DATA(D52_AD20_MARK, PB4_FN),
PINMUX_DATA(D51_AD19_MARK, PB3_FN),
PINMUX_DATA(D50_AD18_MARK, PB2_FN),
PINMUX_DATA(D49_AD17_DB5_MARK, PB1_FN),
PINMUX_DATA(D48_AD16_DB4_MARK, PB0_FN),
/* PC FN */
PINMUX_DATA(D47_AD15_DB3_MARK, PC7_FN),
PINMUX_DATA(D46_AD14_DB2_MARK, PC6_FN),
PINMUX_DATA(D45_AD13_DB1_MARK, PC5_FN),
PINMUX_DATA(D44_AD12_DB0_MARK, PC4_FN),
PINMUX_DATA(D43_AD11_DG5_MARK, PC3_FN),
PINMUX_DATA(D42_AD10_DG4_MARK, PC2_FN),
PINMUX_DATA(D41_AD9_DG3_MARK, PC1_FN),
PINMUX_DATA(D40_AD8_DG2_MARK, PC0_FN),
/* PD FN */
PINMUX_DATA(D39_AD7_DG1_MARK, PD7_FN),
PINMUX_DATA(D38_AD6_DG0_MARK, PD6_FN),
PINMUX_DATA(D37_AD5_DR5_MARK, PD5_FN),
PINMUX_DATA(D36_AD4_DR4_MARK, PD4_FN),
PINMUX_DATA(D35_AD3_DR3_MARK, PD3_FN),
PINMUX_DATA(D34_AD2_DR2_MARK, PD2_FN),
PINMUX_DATA(D33_AD1_DR1_MARK, PD1_FN),
PINMUX_DATA(D32_AD0_DR0_MARK, PD0_FN),
/* PE FN */
PINMUX_DATA(REQ1_MARK, PE5_FN),
PINMUX_DATA(REQ2_MARK, PE4_FN),
PINMUX_DATA(REQ3_MARK, P2MSEL0_0, PE3_FN),
PINMUX_DATA(GNT1_MARK, PE2_FN),
PINMUX_DATA(GNT2_MARK, PE1_FN),
PINMUX_DATA(GNT3_MARK, P2MSEL0_0, PE0_FN),
PINMUX_DATA(MMCCLK_MARK, P2MSEL0_1, PE0_FN),
/* PF FN */
PINMUX_DATA(D31_MARK, PF7_FN),
PINMUX_DATA(D30_MARK, PF6_FN),
PINMUX_DATA(D29_MARK, PF5_FN),
PINMUX_DATA(D28_MARK, PF4_FN),
PINMUX_DATA(D27_MARK, PF3_FN),
PINMUX_DATA(D26_MARK, PF2_FN),
PINMUX_DATA(D25_MARK, PF1_FN),
PINMUX_DATA(D24_MARK, PF0_FN),
/* PF FN */
PINMUX_DATA(D23_MARK, PG7_FN),
PINMUX_DATA(D22_MARK, PG6_FN),
PINMUX_DATA(D21_MARK, PG5_FN),
PINMUX_DATA(D20_MARK, PG4_FN),
PINMUX_DATA(D19_MARK, PG3_FN),
PINMUX_DATA(D18_MARK, PG2_FN),
PINMUX_DATA(D17_MARK, PG1_FN),
PINMUX_DATA(D16_MARK, PG0_FN),
/* PH FN */
PINMUX_DATA(SCIF1_SCK_MARK, PH7_FN),
PINMUX_DATA(SCIF1_RXD_MARK, PH6_FN),
PINMUX_DATA(SCIF1_TXD_MARK, PH5_FN),
PINMUX_DATA(SCIF0_CTS_MARK, PH4_FN),
PINMUX_DATA(INTD_MARK, P1MSEL7_1, PH4_FN),
PINMUX_DATA(FCE_MARK, P1MSEL8_1, P1MSEL7_0, PH4_FN),
PINMUX_DATA(SCIF0_RTS_MARK, P1MSEL8_0, P1MSEL7_0, PH3_FN),
PINMUX_DATA(HSPI_CS_MARK, P1MSEL8_0, P1MSEL7_1, PH3_FN),
PINMUX_DATA(FSE_MARK, P1MSEL8_1, P1MSEL7_0, PH3_FN),
PINMUX_DATA(SCIF0_SCK_MARK, P1MSEL8_0, P1MSEL7_0, PH2_FN),
PINMUX_DATA(HSPI_CLK_MARK, P1MSEL8_0, P1MSEL7_1, PH2_FN),
PINMUX_DATA(FRE_MARK, P1MSEL8_1, P1MSEL7_0, PH2_FN),
PINMUX_DATA(SCIF0_RXD_MARK, P1MSEL8_0, P1MSEL7_0, PH1_FN),
PINMUX_DATA(HSPI_RX_MARK, P1MSEL8_0, P1MSEL7_1, PH1_FN),
PINMUX_DATA(FRB_MARK, P1MSEL8_1, P1MSEL7_0, PH1_FN),
PINMUX_DATA(SCIF0_TXD_MARK, P1MSEL8_0, P1MSEL7_0, PH0_FN),
PINMUX_DATA(HSPI_TX_MARK, P1MSEL8_0, P1MSEL7_1, PH0_FN),
PINMUX_DATA(FWE_MARK, P1MSEL8_1, P1MSEL7_0, PH0_FN),
/* PJ FN */
PINMUX_DATA(SCIF5_TXD_MARK, P1MSEL2_0, P1MSEL1_0, PJ7_FN),
PINMUX_DATA(HAC1_SYNC_MARK, P1MSEL2_0, P1MSEL1_1, PJ7_FN),
PINMUX_DATA(SSI1_WS_MARK, P1MSEL2_1, P1MSEL1_0, PJ7_FN),
PINMUX_DATA(SIOF_TXD_PJ_MARK, P2MSEL1_0, P1MSEL4_0, P1MSEL3_0, PJ6_FN),
PINMUX_DATA(HAC0_SDOUT_MARK, P1MSEL4_0, P1MSEL3_1, PJ6_FN),
PINMUX_DATA(SSI0_SDATA_MARK, P1MSEL4_1, P1MSEL3_0, PJ6_FN),
PINMUX_DATA(SIOF_RXD_PJ_MARK, P2MSEL1_0, P1MSEL4_0, P1MSEL3_0, PJ5_FN),
PINMUX_DATA(HAC0_SDIN_MARK, P1MSEL4_0, P1MSEL3_1, PJ5_FN),
PINMUX_DATA(SSI0_SCK_MARK, P1MSEL4_1, P1MSEL3_0, PJ5_FN),
PINMUX_DATA(SIOF_SYNC_PJ_MARK, P2MSEL1_0, P1MSEL4_0, P1MSEL3_0, PJ4_FN),
PINMUX_DATA(HAC0_SYNC_MARK, P1MSEL4_0, P1MSEL3_1, PJ4_FN),
PINMUX_DATA(SSI0_WS_MARK, P1MSEL4_1, P1MSEL3_0, PJ4_FN),
PINMUX_DATA(SIOF_MCLK_PJ_MARK, P2MSEL1_0, P1MSEL4_0, P1MSEL3_0, PJ3_FN),
PINMUX_DATA(HAC_RES_MARK, P1MSEL4_0, P1MSEL3_1, PJ3_FN),
PINMUX_DATA(SIOF_SCK_PJ_MARK, P2MSEL1_0, P1MSEL4_0, P1MSEL3_0, PJ2_FN),
PINMUX_DATA(HAC0_BITCLK_MARK, P1MSEL4_0, P1MSEL3_1, PJ2_FN),
PINMUX_DATA(SSI0_CLK_MARK, P1MSEL4_1, P1MSEL3_0, PJ2_FN),
PINMUX_DATA(HAC1_BITCLK_MARK, P1MSEL2_0, PJ1_FN),
PINMUX_DATA(SSI1_CLK_MARK, P1MSEL2_1, P1MSEL1_0, PJ1_FN),
PINMUX_DATA(TCLK_MARK, P1MSEL9_0, PJ0_FN),
PINMUX_DATA(IOIS16_MARK, P1MSEL9_1, PJ0_FN),
/* PK FN */
PINMUX_DATA(STATUS0_MARK, P1MSEL15_0, PK7_FN),
PINMUX_DATA(DRAK0_PK3_MARK, P1MSEL15_1, PK7_FN),
PINMUX_DATA(STATUS1_MARK, P1MSEL15_0, PK6_FN),
PINMUX_DATA(DRAK1_PK2_MARK, P1MSEL15_1, PK6_FN),
PINMUX_DATA(DACK2_MARK, P1MSEL12_0, P1MSEL11_0, PK5_FN),
PINMUX_DATA(SCIF2_TXD_MARK, P1MSEL12_1, P1MSEL11_0, PK5_FN),
PINMUX_DATA(MMCCMD_MARK, P1MSEL12_1, P1MSEL11_1, PK5_FN),
PINMUX_DATA(SIOF_TXD_PK_MARK, P2MSEL1_1,
P1MSEL12_0, P1MSEL11_1, PK5_FN),
PINMUX_DATA(DACK3_MARK, P1MSEL12_0, P1MSEL11_0, PK4_FN),
PINMUX_DATA(SCIF2_SCK_MARK, P1MSEL12_1, P1MSEL11_0, PK4_FN),
PINMUX_DATA(MMCDAT_MARK, P1MSEL12_1, P1MSEL11_1, PK4_FN),
PINMUX_DATA(SIOF_SCK_PK_MARK, P2MSEL1_1,
P1MSEL12_0, P1MSEL11_1, PK4_FN),
PINMUX_DATA(DREQ0_MARK, PK3_FN),
PINMUX_DATA(DREQ1_MARK, PK2_FN),
PINMUX_DATA(DRAK0_PK1_MARK, PK1_FN),
PINMUX_DATA(DRAK1_PK0_MARK, PK0_FN),
/* PL FN */
PINMUX_DATA(DREQ2_MARK, P1MSEL13_0, PL7_FN),
PINMUX_DATA(INTB_MARK, P1MSEL13_1, PL7_FN),
PINMUX_DATA(DREQ3_MARK, P1MSEL13_0, PL6_FN),
PINMUX_DATA(INTC_MARK, P1MSEL13_1, PL6_FN),
PINMUX_DATA(DRAK2_MARK, P1MSEL10_0, PL5_FN),
PINMUX_DATA(CE2A_MARK, P1MSEL10_1, PL5_FN),
PINMUX_DATA(IRL4_MARK, P1MSEL14_0, PL4_FN),
PINMUX_DATA(FD4_MARK, P1MSEL14_1, PL4_FN),
PINMUX_DATA(IRL5_MARK, P1MSEL14_0, PL3_FN),
PINMUX_DATA(FD5_MARK, P1MSEL14_1, PL3_FN),
PINMUX_DATA(IRL6_MARK, P1MSEL14_0, PL2_FN),
PINMUX_DATA(FD6_MARK, P1MSEL14_1, PL2_FN),
PINMUX_DATA(IRL7_MARK, P1MSEL14_0, PL1_FN),
PINMUX_DATA(FD7_MARK, P1MSEL14_1, PL1_FN),
PINMUX_DATA(DRAK3_MARK, P1MSEL10_0, PL0_FN),
PINMUX_DATA(CE2B_MARK, P1MSEL10_1, PL0_FN),
/* PM FN */
PINMUX_DATA(BREQ_BSACK_MARK, PM1_FN),
PINMUX_DATA(BACK_BSREQ_MARK, PM0_FN),
/* PN FN */
PINMUX_DATA(SCIF5_RXD_MARK, P1MSEL2_0, P1MSEL1_0, PN7_FN),
PINMUX_DATA(HAC1_SDIN_MARK, P1MSEL2_0, P1MSEL1_1, PN7_FN),
PINMUX_DATA(SSI1_SCK_MARK, P1MSEL2_1, P1MSEL1_0, PN7_FN),
PINMUX_DATA(SCIF5_SCK_MARK, P1MSEL2_0, P1MSEL1_0, PN6_FN),
PINMUX_DATA(HAC1_SDOUT_MARK, P1MSEL2_0, P1MSEL1_1, PN6_FN),
PINMUX_DATA(SSI1_SDATA_MARK, P1MSEL2_1, P1MSEL1_0, PN6_FN),
PINMUX_DATA(SCIF3_TXD_MARK, P1MSEL0_0, PN5_FN),
PINMUX_DATA(FCLE_MARK, P1MSEL0_1, PN5_FN),
PINMUX_DATA(SCIF3_RXD_MARK, P1MSEL0_0, PN4_FN),
PINMUX_DATA(FALE_MARK, P1MSEL0_1, PN4_FN),
PINMUX_DATA(SCIF3_SCK_MARK, P1MSEL0_0, PN3_FN),
PINMUX_DATA(FD0_MARK, P1MSEL0_1, PN3_FN),
PINMUX_DATA(SCIF4_TXD_MARK, P1MSEL0_0, PN2_FN),
PINMUX_DATA(FD1_MARK, P1MSEL0_1, PN2_FN),
PINMUX_DATA(SCIF4_RXD_MARK, P1MSEL0_0, PN1_FN),
PINMUX_DATA(FD2_MARK, P1MSEL0_1, PN1_FN),
PINMUX_DATA(SCIF4_SCK_MARK, P1MSEL0_0, PN0_FN),
PINMUX_DATA(FD3_MARK, P1MSEL0_1, PN0_FN),
/* PP FN */
PINMUX_DATA(DEVSEL_DCLKOUT_MARK, PP5_FN),
PINMUX_DATA(STOP_CDE_MARK, PP4_FN),
PINMUX_DATA(LOCK_ODDF_MARK, PP3_FN),
PINMUX_DATA(TRDY_DISPL_MARK, PP2_FN),
PINMUX_DATA(IRDY_HSYNC_MARK, PP1_FN),
PINMUX_DATA(PCIFRAME_VSYNC_MARK, PP0_FN),
/* PQ FN */
PINMUX_DATA(INTA_MARK, PQ4_FN),
PINMUX_DATA(GNT0_GNTIN_MARK, PQ3_FN),
PINMUX_DATA(REQ0_REQOUT_MARK, PQ2_FN),
PINMUX_DATA(PERR_MARK, PQ1_FN),
PINMUX_DATA(SERR_MARK, PQ0_FN),
/* PR FN */
PINMUX_DATA(WE7_CBE3_MARK, PR3_FN),
PINMUX_DATA(WE6_CBE2_MARK, PR2_FN),
PINMUX_DATA(WE5_CBE1_MARK, PR1_FN),
PINMUX_DATA(WE4_CBE0_MARK, PR0_FN),
/* MISC FN */
PINMUX_DATA(SCIF2_RXD_MARK, P1MSEL6_0, P1MSEL5_0),
PINMUX_DATA(SIOF_RXD_MARK, P2MSEL1_1, P1MSEL6_1, P1MSEL5_0),
PINMUX_DATA(MRESETOUT_MARK, P2MSEL2_0),
PINMUX_DATA(IRQOUT_MARK, P2MSEL2_1),
};
static struct sh_pfc_pin pinmux_pins[] = {
/* PA */
PINMUX_GPIO(GPIO_PA7, PA7_DATA),
PINMUX_GPIO(GPIO_PA6, PA6_DATA),
PINMUX_GPIO(GPIO_PA5, PA5_DATA),
PINMUX_GPIO(GPIO_PA4, PA4_DATA),
PINMUX_GPIO(GPIO_PA3, PA3_DATA),
PINMUX_GPIO(GPIO_PA2, PA2_DATA),
PINMUX_GPIO(GPIO_PA1, PA1_DATA),
PINMUX_GPIO(GPIO_PA0, PA0_DATA),
/* PB */
PINMUX_GPIO(GPIO_PB7, PB7_DATA),
PINMUX_GPIO(GPIO_PB6, PB6_DATA),
PINMUX_GPIO(GPIO_PB5, PB5_DATA),
PINMUX_GPIO(GPIO_PB4, PB4_DATA),
PINMUX_GPIO(GPIO_PB3, PB3_DATA),
PINMUX_GPIO(GPIO_PB2, PB2_DATA),
PINMUX_GPIO(GPIO_PB1, PB1_DATA),
PINMUX_GPIO(GPIO_PB0, PB0_DATA),
/* PC */
PINMUX_GPIO(GPIO_PC7, PC7_DATA),
PINMUX_GPIO(GPIO_PC6, PC6_DATA),
PINMUX_GPIO(GPIO_PC5, PC5_DATA),
PINMUX_GPIO(GPIO_PC4, PC4_DATA),
PINMUX_GPIO(GPIO_PC3, PC3_DATA),
PINMUX_GPIO(GPIO_PC2, PC2_DATA),
PINMUX_GPIO(GPIO_PC1, PC1_DATA),
PINMUX_GPIO(GPIO_PC0, PC0_DATA),
/* PD */
PINMUX_GPIO(GPIO_PD7, PD7_DATA),
PINMUX_GPIO(GPIO_PD6, PD6_DATA),
PINMUX_GPIO(GPIO_PD5, PD5_DATA),
PINMUX_GPIO(GPIO_PD4, PD4_DATA),
PINMUX_GPIO(GPIO_PD3, PD3_DATA),
PINMUX_GPIO(GPIO_PD2, PD2_DATA),
PINMUX_GPIO(GPIO_PD1, PD1_DATA),
PINMUX_GPIO(GPIO_PD0, PD0_DATA),
/* PE */
PINMUX_GPIO(GPIO_PE5, PE5_DATA),
PINMUX_GPIO(GPIO_PE4, PE4_DATA),
PINMUX_GPIO(GPIO_PE3, PE3_DATA),
PINMUX_GPIO(GPIO_PE2, PE2_DATA),
PINMUX_GPIO(GPIO_PE1, PE1_DATA),
PINMUX_GPIO(GPIO_PE0, PE0_DATA),
/* PF */
PINMUX_GPIO(GPIO_PF7, PF7_DATA),
PINMUX_GPIO(GPIO_PF6, PF6_DATA),
PINMUX_GPIO(GPIO_PF5, PF5_DATA),
PINMUX_GPIO(GPIO_PF4, PF4_DATA),
PINMUX_GPIO(GPIO_PF3, PF3_DATA),
PINMUX_GPIO(GPIO_PF2, PF2_DATA),
PINMUX_GPIO(GPIO_PF1, PF1_DATA),
PINMUX_GPIO(GPIO_PF0, PF0_DATA),
/* PG */
PINMUX_GPIO(GPIO_PG7, PG7_DATA),
PINMUX_GPIO(GPIO_PG6, PG6_DATA),
PINMUX_GPIO(GPIO_PG5, PG5_DATA),
PINMUX_GPIO(GPIO_PG4, PG4_DATA),
PINMUX_GPIO(GPIO_PG3, PG3_DATA),
PINMUX_GPIO(GPIO_PG2, PG2_DATA),
PINMUX_GPIO(GPIO_PG1, PG1_DATA),
PINMUX_GPIO(GPIO_PG0, PG0_DATA),
/* PH */
PINMUX_GPIO(GPIO_PH7, PH7_DATA),
PINMUX_GPIO(GPIO_PH6, PH6_DATA),
PINMUX_GPIO(GPIO_PH5, PH5_DATA),
PINMUX_GPIO(GPIO_PH4, PH4_DATA),
PINMUX_GPIO(GPIO_PH3, PH3_DATA),
PINMUX_GPIO(GPIO_PH2, PH2_DATA),
PINMUX_GPIO(GPIO_PH1, PH1_DATA),
PINMUX_GPIO(GPIO_PH0, PH0_DATA),
/* PJ */
PINMUX_GPIO(GPIO_PJ7, PJ7_DATA),
PINMUX_GPIO(GPIO_PJ6, PJ6_DATA),
PINMUX_GPIO(GPIO_PJ5, PJ5_DATA),
PINMUX_GPIO(GPIO_PJ4, PJ4_DATA),
PINMUX_GPIO(GPIO_PJ3, PJ3_DATA),
PINMUX_GPIO(GPIO_PJ2, PJ2_DATA),
PINMUX_GPIO(GPIO_PJ1, PJ1_DATA),
PINMUX_GPIO(GPIO_PJ0, PJ0_DATA),
/* PK */
PINMUX_GPIO(GPIO_PK7, PK7_DATA),
PINMUX_GPIO(GPIO_PK6, PK6_DATA),
PINMUX_GPIO(GPIO_PK5, PK5_DATA),
PINMUX_GPIO(GPIO_PK4, PK4_DATA),
PINMUX_GPIO(GPIO_PK3, PK3_DATA),
PINMUX_GPIO(GPIO_PK2, PK2_DATA),
PINMUX_GPIO(GPIO_PK1, PK1_DATA),
PINMUX_GPIO(GPIO_PK0, PK0_DATA),
/* PL */
PINMUX_GPIO(GPIO_PL7, PL7_DATA),
PINMUX_GPIO(GPIO_PL6, PL6_DATA),
PINMUX_GPIO(GPIO_PL5, PL5_DATA),
PINMUX_GPIO(GPIO_PL4, PL4_DATA),
PINMUX_GPIO(GPIO_PL3, PL3_DATA),
PINMUX_GPIO(GPIO_PL2, PL2_DATA),
PINMUX_GPIO(GPIO_PL1, PL1_DATA),
PINMUX_GPIO(GPIO_PL0, PL0_DATA),
/* PM */
PINMUX_GPIO(GPIO_PM1, PM1_DATA),
PINMUX_GPIO(GPIO_PM0, PM0_DATA),
/* PN */
PINMUX_GPIO(GPIO_PN7, PN7_DATA),
PINMUX_GPIO(GPIO_PN6, PN6_DATA),
PINMUX_GPIO(GPIO_PN5, PN5_DATA),
PINMUX_GPIO(GPIO_PN4, PN4_DATA),
PINMUX_GPIO(GPIO_PN3, PN3_DATA),
PINMUX_GPIO(GPIO_PN2, PN2_DATA),
PINMUX_GPIO(GPIO_PN1, PN1_DATA),
PINMUX_GPIO(GPIO_PN0, PN0_DATA),
/* PP */
PINMUX_GPIO(GPIO_PP5, PP5_DATA),
PINMUX_GPIO(GPIO_PP4, PP4_DATA),
PINMUX_GPIO(GPIO_PP3, PP3_DATA),
PINMUX_GPIO(GPIO_PP2, PP2_DATA),
PINMUX_GPIO(GPIO_PP1, PP1_DATA),
PINMUX_GPIO(GPIO_PP0, PP0_DATA),
/* PQ */
PINMUX_GPIO(GPIO_PQ4, PQ4_DATA),
PINMUX_GPIO(GPIO_PQ3, PQ3_DATA),
PINMUX_GPIO(GPIO_PQ2, PQ2_DATA),
PINMUX_GPIO(GPIO_PQ1, PQ1_DATA),
PINMUX_GPIO(GPIO_PQ0, PQ0_DATA),
/* PR */
PINMUX_GPIO(GPIO_PR3, PR3_DATA),
PINMUX_GPIO(GPIO_PR2, PR2_DATA),
PINMUX_GPIO(GPIO_PR1, PR1_DATA),
PINMUX_GPIO(GPIO_PR0, PR0_DATA),
};
#define PINMUX_FN_BASE ARRAY_SIZE(pinmux_pins)
static const struct pinmux_func pinmux_func_gpios[] = {
/* FN */
GPIO_FN(D63_AD31),
GPIO_FN(D62_AD30),
GPIO_FN(D61_AD29),
GPIO_FN(D60_AD28),
GPIO_FN(D59_AD27),
GPIO_FN(D58_AD26),
GPIO_FN(D57_AD25),
GPIO_FN(D56_AD24),
GPIO_FN(D55_AD23),
GPIO_FN(D54_AD22),
GPIO_FN(D53_AD21),
GPIO_FN(D52_AD20),
GPIO_FN(D51_AD19),
GPIO_FN(D50_AD18),
GPIO_FN(D49_AD17_DB5),
GPIO_FN(D48_AD16_DB4),
GPIO_FN(D47_AD15_DB3),
GPIO_FN(D46_AD14_DB2),
GPIO_FN(D45_AD13_DB1),
GPIO_FN(D44_AD12_DB0),
GPIO_FN(D43_AD11_DG5),
GPIO_FN(D42_AD10_DG4),
GPIO_FN(D41_AD9_DG3),
GPIO_FN(D40_AD8_DG2),
GPIO_FN(D39_AD7_DG1),
GPIO_FN(D38_AD6_DG0),
GPIO_FN(D37_AD5_DR5),
GPIO_FN(D36_AD4_DR4),
GPIO_FN(D35_AD3_DR3),
GPIO_FN(D34_AD2_DR2),
GPIO_FN(D33_AD1_DR1),
GPIO_FN(D32_AD0_DR0),
GPIO_FN(REQ1),
GPIO_FN(REQ2),
GPIO_FN(REQ3),
GPIO_FN(GNT1),
GPIO_FN(GNT2),
GPIO_FN(GNT3),
GPIO_FN(MMCCLK),
GPIO_FN(D31),
GPIO_FN(D30),
GPIO_FN(D29),
GPIO_FN(D28),
GPIO_FN(D27),
GPIO_FN(D26),
GPIO_FN(D25),
GPIO_FN(D24),
GPIO_FN(D23),
GPIO_FN(D22),
GPIO_FN(D21),
GPIO_FN(D20),
GPIO_FN(D19),
GPIO_FN(D18),
GPIO_FN(D17),
GPIO_FN(D16),
GPIO_FN(SCIF1_SCK),
GPIO_FN(SCIF1_RXD),
GPIO_FN(SCIF1_TXD),
GPIO_FN(SCIF0_CTS),
GPIO_FN(INTD),
GPIO_FN(FCE),
GPIO_FN(SCIF0_RTS),
GPIO_FN(HSPI_CS),
GPIO_FN(FSE),
GPIO_FN(SCIF0_SCK),
GPIO_FN(HSPI_CLK),
GPIO_FN(FRE),
GPIO_FN(SCIF0_RXD),
GPIO_FN(HSPI_RX),
GPIO_FN(FRB),
GPIO_FN(SCIF0_TXD),
GPIO_FN(HSPI_TX),
GPIO_FN(FWE),
GPIO_FN(SCIF5_TXD),
GPIO_FN(HAC1_SYNC),
GPIO_FN(SSI1_WS),
GPIO_FN(SIOF_TXD_PJ),
GPIO_FN(HAC0_SDOUT),
GPIO_FN(SSI0_SDATA),
GPIO_FN(SIOF_RXD_PJ),
GPIO_FN(HAC0_SDIN),
GPIO_FN(SSI0_SCK),
GPIO_FN(SIOF_SYNC_PJ),
GPIO_FN(HAC0_SYNC),
GPIO_FN(SSI0_WS),
GPIO_FN(SIOF_MCLK_PJ),
GPIO_FN(HAC_RES),
GPIO_FN(SIOF_SCK_PJ),
GPIO_FN(HAC0_BITCLK),
GPIO_FN(SSI0_CLK),
GPIO_FN(HAC1_BITCLK),
GPIO_FN(SSI1_CLK),
GPIO_FN(TCLK),
GPIO_FN(IOIS16),
GPIO_FN(STATUS0),
GPIO_FN(DRAK0_PK3),
GPIO_FN(STATUS1),
GPIO_FN(DRAK1_PK2),
GPIO_FN(DACK2),
GPIO_FN(SCIF2_TXD),
GPIO_FN(MMCCMD),
GPIO_FN(SIOF_TXD_PK),
GPIO_FN(DACK3),
GPIO_FN(SCIF2_SCK),
GPIO_FN(MMCDAT),
GPIO_FN(SIOF_SCK_PK),
GPIO_FN(DREQ0),
GPIO_FN(DREQ1),
GPIO_FN(DRAK0_PK1),
GPIO_FN(DRAK1_PK0),
GPIO_FN(DREQ2),
GPIO_FN(INTB),
GPIO_FN(DREQ3),
GPIO_FN(INTC),
GPIO_FN(DRAK2),
GPIO_FN(CE2A),
GPIO_FN(IRL4),
GPIO_FN(FD4),
GPIO_FN(IRL5),
GPIO_FN(FD5),
GPIO_FN(IRL6),
GPIO_FN(FD6),
GPIO_FN(IRL7),
GPIO_FN(FD7),
GPIO_FN(DRAK3),
GPIO_FN(CE2B),
GPIO_FN(BREQ_BSACK),
GPIO_FN(BACK_BSREQ),
GPIO_FN(SCIF5_RXD),
GPIO_FN(HAC1_SDIN),
GPIO_FN(SSI1_SCK),
GPIO_FN(SCIF5_SCK),
GPIO_FN(HAC1_SDOUT),
GPIO_FN(SSI1_SDATA),
GPIO_FN(SCIF3_TXD),
GPIO_FN(FCLE),
GPIO_FN(SCIF3_RXD),
GPIO_FN(FALE),
GPIO_FN(SCIF3_SCK),
GPIO_FN(FD0),
GPIO_FN(SCIF4_TXD),
GPIO_FN(FD1),
GPIO_FN(SCIF4_RXD),
GPIO_FN(FD2),
GPIO_FN(SCIF4_SCK),
GPIO_FN(FD3),
GPIO_FN(DEVSEL_DCLKOUT),
GPIO_FN(STOP_CDE),
GPIO_FN(LOCK_ODDF),
GPIO_FN(TRDY_DISPL),
GPIO_FN(IRDY_HSYNC),
GPIO_FN(PCIFRAME_VSYNC),
GPIO_FN(INTA),
GPIO_FN(GNT0_GNTIN),
GPIO_FN(REQ0_REQOUT),
GPIO_FN(PERR),
GPIO_FN(SERR),
GPIO_FN(WE7_CBE3),
GPIO_FN(WE6_CBE2),
GPIO_FN(WE5_CBE1),
GPIO_FN(WE4_CBE0),
GPIO_FN(SCIF2_RXD),
GPIO_FN(SIOF_RXD),
GPIO_FN(MRESETOUT),
GPIO_FN(IRQOUT),
};
static const struct pinmux_cfg_reg pinmux_config_regs[] = {
{ PINMUX_CFG_REG("PACR", 0xffe70000, 16, 2) {
PA7_FN, PA7_OUT, PA7_IN, PA7_IN_PU,
PA6_FN, PA6_OUT, PA6_IN, PA6_IN_PU,
PA5_FN, PA5_OUT, PA5_IN, PA5_IN_PU,
PA4_FN, PA4_OUT, PA4_IN, PA4_IN_PU,
PA3_FN, PA3_OUT, PA3_IN, PA3_IN_PU,
PA2_FN, PA2_OUT, PA2_IN, PA2_IN_PU,
PA1_FN, PA1_OUT, PA1_IN, PA1_IN_PU,
PA0_FN, PA0_OUT, PA0_IN, PA0_IN_PU }
},
{ PINMUX_CFG_REG("PBCR", 0xffe70002, 16, 2) {
PB7_FN, PB7_OUT, PB7_IN, PB7_IN_PU,
PB6_FN, PB6_OUT, PB6_IN, PB6_IN_PU,
PB5_FN, PB5_OUT, PB5_IN, PB5_IN_PU,
PB4_FN, PB4_OUT, PB4_IN, PB4_IN_PU,
PB3_FN, PB3_OUT, PB3_IN, PB3_IN_PU,
PB2_FN, PB2_OUT, PB2_IN, PB2_IN_PU,
PB1_FN, PB1_OUT, PB1_IN, PB1_IN_PU,
PB0_FN, PB0_OUT, PB0_IN, PB0_IN_PU }
},
{ PINMUX_CFG_REG("PCCR", 0xffe70004, 16, 2) {
PC7_FN, PC7_OUT, PC7_IN, PC7_IN_PU,
PC6_FN, PC6_OUT, PC6_IN, PC6_IN_PU,
PC5_FN, PC5_OUT, PC5_IN, PC5_IN_PU,
PC4_FN, PC4_OUT, PC4_IN, PC4_IN_PU,
PC3_FN, PC3_OUT, PC3_IN, PC3_IN_PU,
PC2_FN, PC2_OUT, PC2_IN, PC2_IN_PU,
PC1_FN, PC1_OUT, PC1_IN, PC1_IN_PU,
PC0_FN, PC0_OUT, PC0_IN, PC0_IN_PU }
},
{ PINMUX_CFG_REG("PDCR", 0xffe70006, 16, 2) {
PD7_FN, PD7_OUT, PD7_IN, PD7_IN_PU,
PD6_FN, PD6_OUT, PD6_IN, PD6_IN_PU,
PD5_FN, PD5_OUT, PD5_IN, PD5_IN_PU,
PD4_FN, PD4_OUT, PD4_IN, PD4_IN_PU,
PD3_FN, PD3_OUT, PD3_IN, PD3_IN_PU,
PD2_FN, PD2_OUT, PD2_IN, PD2_IN_PU,
PD1_FN, PD1_OUT, PD1_IN, PD1_IN_PU,
PD0_FN, PD0_OUT, PD0_IN, PD0_IN_PU }
},
{ PINMUX_CFG_REG("PECR", 0xffe70008, 16, 2) {
0, 0, 0, 0,
0, 0, 0, 0,
PE5_FN, PE5_OUT, PE5_IN, PE5_IN_PU,
PE4_FN, PE4_OUT, PE4_IN, PE4_IN_PU,
PE3_FN, PE3_OUT, PE3_IN, PE3_IN_PU,
PE2_FN, PE2_OUT, PE2_IN, PE2_IN_PU,
PE1_FN, PE1_OUT, PE1_IN, PE1_IN_PU,
PE0_FN, PE0_OUT, PE0_IN, PE0_IN_PU }
},
{ PINMUX_CFG_REG("PFCR", 0xffe7000a, 16, 2) {
PF7_FN, PF7_OUT, PF7_IN, PF7_IN_PU,
PF6_FN, PF6_OUT, PF6_IN, PF6_IN_PU,
PF5_FN, PF5_OUT, PF5_IN, PF5_IN_PU,
PF4_FN, PF4_OUT, PF4_IN, PF4_IN_PU,
PF3_FN, PF3_OUT, PF3_IN, PF3_IN_PU,
PF2_FN, PF2_OUT, PF2_IN, PF2_IN_PU,
PF1_FN, PF1_OUT, PF1_IN, PF1_IN_PU,
PF0_FN, PF0_OUT, PF0_IN, PF0_IN_PU }
},
{ PINMUX_CFG_REG("PGCR", 0xffe7000c, 16, 2) {
PG7_FN, PG7_OUT, PG7_IN, PG7_IN_PU,
PG6_FN, PG6_OUT, PG6_IN, PG6_IN_PU,
PG5_FN, PG5_OUT, PG5_IN, PG5_IN_PU,
PG4_FN, PG4_OUT, PG4_IN, PG4_IN_PU,
PG3_FN, PG3_OUT, PG3_IN, PG3_IN_PU,
PG2_FN, PG2_OUT, PG2_IN, PG2_IN_PU,
PG1_FN, PG1_OUT, PG1_IN, PG1_IN_PU,
PG0_FN, PG0_OUT, PG0_IN, PG0_IN_PU }
},
{ PINMUX_CFG_REG("PHCR", 0xffe7000e, 16, 2) {
PH7_FN, PH7_OUT, PH7_IN, PH7_IN_PU,
PH6_FN, PH6_OUT, PH6_IN, PH6_IN_PU,
PH5_FN, PH5_OUT, PH5_IN, PH5_IN_PU,
PH4_FN, PH4_OUT, PH4_IN, PH4_IN_PU,
PH3_FN, PH3_OUT, PH3_IN, PH3_IN_PU,
PH2_FN, PH2_OUT, PH2_IN, PH2_IN_PU,
PH1_FN, PH1_OUT, PH1_IN, PH1_IN_PU,
PH0_FN, PH0_OUT, PH0_IN, PH0_IN_PU }
},
{ PINMUX_CFG_REG("PJCR", 0xffe70010, 16, 2) {
PJ7_FN, PJ7_OUT, PJ7_IN, PJ7_IN_PU,
PJ6_FN, PJ6_OUT, PJ6_IN, PJ6_IN_PU,
PJ5_FN, PJ5_OUT, PJ5_IN, PJ5_IN_PU,
PJ4_FN, PJ4_OUT, PJ4_IN, PJ4_IN_PU,
PJ3_FN, PJ3_OUT, PJ3_IN, PJ3_IN_PU,
PJ2_FN, PJ2_OUT, PJ2_IN, PJ2_IN_PU,
PJ1_FN, PJ1_OUT, PJ1_IN, PJ1_IN_PU,
PJ0_FN, PJ0_OUT, PJ0_IN, PJ0_IN_PU }
},
{ PINMUX_CFG_REG("PKCR", 0xffe70012, 16, 2) {
PK7_FN, PK7_OUT, PK7_IN, PK7_IN_PU,
PK6_FN, PK6_OUT, PK6_IN, PK6_IN_PU,
PK5_FN, PK5_OUT, PK5_IN, PK5_IN_PU,
PK4_FN, PK4_OUT, PK4_IN, PK4_IN_PU,
PK3_FN, PK3_OUT, PK3_IN, PK3_IN_PU,
PK2_FN, PK2_OUT, PK2_IN, PK2_IN_PU,
PK1_FN, PK1_OUT, PK1_IN, PK1_IN_PU,
PK0_FN, PK0_OUT, PK0_IN, PK0_IN_PU }
},
{ PINMUX_CFG_REG("PLCR", 0xffe70014, 16, 2) {
PL7_FN, PL7_OUT, PL7_IN, PL7_IN_PU,
PL6_FN, PL6_OUT, PL6_IN, PL6_IN_PU,
PL5_FN, PL5_OUT, PL5_IN, PL5_IN_PU,
PL4_FN, PL4_OUT, PL4_IN, PL4_IN_PU,
PL3_FN, PL3_OUT, PL3_IN, PL3_IN_PU,
PL2_FN, PL2_OUT, PL2_IN, PL2_IN_PU,
PL1_FN, PL1_OUT, PL1_IN, PL1_IN_PU,
PL0_FN, PL0_OUT, PL0_IN, PL0_IN_PU }
},
{ PINMUX_CFG_REG("PMCR", 0xffe70016, 16, 2) {
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
PM1_FN, PM1_OUT, PM1_IN, PM1_IN_PU,
PM0_FN, PM0_OUT, PM0_IN, PM0_IN_PU }
},
{ PINMUX_CFG_REG("PNCR", 0xffe70018, 16, 2) {
PN7_FN, PN7_OUT, PN7_IN, PN7_IN_PU,
PN6_FN, PN6_OUT, PN6_IN, PN6_IN_PU,
PN5_FN, PN5_OUT, PN5_IN, PN5_IN_PU,
PN4_FN, PN4_OUT, PN4_IN, PN4_IN_PU,
PN3_FN, PN3_OUT, PN3_IN, PN3_IN_PU,
PN2_FN, PN2_OUT, PN2_IN, PN2_IN_PU,
PN1_FN, PN1_OUT, PN1_IN, PN1_IN_PU,
PN0_FN, PN0_OUT, PN0_IN, PN0_IN_PU }
},
{ PINMUX_CFG_REG("PPCR", 0xffe7001a, 16, 2) {
0, 0, 0, 0,
0, 0, 0, 0,
PP5_FN, PP5_OUT, PP5_IN, PP5_IN_PU,
PP4_FN, PP4_OUT, PP4_IN, PP4_IN_PU,
PP3_FN, PP3_OUT, PP3_IN, PP3_IN_PU,
PP2_FN, PP2_OUT, PP2_IN, PP2_IN_PU,
PP1_FN, PP1_OUT, PP1_IN, PP1_IN_PU,
PP0_FN, PP0_OUT, PP0_IN, PP0_IN_PU }
},
{ PINMUX_CFG_REG("PQCR", 0xffe7001c, 16, 2) {
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
PQ4_FN, PQ4_OUT, PQ4_IN, PQ4_IN_PU,
PQ3_FN, PQ3_OUT, PQ3_IN, PQ3_IN_PU,
PQ2_FN, PQ2_OUT, PQ2_IN, PQ2_IN_PU,
PQ1_FN, PQ1_OUT, PQ1_IN, PQ1_IN_PU,
PQ0_FN, PQ0_OUT, PQ0_IN, PQ0_IN_PU }
},
{ PINMUX_CFG_REG("PRCR", 0xffe7001e, 16, 2) {
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
PR3_FN, PR3_OUT, PR3_IN, PR3_IN_PU,
PR2_FN, PR2_OUT, PR2_IN, PR2_IN_PU,
PR1_FN, PR1_OUT, PR1_IN, PR1_IN_PU,
PR0_FN, PR0_OUT, PR0_IN, PR0_IN_PU }
},
{ PINMUX_CFG_REG("P1MSELR", 0xffe70080, 16, 1) {
P1MSEL15_0, P1MSEL15_1,
P1MSEL14_0, P1MSEL14_1,
P1MSEL13_0, P1MSEL13_1,
P1MSEL12_0, P1MSEL12_1,
P1MSEL11_0, P1MSEL11_1,
P1MSEL10_0, P1MSEL10_1,
P1MSEL9_0, P1MSEL9_1,
P1MSEL8_0, P1MSEL8_1,
P1MSEL7_0, P1MSEL7_1,
P1MSEL6_0, P1MSEL6_1,
P1MSEL5_0, 0,
P1MSEL4_0, P1MSEL4_1,
P1MSEL3_0, P1MSEL3_1,
P1MSEL2_0, P1MSEL2_1,
P1MSEL1_0, P1MSEL1_1,
P1MSEL0_0, P1MSEL0_1 }
},
{ PINMUX_CFG_REG("P2MSELR", 0xffe70082, 16, 1) {
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
P2MSEL2_0, P2MSEL2_1,
P2MSEL1_0, P2MSEL1_1,
P2MSEL0_0, P2MSEL0_1 }
},
{}
};
static const struct pinmux_data_reg pinmux_data_regs[] = {
{ PINMUX_DATA_REG("PADR", 0xffe70020, 8) {
PA7_DATA, PA6_DATA, PA5_DATA, PA4_DATA,
PA3_DATA, PA2_DATA, PA1_DATA, PA0_DATA }
},
{ PINMUX_DATA_REG("PBDR", 0xffe70022, 8) {
PB7_DATA, PB6_DATA, PB5_DATA, PB4_DATA,
PB3_DATA, PB2_DATA, PB1_DATA, PB0_DATA }
},
{ PINMUX_DATA_REG("PCDR", 0xffe70024, 8) {
PC7_DATA, PC6_DATA, PC5_DATA, PC4_DATA,
PC3_DATA, PC2_DATA, PC1_DATA, PC0_DATA }
},
{ PINMUX_DATA_REG("PDDR", 0xffe70026, 8) {
PD7_DATA, PD6_DATA, PD5_DATA, PD4_DATA,
PD3_DATA, PD2_DATA, PD1_DATA, PD0_DATA }
},
{ PINMUX_DATA_REG("PEDR", 0xffe70028, 8) {
0, 0, PE5_DATA, PE4_DATA,
PE3_DATA, PE2_DATA, PE1_DATA, PE0_DATA }
},
{ PINMUX_DATA_REG("PFDR", 0xffe7002a, 8) {
PF7_DATA, PF6_DATA, PF5_DATA, PF4_DATA,
PF3_DATA, PF2_DATA, PF1_DATA, PF0_DATA }
},
{ PINMUX_DATA_REG("PGDR", 0xffe7002c, 8) {
PG7_DATA, PG6_DATA, PG5_DATA, PG4_DATA,
PG3_DATA, PG2_DATA, PG1_DATA, PG0_DATA }
},
{ PINMUX_DATA_REG("PHDR", 0xffe7002e, 8) {
PH7_DATA, PH6_DATA, PH5_DATA, PH4_DATA,
PH3_DATA, PH2_DATA, PH1_DATA, PH0_DATA }
},
{ PINMUX_DATA_REG("PJDR", 0xffe70030, 8) {
PJ7_DATA, PJ6_DATA, PJ5_DATA, PJ4_DATA,
PJ3_DATA, PJ2_DATA, PJ1_DATA, PJ0_DATA }
},
{ PINMUX_DATA_REG("PKDR", 0xffe70032, 8) {
PK7_DATA, PK6_DATA, PK5_DATA, PK4_DATA,
PK3_DATA, PK2_DATA, PK1_DATA, PK0_DATA }
},
{ PINMUX_DATA_REG("PLDR", 0xffe70034, 8) {
PL7_DATA, PL6_DATA, PL5_DATA, PL4_DATA,
PL3_DATA, PL2_DATA, PL1_DATA, PL0_DATA }
},
{ PINMUX_DATA_REG("PMDR", 0xffe70036, 8) {
0, 0, 0, 0,
0, 0, PM1_DATA, PM0_DATA }
},
{ PINMUX_DATA_REG("PNDR", 0xffe70038, 8) {
PN7_DATA, PN6_DATA, PN5_DATA, PN4_DATA,
PN3_DATA, PN2_DATA, PN1_DATA, PN0_DATA }
},
{ PINMUX_DATA_REG("PPDR", 0xffe7003a, 8) {
0, 0, PP5_DATA, PP4_DATA,
PP3_DATA, PP2_DATA, PP1_DATA, PP0_DATA }
},
{ PINMUX_DATA_REG("PQDR", 0xffe7003c, 8) {
0, 0, 0, PQ4_DATA,
PQ3_DATA, PQ2_DATA, PQ1_DATA, PQ0_DATA }
},
{ PINMUX_DATA_REG("PRDR", 0xffe7003e, 8) {
0, 0, 0, 0,
PR3_DATA, PR2_DATA, PR1_DATA, PR0_DATA }
},
{ },
};
const struct sh_pfc_soc_info sh7785_pinmux_info = {
.name = "sh7785_pfc",
.input = { PINMUX_INPUT_BEGIN, PINMUX_INPUT_END },
.input_pu = { PINMUX_INPUT_PULLUP_BEGIN, PINMUX_INPUT_PULLUP_END },
.output = { PINMUX_OUTPUT_BEGIN, PINMUX_OUTPUT_END },
.function = { PINMUX_FUNCTION_BEGIN, PINMUX_FUNCTION_END },
.pins = pinmux_pins,
.nr_pins = ARRAY_SIZE(pinmux_pins),
.func_gpios = pinmux_func_gpios,
.nr_func_gpios = ARRAY_SIZE(pinmux_func_gpios),
.cfg_regs = pinmux_config_regs,
.data_regs = pinmux_data_regs,
.gpio_data = pinmux_data,
.gpio_data_size = ARRAY_SIZE(pinmux_data),
};
| gpl-2.0 |
clevermonkey/android_kernel_asus_301us | sound/soc/codecs/cq93vc.c | 2940 | 5611 | /*
* ALSA SoC CQ0093 Voice Codec Driver for DaVinci platforms
*
* Copyright (C) 2010 Texas Instruments, Inc
*
* Author: Miguel Aguilar <miguel.aguilar@ridgerun.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/platform_device.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <linux/clk.h>
#include <linux/mfd/davinci_voicecodec.h>
#include <linux/spi/spi.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/initval.h>
#include <mach/dm365.h>
static inline unsigned int cq93vc_read(struct snd_soc_codec *codec,
unsigned int reg)
{
struct davinci_vc *davinci_vc = codec->control_data;
return readl(davinci_vc->base + reg);
}
static inline int cq93vc_write(struct snd_soc_codec *codec, unsigned int reg,
unsigned int value)
{
struct davinci_vc *davinci_vc = codec->control_data;
writel(value, davinci_vc->base + reg);
return 0;
}
static const struct snd_kcontrol_new cq93vc_snd_controls[] = {
SOC_SINGLE("PGA Capture Volume", DAVINCI_VC_REG05, 0, 0x03, 0),
SOC_SINGLE("Mono DAC Playback Volume", DAVINCI_VC_REG09, 0, 0x3f, 0),
};
static int cq93vc_mute(struct snd_soc_dai *dai, int mute)
{
struct snd_soc_codec *codec = dai->codec;
u8 reg = cq93vc_read(codec, DAVINCI_VC_REG09) & ~DAVINCI_VC_REG09_MUTE;
if (mute)
cq93vc_write(codec, DAVINCI_VC_REG09,
reg | DAVINCI_VC_REG09_MUTE);
else
cq93vc_write(codec, DAVINCI_VC_REG09, reg);
return 0;
}
static int cq93vc_set_dai_sysclk(struct snd_soc_dai *codec_dai,
int clk_id, unsigned int freq, int dir)
{
struct snd_soc_codec *codec = codec_dai->codec;
struct davinci_vc *davinci_vc = codec->control_data;
switch (freq) {
case 22579200:
case 27000000:
case 33868800:
davinci_vc->cq93vc.sysclk = freq;
return 0;
}
return -EINVAL;
}
static int cq93vc_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
switch (level) {
case SND_SOC_BIAS_ON:
cq93vc_write(codec, DAVINCI_VC_REG12,
DAVINCI_VC_REG12_POWER_ALL_ON);
break;
case SND_SOC_BIAS_PREPARE:
break;
case SND_SOC_BIAS_STANDBY:
cq93vc_write(codec, DAVINCI_VC_REG12,
DAVINCI_VC_REG12_POWER_ALL_OFF);
break;
case SND_SOC_BIAS_OFF:
/* force all power off */
cq93vc_write(codec, DAVINCI_VC_REG12,
DAVINCI_VC_REG12_POWER_ALL_OFF);
break;
}
codec->dapm.bias_level = level;
return 0;
}
#define CQ93VC_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000)
#define CQ93VC_FORMATS (SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE)
static struct snd_soc_dai_ops cq93vc_dai_ops = {
.digital_mute = cq93vc_mute,
.set_sysclk = cq93vc_set_dai_sysclk,
};
static struct snd_soc_dai_driver cq93vc_dai = {
.name = "cq93vc-hifi",
.playback = {
.stream_name = "Playback",
.channels_min = 1,
.channels_max = 2,
.rates = CQ93VC_RATES,
.formats = CQ93VC_FORMATS,},
.capture = {
.stream_name = "Capture",
.channels_min = 1,
.channels_max = 2,
.rates = CQ93VC_RATES,
.formats = CQ93VC_FORMATS,},
.ops = &cq93vc_dai_ops,
};
static int cq93vc_resume(struct snd_soc_codec *codec)
{
cq93vc_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
return 0;
}
static int cq93vc_probe(struct snd_soc_codec *codec)
{
struct davinci_vc *davinci_vc = codec->dev->platform_data;
davinci_vc->cq93vc.codec = codec;
codec->control_data = davinci_vc;
/* Set controls */
snd_soc_add_controls(codec, cq93vc_snd_controls,
ARRAY_SIZE(cq93vc_snd_controls));
/* Off, with power on */
cq93vc_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
return 0;
}
static int cq93vc_remove(struct snd_soc_codec *codec)
{
cq93vc_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_cq93vc = {
.read = cq93vc_read,
.write = cq93vc_write,
.set_bias_level = cq93vc_set_bias_level,
.probe = cq93vc_probe,
.remove = cq93vc_remove,
.resume = cq93vc_resume,
};
static int cq93vc_platform_probe(struct platform_device *pdev)
{
return snd_soc_register_codec(&pdev->dev,
&soc_codec_dev_cq93vc, &cq93vc_dai, 1);
}
static int cq93vc_platform_remove(struct platform_device *pdev)
{
snd_soc_unregister_codec(&pdev->dev);
return 0;
}
static struct platform_driver cq93vc_codec_driver = {
.driver = {
.name = "cq93vc-codec",
.owner = THIS_MODULE,
},
.probe = cq93vc_platform_probe,
.remove = __devexit_p(cq93vc_platform_remove),
};
static int __init cq93vc_init(void)
{
return platform_driver_register(&cq93vc_codec_driver);
}
module_init(cq93vc_init);
static void __exit cq93vc_exit(void)
{
platform_driver_unregister(&cq93vc_codec_driver);
}
module_exit(cq93vc_exit);
MODULE_DESCRIPTION("Texas Instruments DaVinci ASoC CQ0093 Voice Codec Driver");
MODULE_AUTHOR("Miguel Aguilar");
MODULE_LICENSE("GPL");
| gpl-2.0 |
agrawa39/linaro-visualize-mem-pages | net/decnet/dn_nsp_out.c | 3964 | 17953 | /*
* DECnet An implementation of the DECnet protocol suite for the LINUX
* operating system. DECnet is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* DECnet Network Services Protocol (Output)
*
* Author: Eduardo Marcelo Serrat <emserrat@geocities.com>
*
* Changes:
*
* Steve Whitehouse: Split into dn_nsp_in.c and dn_nsp_out.c from
* original dn_nsp.c.
* Steve Whitehouse: Updated to work with my new routing architecture.
* Steve Whitehouse: Added changes from Eduardo Serrat's patches.
* Steve Whitehouse: Now conninits have the "return" bit set.
* Steve Whitehouse: Fixes to check alloc'd skbs are non NULL!
* Moved output state machine into one function
* Steve Whitehouse: New output state machine
* Paul Koning: Connect Confirm message fix.
* Eduardo Serrat: Fix to stop dn_nsp_do_disc() sending malformed packets.
* Steve Whitehouse: dn_nsp_output() and friends needed a spring clean
* Steve Whitehouse: Moved dn_nsp_send() in here from route.h
*/
/******************************************************************************
(c) 1995-1998 E.M. Serrat emserrat@geocities.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
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*******************************************************************************/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/inet.h>
#include <linux/route.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/termios.h>
#include <linux/interrupt.h>
#include <linux/proc_fs.h>
#include <linux/stat.h>
#include <linux/init.h>
#include <linux/poll.h>
#include <linux/if_packet.h>
#include <net/neighbour.h>
#include <net/dst.h>
#include <net/flow.h>
#include <net/dn.h>
#include <net/dn_nsp.h>
#include <net/dn_dev.h>
#include <net/dn_route.h>
static int nsp_backoff[NSP_MAXRXTSHIFT + 1] = { 1, 2, 4, 8, 16, 32, 64, 64, 64, 64, 64, 64, 64 };
static void dn_nsp_send(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
struct dn_scp *scp = DN_SK(sk);
struct dst_entry *dst;
struct flowidn fld;
skb_reset_transport_header(skb);
scp->stamp = jiffies;
dst = sk_dst_check(sk, 0);
if (dst) {
try_again:
skb_dst_set(skb, dst);
dst_output(skb);
return;
}
memset(&fld, 0, sizeof(fld));
fld.flowidn_oif = sk->sk_bound_dev_if;
fld.saddr = dn_saddr2dn(&scp->addr);
fld.daddr = dn_saddr2dn(&scp->peer);
dn_sk_ports_copy(&fld, scp);
fld.flowidn_proto = DNPROTO_NSP;
if (dn_route_output_sock(&sk->sk_dst_cache, &fld, sk, 0) == 0) {
dst = sk_dst_get(sk);
sk->sk_route_caps = dst->dev->features;
goto try_again;
}
sk->sk_err = EHOSTUNREACH;
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_state_change(sk);
}
/*
* If sk == NULL, then we assume that we are supposed to be making
* a routing layer skb. If sk != NULL, then we are supposed to be
* creating an skb for the NSP layer.
*
* The eventual aim is for each socket to have a cached header size
* for its outgoing packets, and to set hdr from this when sk != NULL.
*/
struct sk_buff *dn_alloc_skb(struct sock *sk, int size, gfp_t pri)
{
struct sk_buff *skb;
int hdr = 64;
if ((skb = alloc_skb(size + hdr, pri)) == NULL)
return NULL;
skb->protocol = htons(ETH_P_DNA_RT);
skb->pkt_type = PACKET_OUTGOING;
if (sk)
skb_set_owner_w(skb, sk);
skb_reserve(skb, hdr);
return skb;
}
/*
* Calculate persist timer based upon the smoothed round
* trip time and the variance. Backoff according to the
* nsp_backoff[] array.
*/
unsigned long dn_nsp_persist(struct sock *sk)
{
struct dn_scp *scp = DN_SK(sk);
unsigned long t = ((scp->nsp_srtt >> 2) + scp->nsp_rttvar) >> 1;
t *= nsp_backoff[scp->nsp_rxtshift];
if (t < HZ) t = HZ;
if (t > (600*HZ)) t = (600*HZ);
if (scp->nsp_rxtshift < NSP_MAXRXTSHIFT)
scp->nsp_rxtshift++;
/* printk(KERN_DEBUG "rxtshift %lu, t=%lu\n", scp->nsp_rxtshift, t); */
return t;
}
/*
* This is called each time we get an estimate for the rtt
* on the link.
*/
static void dn_nsp_rtt(struct sock *sk, long rtt)
{
struct dn_scp *scp = DN_SK(sk);
long srtt = (long)scp->nsp_srtt;
long rttvar = (long)scp->nsp_rttvar;
long delta;
/*
* If the jiffies clock flips over in the middle of timestamp
* gathering this value might turn out negative, so we make sure
* that is it always positive here.
*/
if (rtt < 0)
rtt = -rtt;
/*
* Add new rtt to smoothed average
*/
delta = ((rtt << 3) - srtt);
srtt += (delta >> 3);
if (srtt >= 1)
scp->nsp_srtt = (unsigned long)srtt;
else
scp->nsp_srtt = 1;
/*
* Add new rtt varience to smoothed varience
*/
delta >>= 1;
rttvar += ((((delta>0)?(delta):(-delta)) - rttvar) >> 2);
if (rttvar >= 1)
scp->nsp_rttvar = (unsigned long)rttvar;
else
scp->nsp_rttvar = 1;
/* printk(KERN_DEBUG "srtt=%lu rttvar=%lu\n", scp->nsp_srtt, scp->nsp_rttvar); */
}
/**
* dn_nsp_clone_and_send - Send a data packet by cloning it
* @skb: The packet to clone and transmit
* @gfp: memory allocation flag
*
* Clone a queued data or other data packet and transmit it.
*
* Returns: The number of times the packet has been sent previously
*/
static inline unsigned int dn_nsp_clone_and_send(struct sk_buff *skb,
gfp_t gfp)
{
struct dn_skb_cb *cb = DN_SKB_CB(skb);
struct sk_buff *skb2;
int ret = 0;
if ((skb2 = skb_clone(skb, gfp)) != NULL) {
ret = cb->xmit_count;
cb->xmit_count++;
cb->stamp = jiffies;
skb2->sk = skb->sk;
dn_nsp_send(skb2);
}
return ret;
}
/**
* dn_nsp_output - Try and send something from socket queues
* @sk: The socket whose queues are to be investigated
*
* Try and send the packet on the end of the data and other data queues.
* Other data gets priority over data, and if we retransmit a packet we
* reduce the window by dividing it in two.
*
*/
void dn_nsp_output(struct sock *sk)
{
struct dn_scp *scp = DN_SK(sk);
struct sk_buff *skb;
unsigned int reduce_win = 0;
/*
* First we check for otherdata/linkservice messages
*/
if ((skb = skb_peek(&scp->other_xmit_queue)) != NULL)
reduce_win = dn_nsp_clone_and_send(skb, GFP_ATOMIC);
/*
* If we may not send any data, we don't.
* If we are still trying to get some other data down the
* channel, we don't try and send any data.
*/
if (reduce_win || (scp->flowrem_sw != DN_SEND))
goto recalc_window;
if ((skb = skb_peek(&scp->data_xmit_queue)) != NULL)
reduce_win = dn_nsp_clone_and_send(skb, GFP_ATOMIC);
/*
* If we've sent any frame more than once, we cut the
* send window size in half. There is always a minimum
* window size of one available.
*/
recalc_window:
if (reduce_win) {
scp->snd_window >>= 1;
if (scp->snd_window < NSP_MIN_WINDOW)
scp->snd_window = NSP_MIN_WINDOW;
}
}
int dn_nsp_xmit_timeout(struct sock *sk)
{
struct dn_scp *scp = DN_SK(sk);
dn_nsp_output(sk);
if (!skb_queue_empty(&scp->data_xmit_queue) ||
!skb_queue_empty(&scp->other_xmit_queue))
scp->persist = dn_nsp_persist(sk);
return 0;
}
static inline __le16 *dn_mk_common_header(struct dn_scp *scp, struct sk_buff *skb, unsigned char msgflag, int len)
{
unsigned char *ptr = skb_push(skb, len);
BUG_ON(len < 5);
*ptr++ = msgflag;
*((__le16 *)ptr) = scp->addrrem;
ptr += 2;
*((__le16 *)ptr) = scp->addrloc;
ptr += 2;
return (__le16 __force *)ptr;
}
static __le16 *dn_mk_ack_header(struct sock *sk, struct sk_buff *skb, unsigned char msgflag, int hlen, int other)
{
struct dn_scp *scp = DN_SK(sk);
unsigned short acknum = scp->numdat_rcv & 0x0FFF;
unsigned short ackcrs = scp->numoth_rcv & 0x0FFF;
__le16 *ptr;
BUG_ON(hlen < 9);
scp->ackxmt_dat = acknum;
scp->ackxmt_oth = ackcrs;
acknum |= 0x8000;
ackcrs |= 0x8000;
/* If this is an "other data/ack" message, swap acknum and ackcrs */
if (other) {
unsigned short tmp = acknum;
acknum = ackcrs;
ackcrs = tmp;
}
/* Set "cross subchannel" bit in ackcrs */
ackcrs |= 0x2000;
ptr = dn_mk_common_header(scp, skb, msgflag, hlen);
*ptr++ = cpu_to_le16(acknum);
*ptr++ = cpu_to_le16(ackcrs);
return ptr;
}
static __le16 *dn_nsp_mk_data_header(struct sock *sk, struct sk_buff *skb, int oth)
{
struct dn_scp *scp = DN_SK(sk);
struct dn_skb_cb *cb = DN_SKB_CB(skb);
__le16 *ptr = dn_mk_ack_header(sk, skb, cb->nsp_flags, 11, oth);
if (unlikely(oth)) {
cb->segnum = scp->numoth;
seq_add(&scp->numoth, 1);
} else {
cb->segnum = scp->numdat;
seq_add(&scp->numdat, 1);
}
*(ptr++) = cpu_to_le16(cb->segnum);
return ptr;
}
void dn_nsp_queue_xmit(struct sock *sk, struct sk_buff *skb,
gfp_t gfp, int oth)
{
struct dn_scp *scp = DN_SK(sk);
struct dn_skb_cb *cb = DN_SKB_CB(skb);
unsigned long t = ((scp->nsp_srtt >> 2) + scp->nsp_rttvar) >> 1;
cb->xmit_count = 0;
dn_nsp_mk_data_header(sk, skb, oth);
/*
* Slow start: If we have been idle for more than
* one RTT, then reset window to min size.
*/
if ((jiffies - scp->stamp) > t)
scp->snd_window = NSP_MIN_WINDOW;
if (oth)
skb_queue_tail(&scp->other_xmit_queue, skb);
else
skb_queue_tail(&scp->data_xmit_queue, skb);
if (scp->flowrem_sw != DN_SEND)
return;
dn_nsp_clone_and_send(skb, gfp);
}
int dn_nsp_check_xmit_queue(struct sock *sk, struct sk_buff *skb, struct sk_buff_head *q, unsigned short acknum)
{
struct dn_skb_cb *cb = DN_SKB_CB(skb);
struct dn_scp *scp = DN_SK(sk);
struct sk_buff *skb2, *n, *ack = NULL;
int wakeup = 0;
int try_retrans = 0;
unsigned long reftime = cb->stamp;
unsigned long pkttime;
unsigned short xmit_count;
unsigned short segnum;
skb_queue_walk_safe(q, skb2, n) {
struct dn_skb_cb *cb2 = DN_SKB_CB(skb2);
if (dn_before_or_equal(cb2->segnum, acknum))
ack = skb2;
/* printk(KERN_DEBUG "ack: %s %04x %04x\n", ack ? "ACK" : "SKIP", (int)cb2->segnum, (int)acknum); */
if (ack == NULL)
continue;
/* printk(KERN_DEBUG "check_xmit_queue: %04x, %d\n", acknum, cb2->xmit_count); */
/* Does _last_ packet acked have xmit_count > 1 */
try_retrans = 0;
/* Remember to wake up the sending process */
wakeup = 1;
/* Keep various statistics */
pkttime = cb2->stamp;
xmit_count = cb2->xmit_count;
segnum = cb2->segnum;
/* Remove and drop ack'ed packet */
skb_unlink(ack, q);
kfree_skb(ack);
ack = NULL;
/*
* We don't expect to see acknowledgements for packets we
* haven't sent yet.
*/
WARN_ON(xmit_count == 0);
/*
* If the packet has only been sent once, we can use it
* to calculate the RTT and also open the window a little
* further.
*/
if (xmit_count == 1) {
if (dn_equal(segnum, acknum))
dn_nsp_rtt(sk, (long)(pkttime - reftime));
if (scp->snd_window < scp->max_window)
scp->snd_window++;
}
/*
* Packet has been sent more than once. If this is the last
* packet to be acknowledged then we want to send the next
* packet in the send queue again (assumes the remote host does
* go-back-N error control).
*/
if (xmit_count > 1)
try_retrans = 1;
}
if (try_retrans)
dn_nsp_output(sk);
return wakeup;
}
void dn_nsp_send_data_ack(struct sock *sk)
{
struct sk_buff *skb = NULL;
if ((skb = dn_alloc_skb(sk, 9, GFP_ATOMIC)) == NULL)
return;
skb_reserve(skb, 9);
dn_mk_ack_header(sk, skb, 0x04, 9, 0);
dn_nsp_send(skb);
}
void dn_nsp_send_oth_ack(struct sock *sk)
{
struct sk_buff *skb = NULL;
if ((skb = dn_alloc_skb(sk, 9, GFP_ATOMIC)) == NULL)
return;
skb_reserve(skb, 9);
dn_mk_ack_header(sk, skb, 0x14, 9, 1);
dn_nsp_send(skb);
}
void dn_send_conn_ack (struct sock *sk)
{
struct dn_scp *scp = DN_SK(sk);
struct sk_buff *skb = NULL;
struct nsp_conn_ack_msg *msg;
if ((skb = dn_alloc_skb(sk, 3, sk->sk_allocation)) == NULL)
return;
msg = (struct nsp_conn_ack_msg *)skb_put(skb, 3);
msg->msgflg = 0x24;
msg->dstaddr = scp->addrrem;
dn_nsp_send(skb);
}
void dn_nsp_delayed_ack(struct sock *sk)
{
struct dn_scp *scp = DN_SK(sk);
if (scp->ackxmt_oth != scp->numoth_rcv)
dn_nsp_send_oth_ack(sk);
if (scp->ackxmt_dat != scp->numdat_rcv)
dn_nsp_send_data_ack(sk);
}
static int dn_nsp_retrans_conn_conf(struct sock *sk)
{
struct dn_scp *scp = DN_SK(sk);
if (scp->state == DN_CC)
dn_send_conn_conf(sk, GFP_ATOMIC);
return 0;
}
void dn_send_conn_conf(struct sock *sk, gfp_t gfp)
{
struct dn_scp *scp = DN_SK(sk);
struct sk_buff *skb = NULL;
struct nsp_conn_init_msg *msg;
__u8 len = (__u8)le16_to_cpu(scp->conndata_out.opt_optl);
if ((skb = dn_alloc_skb(sk, 50 + len, gfp)) == NULL)
return;
msg = (struct nsp_conn_init_msg *)skb_put(skb, sizeof(*msg));
msg->msgflg = 0x28;
msg->dstaddr = scp->addrrem;
msg->srcaddr = scp->addrloc;
msg->services = scp->services_loc;
msg->info = scp->info_loc;
msg->segsize = cpu_to_le16(scp->segsize_loc);
*skb_put(skb,1) = len;
if (len > 0)
memcpy(skb_put(skb, len), scp->conndata_out.opt_data, len);
dn_nsp_send(skb);
scp->persist = dn_nsp_persist(sk);
scp->persist_fxn = dn_nsp_retrans_conn_conf;
}
static __inline__ void dn_nsp_do_disc(struct sock *sk, unsigned char msgflg,
unsigned short reason, gfp_t gfp,
struct dst_entry *dst,
int ddl, unsigned char *dd, __le16 rem, __le16 loc)
{
struct sk_buff *skb = NULL;
int size = 7 + ddl + ((msgflg == NSP_DISCINIT) ? 1 : 0);
unsigned char *msg;
if ((dst == NULL) || (rem == 0)) {
net_dbg_ratelimited("DECnet: dn_nsp_do_disc: BUG! Please report this to SteveW@ACM.org rem=%u dst=%p\n",
le16_to_cpu(rem), dst);
return;
}
if ((skb = dn_alloc_skb(sk, size, gfp)) == NULL)
return;
msg = skb_put(skb, size);
*msg++ = msgflg;
*(__le16 *)msg = rem;
msg += 2;
*(__le16 *)msg = loc;
msg += 2;
*(__le16 *)msg = cpu_to_le16(reason);
msg += 2;
if (msgflg == NSP_DISCINIT)
*msg++ = ddl;
if (ddl) {
memcpy(msg, dd, ddl);
}
/*
* This doesn't go via the dn_nsp_send() function since we need
* to be able to send disc packets out which have no socket
* associations.
*/
skb_dst_set(skb, dst_clone(dst));
dst_output(skb);
}
void dn_nsp_send_disc(struct sock *sk, unsigned char msgflg,
unsigned short reason, gfp_t gfp)
{
struct dn_scp *scp = DN_SK(sk);
int ddl = 0;
if (msgflg == NSP_DISCINIT)
ddl = le16_to_cpu(scp->discdata_out.opt_optl);
if (reason == 0)
reason = le16_to_cpu(scp->discdata_out.opt_status);
dn_nsp_do_disc(sk, msgflg, reason, gfp, __sk_dst_get(sk), ddl,
scp->discdata_out.opt_data, scp->addrrem, scp->addrloc);
}
void dn_nsp_return_disc(struct sk_buff *skb, unsigned char msgflg,
unsigned short reason)
{
struct dn_skb_cb *cb = DN_SKB_CB(skb);
int ddl = 0;
gfp_t gfp = GFP_ATOMIC;
dn_nsp_do_disc(NULL, msgflg, reason, gfp, skb_dst(skb), ddl,
NULL, cb->src_port, cb->dst_port);
}
void dn_nsp_send_link(struct sock *sk, unsigned char lsflags, char fcval)
{
struct dn_scp *scp = DN_SK(sk);
struct sk_buff *skb;
unsigned char *ptr;
gfp_t gfp = GFP_ATOMIC;
if ((skb = dn_alloc_skb(sk, DN_MAX_NSP_DATA_HEADER + 2, gfp)) == NULL)
return;
skb_reserve(skb, DN_MAX_NSP_DATA_HEADER);
ptr = skb_put(skb, 2);
DN_SKB_CB(skb)->nsp_flags = 0x10;
*ptr++ = lsflags;
*ptr = fcval;
dn_nsp_queue_xmit(sk, skb, gfp, 1);
scp->persist = dn_nsp_persist(sk);
scp->persist_fxn = dn_nsp_xmit_timeout;
}
static int dn_nsp_retrans_conninit(struct sock *sk)
{
struct dn_scp *scp = DN_SK(sk);
if (scp->state == DN_CI)
dn_nsp_send_conninit(sk, NSP_RCI);
return 0;
}
void dn_nsp_send_conninit(struct sock *sk, unsigned char msgflg)
{
struct dn_scp *scp = DN_SK(sk);
struct nsp_conn_init_msg *msg;
unsigned char aux;
unsigned char menuver;
struct dn_skb_cb *cb;
unsigned char type = 1;
gfp_t allocation = (msgflg == NSP_CI) ? sk->sk_allocation : GFP_ATOMIC;
struct sk_buff *skb = dn_alloc_skb(sk, 200, allocation);
if (!skb)
return;
cb = DN_SKB_CB(skb);
msg = (struct nsp_conn_init_msg *)skb_put(skb,sizeof(*msg));
msg->msgflg = msgflg;
msg->dstaddr = 0x0000; /* Remote Node will assign it*/
msg->srcaddr = scp->addrloc;
msg->services = scp->services_loc; /* Requested flow control */
msg->info = scp->info_loc; /* Version Number */
msg->segsize = cpu_to_le16(scp->segsize_loc); /* Max segment size */
if (scp->peer.sdn_objnum)
type = 0;
skb_put(skb, dn_sockaddr2username(&scp->peer,
skb_tail_pointer(skb), type));
skb_put(skb, dn_sockaddr2username(&scp->addr,
skb_tail_pointer(skb), 2));
menuver = DN_MENUVER_ACC | DN_MENUVER_USR;
if (scp->peer.sdn_flags & SDF_PROXY)
menuver |= DN_MENUVER_PRX;
if (scp->peer.sdn_flags & SDF_UICPROXY)
menuver |= DN_MENUVER_UIC;
*skb_put(skb, 1) = menuver; /* Menu Version */
aux = scp->accessdata.acc_userl;
*skb_put(skb, 1) = aux;
if (aux > 0)
memcpy(skb_put(skb, aux), scp->accessdata.acc_user, aux);
aux = scp->accessdata.acc_passl;
*skb_put(skb, 1) = aux;
if (aux > 0)
memcpy(skb_put(skb, aux), scp->accessdata.acc_pass, aux);
aux = scp->accessdata.acc_accl;
*skb_put(skb, 1) = aux;
if (aux > 0)
memcpy(skb_put(skb, aux), scp->accessdata.acc_acc, aux);
aux = (__u8)le16_to_cpu(scp->conndata_out.opt_optl);
*skb_put(skb, 1) = aux;
if (aux > 0)
memcpy(skb_put(skb, aux), scp->conndata_out.opt_data, aux);
scp->persist = dn_nsp_persist(sk);
scp->persist_fxn = dn_nsp_retrans_conninit;
cb->rt_flags = DN_RT_F_RQR;
dn_nsp_send(skb);
}
| gpl-2.0 |
SerenityS/android_kernel_pantech_msm8974 | arch/frv/mm/highmem.c | 4476 | 2025 | /* highmem.c: arch-specific highmem stuff
*
* Copyright (C) 2004 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.
*/
#include <linux/highmem.h>
#include <linux/module.h>
void *kmap(struct page *page)
{
might_sleep();
if (!PageHighMem(page))
return page_address(page);
return kmap_high(page);
}
EXPORT_SYMBOL(kmap);
void kunmap(struct page *page)
{
if (in_interrupt())
BUG();
if (!PageHighMem(page))
return;
kunmap_high(page);
}
EXPORT_SYMBOL(kunmap);
struct page *kmap_atomic_to_page(void *ptr)
{
return virt_to_page(ptr);
}
void *kmap_atomic(struct page *page)
{
unsigned long paddr;
int type;
pagefault_disable();
type = kmap_atomic_idx_push();
paddr = page_to_phys(page);
switch (type) {
/*
* The first 4 primary maps are reserved for architecture code
*/
case 0: return __kmap_atomic_primary(4, paddr, 6);
case 1: return __kmap_atomic_primary(5, paddr, 7);
case 2: return __kmap_atomic_primary(6, paddr, 8);
case 3: return __kmap_atomic_primary(7, paddr, 9);
case 4: return __kmap_atomic_primary(8, paddr, 10);
case 5 ... 5 + NR_TLB_LINES - 1:
return __kmap_atomic_secondary(type - 5, paddr);
default:
BUG();
return NULL;
}
}
EXPORT_SYMBOL(kmap_atomic);
void __kunmap_atomic(void *kvaddr)
{
int type = kmap_atomic_idx();
switch (type) {
case 0: __kunmap_atomic_primary(4, 6); break;
case 1: __kunmap_atomic_primary(5, 7); break;
case 2: __kunmap_atomic_primary(6, 8); break;
case 3: __kunmap_atomic_primary(7, 9); break;
case 4: __kunmap_atomic_primary(8, 10); break;
case 5 ... 5 + NR_TLB_LINES - 1:
__kunmap_atomic_secondary(type - 5, kvaddr);
break;
default:
BUG();
}
kmap_atomic_idx_pop();
pagefault_enable();
}
EXPORT_SYMBOL(__kunmap_atomic);
| gpl-2.0 |
Tegra4/android_kernel_hp_phobos | arch/arm/mach-ixp23xx/espresso.c | 4732 | 2109 | /*
* arch/arm/mach-ixp23xx/espresso.c
*
* Double Espresso-specific routines
*
* Author: Lennert Buytenhek <buytenh@wantstofly.org>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/serial.h>
#include <linux/tty.h>
#include <linux/bitops.h>
#include <linux/ioport.h>
#include <linux/serial_8250.h>
#include <linux/serial_core.h>
#include <linux/device.h>
#include <linux/mm.h>
#include <linux/pci.h>
#include <linux/mtd/physmap.h>
#include <asm/types.h>
#include <asm/setup.h>
#include <asm/memory.h>
#include <mach/hardware.h>
#include <asm/mach-types.h>
#include <asm/irq.h>
#include <asm/tlbflush.h>
#include <asm/pgtable.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <asm/mach/arch.h>
#include <asm/mach/pci.h>
static int __init espresso_pci_init(void)
{
if (machine_is_espresso())
ixp23xx_pci_slave_init();
return 0;
};
subsys_initcall(espresso_pci_init);
static struct physmap_flash_data espresso_flash_data = {
.width = 2,
};
static struct resource espresso_flash_resource = {
.start = 0x90000000,
.end = 0x91ffffff,
.flags = IORESOURCE_MEM,
};
static struct platform_device espresso_flash = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &espresso_flash_data,
},
.num_resources = 1,
.resource = &espresso_flash_resource,
};
static void __init espresso_init(void)
{
platform_device_register(&espresso_flash);
/*
* Mark flash as writeable.
*/
IXP23XX_EXP_CS0[0] |= IXP23XX_FLASH_WRITABLE;
IXP23XX_EXP_CS0[1] |= IXP23XX_FLASH_WRITABLE;
ixp23xx_sys_init();
}
MACHINE_START(ESPRESSO, "IP Fabrics Double Espresso")
/* Maintainer: Lennert Buytenhek */
.map_io = ixp23xx_map_io,
.init_irq = ixp23xx_init_irq,
.timer = &ixp23xx_timer,
.atag_offset = 0x100,
.init_machine = espresso_init,
.restart = ixp23xx_restart,
MACHINE_END
| gpl-2.0 |
Sudokamikaze/XKernel-taoshan | arch/arm/mach-imx/mach-mx51_efikamx.c | 4732 | 7498 | /*
* Copyright (C) 2010 Linaro Limited
*
* based on code from the following
* Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved.
* Copyright 2009-2010 Pegatron Corporation. All Rights Reserved.
* Copyright 2009-2010 Genesi USA, Inc. All Rights Reserved.
*
* 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/platform_device.h>
#include <linux/i2c.h>
#include <linux/gpio.h>
#include <linux/leds.h>
#include <linux/input.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/spi/flash.h>
#include <linux/spi/spi.h>
#include <linux/mfd/mc13892.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/consumer.h>
#include <mach/common.h>
#include <mach/hardware.h>
#include <mach/iomux-mx51.h>
#include <asm/setup.h>
#include <asm/system_info.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include "devices-imx51.h"
#include "efika.h"
#define EFIKAMX_PCBID0 IMX_GPIO_NR(3, 16)
#define EFIKAMX_PCBID1 IMX_GPIO_NR(3, 17)
#define EFIKAMX_PCBID2 IMX_GPIO_NR(3, 11)
#define EFIKAMX_BLUE_LED IMX_GPIO_NR(3, 13)
#define EFIKAMX_GREEN_LED IMX_GPIO_NR(3, 14)
#define EFIKAMX_RED_LED IMX_GPIO_NR(3, 15)
#define EFIKAMX_POWER_KEY IMX_GPIO_NR(2, 31)
/* board 1.1 doesn't have same reset gpio */
#define EFIKAMX_RESET1_1 IMX_GPIO_NR(3, 2)
#define EFIKAMX_RESET IMX_GPIO_NR(1, 4)
#define EFIKAMX_POWEROFF IMX_GPIO_NR(4, 13)
#define EFIKAMX_PMIC IMX_GPIO_NR(1, 6)
/* the pci ids pin have pull up. they're driven low according to board id */
#define MX51_PAD_PCBID0 IOMUX_PAD(0x518, 0x130, 3, 0x0, 0, PAD_CTL_PUS_100K_UP)
#define MX51_PAD_PCBID1 IOMUX_PAD(0x51C, 0x134, 3, 0x0, 0, PAD_CTL_PUS_100K_UP)
#define MX51_PAD_PCBID2 IOMUX_PAD(0x504, 0x128, 3, 0x0, 0, PAD_CTL_PUS_100K_UP)
#define MX51_PAD_PWRKEY IOMUX_PAD(0x48c, 0x0f8, 1, 0x0, 0, PAD_CTL_PUS_100K_UP | PAD_CTL_PKE)
static iomux_v3_cfg_t mx51efikamx_pads[] = {
/* board id */
MX51_PAD_PCBID0,
MX51_PAD_PCBID1,
MX51_PAD_PCBID2,
/* leds */
MX51_PAD_CSI1_D9__GPIO3_13,
MX51_PAD_CSI1_VSYNC__GPIO3_14,
MX51_PAD_CSI1_HSYNC__GPIO3_15,
/* power key */
MX51_PAD_PWRKEY,
/* reset */
MX51_PAD_DI1_PIN13__GPIO3_2,
MX51_PAD_GPIO1_4__GPIO1_4,
/* power off */
MX51_PAD_CSI2_VSYNC__GPIO4_13,
};
/* PCBID2 PCBID1 PCBID0 STATE
1 1 1 ER1:rev1.1
1 1 0 ER2:rev1.2
1 0 1 ER3:rev1.3
1 0 0 ER4:rev1.4
*/
static void __init mx51_efikamx_board_id(void)
{
int id;
/* things are taking time to settle */
msleep(150);
gpio_request(EFIKAMX_PCBID0, "pcbid0");
gpio_direction_input(EFIKAMX_PCBID0);
gpio_request(EFIKAMX_PCBID1, "pcbid1");
gpio_direction_input(EFIKAMX_PCBID1);
gpio_request(EFIKAMX_PCBID2, "pcbid2");
gpio_direction_input(EFIKAMX_PCBID2);
id = gpio_get_value(EFIKAMX_PCBID0) ? 1 : 0;
id |= (gpio_get_value(EFIKAMX_PCBID1) ? 1 : 0) << 1;
id |= (gpio_get_value(EFIKAMX_PCBID2) ? 1 : 0) << 2;
switch (id) {
case 7:
system_rev = 0x11;
break;
case 6:
system_rev = 0x12;
break;
case 5:
system_rev = 0x13;
break;
case 4:
system_rev = 0x14;
break;
default:
system_rev = 0x10;
break;
}
if ((system_rev == 0x10)
|| (system_rev == 0x12)
|| (system_rev == 0x14)) {
printk(KERN_WARNING
"EfikaMX: Unsupported board revision 1.%u!\n",
system_rev & 0xf);
}
}
static struct gpio_led mx51_efikamx_leds[] __initdata = {
{
.name = "efikamx:green",
.default_trigger = "default-on",
.gpio = EFIKAMX_GREEN_LED,
},
{
.name = "efikamx:red",
.default_trigger = "ide-disk",
.gpio = EFIKAMX_RED_LED,
},
{
.name = "efikamx:blue",
.default_trigger = "mmc0",
.gpio = EFIKAMX_BLUE_LED,
},
};
static const struct gpio_led_platform_data
mx51_efikamx_leds_data __initconst = {
.leds = mx51_efikamx_leds,
.num_leds = ARRAY_SIZE(mx51_efikamx_leds),
};
static struct esdhc_platform_data sd_pdata = {
.cd_type = ESDHC_CD_CONTROLLER,
.wp_type = ESDHC_WP_CONTROLLER,
};
static struct gpio_keys_button mx51_efikamx_powerkey[] = {
{
.code = KEY_POWER,
.gpio = EFIKAMX_POWER_KEY,
.type = EV_PWR,
.desc = "Power Button (CM)",
.wakeup = 1,
.debounce_interval = 10, /* ms */
},
};
static const struct gpio_keys_platform_data mx51_efikamx_powerkey_data __initconst = {
.buttons = mx51_efikamx_powerkey,
.nbuttons = ARRAY_SIZE(mx51_efikamx_powerkey),
};
static void mx51_efikamx_restart(char mode, const char *cmd)
{
if (system_rev == 0x11)
gpio_direction_output(EFIKAMX_RESET1_1, 0);
else
gpio_direction_output(EFIKAMX_RESET, 0);
}
static struct regulator *pwgt1, *pwgt2, *coincell;
static void mx51_efikamx_power_off(void)
{
if (!IS_ERR(coincell))
regulator_disable(coincell);
if (!IS_ERR(pwgt1) && !IS_ERR(pwgt2)) {
regulator_disable(pwgt2);
regulator_disable(pwgt1);
}
gpio_direction_output(EFIKAMX_POWEROFF, 1);
}
static int __init mx51_efikamx_power_init(void)
{
if (machine_is_mx51_efikamx()) {
pwgt1 = regulator_get(NULL, "pwgt1");
pwgt2 = regulator_get(NULL, "pwgt2");
if (!IS_ERR(pwgt1) && !IS_ERR(pwgt2)) {
regulator_enable(pwgt1);
regulator_enable(pwgt2);
}
gpio_request(EFIKAMX_POWEROFF, "poweroff");
pm_power_off = mx51_efikamx_power_off;
/* enable coincell charger. maybe need a small power driver ? */
coincell = regulator_get(NULL, "coincell");
if (!IS_ERR(coincell)) {
regulator_set_voltage(coincell, 3000000, 3000000);
regulator_enable(coincell);
}
regulator_has_full_constraints();
}
return 0;
}
late_initcall(mx51_efikamx_power_init);
static void __init mx51_efikamx_init(void)
{
imx51_soc_init();
mxc_iomux_v3_setup_multiple_pads(mx51efikamx_pads,
ARRAY_SIZE(mx51efikamx_pads));
efika_board_common_init();
mx51_efikamx_board_id();
/* on < 1.2 boards both SD controllers are used */
if (system_rev < 0x12) {
imx51_add_sdhci_esdhc_imx(0, NULL);
imx51_add_sdhci_esdhc_imx(1, &sd_pdata);
mx51_efikamx_leds[2].default_trigger = "mmc1";
} else
imx51_add_sdhci_esdhc_imx(0, &sd_pdata);
gpio_led_register_device(-1, &mx51_efikamx_leds_data);
imx_add_gpio_keys(&mx51_efikamx_powerkey_data);
if (system_rev == 0x11) {
gpio_request(EFIKAMX_RESET1_1, "reset");
gpio_direction_output(EFIKAMX_RESET1_1, 1);
} else {
gpio_request(EFIKAMX_RESET, "reset");
gpio_direction_output(EFIKAMX_RESET, 1);
}
/*
* enable wifi by default only on mx
* sb and mx have same wlan pin but the value to enable it are
* different :/
*/
gpio_request(EFIKA_WLAN_EN, "wlan_en");
gpio_direction_output(EFIKA_WLAN_EN, 0);
msleep(10);
gpio_request(EFIKA_WLAN_RESET, "wlan_rst");
gpio_direction_output(EFIKA_WLAN_RESET, 0);
msleep(10);
gpio_set_value(EFIKA_WLAN_RESET, 1);
}
static void __init mx51_efikamx_timer_init(void)
{
mx51_clocks_init(32768, 24000000, 22579200, 24576000);
}
static struct sys_timer mx51_efikamx_timer = {
.init = mx51_efikamx_timer_init,
};
MACHINE_START(MX51_EFIKAMX, "Genesi EfikaMX nettop")
/* Maintainer: Amit Kucheria <amit.kucheria@linaro.org> */
.atag_offset = 0x100,
.map_io = mx51_map_io,
.init_early = imx51_init_early,
.init_irq = mx51_init_irq,
.handle_irq = imx51_handle_irq,
.timer = &mx51_efikamx_timer,
.init_machine = mx51_efikamx_init,
.restart = mx51_efikamx_restart,
MACHINE_END
| gpl-2.0 |
motog2014devteam/android_kernel_motorola_titan-OLD | drivers/isdn/hisax/mic.c | 4988 | 5826 | /* $Id: mic.c,v 1.12.2.4 2004/01/13 23:48:39 keil Exp $
*
* low level stuff for mic cards
*
* Author Stephan von Krawczynski
* Copyright by Stephan von Krawczynski <skraw@ithnet.com>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#include <linux/init.h>
#include "hisax.h"
#include "isac.h"
#include "hscx.h"
#include "isdnl1.h"
static const char *mic_revision = "$Revision: 1.12.2.4 $";
#define byteout(addr, val) outb(val, addr)
#define bytein(addr) inb(addr)
#define MIC_ISAC 2
#define MIC_HSCX 1
#define MIC_ADR 7
/* CARD_ADR (Write) */
#define MIC_RESET 0x3 /* same as DOS driver */
static inline u_char
readreg(unsigned int ale, unsigned int adr, u_char off)
{
register u_char ret;
byteout(ale, off);
ret = bytein(adr);
return (ret);
}
static inline void
readfifo(unsigned int ale, unsigned int adr, u_char off, u_char *data, int size)
{
byteout(ale, off);
insb(adr, data, size);
}
static inline void
writereg(unsigned int ale, unsigned int adr, u_char off, u_char data)
{
byteout(ale, off);
byteout(adr, data);
}
static inline void
writefifo(unsigned int ale, unsigned int adr, u_char off, u_char *data, int size)
{
byteout(ale, off);
outsb(adr, data, size);
}
/* Interface functions */
static u_char
ReadISAC(struct IsdnCardState *cs, u_char offset)
{
return (readreg(cs->hw.mic.adr, cs->hw.mic.isac, offset));
}
static void
WriteISAC(struct IsdnCardState *cs, u_char offset, u_char value)
{
writereg(cs->hw.mic.adr, cs->hw.mic.isac, offset, value);
}
static void
ReadISACfifo(struct IsdnCardState *cs, u_char *data, int size)
{
readfifo(cs->hw.mic.adr, cs->hw.mic.isac, 0, data, size);
}
static void
WriteISACfifo(struct IsdnCardState *cs, u_char *data, int size)
{
writefifo(cs->hw.mic.adr, cs->hw.mic.isac, 0, data, size);
}
static u_char
ReadHSCX(struct IsdnCardState *cs, int hscx, u_char offset)
{
return (readreg(cs->hw.mic.adr,
cs->hw.mic.hscx, offset + (hscx ? 0x40 : 0)));
}
static void
WriteHSCX(struct IsdnCardState *cs, int hscx, u_char offset, u_char value)
{
writereg(cs->hw.mic.adr,
cs->hw.mic.hscx, offset + (hscx ? 0x40 : 0), value);
}
/*
* fast interrupt HSCX stuff goes here
*/
#define READHSCX(cs, nr, reg) readreg(cs->hw.mic.adr, \
cs->hw.mic.hscx, reg + (nr ? 0x40 : 0))
#define WRITEHSCX(cs, nr, reg, data) writereg(cs->hw.mic.adr, \
cs->hw.mic.hscx, reg + (nr ? 0x40 : 0), data)
#define READHSCXFIFO(cs, nr, ptr, cnt) readfifo(cs->hw.mic.adr, \
cs->hw.mic.hscx, (nr ? 0x40 : 0), ptr, cnt)
#define WRITEHSCXFIFO(cs, nr, ptr, cnt) writefifo(cs->hw.mic.adr, \
cs->hw.mic.hscx, (nr ? 0x40 : 0), ptr, cnt)
#include "hscx_irq.c"
static irqreturn_t
mic_interrupt(int intno, void *dev_id)
{
struct IsdnCardState *cs = dev_id;
u_char val;
u_long flags;
spin_lock_irqsave(&cs->lock, flags);
val = readreg(cs->hw.mic.adr, cs->hw.mic.hscx, HSCX_ISTA + 0x40);
Start_HSCX:
if (val)
hscx_int_main(cs, val);
val = readreg(cs->hw.mic.adr, cs->hw.mic.isac, ISAC_ISTA);
Start_ISAC:
if (val)
isac_interrupt(cs, val);
val = readreg(cs->hw.mic.adr, cs->hw.mic.hscx, HSCX_ISTA + 0x40);
if (val) {
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "HSCX IntStat after IntRoutine");
goto Start_HSCX;
}
val = readreg(cs->hw.mic.adr, cs->hw.mic.isac, ISAC_ISTA);
if (val) {
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "ISAC IntStat after IntRoutine");
goto Start_ISAC;
}
writereg(cs->hw.mic.adr, cs->hw.mic.hscx, HSCX_MASK, 0xFF);
writereg(cs->hw.mic.adr, cs->hw.mic.hscx, HSCX_MASK + 0x40, 0xFF);
writereg(cs->hw.mic.adr, cs->hw.mic.isac, ISAC_MASK, 0xFF);
writereg(cs->hw.mic.adr, cs->hw.mic.isac, ISAC_MASK, 0x0);
writereg(cs->hw.mic.adr, cs->hw.mic.hscx, HSCX_MASK, 0x0);
writereg(cs->hw.mic.adr, cs->hw.mic.hscx, HSCX_MASK + 0x40, 0x0);
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_HANDLED;
}
static void
release_io_mic(struct IsdnCardState *cs)
{
int bytecnt = 8;
if (cs->hw.mic.cfg_reg)
release_region(cs->hw.mic.cfg_reg, bytecnt);
}
static int
mic_card_msg(struct IsdnCardState *cs, int mt, void *arg)
{
u_long flags;
switch (mt) {
case CARD_RESET:
return (0);
case CARD_RELEASE:
release_io_mic(cs);
return (0);
case CARD_INIT:
spin_lock_irqsave(&cs->lock, flags);
inithscx(cs); /* /RTSA := ISAC RST */
inithscxisac(cs, 3);
spin_unlock_irqrestore(&cs->lock, flags);
return (0);
case CARD_TEST:
return (0);
}
return (0);
}
int __devinit
setup_mic(struct IsdnCard *card)
{
int bytecnt;
struct IsdnCardState *cs = card->cs;
char tmp[64];
strcpy(tmp, mic_revision);
printk(KERN_INFO "HiSax: mic driver Rev. %s\n", HiSax_getrev(tmp));
if (cs->typ != ISDN_CTYPE_MIC)
return (0);
bytecnt = 8;
cs->hw.mic.cfg_reg = card->para[1];
cs->irq = card->para[0];
cs->hw.mic.adr = cs->hw.mic.cfg_reg + MIC_ADR;
cs->hw.mic.isac = cs->hw.mic.cfg_reg + MIC_ISAC;
cs->hw.mic.hscx = cs->hw.mic.cfg_reg + MIC_HSCX;
if (!request_region(cs->hw.mic.cfg_reg, bytecnt, "mic isdn")) {
printk(KERN_WARNING
"HiSax: ith mic config port %x-%x already in use\n",
cs->hw.mic.cfg_reg,
cs->hw.mic.cfg_reg + bytecnt);
return (0);
}
printk(KERN_INFO "mic: defined at 0x%x IRQ %d\n",
cs->hw.mic.cfg_reg, cs->irq);
setup_isac(cs);
cs->readisac = &ReadISAC;
cs->writeisac = &WriteISAC;
cs->readisacfifo = &ReadISACfifo;
cs->writeisacfifo = &WriteISACfifo;
cs->BC_Read_Reg = &ReadHSCX;
cs->BC_Write_Reg = &WriteHSCX;
cs->BC_Send_Data = &hscx_fill_fifo;
cs->cardmsg = &mic_card_msg;
cs->irq_func = &mic_interrupt;
ISACVersion(cs, "mic:");
if (HscxVersion(cs, "mic:")) {
printk(KERN_WARNING
"mic: wrong HSCX versions check IO address\n");
release_io_mic(cs);
return (0);
}
return (1);
}
| gpl-2.0 |
samno1607/Xperia-Z-Source-Differences-JB | drivers/rtc/rtc-pcf8583.c | 4988 | 7009 | /*
* drivers/rtc/rtc-pcf8583.c
*
* Copyright (C) 2000 Russell King
* Copyright (C) 2008 Wolfram Sang & Juergen Beisert, Pengutronix
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Driver for PCF8583 RTC & RAM chip
*
* Converted to the generic RTC susbsystem by G. Liakhovetski (2006)
*/
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/rtc.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/bcd.h>
struct rtc_mem {
unsigned int loc;
unsigned int nr;
unsigned char *data;
};
struct pcf8583 {
struct rtc_device *rtc;
unsigned char ctrl;
};
#define CTRL_STOP 0x80
#define CTRL_HOLD 0x40
#define CTRL_32KHZ 0x00
#define CTRL_MASK 0x08
#define CTRL_ALARMEN 0x04
#define CTRL_ALARM 0x02
#define CTRL_TIMER 0x01
static struct i2c_driver pcf8583_driver;
#define get_ctrl(x) ((struct pcf8583 *)i2c_get_clientdata(x))->ctrl
#define set_ctrl(x, v) get_ctrl(x) = v
#define CMOS_YEAR (64 + 128)
#define CMOS_CHECKSUM (63)
static int pcf8583_get_datetime(struct i2c_client *client, struct rtc_time *dt)
{
unsigned char buf[8], addr[1] = { 1 };
struct i2c_msg msgs[2] = {
{
.addr = client->addr,
.flags = 0,
.len = 1,
.buf = addr,
}, {
.addr = client->addr,
.flags = I2C_M_RD,
.len = 6,
.buf = buf,
}
};
int ret;
memset(buf, 0, sizeof(buf));
ret = i2c_transfer(client->adapter, msgs, 2);
if (ret == 2) {
dt->tm_year = buf[4] >> 6;
dt->tm_wday = buf[5] >> 5;
buf[4] &= 0x3f;
buf[5] &= 0x1f;
dt->tm_sec = bcd2bin(buf[1]);
dt->tm_min = bcd2bin(buf[2]);
dt->tm_hour = bcd2bin(buf[3]);
dt->tm_mday = bcd2bin(buf[4]);
dt->tm_mon = bcd2bin(buf[5]) - 1;
}
return ret == 2 ? 0 : -EIO;
}
static int pcf8583_set_datetime(struct i2c_client *client, struct rtc_time *dt, int datetoo)
{
unsigned char buf[8];
int ret, len = 6;
buf[0] = 0;
buf[1] = get_ctrl(client) | 0x80;
buf[2] = 0;
buf[3] = bin2bcd(dt->tm_sec);
buf[4] = bin2bcd(dt->tm_min);
buf[5] = bin2bcd(dt->tm_hour);
if (datetoo) {
len = 8;
buf[6] = bin2bcd(dt->tm_mday) | (dt->tm_year << 6);
buf[7] = bin2bcd(dt->tm_mon + 1) | (dt->tm_wday << 5);
}
ret = i2c_master_send(client, (char *)buf, len);
if (ret != len)
return -EIO;
buf[1] = get_ctrl(client);
ret = i2c_master_send(client, (char *)buf, 2);
return ret == 2 ? 0 : -EIO;
}
static int pcf8583_get_ctrl(struct i2c_client *client, unsigned char *ctrl)
{
*ctrl = get_ctrl(client);
return 0;
}
static int pcf8583_set_ctrl(struct i2c_client *client, unsigned char *ctrl)
{
unsigned char buf[2];
buf[0] = 0;
buf[1] = *ctrl;
set_ctrl(client, *ctrl);
return i2c_master_send(client, (char *)buf, 2);
}
static int pcf8583_read_mem(struct i2c_client *client, struct rtc_mem *mem)
{
unsigned char addr[1];
struct i2c_msg msgs[2] = {
{
.addr = client->addr,
.flags = 0,
.len = 1,
.buf = addr,
}, {
.addr = client->addr,
.flags = I2C_M_RD,
.len = mem->nr,
.buf = mem->data,
}
};
if (mem->loc < 8)
return -EINVAL;
addr[0] = mem->loc;
return i2c_transfer(client->adapter, msgs, 2) == 2 ? 0 : -EIO;
}
static int pcf8583_write_mem(struct i2c_client *client, struct rtc_mem *mem)
{
unsigned char buf[9];
int ret;
if (mem->loc < 8 || mem->nr > 8)
return -EINVAL;
buf[0] = mem->loc;
memcpy(buf + 1, mem->data, mem->nr);
ret = i2c_master_send(client, buf, mem->nr + 1);
return ret == mem->nr + 1 ? 0 : -EIO;
}
static int pcf8583_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
struct i2c_client *client = to_i2c_client(dev);
unsigned char ctrl, year[2];
struct rtc_mem mem = { CMOS_YEAR, sizeof(year), year };
int real_year, year_offset, err;
/*
* Ensure that the RTC is running.
*/
pcf8583_get_ctrl(client, &ctrl);
if (ctrl & (CTRL_STOP | CTRL_HOLD)) {
unsigned char new_ctrl = ctrl & ~(CTRL_STOP | CTRL_HOLD);
printk(KERN_WARNING "RTC: resetting control %02x -> %02x\n",
ctrl, new_ctrl);
if ((err = pcf8583_set_ctrl(client, &new_ctrl)) < 0)
return err;
}
if (pcf8583_get_datetime(client, tm) ||
pcf8583_read_mem(client, &mem))
return -EIO;
real_year = year[0];
/*
* The RTC year holds the LSB two bits of the current
* year, which should reflect the LSB two bits of the
* CMOS copy of the year. Any difference indicates
* that we have to correct the CMOS version.
*/
year_offset = tm->tm_year - (real_year & 3);
if (year_offset < 0)
/*
* RTC year wrapped. Adjust it appropriately.
*/
year_offset += 4;
tm->tm_year = (real_year + year_offset + year[1] * 100) - 1900;
return 0;
}
static int pcf8583_rtc_set_time(struct device *dev, struct rtc_time *tm)
{
struct i2c_client *client = to_i2c_client(dev);
unsigned char year[2], chk;
struct rtc_mem cmos_year = { CMOS_YEAR, sizeof(year), year };
struct rtc_mem cmos_check = { CMOS_CHECKSUM, 1, &chk };
unsigned int proper_year = tm->tm_year + 1900;
int ret;
/*
* The RTC's own 2-bit year must reflect the least
* significant two bits of the CMOS year.
*/
ret = pcf8583_set_datetime(client, tm, 1);
if (ret)
return ret;
ret = pcf8583_read_mem(client, &cmos_check);
if (ret)
return ret;
ret = pcf8583_read_mem(client, &cmos_year);
if (ret)
return ret;
chk -= year[1] + year[0];
year[1] = proper_year / 100;
year[0] = proper_year % 100;
chk += year[1] + year[0];
ret = pcf8583_write_mem(client, &cmos_year);
if (ret)
return ret;
ret = pcf8583_write_mem(client, &cmos_check);
return ret;
}
static const struct rtc_class_ops pcf8583_rtc_ops = {
.read_time = pcf8583_rtc_read_time,
.set_time = pcf8583_rtc_set_time,
};
static int pcf8583_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct pcf8583 *pcf8583;
int err;
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C))
return -ENODEV;
pcf8583 = kzalloc(sizeof(struct pcf8583), GFP_KERNEL);
if (!pcf8583)
return -ENOMEM;
i2c_set_clientdata(client, pcf8583);
pcf8583->rtc = rtc_device_register(pcf8583_driver.driver.name,
&client->dev, &pcf8583_rtc_ops, THIS_MODULE);
if (IS_ERR(pcf8583->rtc)) {
err = PTR_ERR(pcf8583->rtc);
goto exit_kfree;
}
return 0;
exit_kfree:
kfree(pcf8583);
return err;
}
static int __devexit pcf8583_remove(struct i2c_client *client)
{
struct pcf8583 *pcf8583 = i2c_get_clientdata(client);
if (pcf8583->rtc)
rtc_device_unregister(pcf8583->rtc);
kfree(pcf8583);
return 0;
}
static const struct i2c_device_id pcf8583_id[] = {
{ "pcf8583", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, pcf8583_id);
static struct i2c_driver pcf8583_driver = {
.driver = {
.name = "pcf8583",
.owner = THIS_MODULE,
},
.probe = pcf8583_probe,
.remove = __devexit_p(pcf8583_remove),
.id_table = pcf8583_id,
};
module_i2c_driver(pcf8583_driver);
MODULE_AUTHOR("Russell King");
MODULE_DESCRIPTION("PCF8583 I2C RTC driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
figue/raspberry-pi-kernel | drivers/rtc/rtc-stk17ta8.c | 4988 | 11155 | /*
* A RTC driver for the Simtek STK17TA8
*
* By Thomas Hommel <thomas.hommel@ge.com>
*
* Based on the DS1553 driver from
* Atsushi Nemoto <anemo@mba.ocn.ne.jp>
*
* 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/bcd.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/gfp.h>
#include <linux/delay.h>
#include <linux/jiffies.h>
#include <linux/interrupt.h>
#include <linux/rtc.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/module.h>
#define DRV_VERSION "0.1"
#define RTC_REG_SIZE 0x20000
#define RTC_OFFSET 0x1fff0
#define RTC_FLAGS (RTC_OFFSET + 0)
#define RTC_CENTURY (RTC_OFFSET + 1)
#define RTC_SECONDS_ALARM (RTC_OFFSET + 2)
#define RTC_MINUTES_ALARM (RTC_OFFSET + 3)
#define RTC_HOURS_ALARM (RTC_OFFSET + 4)
#define RTC_DATE_ALARM (RTC_OFFSET + 5)
#define RTC_INTERRUPTS (RTC_OFFSET + 6)
#define RTC_WATCHDOG (RTC_OFFSET + 7)
#define RTC_CALIBRATION (RTC_OFFSET + 8)
#define RTC_SECONDS (RTC_OFFSET + 9)
#define RTC_MINUTES (RTC_OFFSET + 10)
#define RTC_HOURS (RTC_OFFSET + 11)
#define RTC_DAY (RTC_OFFSET + 12)
#define RTC_DATE (RTC_OFFSET + 13)
#define RTC_MONTH (RTC_OFFSET + 14)
#define RTC_YEAR (RTC_OFFSET + 15)
#define RTC_SECONDS_MASK 0x7f
#define RTC_DAY_MASK 0x07
#define RTC_CAL_MASK 0x3f
/* Bits in the Calibration register */
#define RTC_STOP 0x80
/* Bits in the Flags register */
#define RTC_FLAGS_AF 0x40
#define RTC_FLAGS_PF 0x20
#define RTC_WRITE 0x02
#define RTC_READ 0x01
/* Bits in the Interrupts register */
#define RTC_INTS_AIE 0x40
struct rtc_plat_data {
struct rtc_device *rtc;
void __iomem *ioaddr;
unsigned long last_jiffies;
int irq;
unsigned int irqen;
int alrm_sec;
int alrm_min;
int alrm_hour;
int alrm_mday;
spinlock_t lock;
};
static int stk17ta8_rtc_set_time(struct device *dev, struct rtc_time *tm)
{
struct platform_device *pdev = to_platform_device(dev);
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
void __iomem *ioaddr = pdata->ioaddr;
u8 flags;
flags = readb(pdata->ioaddr + RTC_FLAGS);
writeb(flags | RTC_WRITE, pdata->ioaddr + RTC_FLAGS);
writeb(bin2bcd(tm->tm_year % 100), ioaddr + RTC_YEAR);
writeb(bin2bcd(tm->tm_mon + 1), ioaddr + RTC_MONTH);
writeb(bin2bcd(tm->tm_wday) & RTC_DAY_MASK, ioaddr + RTC_DAY);
writeb(bin2bcd(tm->tm_mday), ioaddr + RTC_DATE);
writeb(bin2bcd(tm->tm_hour), ioaddr + RTC_HOURS);
writeb(bin2bcd(tm->tm_min), ioaddr + RTC_MINUTES);
writeb(bin2bcd(tm->tm_sec) & RTC_SECONDS_MASK, ioaddr + RTC_SECONDS);
writeb(bin2bcd((tm->tm_year + 1900) / 100), ioaddr + RTC_CENTURY);
writeb(flags & ~RTC_WRITE, pdata->ioaddr + RTC_FLAGS);
return 0;
}
static int stk17ta8_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
struct platform_device *pdev = to_platform_device(dev);
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
void __iomem *ioaddr = pdata->ioaddr;
unsigned int year, month, day, hour, minute, second, week;
unsigned int century;
u8 flags;
/* give enough time to update RTC in case of continuous read */
if (pdata->last_jiffies == jiffies)
msleep(1);
pdata->last_jiffies = jiffies;
flags = readb(pdata->ioaddr + RTC_FLAGS);
writeb(flags | RTC_READ, ioaddr + RTC_FLAGS);
second = readb(ioaddr + RTC_SECONDS) & RTC_SECONDS_MASK;
minute = readb(ioaddr + RTC_MINUTES);
hour = readb(ioaddr + RTC_HOURS);
day = readb(ioaddr + RTC_DATE);
week = readb(ioaddr + RTC_DAY) & RTC_DAY_MASK;
month = readb(ioaddr + RTC_MONTH);
year = readb(ioaddr + RTC_YEAR);
century = readb(ioaddr + RTC_CENTURY);
writeb(flags & ~RTC_READ, ioaddr + RTC_FLAGS);
tm->tm_sec = bcd2bin(second);
tm->tm_min = bcd2bin(minute);
tm->tm_hour = bcd2bin(hour);
tm->tm_mday = bcd2bin(day);
tm->tm_wday = bcd2bin(week);
tm->tm_mon = bcd2bin(month) - 1;
/* year is 1900 + tm->tm_year */
tm->tm_year = bcd2bin(year) + bcd2bin(century) * 100 - 1900;
if (rtc_valid_tm(tm) < 0) {
dev_err(dev, "retrieved date/time is not valid.\n");
rtc_time_to_tm(0, tm);
}
return 0;
}
static void stk17ta8_rtc_update_alarm(struct rtc_plat_data *pdata)
{
void __iomem *ioaddr = pdata->ioaddr;
unsigned long irqflags;
u8 flags;
spin_lock_irqsave(&pdata->lock, irqflags);
flags = readb(ioaddr + RTC_FLAGS);
writeb(flags | RTC_WRITE, ioaddr + RTC_FLAGS);
writeb(pdata->alrm_mday < 0 || (pdata->irqen & RTC_UF) ?
0x80 : bin2bcd(pdata->alrm_mday),
ioaddr + RTC_DATE_ALARM);
writeb(pdata->alrm_hour < 0 || (pdata->irqen & RTC_UF) ?
0x80 : bin2bcd(pdata->alrm_hour),
ioaddr + RTC_HOURS_ALARM);
writeb(pdata->alrm_min < 0 || (pdata->irqen & RTC_UF) ?
0x80 : bin2bcd(pdata->alrm_min),
ioaddr + RTC_MINUTES_ALARM);
writeb(pdata->alrm_sec < 0 || (pdata->irqen & RTC_UF) ?
0x80 : bin2bcd(pdata->alrm_sec),
ioaddr + RTC_SECONDS_ALARM);
writeb(pdata->irqen ? RTC_INTS_AIE : 0, ioaddr + RTC_INTERRUPTS);
readb(ioaddr + RTC_FLAGS); /* clear interrupts */
writeb(flags & ~RTC_WRITE, ioaddr + RTC_FLAGS);
spin_unlock_irqrestore(&pdata->lock, irqflags);
}
static int stk17ta8_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct platform_device *pdev = to_platform_device(dev);
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
if (pdata->irq <= 0)
return -EINVAL;
pdata->alrm_mday = alrm->time.tm_mday;
pdata->alrm_hour = alrm->time.tm_hour;
pdata->alrm_min = alrm->time.tm_min;
pdata->alrm_sec = alrm->time.tm_sec;
if (alrm->enabled)
pdata->irqen |= RTC_AF;
stk17ta8_rtc_update_alarm(pdata);
return 0;
}
static int stk17ta8_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct platform_device *pdev = to_platform_device(dev);
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
if (pdata->irq <= 0)
return -EINVAL;
alrm->time.tm_mday = pdata->alrm_mday < 0 ? 0 : pdata->alrm_mday;
alrm->time.tm_hour = pdata->alrm_hour < 0 ? 0 : pdata->alrm_hour;
alrm->time.tm_min = pdata->alrm_min < 0 ? 0 : pdata->alrm_min;
alrm->time.tm_sec = pdata->alrm_sec < 0 ? 0 : pdata->alrm_sec;
alrm->enabled = (pdata->irqen & RTC_AF) ? 1 : 0;
return 0;
}
static irqreturn_t stk17ta8_rtc_interrupt(int irq, void *dev_id)
{
struct platform_device *pdev = dev_id;
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
void __iomem *ioaddr = pdata->ioaddr;
unsigned long events = 0;
spin_lock(&pdata->lock);
/* read and clear interrupt */
if (readb(ioaddr + RTC_FLAGS) & RTC_FLAGS_AF) {
events = RTC_IRQF;
if (readb(ioaddr + RTC_SECONDS_ALARM) & 0x80)
events |= RTC_UF;
else
events |= RTC_AF;
if (likely(pdata->rtc))
rtc_update_irq(pdata->rtc, 1, events);
}
spin_unlock(&pdata->lock);
return events ? IRQ_HANDLED : IRQ_NONE;
}
static int stk17ta8_rtc_alarm_irq_enable(struct device *dev,
unsigned int enabled)
{
struct platform_device *pdev = to_platform_device(dev);
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
if (pdata->irq <= 0)
return -EINVAL;
if (enabled)
pdata->irqen |= RTC_AF;
else
pdata->irqen &= ~RTC_AF;
stk17ta8_rtc_update_alarm(pdata);
return 0;
}
static const struct rtc_class_ops stk17ta8_rtc_ops = {
.read_time = stk17ta8_rtc_read_time,
.set_time = stk17ta8_rtc_set_time,
.read_alarm = stk17ta8_rtc_read_alarm,
.set_alarm = stk17ta8_rtc_set_alarm,
.alarm_irq_enable = stk17ta8_rtc_alarm_irq_enable,
};
static ssize_t stk17ta8_nvram_read(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr, char *buf,
loff_t pos, size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct platform_device *pdev = to_platform_device(dev);
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
void __iomem *ioaddr = pdata->ioaddr;
ssize_t count;
for (count = 0; size > 0 && pos < RTC_OFFSET; count++, size--)
*buf++ = readb(ioaddr + pos++);
return count;
}
static ssize_t stk17ta8_nvram_write(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr, char *buf,
loff_t pos, size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct platform_device *pdev = to_platform_device(dev);
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
void __iomem *ioaddr = pdata->ioaddr;
ssize_t count;
for (count = 0; size > 0 && pos < RTC_OFFSET; count++, size--)
writeb(*buf++, ioaddr + pos++);
return count;
}
static struct bin_attribute stk17ta8_nvram_attr = {
.attr = {
.name = "nvram",
.mode = S_IRUGO | S_IWUSR,
},
.size = RTC_OFFSET,
.read = stk17ta8_nvram_read,
.write = stk17ta8_nvram_write,
};
static int __devinit stk17ta8_rtc_probe(struct platform_device *pdev)
{
struct resource *res;
unsigned int cal;
unsigned int flags;
struct rtc_plat_data *pdata;
void __iomem *ioaddr;
int ret = 0;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENODEV;
pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata)
return -ENOMEM;
if (!devm_request_mem_region(&pdev->dev, res->start, RTC_REG_SIZE,
pdev->name))
return -EBUSY;
ioaddr = devm_ioremap(&pdev->dev, res->start, RTC_REG_SIZE);
if (!ioaddr)
return -ENOMEM;
pdata->ioaddr = ioaddr;
pdata->irq = platform_get_irq(pdev, 0);
/* turn RTC on if it was not on */
cal = readb(ioaddr + RTC_CALIBRATION);
if (cal & RTC_STOP) {
cal &= RTC_CAL_MASK;
flags = readb(ioaddr + RTC_FLAGS);
writeb(flags | RTC_WRITE, ioaddr + RTC_FLAGS);
writeb(cal, ioaddr + RTC_CALIBRATION);
writeb(flags & ~RTC_WRITE, ioaddr + RTC_FLAGS);
}
if (readb(ioaddr + RTC_FLAGS) & RTC_FLAGS_PF)
dev_warn(&pdev->dev, "voltage-low detected.\n");
spin_lock_init(&pdata->lock);
pdata->last_jiffies = jiffies;
platform_set_drvdata(pdev, pdata);
if (pdata->irq > 0) {
writeb(0, ioaddr + RTC_INTERRUPTS);
if (devm_request_irq(&pdev->dev, pdata->irq,
stk17ta8_rtc_interrupt,
IRQF_SHARED,
pdev->name, pdev) < 0) {
dev_warn(&pdev->dev, "interrupt not available.\n");
pdata->irq = 0;
}
}
pdata->rtc = rtc_device_register(pdev->name, &pdev->dev,
&stk17ta8_rtc_ops, THIS_MODULE);
if (IS_ERR(pdata->rtc))
return PTR_ERR(pdata->rtc);
ret = sysfs_create_bin_file(&pdev->dev.kobj, &stk17ta8_nvram_attr);
if (ret)
rtc_device_unregister(pdata->rtc);
return ret;
}
static int __devexit stk17ta8_rtc_remove(struct platform_device *pdev)
{
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
sysfs_remove_bin_file(&pdev->dev.kobj, &stk17ta8_nvram_attr);
rtc_device_unregister(pdata->rtc);
if (pdata->irq > 0)
writeb(0, pdata->ioaddr + RTC_INTERRUPTS);
return 0;
}
/* work with hotplug and coldplug */
MODULE_ALIAS("platform:stk17ta8");
static struct platform_driver stk17ta8_rtc_driver = {
.probe = stk17ta8_rtc_probe,
.remove = __devexit_p(stk17ta8_rtc_remove),
.driver = {
.name = "stk17ta8",
.owner = THIS_MODULE,
},
};
module_platform_driver(stk17ta8_rtc_driver);
MODULE_AUTHOR("Thomas Hommel <thomas.hommel@ge.com>");
MODULE_DESCRIPTION("Simtek STK17TA8 RTC driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
| gpl-2.0 |
brymaster5000/m7-gpe-444 | drivers/isdn/hisax/teles3.c | 4988 | 13628 | /* $Id: teles3.c,v 2.19.2.4 2004/01/13 23:48:39 keil Exp $
*
* low level stuff for Teles 16.3 & PNP isdn cards
*
* Author Karsten Keil
* Copyright by Karsten Keil <keil@isdn4linux.de>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
* Thanks to Jan den Ouden
* Fritz Elfert
* Beat Doebeli
*
*/
#include <linux/init.h>
#include <linux/isapnp.h>
#include "hisax.h"
#include "isac.h"
#include "hscx.h"
#include "isdnl1.h"
static const char *teles3_revision = "$Revision: 2.19.2.4 $";
#define byteout(addr, val) outb(val, addr)
#define bytein(addr) inb(addr)
static inline u_char
readreg(unsigned int adr, u_char off)
{
return (bytein(adr + off));
}
static inline void
writereg(unsigned int adr, u_char off, u_char data)
{
byteout(adr + off, data);
}
static inline void
read_fifo(unsigned int adr, u_char *data, int size)
{
insb(adr, data, size);
}
static void
write_fifo(unsigned int adr, u_char *data, int size)
{
outsb(adr, data, size);
}
/* Interface functions */
static u_char
ReadISAC(struct IsdnCardState *cs, u_char offset)
{
return (readreg(cs->hw.teles3.isac, offset));
}
static void
WriteISAC(struct IsdnCardState *cs, u_char offset, u_char value)
{
writereg(cs->hw.teles3.isac, offset, value);
}
static void
ReadISACfifo(struct IsdnCardState *cs, u_char *data, int size)
{
read_fifo(cs->hw.teles3.isacfifo, data, size);
}
static void
WriteISACfifo(struct IsdnCardState *cs, u_char *data, int size)
{
write_fifo(cs->hw.teles3.isacfifo, data, size);
}
static u_char
ReadHSCX(struct IsdnCardState *cs, int hscx, u_char offset)
{
return (readreg(cs->hw.teles3.hscx[hscx], offset));
}
static void
WriteHSCX(struct IsdnCardState *cs, int hscx, u_char offset, u_char value)
{
writereg(cs->hw.teles3.hscx[hscx], offset, value);
}
/*
* fast interrupt HSCX stuff goes here
*/
#define READHSCX(cs, nr, reg) readreg(cs->hw.teles3.hscx[nr], reg)
#define WRITEHSCX(cs, nr, reg, data) writereg(cs->hw.teles3.hscx[nr], reg, data)
#define READHSCXFIFO(cs, nr, ptr, cnt) read_fifo(cs->hw.teles3.hscxfifo[nr], ptr, cnt)
#define WRITEHSCXFIFO(cs, nr, ptr, cnt) write_fifo(cs->hw.teles3.hscxfifo[nr], ptr, cnt)
#include "hscx_irq.c"
static irqreturn_t
teles3_interrupt(int intno, void *dev_id)
{
#define MAXCOUNT 5
struct IsdnCardState *cs = dev_id;
u_char val;
u_long flags;
int count = 0;
spin_lock_irqsave(&cs->lock, flags);
val = readreg(cs->hw.teles3.hscx[1], HSCX_ISTA);
Start_HSCX:
if (val)
hscx_int_main(cs, val);
val = readreg(cs->hw.teles3.isac, ISAC_ISTA);
Start_ISAC:
if (val)
isac_interrupt(cs, val);
count++;
val = readreg(cs->hw.teles3.hscx[1], HSCX_ISTA);
if (val && count < MAXCOUNT) {
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "HSCX IntStat after IntRoutine");
goto Start_HSCX;
}
val = readreg(cs->hw.teles3.isac, ISAC_ISTA);
if (val && count < MAXCOUNT) {
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "ISAC IntStat after IntRoutine");
goto Start_ISAC;
}
if (count >= MAXCOUNT)
printk(KERN_WARNING "Teles3: more than %d loops in teles3_interrupt\n", count);
writereg(cs->hw.teles3.hscx[0], HSCX_MASK, 0xFF);
writereg(cs->hw.teles3.hscx[1], HSCX_MASK, 0xFF);
writereg(cs->hw.teles3.isac, ISAC_MASK, 0xFF);
writereg(cs->hw.teles3.isac, ISAC_MASK, 0x0);
writereg(cs->hw.teles3.hscx[0], HSCX_MASK, 0x0);
writereg(cs->hw.teles3.hscx[1], HSCX_MASK, 0x0);
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_HANDLED;
}
static inline void
release_ioregs(struct IsdnCardState *cs, int mask)
{
if (mask & 1)
release_region(cs->hw.teles3.isac + 32, 32);
if (mask & 2)
release_region(cs->hw.teles3.hscx[0] + 32, 32);
if (mask & 4)
release_region(cs->hw.teles3.hscx[1] + 32, 32);
}
static void
release_io_teles3(struct IsdnCardState *cs)
{
if (cs->typ == ISDN_CTYPE_TELESPCMCIA) {
release_region(cs->hw.teles3.hscx[1], 96);
} else {
if (cs->hw.teles3.cfg_reg) {
if (cs->typ == ISDN_CTYPE_COMPAQ_ISA) {
release_region(cs->hw.teles3.cfg_reg, 1);
} else {
release_region(cs->hw.teles3.cfg_reg, 8);
}
}
release_ioregs(cs, 0x7);
}
}
static int
reset_teles3(struct IsdnCardState *cs)
{
u_char irqcfg;
if (cs->typ != ISDN_CTYPE_TELESPCMCIA) {
if ((cs->hw.teles3.cfg_reg) && (cs->typ != ISDN_CTYPE_COMPAQ_ISA)) {
switch (cs->irq) {
case 2:
case 9:
irqcfg = 0x00;
break;
case 3:
irqcfg = 0x02;
break;
case 4:
irqcfg = 0x04;
break;
case 5:
irqcfg = 0x06;
break;
case 10:
irqcfg = 0x08;
break;
case 11:
irqcfg = 0x0A;
break;
case 12:
irqcfg = 0x0C;
break;
case 15:
irqcfg = 0x0E;
break;
default:
return (1);
}
byteout(cs->hw.teles3.cfg_reg + 4, irqcfg);
HZDELAY(HZ / 10 + 1);
byteout(cs->hw.teles3.cfg_reg + 4, irqcfg | 1);
HZDELAY(HZ / 10 + 1);
} else if (cs->typ == ISDN_CTYPE_COMPAQ_ISA) {
byteout(cs->hw.teles3.cfg_reg, 0xff);
HZDELAY(2);
byteout(cs->hw.teles3.cfg_reg, 0x00);
HZDELAY(2);
} else {
/* Reset off for 16.3 PnP , thanks to Georg Acher */
byteout(cs->hw.teles3.isac + 0x3c, 0);
HZDELAY(2);
byteout(cs->hw.teles3.isac + 0x3c, 1);
HZDELAY(2);
}
}
return (0);
}
static int
Teles_card_msg(struct IsdnCardState *cs, int mt, void *arg)
{
u_long flags;
switch (mt) {
case CARD_RESET:
spin_lock_irqsave(&cs->lock, flags);
reset_teles3(cs);
spin_unlock_irqrestore(&cs->lock, flags);
return (0);
case CARD_RELEASE:
release_io_teles3(cs);
return (0);
case CARD_INIT:
spin_lock_irqsave(&cs->lock, flags);
inithscxisac(cs, 3);
spin_unlock_irqrestore(&cs->lock, flags);
return (0);
case CARD_TEST:
return (0);
}
return (0);
}
#ifdef __ISAPNP__
static struct isapnp_device_id teles_ids[] __devinitdata = {
{ ISAPNP_VENDOR('T', 'A', 'G'), ISAPNP_FUNCTION(0x2110),
ISAPNP_VENDOR('T', 'A', 'G'), ISAPNP_FUNCTION(0x2110),
(unsigned long) "Teles 16.3 PnP" },
{ ISAPNP_VENDOR('C', 'T', 'X'), ISAPNP_FUNCTION(0x0),
ISAPNP_VENDOR('C', 'T', 'X'), ISAPNP_FUNCTION(0x0),
(unsigned long) "Creatix 16.3 PnP" },
{ ISAPNP_VENDOR('C', 'P', 'Q'), ISAPNP_FUNCTION(0x1002),
ISAPNP_VENDOR('C', 'P', 'Q'), ISAPNP_FUNCTION(0x1002),
(unsigned long) "Compaq ISDN S0" },
{ 0, }
};
static struct isapnp_device_id *ipid __devinitdata = &teles_ids[0];
static struct pnp_card *pnp_c __devinitdata = NULL;
#endif
int __devinit
setup_teles3(struct IsdnCard *card)
{
u_char val;
struct IsdnCardState *cs = card->cs;
char tmp[64];
strcpy(tmp, teles3_revision);
printk(KERN_INFO "HiSax: Teles IO driver Rev. %s\n", HiSax_getrev(tmp));
if ((cs->typ != ISDN_CTYPE_16_3) && (cs->typ != ISDN_CTYPE_PNP)
&& (cs->typ != ISDN_CTYPE_TELESPCMCIA) && (cs->typ != ISDN_CTYPE_COMPAQ_ISA))
return (0);
#ifdef __ISAPNP__
if (!card->para[1] && isapnp_present()) {
struct pnp_dev *pnp_d;
while (ipid->card_vendor) {
if ((pnp_c = pnp_find_card(ipid->card_vendor,
ipid->card_device, pnp_c))) {
pnp_d = NULL;
if ((pnp_d = pnp_find_dev(pnp_c,
ipid->vendor, ipid->function, pnp_d))) {
int err;
printk(KERN_INFO "HiSax: %s detected\n",
(char *)ipid->driver_data);
pnp_disable_dev(pnp_d);
err = pnp_activate_dev(pnp_d);
if (err < 0) {
printk(KERN_WARNING "%s: pnp_activate_dev ret(%d)\n",
__func__, err);
return (0);
}
card->para[3] = pnp_port_start(pnp_d, 2);
card->para[2] = pnp_port_start(pnp_d, 1);
card->para[1] = pnp_port_start(pnp_d, 0);
card->para[0] = pnp_irq(pnp_d, 0);
if (!card->para[0] || !card->para[1] || !card->para[2]) {
printk(KERN_ERR "Teles PnP:some resources are missing %ld/%lx/%lx\n",
card->para[0], card->para[1], card->para[2]);
pnp_disable_dev(pnp_d);
return (0);
}
break;
} else {
printk(KERN_ERR "Teles PnP: PnP error card found, no device\n");
}
}
ipid++;
pnp_c = NULL;
}
if (!ipid->card_vendor) {
printk(KERN_INFO "Teles PnP: no ISAPnP card found\n");
return (0);
}
}
#endif
if (cs->typ == ISDN_CTYPE_16_3) {
cs->hw.teles3.cfg_reg = card->para[1];
switch (cs->hw.teles3.cfg_reg) {
case 0x180:
case 0x280:
case 0x380:
cs->hw.teles3.cfg_reg |= 0xc00;
break;
}
cs->hw.teles3.isac = cs->hw.teles3.cfg_reg - 0x420;
cs->hw.teles3.hscx[0] = cs->hw.teles3.cfg_reg - 0xc20;
cs->hw.teles3.hscx[1] = cs->hw.teles3.cfg_reg - 0x820;
} else if (cs->typ == ISDN_CTYPE_TELESPCMCIA) {
cs->hw.teles3.cfg_reg = 0;
cs->hw.teles3.hscx[0] = card->para[1] - 0x20;
cs->hw.teles3.hscx[1] = card->para[1];
cs->hw.teles3.isac = card->para[1] + 0x20;
} else if (cs->typ == ISDN_CTYPE_COMPAQ_ISA) {
cs->hw.teles3.cfg_reg = card->para[3];
cs->hw.teles3.isac = card->para[2] - 32;
cs->hw.teles3.hscx[0] = card->para[1] - 32;
cs->hw.teles3.hscx[1] = card->para[1];
} else { /* PNP */
cs->hw.teles3.cfg_reg = 0;
cs->hw.teles3.isac = card->para[1] - 32;
cs->hw.teles3.hscx[0] = card->para[2] - 32;
cs->hw.teles3.hscx[1] = card->para[2];
}
cs->irq = card->para[0];
cs->hw.teles3.isacfifo = cs->hw.teles3.isac + 0x3e;
cs->hw.teles3.hscxfifo[0] = cs->hw.teles3.hscx[0] + 0x3e;
cs->hw.teles3.hscxfifo[1] = cs->hw.teles3.hscx[1] + 0x3e;
if (cs->typ == ISDN_CTYPE_TELESPCMCIA) {
if (!request_region(cs->hw.teles3.hscx[1], 96, "HiSax Teles PCMCIA")) {
printk(KERN_WARNING
"HiSax: %s ports %x-%x already in use\n",
CardType[cs->typ],
cs->hw.teles3.hscx[1],
cs->hw.teles3.hscx[1] + 96);
return (0);
}
cs->irq_flags |= IRQF_SHARED; /* cardbus can share */
} else {
if (cs->hw.teles3.cfg_reg) {
if (cs->typ == ISDN_CTYPE_COMPAQ_ISA) {
if (!request_region(cs->hw.teles3.cfg_reg, 1, "teles3 cfg")) {
printk(KERN_WARNING
"HiSax: %s config port %x already in use\n",
CardType[card->typ],
cs->hw.teles3.cfg_reg);
return (0);
}
} else {
if (!request_region(cs->hw.teles3.cfg_reg, 8, "teles3 cfg")) {
printk(KERN_WARNING
"HiSax: %s config port %x-%x already in use\n",
CardType[card->typ],
cs->hw.teles3.cfg_reg,
cs->hw.teles3.cfg_reg + 8);
return (0);
}
}
}
if (!request_region(cs->hw.teles3.isac + 32, 32, "HiSax isac")) {
printk(KERN_WARNING
"HiSax: %s isac ports %x-%x already in use\n",
CardType[cs->typ],
cs->hw.teles3.isac + 32,
cs->hw.teles3.isac + 64);
if (cs->hw.teles3.cfg_reg) {
if (cs->typ == ISDN_CTYPE_COMPAQ_ISA) {
release_region(cs->hw.teles3.cfg_reg, 1);
} else {
release_region(cs->hw.teles3.cfg_reg, 8);
}
}
return (0);
}
if (!request_region(cs->hw.teles3.hscx[0] + 32, 32, "HiSax hscx A")) {
printk(KERN_WARNING
"HiSax: %s hscx A ports %x-%x already in use\n",
CardType[cs->typ],
cs->hw.teles3.hscx[0] + 32,
cs->hw.teles3.hscx[0] + 64);
if (cs->hw.teles3.cfg_reg) {
if (cs->typ == ISDN_CTYPE_COMPAQ_ISA) {
release_region(cs->hw.teles3.cfg_reg, 1);
} else {
release_region(cs->hw.teles3.cfg_reg, 8);
}
}
release_ioregs(cs, 1);
return (0);
}
if (!request_region(cs->hw.teles3.hscx[1] + 32, 32, "HiSax hscx B")) {
printk(KERN_WARNING
"HiSax: %s hscx B ports %x-%x already in use\n",
CardType[cs->typ],
cs->hw.teles3.hscx[1] + 32,
cs->hw.teles3.hscx[1] + 64);
if (cs->hw.teles3.cfg_reg) {
if (cs->typ == ISDN_CTYPE_COMPAQ_ISA) {
release_region(cs->hw.teles3.cfg_reg, 1);
} else {
release_region(cs->hw.teles3.cfg_reg, 8);
}
}
release_ioregs(cs, 3);
return (0);
}
}
if ((cs->hw.teles3.cfg_reg) && (cs->typ != ISDN_CTYPE_COMPAQ_ISA)) {
if ((val = bytein(cs->hw.teles3.cfg_reg + 0)) != 0x51) {
printk(KERN_WARNING "Teles: 16.3 Byte at %x is %x\n",
cs->hw.teles3.cfg_reg + 0, val);
release_io_teles3(cs);
return (0);
}
if ((val = bytein(cs->hw.teles3.cfg_reg + 1)) != 0x93) {
printk(KERN_WARNING "Teles: 16.3 Byte at %x is %x\n",
cs->hw.teles3.cfg_reg + 1, val);
release_io_teles3(cs);
return (0);
}
val = bytein(cs->hw.teles3.cfg_reg + 2);/* 0x1e=without AB
* 0x1f=with AB
* 0x1c 16.3 ???
* 0x39 16.3 1.1
* 0x38 16.3 1.3
* 0x46 16.3 with AB + Video (Teles-Vision)
*/
if (val != 0x46 && val != 0x39 && val != 0x38 && val != 0x1c && val != 0x1e && val != 0x1f) {
printk(KERN_WARNING "Teles: 16.3 Byte at %x is %x\n",
cs->hw.teles3.cfg_reg + 2, val);
release_io_teles3(cs);
return (0);
}
}
printk(KERN_INFO
"HiSax: %s config irq:%d isac:0x%X cfg:0x%X\n",
CardType[cs->typ], cs->irq,
cs->hw.teles3.isac + 32, cs->hw.teles3.cfg_reg);
printk(KERN_INFO
"HiSax: hscx A:0x%X hscx B:0x%X\n",
cs->hw.teles3.hscx[0] + 32, cs->hw.teles3.hscx[1] + 32);
setup_isac(cs);
if (reset_teles3(cs)) {
printk(KERN_WARNING "Teles3: wrong IRQ\n");
release_io_teles3(cs);
return (0);
}
cs->readisac = &ReadISAC;
cs->writeisac = &WriteISAC;
cs->readisacfifo = &ReadISACfifo;
cs->writeisacfifo = &WriteISACfifo;
cs->BC_Read_Reg = &ReadHSCX;
cs->BC_Write_Reg = &WriteHSCX;
cs->BC_Send_Data = &hscx_fill_fifo;
cs->cardmsg = &Teles_card_msg;
cs->irq_func = &teles3_interrupt;
ISACVersion(cs, "Teles3:");
if (HscxVersion(cs, "Teles3:")) {
printk(KERN_WARNING
"Teles3: wrong HSCX versions check IO address\n");
release_io_teles3(cs);
return (0);
}
return (1);
}
| gpl-2.0 |
TeamEOS/kernel_samsung_manta | drivers/rtc/rtc-rx8025.c | 4988 | 16365 | /*
* Driver for Epson's RTC module RX-8025 SA/NB
*
* Copyright (C) 2009 Wolfgang Grandegger <wg@grandegger.com>
*
* Copyright (C) 2005 by Digi International Inc.
* All rights reserved.
*
* Modified by fengjh at rising.com.cn
* <http://lists.lm-sensors.org/mailman/listinfo/lm-sensors>
* 2006.11
*
* Code cleanup by Sergei Poselenov, <sposelenov@emcraft.com>
* Converted to new style by Wolfgang Grandegger <wg@grandegger.com>
* Alarm and periodic interrupt added by Dmitry Rakhchev <rda@emcraft.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/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/bcd.h>
#include <linux/i2c.h>
#include <linux/list.h>
#include <linux/rtc.h>
/* Register definitions */
#define RX8025_REG_SEC 0x00
#define RX8025_REG_MIN 0x01
#define RX8025_REG_HOUR 0x02
#define RX8025_REG_WDAY 0x03
#define RX8025_REG_MDAY 0x04
#define RX8025_REG_MONTH 0x05
#define RX8025_REG_YEAR 0x06
#define RX8025_REG_DIGOFF 0x07
#define RX8025_REG_ALWMIN 0x08
#define RX8025_REG_ALWHOUR 0x09
#define RX8025_REG_ALWWDAY 0x0a
#define RX8025_REG_ALDMIN 0x0b
#define RX8025_REG_ALDHOUR 0x0c
/* 0x0d is reserved */
#define RX8025_REG_CTRL1 0x0e
#define RX8025_REG_CTRL2 0x0f
#define RX8025_BIT_CTRL1_CT (7 << 0)
/* 1 Hz periodic level irq */
#define RX8025_BIT_CTRL1_CT_1HZ 4
#define RX8025_BIT_CTRL1_TEST (1 << 3)
#define RX8025_BIT_CTRL1_1224 (1 << 5)
#define RX8025_BIT_CTRL1_DALE (1 << 6)
#define RX8025_BIT_CTRL1_WALE (1 << 7)
#define RX8025_BIT_CTRL2_DAFG (1 << 0)
#define RX8025_BIT_CTRL2_WAFG (1 << 1)
#define RX8025_BIT_CTRL2_CTFG (1 << 2)
#define RX8025_BIT_CTRL2_PON (1 << 4)
#define RX8025_BIT_CTRL2_XST (1 << 5)
#define RX8025_BIT_CTRL2_VDET (1 << 6)
/* Clock precision adjustment */
#define RX8025_ADJ_RESOLUTION 3050 /* in ppb */
#define RX8025_ADJ_DATA_MAX 62
#define RX8025_ADJ_DATA_MIN -62
static const struct i2c_device_id rx8025_id[] = {
{ "rx8025", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, rx8025_id);
struct rx8025_data {
struct i2c_client *client;
struct rtc_device *rtc;
struct work_struct work;
u8 ctrl1;
unsigned exiting:1;
};
static int rx8025_read_reg(struct i2c_client *client, int number, u8 *value)
{
int ret = i2c_smbus_read_byte_data(client, (number << 4) | 0x08);
if (ret < 0) {
dev_err(&client->dev, "Unable to read register #%d\n", number);
return ret;
}
*value = ret;
return 0;
}
static int rx8025_read_regs(struct i2c_client *client,
int number, u8 length, u8 *values)
{
int ret = i2c_smbus_read_i2c_block_data(client, (number << 4) | 0x08,
length, values);
if (ret != length) {
dev_err(&client->dev, "Unable to read registers #%d..#%d\n",
number, number + length - 1);
return ret < 0 ? ret : -EIO;
}
return 0;
}
static int rx8025_write_reg(struct i2c_client *client, int number, u8 value)
{
int ret = i2c_smbus_write_byte_data(client, number << 4, value);
if (ret)
dev_err(&client->dev, "Unable to write register #%d\n",
number);
return ret;
}
static int rx8025_write_regs(struct i2c_client *client,
int number, u8 length, u8 *values)
{
int ret = i2c_smbus_write_i2c_block_data(client, (number << 4) | 0x08,
length, values);
if (ret)
dev_err(&client->dev, "Unable to write registers #%d..#%d\n",
number, number + length - 1);
return ret;
}
static irqreturn_t rx8025_irq(int irq, void *dev_id)
{
struct i2c_client *client = dev_id;
struct rx8025_data *rx8025 = i2c_get_clientdata(client);
disable_irq_nosync(irq);
schedule_work(&rx8025->work);
return IRQ_HANDLED;
}
static void rx8025_work(struct work_struct *work)
{
struct rx8025_data *rx8025 = container_of(work, struct rx8025_data,
work);
struct i2c_client *client = rx8025->client;
struct mutex *lock = &rx8025->rtc->ops_lock;
u8 status;
mutex_lock(lock);
if (rx8025_read_reg(client, RX8025_REG_CTRL2, &status))
goto out;
if (!(status & RX8025_BIT_CTRL2_XST))
dev_warn(&client->dev, "Oscillation stop was detected,"
"you may have to readjust the clock\n");
if (status & RX8025_BIT_CTRL2_CTFG) {
/* periodic */
status &= ~RX8025_BIT_CTRL2_CTFG;
local_irq_disable();
rtc_update_irq(rx8025->rtc, 1, RTC_PF | RTC_IRQF);
local_irq_enable();
}
if (status & RX8025_BIT_CTRL2_DAFG) {
/* alarm */
status &= RX8025_BIT_CTRL2_DAFG;
if (rx8025_write_reg(client, RX8025_REG_CTRL1,
rx8025->ctrl1 & ~RX8025_BIT_CTRL1_DALE))
goto out;
local_irq_disable();
rtc_update_irq(rx8025->rtc, 1, RTC_AF | RTC_IRQF);
local_irq_enable();
}
/* acknowledge IRQ */
rx8025_write_reg(client, RX8025_REG_CTRL2,
status | RX8025_BIT_CTRL2_XST);
out:
if (!rx8025->exiting)
enable_irq(client->irq);
mutex_unlock(lock);
}
static int rx8025_get_time(struct device *dev, struct rtc_time *dt)
{
struct rx8025_data *rx8025 = dev_get_drvdata(dev);
u8 date[7];
int err;
err = rx8025_read_regs(rx8025->client, RX8025_REG_SEC, 7, date);
if (err)
return err;
dev_dbg(dev, "%s: read 0x%02x 0x%02x "
"0x%02x 0x%02x 0x%02x 0x%02x 0x%02x\n", __func__,
date[0], date[1], date[2], date[3], date[4],
date[5], date[6]);
dt->tm_sec = bcd2bin(date[RX8025_REG_SEC] & 0x7f);
dt->tm_min = bcd2bin(date[RX8025_REG_MIN] & 0x7f);
if (rx8025->ctrl1 & RX8025_BIT_CTRL1_1224)
dt->tm_hour = bcd2bin(date[RX8025_REG_HOUR] & 0x3f);
else
dt->tm_hour = bcd2bin(date[RX8025_REG_HOUR] & 0x1f) % 12
+ (date[RX8025_REG_HOUR] & 0x20 ? 12 : 0);
dt->tm_mday = bcd2bin(date[RX8025_REG_MDAY] & 0x3f);
dt->tm_mon = bcd2bin(date[RX8025_REG_MONTH] & 0x1f) - 1;
dt->tm_year = bcd2bin(date[RX8025_REG_YEAR]);
if (dt->tm_year < 70)
dt->tm_year += 100;
dev_dbg(dev, "%s: date %ds %dm %dh %dmd %dm %dy\n", __func__,
dt->tm_sec, dt->tm_min, dt->tm_hour,
dt->tm_mday, dt->tm_mon, dt->tm_year);
return rtc_valid_tm(dt);
}
static int rx8025_set_time(struct device *dev, struct rtc_time *dt)
{
struct rx8025_data *rx8025 = dev_get_drvdata(dev);
u8 date[7];
/*
* BUG: The HW assumes every year that is a multiple of 4 to be a leap
* year. Next time this is wrong is 2100, which will not be a leap
* year.
*/
/*
* Here the read-only bits are written as "0". I'm not sure if that
* is sound.
*/
date[RX8025_REG_SEC] = bin2bcd(dt->tm_sec);
date[RX8025_REG_MIN] = bin2bcd(dt->tm_min);
if (rx8025->ctrl1 & RX8025_BIT_CTRL1_1224)
date[RX8025_REG_HOUR] = bin2bcd(dt->tm_hour);
else
date[RX8025_REG_HOUR] = (dt->tm_hour >= 12 ? 0x20 : 0)
| bin2bcd((dt->tm_hour + 11) % 12 + 1);
date[RX8025_REG_WDAY] = bin2bcd(dt->tm_wday);
date[RX8025_REG_MDAY] = bin2bcd(dt->tm_mday);
date[RX8025_REG_MONTH] = bin2bcd(dt->tm_mon + 1);
date[RX8025_REG_YEAR] = bin2bcd(dt->tm_year % 100);
dev_dbg(dev,
"%s: write 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x\n",
__func__,
date[0], date[1], date[2], date[3], date[4], date[5], date[6]);
return rx8025_write_regs(rx8025->client, RX8025_REG_SEC, 7, date);
}
static int rx8025_init_client(struct i2c_client *client, int *need_reset)
{
struct rx8025_data *rx8025 = i2c_get_clientdata(client);
u8 ctrl[2], ctrl2;
int need_clear = 0;
int err;
err = rx8025_read_regs(rx8025->client, RX8025_REG_CTRL1, 2, ctrl);
if (err)
goto out;
/* Keep test bit zero ! */
rx8025->ctrl1 = ctrl[0] & ~RX8025_BIT_CTRL1_TEST;
if (ctrl[1] & RX8025_BIT_CTRL2_PON) {
dev_warn(&client->dev, "power-on reset was detected, "
"you may have to readjust the clock\n");
*need_reset = 1;
}
if (ctrl[1] & RX8025_BIT_CTRL2_VDET) {
dev_warn(&client->dev, "a power voltage drop was detected, "
"you may have to readjust the clock\n");
*need_reset = 1;
}
if (!(ctrl[1] & RX8025_BIT_CTRL2_XST)) {
dev_warn(&client->dev, "Oscillation stop was detected,"
"you may have to readjust the clock\n");
*need_reset = 1;
}
if (ctrl[1] & (RX8025_BIT_CTRL2_DAFG | RX8025_BIT_CTRL2_WAFG)) {
dev_warn(&client->dev, "Alarm was detected\n");
need_clear = 1;
}
if (!(ctrl[1] & RX8025_BIT_CTRL2_CTFG))
need_clear = 1;
if (*need_reset || need_clear) {
ctrl2 = ctrl[0];
ctrl2 &= ~(RX8025_BIT_CTRL2_PON | RX8025_BIT_CTRL2_VDET |
RX8025_BIT_CTRL2_CTFG | RX8025_BIT_CTRL2_WAFG |
RX8025_BIT_CTRL2_DAFG);
ctrl2 |= RX8025_BIT_CTRL2_XST;
err = rx8025_write_reg(client, RX8025_REG_CTRL2, ctrl2);
}
out:
return err;
}
/* Alarm support */
static int rx8025_read_alarm(struct device *dev, struct rtc_wkalrm *t)
{
struct rx8025_data *rx8025 = dev_get_drvdata(dev);
struct i2c_client *client = rx8025->client;
u8 ctrl2, ald[2];
int err;
if (client->irq <= 0)
return -EINVAL;
err = rx8025_read_regs(client, RX8025_REG_ALDMIN, 2, ald);
if (err)
return err;
err = rx8025_read_reg(client, RX8025_REG_CTRL2, &ctrl2);
if (err)
return err;
dev_dbg(dev, "%s: read alarm 0x%02x 0x%02x ctrl2 %02x\n",
__func__, ald[0], ald[1], ctrl2);
/* Hardware alarms precision is 1 minute! */
t->time.tm_sec = 0;
t->time.tm_min = bcd2bin(ald[0] & 0x7f);
if (rx8025->ctrl1 & RX8025_BIT_CTRL1_1224)
t->time.tm_hour = bcd2bin(ald[1] & 0x3f);
else
t->time.tm_hour = bcd2bin(ald[1] & 0x1f) % 12
+ (ald[1] & 0x20 ? 12 : 0);
t->time.tm_wday = -1;
t->time.tm_mday = -1;
t->time.tm_mon = -1;
t->time.tm_year = -1;
dev_dbg(dev, "%s: date: %ds %dm %dh %dmd %dm %dy\n",
__func__,
t->time.tm_sec, t->time.tm_min, t->time.tm_hour,
t->time.tm_mday, t->time.tm_mon, t->time.tm_year);
t->enabled = !!(rx8025->ctrl1 & RX8025_BIT_CTRL1_DALE);
t->pending = (ctrl2 & RX8025_BIT_CTRL2_DAFG) && t->enabled;
return err;
}
static int rx8025_set_alarm(struct device *dev, struct rtc_wkalrm *t)
{
struct i2c_client *client = to_i2c_client(dev);
struct rx8025_data *rx8025 = dev_get_drvdata(dev);
u8 ald[2];
int err;
if (client->irq <= 0)
return -EINVAL;
/* Hardware alarm precision is 1 minute! */
ald[0] = bin2bcd(t->time.tm_min);
if (rx8025->ctrl1 & RX8025_BIT_CTRL1_1224)
ald[1] = bin2bcd(t->time.tm_hour);
else
ald[1] = (t->time.tm_hour >= 12 ? 0x20 : 0)
| bin2bcd((t->time.tm_hour + 11) % 12 + 1);
dev_dbg(dev, "%s: write 0x%02x 0x%02x\n", __func__, ald[0], ald[1]);
if (rx8025->ctrl1 & RX8025_BIT_CTRL1_DALE) {
rx8025->ctrl1 &= ~RX8025_BIT_CTRL1_DALE;
err = rx8025_write_reg(rx8025->client, RX8025_REG_CTRL1,
rx8025->ctrl1);
if (err)
return err;
}
err = rx8025_write_regs(rx8025->client, RX8025_REG_ALDMIN, 2, ald);
if (err)
return err;
if (t->enabled) {
rx8025->ctrl1 |= RX8025_BIT_CTRL1_DALE;
err = rx8025_write_reg(rx8025->client, RX8025_REG_CTRL1,
rx8025->ctrl1);
if (err)
return err;
}
return 0;
}
static int rx8025_alarm_irq_enable(struct device *dev, unsigned int enabled)
{
struct rx8025_data *rx8025 = dev_get_drvdata(dev);
u8 ctrl1;
int err;
ctrl1 = rx8025->ctrl1;
if (enabled)
ctrl1 |= RX8025_BIT_CTRL1_DALE;
else
ctrl1 &= ~RX8025_BIT_CTRL1_DALE;
if (ctrl1 != rx8025->ctrl1) {
rx8025->ctrl1 = ctrl1;
err = rx8025_write_reg(rx8025->client, RX8025_REG_CTRL1,
rx8025->ctrl1);
if (err)
return err;
}
return 0;
}
static struct rtc_class_ops rx8025_rtc_ops = {
.read_time = rx8025_get_time,
.set_time = rx8025_set_time,
.read_alarm = rx8025_read_alarm,
.set_alarm = rx8025_set_alarm,
.alarm_irq_enable = rx8025_alarm_irq_enable,
};
/*
* Clock precision adjustment support
*
* According to the RX8025 SA/NB application manual the frequency and
* temperature characteristics can be approximated using the following
* equation:
*
* df = a * (ut - t)**2
*
* df: Frequency deviation in any temperature
* a : Coefficient = (-35 +-5) * 10**-9
* ut: Ultimate temperature in degree = +25 +-5 degree
* t : Any temperature in degree
*
* Note that the clock adjustment in ppb must be entered (which is
* the negative value of the deviation).
*/
static int rx8025_get_clock_adjust(struct device *dev, int *adj)
{
struct i2c_client *client = to_i2c_client(dev);
u8 digoff;
int err;
err = rx8025_read_reg(client, RX8025_REG_DIGOFF, &digoff);
if (err)
return err;
*adj = digoff >= 64 ? digoff - 128 : digoff;
if (*adj > 0)
(*adj)--;
*adj *= -RX8025_ADJ_RESOLUTION;
return 0;
}
static int rx8025_set_clock_adjust(struct device *dev, int adj)
{
struct i2c_client *client = to_i2c_client(dev);
u8 digoff;
int err;
adj /= -RX8025_ADJ_RESOLUTION;
if (adj > RX8025_ADJ_DATA_MAX)
adj = RX8025_ADJ_DATA_MAX;
else if (adj < RX8025_ADJ_DATA_MIN)
adj = RX8025_ADJ_DATA_MIN;
else if (adj > 0)
adj++;
else if (adj < 0)
adj += 128;
digoff = adj;
err = rx8025_write_reg(client, RX8025_REG_DIGOFF, digoff);
if (err)
return err;
dev_dbg(dev, "%s: write 0x%02x\n", __func__, digoff);
return 0;
}
static ssize_t rx8025_sysfs_show_clock_adjust(struct device *dev,
struct device_attribute *attr,
char *buf)
{
int err, adj;
err = rx8025_get_clock_adjust(dev, &adj);
if (err)
return err;
return sprintf(buf, "%d\n", adj);
}
static ssize_t rx8025_sysfs_store_clock_adjust(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int adj, err;
if (sscanf(buf, "%i", &adj) != 1)
return -EINVAL;
err = rx8025_set_clock_adjust(dev, adj);
return err ? err : count;
}
static DEVICE_ATTR(clock_adjust_ppb, S_IRUGO | S_IWUSR,
rx8025_sysfs_show_clock_adjust,
rx8025_sysfs_store_clock_adjust);
static int rx8025_sysfs_register(struct device *dev)
{
return device_create_file(dev, &dev_attr_clock_adjust_ppb);
}
static void rx8025_sysfs_unregister(struct device *dev)
{
device_remove_file(dev, &dev_attr_clock_adjust_ppb);
}
static int __devinit rx8025_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
struct rx8025_data *rx8025;
int err, need_reset = 0;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA
| I2C_FUNC_SMBUS_I2C_BLOCK)) {
dev_err(&adapter->dev,
"doesn't support required functionality\n");
err = -EIO;
goto errout;
}
rx8025 = kzalloc(sizeof(*rx8025), GFP_KERNEL);
if (!rx8025) {
dev_err(&adapter->dev, "failed to alloc memory\n");
err = -ENOMEM;
goto errout;
}
rx8025->client = client;
i2c_set_clientdata(client, rx8025);
INIT_WORK(&rx8025->work, rx8025_work);
err = rx8025_init_client(client, &need_reset);
if (err)
goto errout_free;
if (need_reset) {
struct rtc_time tm;
dev_info(&client->dev,
"bad conditions detected, resetting date\n");
rtc_time_to_tm(0, &tm); /* 1970/1/1 */
rx8025_set_time(&client->dev, &tm);
}
rx8025->rtc = rtc_device_register(client->name, &client->dev,
&rx8025_rtc_ops, THIS_MODULE);
if (IS_ERR(rx8025->rtc)) {
err = PTR_ERR(rx8025->rtc);
dev_err(&client->dev, "unable to register the class device\n");
goto errout_free;
}
if (client->irq > 0) {
dev_info(&client->dev, "IRQ %d supplied\n", client->irq);
err = request_irq(client->irq, rx8025_irq,
0, "rx8025", client);
if (err) {
dev_err(&client->dev, "unable to request IRQ\n");
goto errout_reg;
}
}
rx8025->rtc->irq_freq = 1;
rx8025->rtc->max_user_freq = 1;
err = rx8025_sysfs_register(&client->dev);
if (err)
goto errout_irq;
return 0;
errout_irq:
if (client->irq > 0)
free_irq(client->irq, client);
errout_reg:
rtc_device_unregister(rx8025->rtc);
errout_free:
kfree(rx8025);
errout:
dev_err(&adapter->dev, "probing for rx8025 failed\n");
return err;
}
static int __devexit rx8025_remove(struct i2c_client *client)
{
struct rx8025_data *rx8025 = i2c_get_clientdata(client);
struct mutex *lock = &rx8025->rtc->ops_lock;
if (client->irq > 0) {
mutex_lock(lock);
rx8025->exiting = 1;
mutex_unlock(lock);
free_irq(client->irq, client);
cancel_work_sync(&rx8025->work);
}
rx8025_sysfs_unregister(&client->dev);
rtc_device_unregister(rx8025->rtc);
kfree(rx8025);
return 0;
}
static struct i2c_driver rx8025_driver = {
.driver = {
.name = "rtc-rx8025",
.owner = THIS_MODULE,
},
.probe = rx8025_probe,
.remove = __devexit_p(rx8025_remove),
.id_table = rx8025_id,
};
module_i2c_driver(rx8025_driver);
MODULE_AUTHOR("Wolfgang Grandegger <wg@grandegger.com>");
MODULE_DESCRIPTION("RX-8025 SA/NB RTC driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
johnnyslt/pyramid-3.4.10 | drivers/acpi/fan.c | 5500 | 5800 | /*
* acpi_fan.c - ACPI Fan Driver ($Revision: 29 $)
*
* Copyright (C) 2001, 2002 Andy Grover <andrew.grover@intel.com>
* Copyright (C) 2001, 2002 Paul Diefenbaugh <paul.s.diefenbaugh@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.
*
* 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/types.h>
#include <asm/uaccess.h>
#include <linux/thermal.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#define PREFIX "ACPI: "
#define ACPI_FAN_CLASS "fan"
#define ACPI_FAN_FILE_STATE "state"
#define _COMPONENT ACPI_FAN_COMPONENT
ACPI_MODULE_NAME("fan");
MODULE_AUTHOR("Paul Diefenbaugh");
MODULE_DESCRIPTION("ACPI Fan Driver");
MODULE_LICENSE("GPL");
static int acpi_fan_add(struct acpi_device *device);
static int acpi_fan_remove(struct acpi_device *device, int type);
static int acpi_fan_suspend(struct acpi_device *device, pm_message_t state);
static int acpi_fan_resume(struct acpi_device *device);
static const struct acpi_device_id fan_device_ids[] = {
{"PNP0C0B", 0},
{"", 0},
};
MODULE_DEVICE_TABLE(acpi, fan_device_ids);
static struct acpi_driver acpi_fan_driver = {
.name = "fan",
.class = ACPI_FAN_CLASS,
.ids = fan_device_ids,
.ops = {
.add = acpi_fan_add,
.remove = acpi_fan_remove,
.suspend = acpi_fan_suspend,
.resume = acpi_fan_resume,
},
};
/* thermal cooling device callbacks */
static int fan_get_max_state(struct thermal_cooling_device *cdev, unsigned long
*state)
{
/* ACPI fan device only support two states: ON/OFF */
*state = 1;
return 0;
}
static int fan_get_cur_state(struct thermal_cooling_device *cdev, unsigned long
*state)
{
struct acpi_device *device = cdev->devdata;
int result;
int acpi_state;
if (!device)
return -EINVAL;
result = acpi_bus_update_power(device->handle, &acpi_state);
if (result)
return result;
*state = (acpi_state == ACPI_STATE_D3 ? 0 :
(acpi_state == ACPI_STATE_D0 ? 1 : -1));
return 0;
}
static int
fan_set_cur_state(struct thermal_cooling_device *cdev, unsigned long state)
{
struct acpi_device *device = cdev->devdata;
int result;
if (!device || (state != 0 && state != 1))
return -EINVAL;
result = acpi_bus_set_power(device->handle,
state ? ACPI_STATE_D0 : ACPI_STATE_D3);
return result;
}
static const struct thermal_cooling_device_ops fan_cooling_ops = {
.get_max_state = fan_get_max_state,
.get_cur_state = fan_get_cur_state,
.set_cur_state = fan_set_cur_state,
};
/* --------------------------------------------------------------------------
Driver Interface
-------------------------------------------------------------------------- */
static int acpi_fan_add(struct acpi_device *device)
{
int result = 0;
struct thermal_cooling_device *cdev;
if (!device)
return -EINVAL;
strcpy(acpi_device_name(device), "Fan");
strcpy(acpi_device_class(device), ACPI_FAN_CLASS);
result = acpi_bus_update_power(device->handle, NULL);
if (result) {
printk(KERN_ERR PREFIX "Setting initial power state\n");
goto end;
}
cdev = thermal_cooling_device_register("Fan", device,
&fan_cooling_ops);
if (IS_ERR(cdev)) {
result = PTR_ERR(cdev);
goto end;
}
dev_dbg(&device->dev, "registered as cooling_device%d\n", cdev->id);
device->driver_data = cdev;
result = sysfs_create_link(&device->dev.kobj,
&cdev->device.kobj,
"thermal_cooling");
if (result)
dev_err(&device->dev, "Failed to create sysfs link "
"'thermal_cooling'\n");
result = sysfs_create_link(&cdev->device.kobj,
&device->dev.kobj,
"device");
if (result)
dev_err(&device->dev, "Failed to create sysfs link "
"'device'\n");
printk(KERN_INFO PREFIX "%s [%s] (%s)\n",
acpi_device_name(device), acpi_device_bid(device),
!device->power.state ? "on" : "off");
end:
return result;
}
static int acpi_fan_remove(struct acpi_device *device, int type)
{
struct thermal_cooling_device *cdev = acpi_driver_data(device);
if (!device || !cdev)
return -EINVAL;
sysfs_remove_link(&device->dev.kobj, "thermal_cooling");
sysfs_remove_link(&cdev->device.kobj, "device");
thermal_cooling_device_unregister(cdev);
return 0;
}
static int acpi_fan_suspend(struct acpi_device *device, pm_message_t state)
{
if (!device)
return -EINVAL;
acpi_bus_set_power(device->handle, ACPI_STATE_D0);
return AE_OK;
}
static int acpi_fan_resume(struct acpi_device *device)
{
int result;
if (!device)
return -EINVAL;
result = acpi_bus_update_power(device->handle, NULL);
if (result)
printk(KERN_ERR PREFIX "Error updating fan power state\n");
return result;
}
static int __init acpi_fan_init(void)
{
int result = 0;
result = acpi_bus_register_driver(&acpi_fan_driver);
if (result < 0)
return -ENODEV;
return 0;
}
static void __exit acpi_fan_exit(void)
{
acpi_bus_unregister_driver(&acpi_fan_driver);
return;
}
module_init(acpi_fan_init);
module_exit(acpi_fan_exit);
| gpl-2.0 |
Tim1928/DBK-3.0_4.1 | net/rxrpc/af_rxrpc.c | 6268 | 20966 | /* AF_RXRPC implementation
*
* 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.
*/
#include <linux/module.h>
#include <linux/net.h>
#include <linux/slab.h>
#include <linux/skbuff.h>
#include <linux/poll.h>
#include <linux/proc_fs.h>
#include <linux/key-type.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <net/af_rxrpc.h>
#include "ar-internal.h"
MODULE_DESCRIPTION("RxRPC network protocol");
MODULE_AUTHOR("Red Hat, Inc.");
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_RXRPC);
unsigned rxrpc_debug; // = RXRPC_DEBUG_KPROTO;
module_param_named(debug, rxrpc_debug, uint, S_IWUSR | S_IRUGO);
MODULE_PARM_DESC(debug, "RxRPC debugging mask");
static int sysctl_rxrpc_max_qlen __read_mostly = 10;
static struct proto rxrpc_proto;
static const struct proto_ops rxrpc_rpc_ops;
/* local epoch for detecting local-end reset */
__be32 rxrpc_epoch;
/* current debugging ID */
atomic_t rxrpc_debug_id;
/* count of skbs currently in use */
atomic_t rxrpc_n_skbs;
struct workqueue_struct *rxrpc_workqueue;
static void rxrpc_sock_destructor(struct sock *);
/*
* see if an RxRPC socket is currently writable
*/
static inline int rxrpc_writable(struct sock *sk)
{
return atomic_read(&sk->sk_wmem_alloc) < (size_t) sk->sk_sndbuf;
}
/*
* wait for write bufferage to become available
*/
static void rxrpc_write_space(struct sock *sk)
{
_enter("%p", sk);
rcu_read_lock();
if (rxrpc_writable(sk)) {
struct socket_wq *wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible(&wq->wait);
sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
}
rcu_read_unlock();
}
/*
* validate an RxRPC address
*/
static int rxrpc_validate_address(struct rxrpc_sock *rx,
struct sockaddr_rxrpc *srx,
int len)
{
if (len < sizeof(struct sockaddr_rxrpc))
return -EINVAL;
if (srx->srx_family != AF_RXRPC)
return -EAFNOSUPPORT;
if (srx->transport_type != SOCK_DGRAM)
return -ESOCKTNOSUPPORT;
len -= offsetof(struct sockaddr_rxrpc, transport);
if (srx->transport_len < sizeof(sa_family_t) ||
srx->transport_len > len)
return -EINVAL;
if (srx->transport.family != rx->proto)
return -EAFNOSUPPORT;
switch (srx->transport.family) {
case AF_INET:
_debug("INET: %x @ %pI4",
ntohs(srx->transport.sin.sin_port),
&srx->transport.sin.sin_addr);
if (srx->transport_len > 8)
memset((void *)&srx->transport + 8, 0,
srx->transport_len - 8);
break;
case AF_INET6:
default:
return -EAFNOSUPPORT;
}
return 0;
}
/*
* bind a local address to an RxRPC socket
*/
static int rxrpc_bind(struct socket *sock, struct sockaddr *saddr, int len)
{
struct sockaddr_rxrpc *srx = (struct sockaddr_rxrpc *) saddr;
struct sock *sk = sock->sk;
struct rxrpc_local *local;
struct rxrpc_sock *rx = rxrpc_sk(sk), *prx;
__be16 service_id;
int ret;
_enter("%p,%p,%d", rx, saddr, len);
ret = rxrpc_validate_address(rx, srx, len);
if (ret < 0)
goto error;
lock_sock(&rx->sk);
if (rx->sk.sk_state != RXRPC_UNCONNECTED) {
ret = -EINVAL;
goto error_unlock;
}
memcpy(&rx->srx, srx, sizeof(rx->srx));
/* find a local transport endpoint if we don't have one already */
local = rxrpc_lookup_local(&rx->srx);
if (IS_ERR(local)) {
ret = PTR_ERR(local);
goto error_unlock;
}
rx->local = local;
if (srx->srx_service) {
service_id = htons(srx->srx_service);
write_lock_bh(&local->services_lock);
list_for_each_entry(prx, &local->services, listen_link) {
if (prx->service_id == service_id)
goto service_in_use;
}
rx->service_id = service_id;
list_add_tail(&rx->listen_link, &local->services);
write_unlock_bh(&local->services_lock);
rx->sk.sk_state = RXRPC_SERVER_BOUND;
} else {
rx->sk.sk_state = RXRPC_CLIENT_BOUND;
}
release_sock(&rx->sk);
_leave(" = 0");
return 0;
service_in_use:
ret = -EADDRINUSE;
write_unlock_bh(&local->services_lock);
error_unlock:
release_sock(&rx->sk);
error:
_leave(" = %d", ret);
return ret;
}
/*
* set the number of pending calls permitted on a listening socket
*/
static int rxrpc_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
struct rxrpc_sock *rx = rxrpc_sk(sk);
int ret;
_enter("%p,%d", rx, backlog);
lock_sock(&rx->sk);
switch (rx->sk.sk_state) {
case RXRPC_UNCONNECTED:
ret = -EADDRNOTAVAIL;
break;
case RXRPC_CLIENT_BOUND:
case RXRPC_CLIENT_CONNECTED:
default:
ret = -EBUSY;
break;
case RXRPC_SERVER_BOUND:
ASSERT(rx->local != NULL);
sk->sk_max_ack_backlog = backlog;
rx->sk.sk_state = RXRPC_SERVER_LISTENING;
ret = 0;
break;
}
release_sock(&rx->sk);
_leave(" = %d", ret);
return ret;
}
/*
* find a transport by address
*/
static struct rxrpc_transport *rxrpc_name_to_transport(struct socket *sock,
struct sockaddr *addr,
int addr_len, int flags,
gfp_t gfp)
{
struct sockaddr_rxrpc *srx = (struct sockaddr_rxrpc *) addr;
struct rxrpc_transport *trans;
struct rxrpc_sock *rx = rxrpc_sk(sock->sk);
struct rxrpc_peer *peer;
_enter("%p,%p,%d,%d", rx, addr, addr_len, flags);
ASSERT(rx->local != NULL);
ASSERT(rx->sk.sk_state > RXRPC_UNCONNECTED);
if (rx->srx.transport_type != srx->transport_type)
return ERR_PTR(-ESOCKTNOSUPPORT);
if (rx->srx.transport.family != srx->transport.family)
return ERR_PTR(-EAFNOSUPPORT);
/* find a remote transport endpoint from the local one */
peer = rxrpc_get_peer(srx, gfp);
if (IS_ERR(peer))
return ERR_CAST(peer);
/* find a transport */
trans = rxrpc_get_transport(rx->local, peer, gfp);
rxrpc_put_peer(peer);
_leave(" = %p", trans);
return trans;
}
/**
* rxrpc_kernel_begin_call - Allow a kernel service to begin a call
* @sock: The socket on which to make the call
* @srx: The address of the peer to contact (defaults to socket setting)
* @key: The security context to use (defaults to socket setting)
* @user_call_ID: The ID to use
*
* Allow a kernel service to begin a call on the nominated socket. This just
* sets up all the internal tracking structures and allocates connection and
* call IDs as appropriate. The call to be used is returned.
*
* The default socket destination address and security may be overridden by
* supplying @srx and @key.
*/
struct rxrpc_call *rxrpc_kernel_begin_call(struct socket *sock,
struct sockaddr_rxrpc *srx,
struct key *key,
unsigned long user_call_ID,
gfp_t gfp)
{
struct rxrpc_conn_bundle *bundle;
struct rxrpc_transport *trans;
struct rxrpc_call *call;
struct rxrpc_sock *rx = rxrpc_sk(sock->sk);
__be16 service_id;
_enter(",,%x,%lx", key_serial(key), user_call_ID);
lock_sock(&rx->sk);
if (srx) {
trans = rxrpc_name_to_transport(sock, (struct sockaddr *) srx,
sizeof(*srx), 0, gfp);
if (IS_ERR(trans)) {
call = ERR_CAST(trans);
trans = NULL;
goto out_notrans;
}
} else {
trans = rx->trans;
if (!trans) {
call = ERR_PTR(-ENOTCONN);
goto out_notrans;
}
atomic_inc(&trans->usage);
}
service_id = rx->service_id;
if (srx)
service_id = htons(srx->srx_service);
if (!key)
key = rx->key;
if (key && !key->payload.data)
key = NULL; /* a no-security key */
bundle = rxrpc_get_bundle(rx, trans, key, service_id, gfp);
if (IS_ERR(bundle)) {
call = ERR_CAST(bundle);
goto out;
}
call = rxrpc_get_client_call(rx, trans, bundle, user_call_ID, true,
gfp);
rxrpc_put_bundle(trans, bundle);
out:
rxrpc_put_transport(trans);
out_notrans:
release_sock(&rx->sk);
_leave(" = %p", call);
return call;
}
EXPORT_SYMBOL(rxrpc_kernel_begin_call);
/**
* rxrpc_kernel_end_call - Allow a kernel service to end a call it was using
* @call: The call to end
*
* Allow a kernel service to end a call it was using. The call must be
* complete before this is called (the call should be aborted if necessary).
*/
void rxrpc_kernel_end_call(struct rxrpc_call *call)
{
_enter("%d{%d}", call->debug_id, atomic_read(&call->usage));
rxrpc_remove_user_ID(call->socket, call);
rxrpc_put_call(call);
}
EXPORT_SYMBOL(rxrpc_kernel_end_call);
/**
* rxrpc_kernel_intercept_rx_messages - Intercept received RxRPC messages
* @sock: The socket to intercept received messages on
* @interceptor: The function to pass the messages to
*
* Allow a kernel service to intercept messages heading for the Rx queue on an
* RxRPC socket. They get passed to the specified function instead.
* @interceptor should free the socket buffers it is given. @interceptor is
* called with the socket receive queue spinlock held and softirqs disabled -
* this ensures that the messages will be delivered in the right order.
*/
void rxrpc_kernel_intercept_rx_messages(struct socket *sock,
rxrpc_interceptor_t interceptor)
{
struct rxrpc_sock *rx = rxrpc_sk(sock->sk);
_enter("");
rx->interceptor = interceptor;
}
EXPORT_SYMBOL(rxrpc_kernel_intercept_rx_messages);
/*
* connect an RxRPC socket
* - this just targets it at a specific destination; no actual connection
* negotiation takes place
*/
static int rxrpc_connect(struct socket *sock, struct sockaddr *addr,
int addr_len, int flags)
{
struct sockaddr_rxrpc *srx = (struct sockaddr_rxrpc *) addr;
struct sock *sk = sock->sk;
struct rxrpc_transport *trans;
struct rxrpc_local *local;
struct rxrpc_sock *rx = rxrpc_sk(sk);
int ret;
_enter("%p,%p,%d,%d", rx, addr, addr_len, flags);
ret = rxrpc_validate_address(rx, srx, addr_len);
if (ret < 0) {
_leave(" = %d [bad addr]", ret);
return ret;
}
lock_sock(&rx->sk);
switch (rx->sk.sk_state) {
case RXRPC_UNCONNECTED:
/* find a local transport endpoint if we don't have one already */
ASSERTCMP(rx->local, ==, NULL);
rx->srx.srx_family = AF_RXRPC;
rx->srx.srx_service = 0;
rx->srx.transport_type = srx->transport_type;
rx->srx.transport_len = sizeof(sa_family_t);
rx->srx.transport.family = srx->transport.family;
local = rxrpc_lookup_local(&rx->srx);
if (IS_ERR(local)) {
release_sock(&rx->sk);
return PTR_ERR(local);
}
rx->local = local;
rx->sk.sk_state = RXRPC_CLIENT_BOUND;
case RXRPC_CLIENT_BOUND:
break;
case RXRPC_CLIENT_CONNECTED:
release_sock(&rx->sk);
return -EISCONN;
default:
release_sock(&rx->sk);
return -EBUSY; /* server sockets can't connect as well */
}
trans = rxrpc_name_to_transport(sock, addr, addr_len, flags,
GFP_KERNEL);
if (IS_ERR(trans)) {
release_sock(&rx->sk);
_leave(" = %ld", PTR_ERR(trans));
return PTR_ERR(trans);
}
rx->trans = trans;
rx->service_id = htons(srx->srx_service);
rx->sk.sk_state = RXRPC_CLIENT_CONNECTED;
release_sock(&rx->sk);
return 0;
}
/*
* send a message through an RxRPC socket
* - in a client this does a number of things:
* - finds/sets up a connection for the security specified (if any)
* - initiates a call (ID in control data)
* - ends the request phase of a call (if MSG_MORE is not set)
* - sends a call data packet
* - may send an abort (abort code in control data)
*/
static int rxrpc_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t len)
{
struct rxrpc_transport *trans;
struct rxrpc_sock *rx = rxrpc_sk(sock->sk);
int ret;
_enter(",{%d},,%zu", rx->sk.sk_state, len);
if (m->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
if (m->msg_name) {
ret = rxrpc_validate_address(rx, m->msg_name, m->msg_namelen);
if (ret < 0) {
_leave(" = %d [bad addr]", ret);
return ret;
}
}
trans = NULL;
lock_sock(&rx->sk);
if (m->msg_name) {
ret = -EISCONN;
trans = rxrpc_name_to_transport(sock, m->msg_name,
m->msg_namelen, 0, GFP_KERNEL);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
trans = NULL;
goto out;
}
} else {
trans = rx->trans;
if (trans)
atomic_inc(&trans->usage);
}
switch (rx->sk.sk_state) {
case RXRPC_SERVER_LISTENING:
if (!m->msg_name) {
ret = rxrpc_server_sendmsg(iocb, rx, m, len);
break;
}
case RXRPC_SERVER_BOUND:
case RXRPC_CLIENT_BOUND:
if (!m->msg_name) {
ret = -ENOTCONN;
break;
}
case RXRPC_CLIENT_CONNECTED:
ret = rxrpc_client_sendmsg(iocb, rx, trans, m, len);
break;
default:
ret = -ENOTCONN;
break;
}
out:
release_sock(&rx->sk);
if (trans)
rxrpc_put_transport(trans);
_leave(" = %d", ret);
return ret;
}
/*
* set RxRPC socket options
*/
static int rxrpc_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct rxrpc_sock *rx = rxrpc_sk(sock->sk);
unsigned min_sec_level;
int ret;
_enter(",%d,%d,,%d", level, optname, optlen);
lock_sock(&rx->sk);
ret = -EOPNOTSUPP;
if (level == SOL_RXRPC) {
switch (optname) {
case RXRPC_EXCLUSIVE_CONNECTION:
ret = -EINVAL;
if (optlen != 0)
goto error;
ret = -EISCONN;
if (rx->sk.sk_state != RXRPC_UNCONNECTED)
goto error;
set_bit(RXRPC_SOCK_EXCLUSIVE_CONN, &rx->flags);
goto success;
case RXRPC_SECURITY_KEY:
ret = -EINVAL;
if (rx->key)
goto error;
ret = -EISCONN;
if (rx->sk.sk_state != RXRPC_UNCONNECTED)
goto error;
ret = rxrpc_request_key(rx, optval, optlen);
goto error;
case RXRPC_SECURITY_KEYRING:
ret = -EINVAL;
if (rx->key)
goto error;
ret = -EISCONN;
if (rx->sk.sk_state != RXRPC_UNCONNECTED)
goto error;
ret = rxrpc_server_keyring(rx, optval, optlen);
goto error;
case RXRPC_MIN_SECURITY_LEVEL:
ret = -EINVAL;
if (optlen != sizeof(unsigned))
goto error;
ret = -EISCONN;
if (rx->sk.sk_state != RXRPC_UNCONNECTED)
goto error;
ret = get_user(min_sec_level,
(unsigned __user *) optval);
if (ret < 0)
goto error;
ret = -EINVAL;
if (min_sec_level > RXRPC_SECURITY_MAX)
goto error;
rx->min_sec_level = min_sec_level;
goto success;
default:
break;
}
}
success:
ret = 0;
error:
release_sock(&rx->sk);
return ret;
}
/*
* permit an RxRPC socket to be polled
*/
static unsigned int rxrpc_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
unsigned int mask;
struct sock *sk = sock->sk;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
/* the socket is readable if there are any messages waiting on the Rx
* queue */
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
/* the socket is writable if there is space to add new data to the
* socket; there is no guarantee that any particular call in progress
* on the socket may have space in the Tx ACK window */
if (rxrpc_writable(sk))
mask |= POLLOUT | POLLWRNORM;
return mask;
}
/*
* create an RxRPC socket
*/
static int rxrpc_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct rxrpc_sock *rx;
struct sock *sk;
_enter("%p,%d", sock, protocol);
if (!net_eq(net, &init_net))
return -EAFNOSUPPORT;
/* we support transport protocol UDP only */
if (protocol != PF_INET)
return -EPROTONOSUPPORT;
if (sock->type != SOCK_DGRAM)
return -ESOCKTNOSUPPORT;
sock->ops = &rxrpc_rpc_ops;
sock->state = SS_UNCONNECTED;
sk = sk_alloc(net, PF_RXRPC, GFP_KERNEL, &rxrpc_proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
sk->sk_state = RXRPC_UNCONNECTED;
sk->sk_write_space = rxrpc_write_space;
sk->sk_max_ack_backlog = sysctl_rxrpc_max_qlen;
sk->sk_destruct = rxrpc_sock_destructor;
rx = rxrpc_sk(sk);
rx->proto = protocol;
rx->calls = RB_ROOT;
INIT_LIST_HEAD(&rx->listen_link);
INIT_LIST_HEAD(&rx->secureq);
INIT_LIST_HEAD(&rx->acceptq);
rwlock_init(&rx->call_lock);
memset(&rx->srx, 0, sizeof(rx->srx));
_leave(" = 0 [%p]", rx);
return 0;
}
/*
* RxRPC socket destructor
*/
static void rxrpc_sock_destructor(struct sock *sk)
{
_enter("%p", sk);
rxrpc_purge_queue(&sk->sk_receive_queue);
WARN_ON(atomic_read(&sk->sk_wmem_alloc));
WARN_ON(!sk_unhashed(sk));
WARN_ON(sk->sk_socket);
if (!sock_flag(sk, SOCK_DEAD)) {
printk("Attempt to release alive rxrpc socket: %p\n", sk);
return;
}
}
/*
* release an RxRPC socket
*/
static int rxrpc_release_sock(struct sock *sk)
{
struct rxrpc_sock *rx = rxrpc_sk(sk);
_enter("%p{%d,%d}", sk, sk->sk_state, atomic_read(&sk->sk_refcnt));
/* declare the socket closed for business */
sock_orphan(sk);
sk->sk_shutdown = SHUTDOWN_MASK;
spin_lock_bh(&sk->sk_receive_queue.lock);
sk->sk_state = RXRPC_CLOSE;
spin_unlock_bh(&sk->sk_receive_queue.lock);
ASSERTCMP(rx->listen_link.next, !=, LIST_POISON1);
if (!list_empty(&rx->listen_link)) {
write_lock_bh(&rx->local->services_lock);
list_del(&rx->listen_link);
write_unlock_bh(&rx->local->services_lock);
}
/* try to flush out this socket */
rxrpc_release_calls_on_socket(rx);
flush_workqueue(rxrpc_workqueue);
rxrpc_purge_queue(&sk->sk_receive_queue);
if (rx->conn) {
rxrpc_put_connection(rx->conn);
rx->conn = NULL;
}
if (rx->bundle) {
rxrpc_put_bundle(rx->trans, rx->bundle);
rx->bundle = NULL;
}
if (rx->trans) {
rxrpc_put_transport(rx->trans);
rx->trans = NULL;
}
if (rx->local) {
rxrpc_put_local(rx->local);
rx->local = NULL;
}
key_put(rx->key);
rx->key = NULL;
key_put(rx->securities);
rx->securities = NULL;
sock_put(sk);
_leave(" = 0");
return 0;
}
/*
* release an RxRPC BSD socket on close() or equivalent
*/
static int rxrpc_release(struct socket *sock)
{
struct sock *sk = sock->sk;
_enter("%p{%p}", sock, sk);
if (!sk)
return 0;
sock->sk = NULL;
return rxrpc_release_sock(sk);
}
/*
* RxRPC network protocol
*/
static const struct proto_ops rxrpc_rpc_ops = {
.family = PF_UNIX,
.owner = THIS_MODULE,
.release = rxrpc_release,
.bind = rxrpc_bind,
.connect = rxrpc_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = sock_no_getname,
.poll = rxrpc_poll,
.ioctl = sock_no_ioctl,
.listen = rxrpc_listen,
.shutdown = sock_no_shutdown,
.setsockopt = rxrpc_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = rxrpc_sendmsg,
.recvmsg = rxrpc_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static struct proto rxrpc_proto = {
.name = "RXRPC",
.owner = THIS_MODULE,
.obj_size = sizeof(struct rxrpc_sock),
.max_header = sizeof(struct rxrpc_header),
};
static const struct net_proto_family rxrpc_family_ops = {
.family = PF_RXRPC,
.create = rxrpc_create,
.owner = THIS_MODULE,
};
/*
* initialise and register the RxRPC protocol
*/
static int __init af_rxrpc_init(void)
{
struct sk_buff *dummy_skb;
int ret = -1;
BUILD_BUG_ON(sizeof(struct rxrpc_skb_priv) > sizeof(dummy_skb->cb));
rxrpc_epoch = htonl(get_seconds());
ret = -ENOMEM;
rxrpc_call_jar = kmem_cache_create(
"rxrpc_call_jar", sizeof(struct rxrpc_call), 0,
SLAB_HWCACHE_ALIGN, NULL);
if (!rxrpc_call_jar) {
printk(KERN_NOTICE "RxRPC: Failed to allocate call jar\n");
goto error_call_jar;
}
rxrpc_workqueue = alloc_workqueue("krxrpcd", 0, 1);
if (!rxrpc_workqueue) {
printk(KERN_NOTICE "RxRPC: Failed to allocate work queue\n");
goto error_work_queue;
}
ret = proto_register(&rxrpc_proto, 1);
if (ret < 0) {
printk(KERN_CRIT "RxRPC: Cannot register protocol\n");
goto error_proto;
}
ret = sock_register(&rxrpc_family_ops);
if (ret < 0) {
printk(KERN_CRIT "RxRPC: Cannot register socket family\n");
goto error_sock;
}
ret = register_key_type(&key_type_rxrpc);
if (ret < 0) {
printk(KERN_CRIT "RxRPC: Cannot register client key type\n");
goto error_key_type;
}
ret = register_key_type(&key_type_rxrpc_s);
if (ret < 0) {
printk(KERN_CRIT "RxRPC: Cannot register server key type\n");
goto error_key_type_s;
}
#ifdef CONFIG_PROC_FS
proc_net_fops_create(&init_net, "rxrpc_calls", 0, &rxrpc_call_seq_fops);
proc_net_fops_create(&init_net, "rxrpc_conns", 0, &rxrpc_connection_seq_fops);
#endif
return 0;
error_key_type_s:
unregister_key_type(&key_type_rxrpc);
error_key_type:
sock_unregister(PF_RXRPC);
error_sock:
proto_unregister(&rxrpc_proto);
error_proto:
destroy_workqueue(rxrpc_workqueue);
error_work_queue:
kmem_cache_destroy(rxrpc_call_jar);
error_call_jar:
return ret;
}
/*
* unregister the RxRPC protocol
*/
static void __exit af_rxrpc_exit(void)
{
_enter("");
unregister_key_type(&key_type_rxrpc_s);
unregister_key_type(&key_type_rxrpc);
sock_unregister(PF_RXRPC);
proto_unregister(&rxrpc_proto);
rxrpc_destroy_all_calls();
rxrpc_destroy_all_connections();
rxrpc_destroy_all_transports();
rxrpc_destroy_all_peers();
rxrpc_destroy_all_locals();
ASSERTCMP(atomic_read(&rxrpc_n_skbs), ==, 0);
_debug("flush scheduled work");
flush_workqueue(rxrpc_workqueue);
proc_net_remove(&init_net, "rxrpc_conns");
proc_net_remove(&init_net, "rxrpc_calls");
destroy_workqueue(rxrpc_workqueue);
kmem_cache_destroy(rxrpc_call_jar);
_leave("");
}
module_init(af_rxrpc_init);
module_exit(af_rxrpc_exit);
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.